Skip to content

Commit cd8c2c5

Browse files
fix(web): the Cite button comes back once the timeline stops scrolling (pingdotgg#15818)
Co-authored-by: Julius Marminge <[email protected]>
1 parent 462fa32 commit cd8c2c5

3 files changed

Lines changed: 165 additions & 4 deletions

File tree

‎apps/web/src/components/chat/AssistantSelectionToolbar.tsx‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
type AssistantCitationSourceAnchor,
1313
} from "~/lib/assistantTextSelection";
1414
import {
15+
isSelectionRectVisible,
1516
observeSelectionActions,
1617
resolveSelectionActionPosition,
1718
type SelectionActionPoint,
@@ -56,7 +57,53 @@ export function AssistantSelectionToolbar({
5657
}
5758
const rect = captured.range.getBoundingClientRect();
5859
const viewportRect = viewport.getBoundingClientRect();
59-
if (rect.bottom < viewportRect.top || rect.top > viewportRect.bottom || rect.width === 0) {
60+
if (!isSelectionRectVisible(rect, [viewportRect])) {
61+
clear();
62+
return;
63+
}
64+
// A selection can cross blocks with different clipping ancestors.
65+
const common = captured.range.commonAncestorContainer;
66+
const walker = document.createTreeWalker(common, NodeFilter.SHOW_TEXT);
67+
let node = common.nodeType === Node.TEXT_NODE ? common : walker.nextNode();
68+
let visible = false;
69+
for (; node && !visible; node = walker.nextNode()) {
70+
if (!captured.range.intersectsNode(node)) continue;
71+
if (node.parentElement && getComputedStyle(node.parentElement).userSelect === "none")
72+
continue;
73+
const fragment = document.createRange();
74+
fragment.selectNodeContents(node);
75+
if (node === captured.range.startContainer) {
76+
fragment.setStart(node, captured.range.startOffset);
77+
}
78+
if (node === captured.range.endContainer) {
79+
fragment.setEnd(node, captured.range.endOffset);
80+
}
81+
if (!fragment.toString().trim()) continue;
82+
const lines = Array.from(fragment.getClientRects());
83+
if (!lines.some((line) => isSelectionRectVisible(line, [viewportRect]))) continue;
84+
const clips: Pick<DOMRect, "left" | "right" | "top" | "bottom">[] = [viewportRect];
85+
for (
86+
let element = node.parentElement;
87+
element && element !== viewport;
88+
element = element.parentElement
89+
) {
90+
const style = getComputedStyle(element);
91+
const clipX = style.overflowX !== "visible";
92+
const clipY = style.overflowY !== "visible";
93+
if (!clipX && !clipY) continue;
94+
const bounds = element.getBoundingClientRect();
95+
const left = bounds.left + element.clientLeft;
96+
const top = bounds.top + element.clientTop;
97+
clips.push({
98+
left: clipX ? left : -Infinity,
99+
right: clipX ? left + element.clientWidth : Infinity,
100+
top: clipY ? top : -Infinity,
101+
bottom: clipY ? top + element.clientHeight : Infinity,
102+
});
103+
}
104+
visible = lines.some((line) => isSelectionRectVisible(line, clips));
105+
}
106+
if (!visible) {
60107
clear();
61108
return;
62109
}
@@ -89,6 +136,7 @@ export function AssistantSelectionToolbar({
89136
const actions = observeSelectionActions({
90137
element: viewport,
91138
getActionElement: () => toolbarRef.current,
139+
restoreAfterScroll: true,
92140
onSelection: update,
93141
onDismiss: clear,
94142
});

‎apps/web/src/lib/selectionActions.test.ts‎

Lines changed: 94 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
22

3-
import { observeSelectionActions, resolveSelectionActionPosition } from "./selectionActions";
3+
import {
4+
isSelectionRectVisible,
5+
observeSelectionActions,
6+
resolveSelectionActionPosition,
7+
} from "./selectionActions";
48

59
function event(type: string, values: Record<string, unknown> = {}) {
610
return Object.assign(new Event(type, { cancelable: true }), values);
711
}
812

9-
function createSelectionSurface({ interactiveActions = false } = {}) {
13+
function createSelectionSurface({ interactiveActions = false, restoreAfterScroll = false } = {}) {
1014
const frames = new Map<number, FrameRequestCallback>();
1115
let frameId = 0;
1216
const view = Object.assign(new EventTarget(), {
@@ -42,6 +46,7 @@ function createSelectionSurface({ interactiveActions = false } = {}) {
4246
...(interactiveActions
4347
? { getActionElement: () => actionElement as unknown as HTMLElement }
4448
: {}),
49+
restoreAfterScroll,
4550
onSelection,
4651
onDismiss,
4752
});
@@ -294,6 +299,69 @@ describe("selection action gestures", () => {
294299
expect(surface.onSelection).toHaveBeenCalledOnce();
295300
});
296301

302+
it("restores after scrolling settles with a fresh anchor, without interrupting a held drag", () => {
303+
const surface = createSelectionSurface({ restoreAfterScroll: true });
304+
surface.down();
305+
surface.element.dispatchEvent(event("scroll"));
306+
surface.change();
307+
surface.flush(1000);
308+
expect(surface.onSelection).not.toHaveBeenCalled();
309+
surface.up({ x: 420, y: 310 });
310+
surface.flush();
311+
expect(surface.onSelection.mock.calls).toEqual([[{ x: 420, y: 310 }]]);
312+
313+
surface.onDismiss.mockClear();
314+
surface.element.dispatchEvent(event("scroll"));
315+
expect(surface.onDismiss).toHaveBeenCalledWith("cancel");
316+
surface.flush(100);
317+
surface.element.dispatchEvent(event("scroll"));
318+
surface.change();
319+
surface.flush(100);
320+
expect(surface.onSelection).toHaveBeenCalledOnce();
321+
surface.flush(50);
322+
expect(surface.onSelection.mock.calls).toEqual([[{ x: 420, y: 310 }], [null]]);
323+
surface.flush(1000);
324+
expect(surface.onSelection).toHaveBeenCalledTimes(2);
325+
326+
surface.down();
327+
surface.up();
328+
vi.advanceTimersByTime(0);
329+
surface.element.dispatchEvent(event("scroll"));
330+
surface.flush(149);
331+
expect(surface.onSelection).toHaveBeenCalledTimes(2);
332+
surface.flush(1);
333+
expect(surface.onSelection.mock.calls).toEqual([[{ x: 420, y: 310 }], [null], [null]]);
334+
});
335+
336+
it("keeps Escape during scroll settling dismissed through later scrolling", () => {
337+
const surface = createSelectionSurface({ restoreAfterScroll: true });
338+
surface.down();
339+
surface.up();
340+
surface.flush();
341+
surface.element.dispatchEvent(event("scroll"));
342+
surface.key("Escape");
343+
surface.change();
344+
surface.flush(1000);
345+
expect(surface.onSelection).toHaveBeenCalledOnce();
346+
347+
surface.key("PageDown");
348+
surface.element.dispatchEvent(event("scroll"));
349+
surface.change();
350+
surface.flush(1000);
351+
expect(surface.onSelection).toHaveBeenCalledOnce();
352+
353+
surface.document.dispatchEvent(event("keydown", { key: "ArrowRight", shiftKey: true }));
354+
surface.change();
355+
surface.element.dispatchEvent(event("scroll"));
356+
surface.flush(150);
357+
expect(surface.onSelection.mock.calls).toEqual([[{ x: 300, y: 200 }], [null]]);
358+
surface.key("Escape");
359+
surface.down();
360+
surface.up();
361+
surface.flush();
362+
expect(surface.onSelection).toHaveBeenCalledTimes(3);
363+
});
364+
297365
it("cancels a queued animation frame when a new press supersedes the release", () => {
298366
const surface = createSelectionSurface();
299367
surface.down();
@@ -387,6 +455,30 @@ describe("interactive selection actions", () => {
387455
});
388456
});
389457

458+
describe("selection visibility", () => {
459+
const rect = (left: number, top: number, right: number, bottom: number) => ({
460+
left,
461+
top,
462+
right,
463+
bottom,
464+
width: right - left,
465+
});
466+
const timeline = rect(0, 0, 800, 600);
467+
const codeBlock = rect(100, 200, 400, 260);
468+
469+
it("only shows text overlapping both the timeline and its nested scroller", () => {
470+
expect(isSelectionRectVisible(rect(150, 210, 220, 226), [timeline, codeBlock])).toBe(true);
471+
expect(isSelectionRectVisible(rect(420, 210, 480, 226), [timeline, codeBlock])).toBe(false);
472+
expect(isSelectionRectVisible(rect(380, 210, 460, 226), [timeline, codeBlock])).toBe(true);
473+
expect(
474+
isSelectionRectVisible(rect(150, -40, 220, -24), [timeline, rect(100, -50, 400, 260)]),
475+
).toBe(false);
476+
expect(
477+
isSelectionRectVisible(rect(-200, 210, 220, 226), [timeline, rect(-200, 200, -20, 260)]),
478+
).toBe(false);
479+
});
480+
});
481+
390482
describe("selection action positioning", () => {
391483
const bounds = { left: 100, top: 50, width: 500, height: 220 };
392484
const viewport = { width: 1024, height: 768 };

‎apps/web/src/lib/selectionActions.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
export type SelectionActionPoint = { x: number; y: number };
22

33
export const SELECTION_MULTI_CLICK_INTERVAL_MS = 500;
4+
const SELECTION_SCROLL_SETTLE_MS = 150;
45

56
export function resolveSelectionActionPosition(options: {
67
bounds: { left: number; top: number; width: number; height: number };
@@ -25,18 +26,33 @@ export function resolveSelectionActionPosition(options: {
2526
};
2627
}
2728

29+
type SelectionRect = { left: number; top: number; right: number; bottom: number };
30+
31+
export function isSelectionRectVisible(rect: SelectionRect, clips: readonly SelectionRect[]) {
32+
let { left, top, right, bottom } = rect;
33+
for (const clip of clips) {
34+
left = Math.max(left, clip.left);
35+
top = Math.max(top, clip.top);
36+
right = Math.min(right, clip.right);
37+
bottom = Math.min(bottom, clip.bottom);
38+
}
39+
return right > left && bottom > top;
40+
}
41+
2842
/**
2943
* Interactive popovers pass getActionElement to keep editing their fields from replacing the
3044
* captured source selection.
3145
*/
3246
export function observeSelectionActions({
3347
element,
3448
getActionElement,
49+
restoreAfterScroll = false,
3550
onSelection,
3651
onDismiss,
3752
}: {
3853
element: HTMLElement;
3954
getActionElement?: () => HTMLElement | null;
55+
restoreAfterScroll?: boolean;
4056
onSelection: (pointer: SelectionActionPoint | null) => void;
4157
onDismiss: (reason: "interaction" | "cancel") => void;
4258
}) {
@@ -45,6 +61,7 @@ export function observeSelectionActions({
4561
let pointerDown = false;
4662
let gestureActive = false;
4763
let dismissed = false;
64+
let restorable = false;
4865
let pointer: SelectionActionPoint | null = null;
4966
let timer: number | null = null;
5067
let frame: number | null = null;
@@ -62,6 +79,7 @@ export function observeSelectionActions({
6279
pointerDown = gestureActive = false;
6380
pointer = null;
6481
dismissed = true;
82+
restorable = false;
6583
};
6684
const dismiss = () => {
6785
cancel();
@@ -72,6 +90,7 @@ export function observeSelectionActions({
7290
onDismiss("interaction");
7391
};
7492
const schedule = (delay: number) => {
93+
restorable = true;
7594
cancelPending();
7695
timer = view.setTimeout(() => {
7796
timer = null;
@@ -92,6 +111,7 @@ export function observeSelectionActions({
92111
const inside = element.contains(event.target as Node);
93112
gestureActive = false;
94113
dismissed = true;
114+
restorable = false;
95115
pointer = null;
96116
if (inside) onDismiss("interaction");
97117
else if (getActionElement?.()) onDismiss("cancel");
@@ -135,7 +155,8 @@ export function observeSelectionActions({
135155
// Autoscroll during a drag must not cancel that gesture's eventual release.
136156
if (!pointerDown) {
137157
pointer = null;
138-
dismissed = true;
158+
if (restoreAfterScroll && !dismissed && restorable) schedule(SELECTION_SCROLL_SETTLE_MS);
159+
else dismissed = true;
139160
}
140161
onDismiss("cancel");
141162
};

0 commit comments

Comments
 (0)