Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Transcript: a selection survives scrolling away, and window steps mount 30 rows between frames (#6674)

Milind Sonie5b9ae8f9b95
diff --git a/src/hooks/use-transcript-viewport.test.ts b/src/hooks/use-transcript-viewport.test.ts
index a31ea2cc40..dcee889587 100644
--- a/src/hooks/use-transcript-viewport.test.ts
+++ b/src/hooks/use-transcript-viewport.test.ts
@@ -83,7 +83,7 @@ vi.mock("@/state/store", () => ({ useStore: () => store }));
vi.mock("@/lib/focus-message", () => ({ useFocusMessage: () => {} }));
import { useTranscriptViewport } from "./use-transcript-viewport";
-import { TRANSCRIPT_WINDOW_MAX } from "@/lib/transcript-window";
+import { TRANSCRIPT_WINDOW_MAX, TRANSCRIPT_WINDOW_STEP } from "@/lib/transcript-window";
import { forgetTranscriptPositions } from "@/lib/transcript-follow";
import { noteLiveReplyEvent, resetLiveReplies } from "@/state/live-reply";
import type { RuntimeEvent } from "../../shared/runtime-events";
@@ -276,7 +276,7 @@ describe("transcript viewport", () => {
expect(view.current.hiddenCount).toBe(180);
view.act(() => view.current.showEarlier());
- expect(view.current.hiddenCount).toBe(60);
+ expect(view.current.hiddenCount).toBe(180 - TRANSCRIPT_WINDOW_STEP);
view.rerender({ threadId: "other", messages: [{ id: "ask", role: "user" }, ...rows(299, 1_001)] });
expect(view.current.transcriptKey).toBe("bot:other");
@@ -374,7 +374,7 @@ describe("transcript viewport", () => {
it("slides back to the latest window when the reader returns to the bottom", () => {
const view = mount({ messages: rows(300) });
- view.act(() => view.current.showEarlier());
+ while (view.current.windowedMessages.length < TRANSCRIPT_WINDOW_MAX) view.act(() => view.current.showEarlier());
view.act(() => {
scroller.scrollTop = 1_000;
view.current.scrollHandlers.onScroll();
@@ -454,8 +454,8 @@ describe("transcript viewport", () => {
const view = mount({ messages: rows(300) });
scroller.scrollTop = 1_000;
view.act(() => view.current.showEarlier());
- expect(view.current.windowedMessages[0]?.id).toBe("m60");
- expect(scroller.scrollTop).toBe(1_000 + 120 * ROW);
+ expect(view.current.windowedMessages[0]?.id).toBe(`m${180 - TRANSCRIPT_WINDOW_STEP}`);
+ expect(scroller.scrollTop).toBe(1_000 + TRANSCRIPT_WINDOW_STEP * ROW);
expect(view.current.following).toBe(false);
});
@@ -473,7 +473,7 @@ describe("transcript viewport", () => {
store.state.loadingOlder = {};
view.rerender({ messages: [...rows(50, 50), ...rows(50, 100)] });
expect(view.current.olderPending).toBe(false);
- expect(scroller.scrollTop).toBe(300 + 50 * ROW);
+ expect(scroller.scrollTop).toBe(300 + TRANSCRIPT_WINDOW_STEP * ROW);
});
it("drops a height capture taken in the thread the reader left", () => {
@@ -507,7 +507,7 @@ describe("transcript viewport", () => {
expect(view.current.following).toBe(false);
view.act(() => view.current.showLater());
- expect(view.current.laterCount).toBe(60);
+ expect(view.current.laterCount).toBe(180 - TRANSCRIPT_WINDOW_STEP);
});
it("pages on past a search result as the reader scrolls down, and follows only from the newest row", () => {
@@ -519,9 +519,9 @@ describe("transcript viewport", () => {
});
expect(view.current.following).toBe(false);
expect(view.current.windowedMessages[0]?.id).toBe("m0");
- expect(view.current.laterCount).toBe(60);
+ expect(view.current.laterCount).toBe(180 - TRANSCRIPT_WINDOW_STEP);
view.rerender({ messages: rows(301) });
- expect(view.current.laterCount).toBe(61);
+ expect(view.current.laterCount).toBe(181 - TRANSCRIPT_WINDOW_STEP);
expect(view.current.showJumpToLatest || view.current.following).toBe(false);
});
@@ -566,10 +566,10 @@ describe("transcript viewport", () => {
const view = mount({ messages: rows(300) });
expect(view.current.hiddenCount).toBe(180);
view.act(() => view.current.scrollHandlers.onWheel({ deltaY: -40 } as never));
- expect(view.current.hiddenCount).toBe(60);
+ expect(view.current.hiddenCount).toBe(180 - TRANSCRIPT_WINDOW_STEP);
view.act(() => view.current.scrollHandlers.onTouchStart({ touches: [{ clientY: 100 }] } as never));
view.act(() => view.current.scrollHandlers.onTouchMove({ touches: [{ clientY: 200 }] } as never));
- expect(view.current.hiddenCount).toBe(0);
+ expect(view.current.hiddenCount).toBe(180 - 2 * TRANSCRIPT_WINDOW_STEP);
});
it("loads an older page on an upward scroll when the whole thread so far is too short to scroll (#4365)", () => {
@@ -639,7 +639,7 @@ describe("transcript viewport", () => {
view.current.scrollHandlers.onScroll();
});
- expect(view.current.hiddenCount).toBe(60);
+ expect(view.current.hiddenCount).toBe(180 - TRANSCRIPT_WINDOW_STEP);
});
it("automatically loads older messages from server when at top of window and hasMore is true", () => {
@@ -674,7 +674,7 @@ describe("a long conversation read from its end to its start and back", () => {
const view = mount({ messages: rows(3_000) });
view.act(() => view.current.scrollHandlers.onWheel({ deltaY: -40 } as never));
let steps = 0;
- while (view.current.hiddenCount > 0 && steps++ < 100) {
+ while (view.current.hiddenCount > 0 && steps++ < 200) {
scrollTo(view, 400);
const reading = readAt(view, 200);
expect(view.current.windowedMessages.length).toBeLessThanOrEqual(TRANSCRIPT_WINDOW_MAX);
@@ -686,7 +686,7 @@ describe("a long conversation read from its end to its start and back", () => {
expect(view.current.following).toBe(false);
steps = 0;
- while (view.current.laterCount > 0 && steps++ < 100) {
+ while (view.current.laterCount > 0 && steps++ < 200) {
scrollTo(view, scroller.bottom - 800);
const reading = readAt(view, scroller.bottom - 100);
expect(view.current.windowedMessages.length).toBeLessThanOrEqual(TRANSCRIPT_WINDOW_MAX);
@@ -705,11 +705,11 @@ describe("a long conversation read from its end to its start and back", () => {
view.act(() => view.current.scrollHandlers.onWheel({ deltaY: -40 } as never));
for (let page = 13; page >= 0; page--) {
while (view.current.hiddenCount > 0) {
- scrollTo(view, 400);
+ scrollTo(view, 900);
scrollTo(view, 100);
}
dispatched = [];
- scrollTo(view, 400);
+ scrollTo(view, 900);
scrollTo(view, 100);
expect(dispatched).toEqual([{ type: "loadOlderMessages", threadId: "thread" }]);
const reading = topId(view);
diff --git a/src/hooks/use-transcript-viewport.ts b/src/hooks/use-transcript-viewport.ts
index 1ccd74b34c..3bc3ffb8bc 100644
--- a/src/hooks/use-transcript-viewport.ts
+++ b/src/hooks/use-transcript-viewport.ts
@@ -21,6 +21,7 @@ import {
firstFrameRow,
focusWindowRange,
followWindowStart,
+ holdRows,
resolveTranscriptWindow,
restoreWindow,
tailWindowStart,
@@ -31,11 +32,13 @@ import {
type TranscriptWindowBounds,
} from "@/lib/transcript-window";
import { reducedMotion } from "@/lib/onboarding";
+import { restoreSelection, selectedRows, setSelectionAside, type SetAsideSelection } from "@/lib/transcript-selection";
import {
JUMP_TO_LATEST_DELAY_MS,
initialTranscriptFollow,
readTranscriptPosition,
rememberTranscriptPosition,
+ rowContentTop,
rowScrollTop,
rowsInView,
settleScroll,
@@ -49,6 +52,9 @@ import { hasLiveReply } from "@/state/live-reply";
import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
export const AUTO_EXPAND_TOP_THRESHOLD = 250;
+/** How far from a window edge, in views, the next step is drawn: ahead of the reader, so it lands before they get there. */
+const STEP_AHEAD_VIEWS = 1.5;
+const stepAhead = (el: HTMLElement) => Math.max(AUTO_EXPAND_TOP_THRESHOLD, el.clientHeight * STEP_AHEAD_VIEWS);
const WIDGETS_WITH_OWN_ARROW_KEYS = '[role="menu"], [role="menubar"], [role="listbox"], [role="tree"], [role="grid"], [role="tablist"], [role="radiogroup"], [role="slider"], select, [contenteditable="true"]';
@@ -117,12 +123,34 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
const transcriptKey = `${ownerId}:${threadId}`;
const tailStart = tailWindowStart(messages.length);
- /** The rows on screen before a window step; the commit after it puts the first one still drawn back in place. */
- const anchor = useRef<{ key: string; rows: ReturnType<typeof rowsInView>; height: number } | null>(null);
+ /**
+ * The rows on screen before a window step, each with its top in the content; the commit after it moves the view by as
+ * much as the first one still drawn moved, so a step drawn a few frames later keeps where the reader has scrolled since.
+ */
+ const anchor = useRef<{ key: string; rows: { rowId: string; contentTop: number }[]; height: number; from: TranscriptWindowBounds | null } | null>(null);
const restingCardId = useRef<string | undefined>(undefined);
- const holdRow = () => {
+ /** `from`: the window a step drawn in a transition leaves; commits that still draw it are not the step's. */
+ const holdRow = (from: TranscriptWindowBounds | null = null) => {
const el = scrollRef.current, list = transcriptRef.current;
- anchor.current = el ? { key: transcriptKey, rows: list ? rowsInView(el, list, restingCardId.current) : [], height: el.scrollHeight } : null;
+ const rows = el && list ? rowsInView(el, list, restingCardId.current).map((row) => ({ rowId: row.rowId, contentTop: el.scrollTop - row.offsetWithinRow })) : [];
+ anchor.current = el ? { key: transcriptKey, rows, height: el.scrollHeight, from } : null;
+ };
+ const dragging = useRef(false);
+ const setAside = useRef<{ key: string; selection: SetAsideSelection } | null>(null);
+ /**
+ * `next`, widened over the rows a text selection spans so a step never lets them go. Past the hold's cap a drag keeps
+ * `refused` (the drawn window), and anything else sets the selection aside until its rows are drawn again.
+ */
+ const keepSelection = (next: TranscriptWindowBounds, refused?: TranscriptWindowBounds): TranscriptWindowBounds => {
+ const list = transcriptRef.current;
+ if (!list || typeof document === "undefined") return next;
+ const held = selectedRows(list, (rowId) => rowId.startsWith("live:") ? messages.length - 1 : messages.findIndex((message) => message.id === rowId));
+ const kept = held && holdRows(next, messages.length, held);
+ if (!held || kept) return kept ?? next;
+ if (dragging.current && refused) return refused;
+ const aside = setSelectionAside(list);
+ if (aside) setAside.current = { key: transcriptKey, selection: aside };
+ return next;
};
const readingBottom = () => {
const el = scrollRef.current;
@@ -147,9 +175,11 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
const follow = followNow.current.follow;
const following = follow.mode === "following";
const first = messages[0]?.id;
- const next = switched
+ const proposed = switched
? { start: current.restore?.start ?? tailStart, end: current.restore?.end ?? null, added: -1 }
: nextWindow(transcriptWindow, messages, following, readingBottom);
+ const moves = proposed.start !== transcriptWindow.start || proposed.end !== transcriptWindow.end;
+ const next = !switched && moves ? { ...proposed, ...keepSelection(proposed) } : proposed;
if (switched || next.start !== transcriptWindow.start || next.end !== transcriptWindow.end || first !== transcriptWindow.first) {
// Rows came in front of the drawn ones or left their top: the DOM is still the last commit's, so it is read now.
if (!switched && !following && (next.added > 0 || next.start > transcriptWindow.start)) holdRow();
@@ -205,7 +235,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
const atLiveEnd = (el: HTMLElement | null) => laterRef.current === 0 && atEndOf(el);
const nearWindowBottom = () => {
const el = scrollRef.current;
- return laterCount > 0 && Boolean(el) && gapBelow(el!) <= AUTO_EXPAND_TOP_THRESHOLD;
+ return laterCount > 0 && Boolean(el) && gapBelow(el!) <= stepAhead(el!);
};
const [, setFollowShown] = useState(follow);
@@ -291,7 +321,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
followEvent({ type: "navigated" });
followEvent({ type: "leftEnd" });
if (drawFromRef.current) setFirstFrame(null);
- setTranscriptWindow({ key: transcriptKey, first: messages[0]?.id, start: range.start, end: range.end });
+ setTranscriptWindow({ key: transcriptKey, first: messages[0]?.id, ...keepSelection(range) });
}, [threadId, messages, followEvent, focusMessage, transcriptKey]);
useFocusMessage(threadId, messages.length > 0, scrollRef);
@@ -316,21 +346,52 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
useLayoutEffect(() => {
const el = scrollRef.current, list = transcriptRef.current, held = anchor.current;
if (!held || !el) return;
+ if (held.key === transcriptKey && held.from?.start === transcriptWindow.start && held.from.end === transcriptWindow.end) return;
anchor.current = null;
expandingRef.current = false;
if (held.key !== transcriptKey) return;
- let top: number | undefined;
+ let moved: number | undefined;
for (const row of list ? held.rows : []) {
- top = rowScrollTop(el, list!, row.rowId, row.offsetWithinRow);
- if (top !== undefined) break;
+ const top = rowContentTop(el, list!, row.rowId);
+ if (top !== undefined) {
+ moved = top - row.contentTop;
+ break;
+ }
}
- el.scrollTop = top ?? el.scrollTop + el.scrollHeight - held.height;
+ el.scrollTop += moved ?? el.scrollHeight - held.height;
lastTop.current = el.scrollTop;
});
+ // A selection set aside comes back once both of its rows are drawn again; a click elsewhere lets it go.
+ useLayoutEffect(() => {
+ const aside = setAside.current, list = transcriptRef.current;
+ if (!aside || !list) return;
+ if (aside.key !== transcriptKey || restoreSelection(list, aside.selection) !== "waiting") setAside.current = null;
+ });
+ useEffect(() => {
+ const pressed = () => {
+ setAside.current = null;
+ };
+ const released = () => {
+ dragging.current = false;
+ };
+ window.addEventListener("pointerdown", pressed, true);
+ window.addEventListener("pointerup", released, true);
+ window.addEventListener("pointercancel", released, true);
+ return () => {
+ window.removeEventListener("pointerdown", pressed, true);
+ window.removeEventListener("pointerup", released, true);
+ window.removeEventListener("pointercancel", released, true);
+ };
+ }, []);
+
+ /** Draws the window `step` gives, in a transition so its rows mount between frames; false when there is nothing to draw. */
const stepWindow = (step: (window: TranscriptWindowBounds, total: number) => TranscriptWindowBounds) => {
- holdRow();
- setTranscriptWindow((w) => ({ ...w, ...step(drawnBounds, messages.length) }));
+ const target = keepSelection(step(drawnBounds, messages.length), drawnBounds);
+ if (target.start === drawnBounds.start && target.end === drawnBounds.end) return false;
+ holdRow(windowRef.current);
+ startTransition(() => setTranscriptWindow((w) => w.key === transcriptKey ? { ...w, ...target } : w));
+ return true;
};
const showEarlier = () => {
setBottomFollow(false);
@@ -362,9 +423,8 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
const triggerAutoEarlier = useCallback(() => {
if (expandingRef.current || drawFromRef.current) return;
if (hiddenCount > 0) {
- expandingRef.current = true;
setBottomFollow(false);
- stepWindow(windowEarlier);
+ expandingRef.current = stepWindow(windowEarlier);
} else if (hasMore && !olderPending) {
expandingRef.current = true;
holdRowForPrepend();
@@ -373,8 +433,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
}, [hiddenCount, startIndex, laterCount, endIndex, messages.length, hasMore, olderPending, threadId, dispatch, transcriptKey]);
const triggerAutoLater = () => {
if (expandingRef.current || drawFromRef.current || laterCount === 0) return;
- expandingRef.current = true;
- stepWindow(windowLater);
+ expandingRef.current = stepWindow(windowLater);
};
useEffect(() => {
@@ -388,7 +447,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
triggerAutoEarlier();
}
},
- { root, rootMargin: "250px 0px 0px 0px" },
+ { root, rootMargin: `${STEP_AHEAD_VIEWS * 100}% 0px 0px 0px` },
);
observer.observe(sentinel);
return () => observer.disconnect();
@@ -416,7 +475,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
const canScrollUp = () => canScroll() || hiddenCount > 0 || Boolean(hasMore);
const jumpToLatest = () => {
setBottomFollow(true);
- setTranscriptWindow({ key: transcriptKey, first: messages[0]?.id, start: tailStart, end: null });
+ setTranscriptWindow({ key: transcriptKey, first: messages[0]?.id, ...keepSelection({ start: tailStart, end: null }) });
requestAnimationFrame(() => {
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: reducedMotion() ? "auto" : "smooth" });
});
@@ -427,13 +486,14 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
// Grabbing the scrollbar is a scroll gesture: its lane lies past clientWidth.
const el = scrollRef.current;
if (el && e.target === el && e.nativeEvent.offsetX >= el.clientWidth) setBottomFollow(false);
+ else if (e.button === 0) dragging.current = true;
},
onWheel: (e: WheelEvent<HTMLDivElement>) => {
movingDown.current = e.deltaY > 0;
if (e.deltaY < 0 && canScrollUp()) {
setBottomFollow(false);
const el = scrollRef.current;
- if (el && el.scrollTop <= AUTO_EXPAND_TOP_THRESHOLD) {
+ if (el && el.scrollTop <= stepAhead(el)) {
triggerAutoEarlier();
}
} else if (nearEnd()) {
@@ -451,7 +511,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
if (y > touchY.current + 4 && canScrollUp()) {
setBottomFollow(false);
const el = scrollRef.current;
- if (el && el.scrollTop <= AUTO_EXPAND_TOP_THRESHOLD) {
+ if (el && el.scrollTop <= stepAhead(el)) {
triggerAutoEarlier();
}
} else if (nearEnd()) {
@@ -470,7 +530,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
recordPosition();
if (followRef.current) return;
// Each edge steps only on a move toward it, so the scrollTop set after a step never steps the other way.
- if (moved < 0 && el.scrollTop <= AUTO_EXPAND_TOP_THRESHOLD) triggerAutoEarlier();
+ if (moved < 0 && el.scrollTop <= stepAhead(el)) triggerAutoEarlier();
else if (moved > 0 && nearWindowBottom()) triggerAutoLater();
},
};
diff --git a/src/lib/transcript-follow.ts b/src/lib/transcript-follow.ts
index c89f7a23f8..f11bcf0878 100644
--- a/src/lib/transcript-follow.ts
+++ b/src/lib/transcript-follow.ts
@@ -101,7 +101,10 @@ export function rowsInView(scroller: HTMLElement, transcript: HTMLElement, skip?
if (typeof transcript.querySelectorAll !== "function") return [];
const view = scroller.getBoundingClientRect();
const ranked: { rowId: string; offsetWithinRow: number; rank: number }[] = [];
- Array.from(transcript.querySelectorAll<HTMLElement>(ROW_SELECTOR)).some((row, index) => {
+ const rows = Array.from(transcript.querySelectorAll<HTMLElement>(ROW_SELECTOR));
+ const from = Math.max(0, firstRowEndingBelow(rows, view.top) - 1);
+ rows.slice(from).some((row, at) => {
+ const index = from + at;
const rowId = row.dataset.mid;
if (!rowId || rowId.startsWith("live:") || rowId === skip) return false;
const box = rowBox(row);
@@ -112,6 +115,27 @@ export function rowsInView(scroller: HTMLElement, transcript: HTMLElement, skip?
return ranked.sort((a, b) => a.rank - b.rank).map(({ rowId, offsetWithinRow }) => ({ rowId, offsetWithinRow }));
}
+/** The first of `rows` (in page order) whose box ends below `y`, found in a few box reads; rows that draw nothing are passed. */
+function firstRowEndingBelow(rows: readonly Element[], y: number): number {
+ let low = 0, high = rows.length;
+ while (low < high) {
+ const middle = (low + high) >> 1;
+ let probe = middle, box = rowBox(rows[probe]!);
+ while (box.bottom === box.top && probe + 1 < high) box = rowBox(rows[++probe]!);
+ if (box.bottom === box.top) high = middle;
+ else if (box.bottom > y) high = middle;
+ else low = probe + 1;
+ }
+ return low;
+}
+
+/** Where `rowId`'s top lies in the scrolled content, or undefined when the row is not drawn. */
+export function rowContentTop(scroller: HTMLElement, transcript: HTMLElement, rowId: string): number | undefined {
+ if (typeof transcript.querySelectorAll !== "function") return undefined;
+ const row = Array.from(transcript.querySelectorAll<HTMLElement>(ROW_SELECTOR)).find((candidate) => candidate.dataset.mid === rowId);
+ return row ? scroller.scrollTop + rowBox(row).top - scroller.getBoundingClientRect().top : undefined;
+}
+
/** The scrollTop that puts `rowId` back where `topRow` found it, or undefined when the row is not drawn. */
export function rowScrollTop(scroller: HTMLElement, transcript: HTMLElement, rowId: string, offsetWithinRow: number): number | undefined {
if (typeof transcript.querySelectorAll !== "function") return undefined;
diff --git a/src/lib/transcript-selection.test.ts b/src/lib/transcript-selection.test.ts
new file mode 100644
index 0000000000..202486355f
--- /dev/null
+++ b/src/lib/transcript-selection.test.ts
@@ -0,0 +1,133 @@
+// @vitest-environment happy-dom
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { restoreSelection, selectedRows, setSelectionAside, type SetAsideSelection } from "./transcript-selection";
+import { SELECTION_HOLD_MAX, TRANSCRIPT_WINDOW_MAX, holdRows, tailWindowStart, windowEarlier, windowLater, type TranscriptWindowBounds } from "./transcript-window";
+
+const TOTAL = 3_000;
+const ids = Array.from({ length: TOTAL }, (_, index) => `m${index}`);
+const indexOf = (rowId: string) => ids.indexOf(rowId);
+let list: HTMLElement;
+
+/** Draws the window's rows as React's keyed list does: rows still drawn keep their nodes, the others come and go. */
+function draw({ start, end }: TranscriptWindowBounds) {
+ const wanted = ids.slice(start, end ?? TOTAL);
+ const kept = new Map(Array.from(list.querySelectorAll<HTMLElement>("[data-mid]")).map((row) => [row.dataset.mid!, row]));
+ for (const [rowId, row] of kept) if (!wanted.includes(rowId)) row.remove();
+ const after = list.querySelector("button");
+ for (const rowId of wanted) {
+ let row = kept.get(rowId);
+ if (!row) {
+ row = document.createElement("div");
+ row.dataset.mid = rowId;
+ row.innerHTML = `<p>Reply <b>${rowId}</b> says</p><p>more of ${rowId}</p>`;
+ }
+ list.insertBefore(row, after);
+ }
+}
+
+const row = (rowId: string) => list.querySelector<HTMLElement>(`[data-mid="${rowId}"]`)!;
+const selected = () => String(document.getSelection());
+
+/** One window step as the viewport takes it: widened over the selected rows, or the selection set aside past the cap. */
+function step(window: TranscriptWindowBounds, move: typeof windowEarlier, aside: { held: SetAsideSelection | null }) {
+ const next = move(window, TOTAL);
+ const held = selectedRows(list, indexOf);
+ const kept = held && holdRows(next, TOTAL, held);
+ if (held && !kept) aside.held = setSelectionAside(list);
+ const drawn = kept ?? next;
+ draw(drawn);
+ if (aside.held && restoreSelection(list, aside.held) !== "waiting") aside.held = null;
+ return drawn;
+}
+
+beforeEach(() => {
+ document.body.innerHTML = `<header>Chat with a bot</header><div role="log"><button>Show later</button></div>`;
+ list = document.querySelector<HTMLElement>('[role="log"]')!;
+});
+
+describe("a text selection in a windowed transcript", () => {
+ it("keeps its rows drawn while the reader scrolls a few steps away, and copies the same text on return", () => {
+ let window: TranscriptWindowBounds = { start: tailWindowStart(TOTAL), end: null };
+ draw(window);
+ document.getSelection()!.setBaseAndExtent(row("m2950").querySelector("b")!.firstChild!, 1, row("m2952").querySelector("p")!.firstChild!, 3);
+ const text = selected();
+ const anchor = document.getSelection()!.anchorNode;
+ expect(text).toContain("more of m2950");
+ const aside = { held: null as SetAsideSelection | null };
+ for (let steps = 0; steps < 10; steps++) {
+ window = step(window, windowEarlier, aside);
+ expect(list.contains(anchor), "a row holding an end of the selection is never let go").toBe(true);
+ expect(window.end ?? TOTAL).toBeGreaterThan(2_952);
+ expect((window.end ?? TOTAL) - window.start).toBeLessThanOrEqual(SELECTION_HOLD_MAX);
+ expect(selected()).toBe(text);
+ }
+ for (let steps = 0; steps < 10; steps++) window = step(window, windowLater, aside);
+ expect(selected()).toBe(text);
+ });
+
+ it("is set aside past the hold's cap and put back with the same text when its rows return", () => {
+ let window: TranscriptWindowBounds = { start: tailWindowStart(TOTAL), end: null };
+ draw(window);
+ document.getSelection()!.setBaseAndExtent(row("m2990").querySelector("p")!.lastChild!, 2, row("m2950").querySelector("b")!.firstChild!, 2);
+ const text = selected();
+ const aside = { held: null as SetAsideSelection | null };
+ let widest = 0;
+ for (let steps = 0; steps < 60; steps++) {
+ window = step(window, windowEarlier, aside);
+ widest = Math.max(widest, (window.end ?? TOTAL) - window.start);
+ }
+ expect(widest).toBeLessThanOrEqual(SELECTION_HOLD_MAX);
+ expect(aside.held, "set aside once the reader is past the cap").not.toBeNull();
+ expect(document.getSelection()!.isCollapsed).toBe(true);
+ expect((window.end ?? TOTAL) - window.start).toBeLessThanOrEqual(TRANSCRIPT_WINDOW_MAX);
+ for (let steps = 0; steps < 60 && window.end !== null; steps++) window = step(window, windowLater, aside);
+ expect(aside.held).toBeNull();
+ expect(selected()).toBe(text);
+ const selection = document.getSelection()!;
+ expect(selection.anchorNode?.parentElement?.closest("[data-mid]")?.getAttribute("data-mid"), "the direction is kept").toBe("m2990");
+ });
+
+ it("never takes in rows drawn next to an end that lies outside the rows", () => {
+ draw({ start: 100, end: 110 });
+ document.getSelection()!.setBaseAndExtent(list, 0, row("m102").querySelector("p")!.firstChild!, 4);
+ const text = selected();
+ expect(selectedRows(list, indexOf)).toEqual({ first: 100, last: 102 });
+ draw({ start: 70, end: 110 });
+ expect(selected()).toBe(text);
+ });
+
+ it("moves an end outside the transcript onto the nearest selected row", () => {
+ draw({ start: 100, end: 110 });
+ document.getSelection()!.setBaseAndExtent(document.querySelector("header")!.firstChild!, 0, row("m101").querySelector("b")!.firstChild!, 2);
+ expect(selectedRows(list, indexOf)).toEqual({ first: 100, last: 101 });
+ const selection = document.getSelection()!;
+ expect(selection.anchorNode).toBe(row("m100"));
+ expect(selected().startsWith("Reply m100")).toBe(true);
+ });
+
+ it("puts a selection back when only the blank lines between its rows changed", () => {
+ draw({ start: 100, end: 110 });
+ document.getSelection()!.setBaseAndExtent(row("m101").querySelector("b")!.firstChild!, 0, row("m103").querySelector("b")!.firstChild!, 4);
+ const text = selected();
+ const aside = setSelectionAside(list)!;
+ draw({ start: 0, end: 10 });
+ draw({ start: 100, end: 110 });
+ row("m102").append("\n\n");
+ expect(restoreSelection(list, aside)).toBe("restored");
+ expect(selected().replace(/\s+/g, "")).toBe(text.replace(/\s+/g, ""));
+ });
+
+ it("drops a set-aside selection whose rows no longer hold its text", () => {
+ draw({ start: 100, end: 110 });
+ document.getSelection()!.setBaseAndExtent(row("m101").querySelector("b")!.firstChild!, 0, row("m103").querySelector("b")!.firstChild!, 4);
+ const aside = setSelectionAside(list)!;
+ expect(document.getSelection()!.isCollapsed).toBe(true);
+ draw({ start: 0, end: 10 });
+ expect(restoreSelection(list, aside)).toBe("waiting");
+ draw({ start: 100, end: 110 });
+ row("m102").querySelector("b")!.textContent = "changed";
+ expect(restoreSelection(list, aside)).toBe("dropped");
+ expect(document.getSelection()!.isCollapsed).toBe(true);
+ });
+});
diff --git a/src/lib/transcript-selection.ts b/src/lib/transcript-selection.ts
new file mode 100644
index 0000000000..db49b6fff1
--- /dev/null
+++ b/src/lib/transcript-selection.ts
@@ -0,0 +1,127 @@
+const ROW = "[data-mid]";
+
+/** The first and last transcript rows a text selection spans, as indexes into the conversation. */
+export interface SelectedRows {
+ first: number;
+ last: number;
+}
+
+interface TextPoint {
+ rowId: string;
+ offset: number;
+}
+
+/** A selection taken off rows about to be let go: each end as its row and a text offset into it, and the text it held. */
+export interface SetAsideSelection {
+ anchor: TextPoint;
+ focus: TextPoint;
+ text: string;
+}
+
+function rowOf(node: Node | null, list: Element): HTMLElement | null {
+ const element = node && (node.nodeType === 1 ? (node as Element) : node.parentElement);
+ const row = element?.closest<HTMLElement>(ROW);
+ return row && list.contains(row) ? row : null;
+}
+
+/** The selection, when it is not collapsed and one of its ends lies in `list`. */
+function selectionIn(list: Element): { selection: Selection; range: Range } | null {
+ const selection = list.ownerDocument.getSelection();
+ if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return null;
+ const range = selection.getRangeAt(0);
+ if (!list.contains(range.startContainer) && !list.contains(range.endContainer)) return null;
+ return { selection, range };
+}
+
+const isBackward = (selection: Selection, range: Range) =>
+ selection.anchorNode === range.endContainer && selection.anchorOffset === range.endOffset;
+
+/**
+ * The rows a selection with an end in `list` spans. An end outside any row (between rows, below them, or outside the
+ * transcript) is first moved onto the edge of the nearest selected row: rows drawn next to such an end would otherwise
+ * join the selection.
+ */
+export function selectedRows(list: Element, indexOf: (rowId: string) => number): SelectedRows | null {
+ const held = selectionIn(list);
+ if (!held) return null;
+ const { selection, range } = held;
+ let start = rowOf(range.startContainer, list), end = rowOf(range.endContainer, list);
+ if (!start || !end) {
+ const spanned = Array.from(list.querySelectorAll<HTMLElement>(ROW)).filter((row) => range.intersectsNode(row));
+ if (!spanned.length) return null;
+ const from = start ? { node: range.startContainer, offset: range.startOffset } : { node: spanned[0]!, offset: 0 };
+ const last = spanned.at(-1)!;
+ const to = end ? { node: range.endContainer, offset: range.endOffset } : { node: last, offset: last.childNodes.length };
+ const [anchor, focus] = isBackward(selection, range) ? [to, from] : [from, to];
+ selection.setBaseAndExtent(anchor.node, anchor.offset, focus.node, focus.offset);
+ start ??= spanned[0]!;
+ end ??= last;
+ }
+ const first = rowIndex(start, list, indexOf), last = rowIndex(end, list, indexOf);
+ if (first < 0 || last < 0) return null;
+ return { first: Math.min(first, last), last: Math.max(first, last) };
+}
+
+/** A row inside a row (a step in a run) counts as its own row when the conversation has it, else as the row around it. */
+function rowIndex(row: HTMLElement | null, list: Element, indexOf: (rowId: string) => number): number {
+ for (; row; row = rowOf(row.parentElement, list)) {
+ const index = indexOf(row.dataset.mid!);
+ if (index >= 0) return index;
+ }
+ return -1;
+}
+
+function textOffset(row: HTMLElement, node: Node, offset: number): number {
+ const range = row.ownerDocument.createRange();
+ range.setStart(row, 0);
+ range.setEnd(node, offset);
+ return range.toString().length;
+}
+
+/** Takes a selection with an end in `list` off the page, so letting its rows go can neither collapse it onto the list nor
+ * grow it over rows drawn later. */
+export function setSelectionAside(list: Element): SetAsideSelection | null {
+ const held = selectionIn(list);
+ if (!held) return null;
+ const { selection } = held;
+ const anchorRow = rowOf(selection.anchorNode, list), focusRow = rowOf(selection.focusNode, list);
+ const aside = anchorRow && focusRow ? {
+ anchor: { rowId: anchorRow.dataset.mid!, offset: textOffset(anchorRow, selection.anchorNode!, selection.anchorOffset) },
+ focus: { rowId: focusRow.dataset.mid!, offset: textOffset(focusRow, selection.focusNode!, selection.focusOffset) },
+ text: selection.toString(),
+ } : null;
+ selection.removeAllRanges();
+ return aside;
+}
+
+function pointAt(row: HTMLElement, offset: number): { node: Node; offset: number } {
+ const walker = row.ownerDocument.createTreeWalker(row, 4);
+ let passed = 0;
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ const length = (node as Text).data.length;
+ if (passed + length >= offset) return { node, offset: offset - passed };
+ passed += length;
+ }
+ return { node: row, offset: row.childNodes.length };
+}
+
+/** A selection's text without the line breaks its rows' hover-only parts add or take away. */
+const words = (text: string) => text.replace(/\s+/g, "");
+
+/**
+ * Puts a set-aside selection back once both of its rows are drawn again. "waiting" while one is not; "dropped" when the
+ * rows no longer hold the same text, so a selection is never put back over other words.
+ */
+export function restoreSelection(list: Element, aside: SetAsideSelection): "waiting" | "restored" | "dropped" {
+ const rows = Array.from(list.querySelectorAll<HTMLElement>(ROW));
+ const anchorRow = rows.find((row) => row.dataset.mid === aside.anchor.rowId);
+ const focusRow = rows.find((row) => row.dataset.mid === aside.focus.rowId);
+ if (!anchorRow || !focusRow) return "waiting";
+ const selection = list.ownerDocument.getSelection();
+ if (!selection) return "dropped";
+ const anchor = pointAt(anchorRow, aside.anchor.offset), focus = pointAt(focusRow, aside.focus.offset);
+ selection.setBaseAndExtent(anchor.node, anchor.offset, focus.node, focus.offset);
+ if (words(selection.toString()) === words(aside.text)) return "restored";
+ selection.removeAllRanges();
+ return "dropped";
+}
diff --git a/src/lib/transcript-window.test.ts b/src/lib/transcript-window.test.ts
index f0172f2581..94a01313fb 100644
--- a/src/lib/transcript-window.test.ts
+++ b/src/lib/transcript-window.test.ts
@@ -1,12 +1,15 @@
import { describe, expect, it } from "vitest";
import {
+ SELECTION_HOLD_MAX,
TRANSCRIPT_WINDOW_MAX,
TRANSCRIPT_WINDOW_SIZE,
+ TRANSCRIPT_WINDOW_STEP,
capWindowEnd,
expandWindowStart,
focusWindowRange,
followWindowStart,
+ holdRows,
resolveTranscriptWindow,
restoreWindow,
tailWindowStart,
@@ -200,9 +203,10 @@ describe("a two-sided window", () => {
it("draws at most the cap however many steps up the reader takes, then as many back down", () => {
const total = 3_000;
+ const steps = Math.ceil(total / TRANSCRIPT_WINDOW_STEP);
let window: TranscriptWindowBounds = { start: tailWindowStart(total), end: null };
const seen = new Set<number>();
- for (let step = 0; step < 30; step++) {
+ for (let step = 0; step < steps; step++) {
window = windowEarlier(window, total);
const shown = drawn(total, window);
expect(shown.visible.length).toBeLessThanOrEqual(TRANSCRIPT_WINDOW_MAX);
@@ -212,18 +216,21 @@ describe("a two-sided window", () => {
expect(window).toEqual({ start: 0, end: TRANSCRIPT_WINDOW_MAX });
expect(seen.size, "every row was drawn on the way up").toBe(total);
- for (let step = 0; step < 30; step++) {
+ for (let step = 0; step < steps; step++) {
+ const before = window;
window = windowLater(window, total);
expect(drawn(total, window).visible.length).toBeLessThanOrEqual(TRANSCRIPT_WINDOW_MAX);
+ expect((window.end ?? total) - (before.end ?? total), "a step mounts at most one step of rows").toBeLessThanOrEqual(TRANSCRIPT_WINDOW_STEP);
}
expect(window).toEqual({ start: total - TRANSCRIPT_WINDOW_MAX, end: null });
});
it("keeps the rows it had on each step, so the row under the reader stays drawn", () => {
const total = 1_000;
+ expect(TRANSCRIPT_WINDOW_STEP).toBe(30);
const up = windowEarlier({ start: 500, end: 740 }, total);
- expect(up).toEqual({ start: 380, end: 620 });
- const down = windowLater({ start: 380, end: 620 }, total);
+ expect(up).toEqual({ start: 470, end: 710 });
+ const down = windowLater({ start: 470, end: 710 }, total);
expect(down).toEqual({ start: 500, end: 740 });
});
@@ -234,11 +241,20 @@ describe("a two-sided window", () => {
});
it("moves over an older page put in front: one step of it at the top, the same rows anywhere else", () => {
- expect(windowAfterPrepend({ start: 0, end: null }, 200, 400)).toEqual({ start: 80, end: 320 });
- expect(windowAfterPrepend({ start: 0, end: null }, 50, 100)).toEqual({ start: 0, end: null });
+ expect(windowAfterPrepend({ start: 0, end: null }, 200, 400)).toEqual({ start: 170, end: null });
+ expect(windowAfterPrepend({ start: 0, end: null }, 50, 100)).toEqual({ start: 50 - TRANSCRIPT_WINDOW_STEP, end: null });
expect(windowAfterPrepend({ start: 40, end: 200 }, 200, 600)).toEqual({ start: 240, end: 400 });
});
+ it("widens a window over the rows a selection spans, up to the hold's cap", () => {
+ expect(holdRows({ start: 500, end: 740 }, 3_000, { first: 400, last: 410 })).toEqual({ start: 400, end: 740 });
+ expect(holdRows({ start: 500, end: 740 }, 3_000, { first: 760, last: 800 })).toEqual({ start: 500, end: 801 });
+ expect(holdRows({ start: 500, end: 740 }, 3_000, { first: 600, last: 610 })).toEqual({ start: 500, end: 740 });
+ expect(holdRows({ start: 2_800, end: null }, 3_000, { first: 2_700, last: 2_999 })).toEqual({ start: 2_700, end: null });
+ expect(holdRows({ start: 500, end: 740 }, 3_000, { first: 740 + SELECTION_HOLD_MAX, last: 740 + SELECTION_HOLD_MAX })).toBeNull();
+ expect(holdRows({ start: 1_000, end: 1_240 }, 3_000, { first: 1_240 - SELECTION_HOLD_MAX, last: 1_000 })).toEqual({ start: 1_240 - SELECTION_HOLD_MAX, end: 1_240 });
+ });
+
it("puts a remembered row back inside a capped window", () => {
const window = restoreWindow(3_000, 1_000, 0);
expect(window.start).toBeLessThanOrEqual(1_000);
diff --git a/src/lib/transcript-window.ts b/src/lib/transcript-window.ts
index c4d98a4672..82b6830ad9 100644
--- a/src/lib/transcript-window.ts
+++ b/src/lib/transcript-window.ts
@@ -1,6 +1,10 @@
export const TRANSCRIPT_WINDOW_SIZE = 120;
/** The most rows drawn at once while the reader is away from the end: one step past it unloads rows at the far edge. */
export const TRANSCRIPT_WINDOW_MAX = 2 * TRANSCRIPT_WINDOW_SIZE;
+/** Rows one scroll step draws at a window edge: small enough to mount without a long frame. */
+export const TRANSCRIPT_WINDOW_STEP = 30;
+/** The most rows drawn while a text selection holds rows the reader has scrolled away from; past it the selection is set aside. */
+export const SELECTION_HOLD_MAX = 2 * TRANSCRIPT_WINDOW_MAX;
export interface TranscriptWindow<T> {
visible: T[];
@@ -54,22 +58,30 @@ export function capWindowEnd({ start, end }: TranscriptWindowBounds, total: numb
}
export function windowEarlier(window: TranscriptWindowBounds, total: number): TranscriptWindowBounds {
- return capWindowEnd({ start: expandWindowStart(window.start), end: window.end }, total);
+ return capWindowEnd({ start: expandWindowStart(window.start, TRANSCRIPT_WINDOW_STEP), end: window.end }, total);
}
/** One step down: rows below join and, past the cap, rows at the top leave. */
export function windowLater({ start, end }: TranscriptWindowBounds, total: number): TranscriptWindowBounds {
if (end === null) return { start, end };
- const nextEnd = Math.min(total, end + TRANSCRIPT_WINDOW_SIZE);
+ const nextEnd = Math.min(total, end + TRANSCRIPT_WINDOW_STEP);
return { start: Math.max(start, nextEnd - TRANSCRIPT_WINDOW_MAX), end: nextEnd >= total ? null : nextEnd };
}
/** The window after `added` older rows were put in front of the transcript: a window at the top shows one step of them. */
export function windowAfterPrepend({ start, end }: TranscriptWindowBounds, added: number, total: number): TranscriptWindowBounds {
- const moved = { start: start === 0 ? Math.max(0, added - TRANSCRIPT_WINDOW_SIZE) : start + added, end: end === null ? null : end + added };
+ const moved = { start: start === 0 ? Math.max(0, added - TRANSCRIPT_WINDOW_STEP) : start + added, end: end === null ? null : end + added };
return capWindowEnd(moved, total);
}
+/** `window` widened to draw rows `first` to `last`, or null when that would draw more than `SELECTION_HOLD_MAX` rows. */
+export function holdRows({ start, end }: TranscriptWindowBounds, total: number, { first, last }: { first: number; last: number }): TranscriptWindowBounds | null {
+ const from = Math.max(0, Math.min(start, first));
+ const to = Math.min(total, Math.max(end ?? total, last + 1));
+ if (to - from > SELECTION_HOLD_MAX) return null;
+ return { start: from, end: end === null || to >= total ? null : to };
+}
+
/** The window that puts a remembered row back on screen, drawing at most `TRANSCRIPT_WINDOW_MAX` rows. */
export function restoreWindow(total: number, rowIndex: number, rememberedStart: number | undefined): TranscriptWindowBounds {
const start = Math.max(0, rowIndex - TRANSCRIPT_WINDOW_SIZE, Math.min(rowIndex, rememberedStart ?? rowIndex, tailWindowStart(total)));