Skip to content
TypeScript

fix(web): the Cite button comes back once the timeline stops scrolling (#15818)

Igor Makowskicd8c2c593275
diff --git a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx
index 156a773e021..ea27de728e1 100644
--- a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx
+++ b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx
@@ -12,6 +12,7 @@ import {
type AssistantCitationSourceAnchor,
} from "~/lib/assistantTextSelection";
import {
+ isSelectionRectVisible,
observeSelectionActions,
resolveSelectionActionPosition,
type SelectionActionPoint,
@@ -56,7 +57,53 @@ export function AssistantSelectionToolbar({
}
const rect = captured.range.getBoundingClientRect();
const viewportRect = viewport.getBoundingClientRect();
- if (rect.bottom < viewportRect.top || rect.top > viewportRect.bottom || rect.width === 0) {
+ if (!isSelectionRectVisible(rect, [viewportRect])) {
+ clear();
+ return;
+ }
+ // A selection can cross blocks with different clipping ancestors.
+ const common = captured.range.commonAncestorContainer;
+ const walker = document.createTreeWalker(common, NodeFilter.SHOW_TEXT);
+ let node = common.nodeType === Node.TEXT_NODE ? common : walker.nextNode();
+ let visible = false;
+ for (; node && !visible; node = walker.nextNode()) {
+ if (!captured.range.intersectsNode(node)) continue;
+ if (node.parentElement && getComputedStyle(node.parentElement).userSelect === "none")
+ continue;
+ const fragment = document.createRange();
+ fragment.selectNodeContents(node);
+ if (node === captured.range.startContainer) {
+ fragment.setStart(node, captured.range.startOffset);
+ }
+ if (node === captured.range.endContainer) {
+ fragment.setEnd(node, captured.range.endOffset);
+ }
+ if (!fragment.toString().trim()) continue;
+ const lines = Array.from(fragment.getClientRects());
+ if (!lines.some((line) => isSelectionRectVisible(line, [viewportRect]))) continue;
+ const clips: Pick<DOMRect, "left" | "right" | "top" | "bottom">[] = [viewportRect];
+ for (
+ let element = node.parentElement;
+ element && element !== viewport;
+ element = element.parentElement
+ ) {
+ const style = getComputedStyle(element);
+ const clipX = style.overflowX !== "visible";
+ const clipY = style.overflowY !== "visible";
+ if (!clipX && !clipY) continue;
+ const bounds = element.getBoundingClientRect();
+ const left = bounds.left + element.clientLeft;
+ const top = bounds.top + element.clientTop;
+ clips.push({
+ left: clipX ? left : -Infinity,
+ right: clipX ? left + element.clientWidth : Infinity,
+ top: clipY ? top : -Infinity,
+ bottom: clipY ? top + element.clientHeight : Infinity,
+ });
+ }
+ visible = lines.some((line) => isSelectionRectVisible(line, clips));
+ }
+ if (!visible) {
clear();
return;
}
@@ -89,6 +136,7 @@ export function AssistantSelectionToolbar({
const actions = observeSelectionActions({
element: viewport,
getActionElement: () => toolbarRef.current,
+ restoreAfterScroll: true,
onSelection: update,
onDismiss: clear,
});
diff --git a/apps/web/src/lib/selectionActions.test.ts b/apps/web/src/lib/selectionActions.test.ts
index d677b285877..86b52c8e04d 100644
--- a/apps/web/src/lib/selectionActions.test.ts
+++ b/apps/web/src/lib/selectionActions.test.ts
@@ -1,12 +1,16 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
-import { observeSelectionActions, resolveSelectionActionPosition } from "./selectionActions";
+import {
+ isSelectionRectVisible,
+ observeSelectionActions,
+ resolveSelectionActionPosition,
+} from "./selectionActions";
function event(type: string, values: Record<string, unknown> = {}) {
return Object.assign(new Event(type, { cancelable: true }), values);
}
-function createSelectionSurface({ interactiveActions = false } = {}) {
+function createSelectionSurface({ interactiveActions = false, restoreAfterScroll = false } = {}) {
const frames = new Map<number, FrameRequestCallback>();
let frameId = 0;
const view = Object.assign(new EventTarget(), {
@@ -42,6 +46,7 @@ function createSelectionSurface({ interactiveActions = false } = {}) {
...(interactiveActions
? { getActionElement: () => actionElement as unknown as HTMLElement }
: {}),
+ restoreAfterScroll,
onSelection,
onDismiss,
});
@@ -294,6 +299,69 @@ describe("selection action gestures", () => {
expect(surface.onSelection).toHaveBeenCalledOnce();
});
+ it("restores after scrolling settles with a fresh anchor, without interrupting a held drag", () => {
+ const surface = createSelectionSurface({ restoreAfterScroll: true });
+ surface.down();
+ surface.element.dispatchEvent(event("scroll"));
+ surface.change();
+ surface.flush(1000);
+ expect(surface.onSelection).not.toHaveBeenCalled();
+ surface.up({ x: 420, y: 310 });
+ surface.flush();
+ expect(surface.onSelection.mock.calls).toEqual([[{ x: 420, y: 310 }]]);
+
+ surface.onDismiss.mockClear();
+ surface.element.dispatchEvent(event("scroll"));
+ expect(surface.onDismiss).toHaveBeenCalledWith("cancel");
+ surface.flush(100);
+ surface.element.dispatchEvent(event("scroll"));
+ surface.change();
+ surface.flush(100);
+ expect(surface.onSelection).toHaveBeenCalledOnce();
+ surface.flush(50);
+ expect(surface.onSelection.mock.calls).toEqual([[{ x: 420, y: 310 }], [null]]);
+ surface.flush(1000);
+ expect(surface.onSelection).toHaveBeenCalledTimes(2);
+
+ surface.down();
+ surface.up();
+ vi.advanceTimersByTime(0);
+ surface.element.dispatchEvent(event("scroll"));
+ surface.flush(149);
+ expect(surface.onSelection).toHaveBeenCalledTimes(2);
+ surface.flush(1);
+ expect(surface.onSelection.mock.calls).toEqual([[{ x: 420, y: 310 }], [null], [null]]);
+ });
+
+ it("keeps Escape during scroll settling dismissed through later scrolling", () => {
+ const surface = createSelectionSurface({ restoreAfterScroll: true });
+ surface.down();
+ surface.up();
+ surface.flush();
+ surface.element.dispatchEvent(event("scroll"));
+ surface.key("Escape");
+ surface.change();
+ surface.flush(1000);
+ expect(surface.onSelection).toHaveBeenCalledOnce();
+
+ surface.key("PageDown");
+ surface.element.dispatchEvent(event("scroll"));
+ surface.change();
+ surface.flush(1000);
+ expect(surface.onSelection).toHaveBeenCalledOnce();
+
+ surface.document.dispatchEvent(event("keydown", { key: "ArrowRight", shiftKey: true }));
+ surface.change();
+ surface.element.dispatchEvent(event("scroll"));
+ surface.flush(150);
+ expect(surface.onSelection.mock.calls).toEqual([[{ x: 300, y: 200 }], [null]]);
+ surface.key("Escape");
+ surface.down();
+ surface.up();
+ surface.flush();
+ expect(surface.onSelection).toHaveBeenCalledTimes(3);
+ });
+
it("cancels a queued animation frame when a new press supersedes the release", () => {
const surface = createSelectionSurface();
surface.down();
@@ -387,6 +455,30 @@ describe("interactive selection actions", () => {
});
});
+describe("selection visibility", () => {
+ const rect = (left: number, top: number, right: number, bottom: number) => ({
+ left,
+ top,
+ right,
+ bottom,
+ width: right - left,
+ });
+ const timeline = rect(0, 0, 800, 600);
+ const codeBlock = rect(100, 200, 400, 260);
+
+ it("only shows text overlapping both the timeline and its nested scroller", () => {
+ expect(isSelectionRectVisible(rect(150, 210, 220, 226), [timeline, codeBlock])).toBe(true);
+ expect(isSelectionRectVisible(rect(420, 210, 480, 226), [timeline, codeBlock])).toBe(false);
+ expect(isSelectionRectVisible(rect(380, 210, 460, 226), [timeline, codeBlock])).toBe(true);
+ expect(
+ isSelectionRectVisible(rect(150, -40, 220, -24), [timeline, rect(100, -50, 400, 260)]),
+ ).toBe(false);
+ expect(
+ isSelectionRectVisible(rect(-200, 210, 220, 226), [timeline, rect(-200, 200, -20, 260)]),
+ ).toBe(false);
+ });
+});
+
describe("selection action positioning", () => {
const bounds = { left: 100, top: 50, width: 500, height: 220 };
const viewport = { width: 1024, height: 768 };
diff --git a/apps/web/src/lib/selectionActions.ts b/apps/web/src/lib/selectionActions.ts
index 9989c5cbf3c..93036020975 100644
--- a/apps/web/src/lib/selectionActions.ts
+++ b/apps/web/src/lib/selectionActions.ts
@@ -1,6 +1,7 @@
export type SelectionActionPoint = { x: number; y: number };
export const SELECTION_MULTI_CLICK_INTERVAL_MS = 500;
+const SELECTION_SCROLL_SETTLE_MS = 150;
export function resolveSelectionActionPosition(options: {
bounds: { left: number; top: number; width: number; height: number };
@@ -25,6 +26,19 @@ export function resolveSelectionActionPosition(options: {
};
}
+type SelectionRect = { left: number; top: number; right: number; bottom: number };
+
+export function isSelectionRectVisible(rect: SelectionRect, clips: readonly SelectionRect[]) {
+ let { left, top, right, bottom } = rect;
+ for (const clip of clips) {
+ left = Math.max(left, clip.left);
+ top = Math.max(top, clip.top);
+ right = Math.min(right, clip.right);
+ bottom = Math.min(bottom, clip.bottom);
+ }
+ return right > left && bottom > top;
+}
+
/**
* Interactive popovers pass getActionElement to keep editing their fields from replacing the
* captured source selection.
@@ -32,11 +46,13 @@ export function resolveSelectionActionPosition(options: {
export function observeSelectionActions({
element,
getActionElement,
+ restoreAfterScroll = false,
onSelection,
onDismiss,
}: {
element: HTMLElement;
getActionElement?: () => HTMLElement | null;
+ restoreAfterScroll?: boolean;
onSelection: (pointer: SelectionActionPoint | null) => void;
onDismiss: (reason: "interaction" | "cancel") => void;
}) {
@@ -45,6 +61,7 @@ export function observeSelectionActions({
let pointerDown = false;
let gestureActive = false;
let dismissed = false;
+ let restorable = false;
let pointer: SelectionActionPoint | null = null;
let timer: number | null = null;
let frame: number | null = null;
@@ -62,6 +79,7 @@ export function observeSelectionActions({
pointerDown = gestureActive = false;
pointer = null;
dismissed = true;
+ restorable = false;
};
const dismiss = () => {
cancel();
@@ -72,6 +90,7 @@ export function observeSelectionActions({
onDismiss("interaction");
};
const schedule = (delay: number) => {
+ restorable = true;
cancelPending();
timer = view.setTimeout(() => {
timer = null;
@@ -92,6 +111,7 @@ export function observeSelectionActions({
const inside = element.contains(event.target as Node);
gestureActive = false;
dismissed = true;
+ restorable = false;
pointer = null;
if (inside) onDismiss("interaction");
else if (getActionElement?.()) onDismiss("cancel");
@@ -135,7 +155,8 @@ export function observeSelectionActions({
// Autoscroll during a drag must not cancel that gesture's eventual release.
if (!pointerDown) {
pointer = null;
- dismissed = true;
+ if (restoreAfterScroll && !dismissed && restorable) schedule(SELECTION_SCROLL_SETTLE_MS);
+ else dismissed = true;
}
onDismiss("cancel");
};