Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -682,6 +682,54 @@ it("reopens a long draft scrolled to its caret without taking focus", async () =
expect(caret.bottom).toBeLessThanOrEqual(scroller.getBoundingClientRect().bottom - 48 + 1);
});

it.each(["none", "caret", "selection"] as const)(
"keeps the reading position when a draft rewraps (focus: %s)",
async (focus) => {
const focused = focus !== "none";
const value = "A long wrapped paragraph should keep the sentence being read in view. ".repeat(
100,
);
const style = document.head.appendChild(document.createElement("style"));
style.textContent = ".composer-tiptap { width: 700px; max-height: 160px; overflow-y: auto; }";
using _style = { [Symbol.dispose]: () => style.remove() };
await using screen = await mountEditor(value);
const { editor } = screen;
const scroller = editor.view.dom;
await vi.waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(500));
if (focused) await focusAt(editor, 2000);
scroller.scrollTop = 300;
scroller.dispatchEvent(new Event("scroll"));
const box = scroller.getBoundingClientRect();
const position = editor.view.posAtCoords({
left: box.left + box.width / 2,
top: box.top + 25,
})!;
const before = editor.view.coordsAtPos(position.pos).top - box.top;
if (focused) await focusAt(editor, position.pos);
if (focus === "selection") {
editor.commands.setTextSelection({ from: position.pos, to: position.pos + 20 });
}
document.dispatchEvent(new Event("selectionchange"));
const selection = editor.state.selection.toJSON();
for (const width of [420, 700]) {
// The panel toggle shortcut reaches the focused editor before the width changes.
if (focused) {
scroller.dispatchEvent(
new KeyboardEvent("keydown", { key: "b", ctrlKey: true, altKey: true, bubbles: true }),
);
}
scroller.style.width = `${width}px`;
await vi.waitFor(() => {
const after =
editor.view.coordsAtPos(position.pos).top - scroller.getBoundingClientRect().top;
expect(Math.abs(after - before)).toBeLessThan(25);
});
expect(editor.state.selection.toJSON()).toEqual(selection);
expect(editor.view.hasFocus()).toBe(focused);
}
},
);

it("does not outline the line under a click made with the node-select modifier held", async () => {
await using screen = await mountEditor("ship it");
const { editor } = screen;
Expand Down
6 changes: 6 additions & 0 deletions apps/web/src/components/ComposerPromptEditorTiptap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ import {
pastedPathQueryLength,
} from "~/composer-logic";
import { useStableCallback } from "~/hooks/useStableCallback";
import { preserveReadingPosition } from "~/lib/preserveReadingPosition";
import { caretLineDirection, ComposerTextDirectionExtension } from "~/composer-text-direction";
import {
collapseShownMarkdownSource,
Expand Down Expand Up @@ -1765,6 +1766,11 @@ function ComposerPromptEditorTiptapInner(
if (replacements.length > 0) replaceSkillChips(editor, replacements);
}, [editor, literalText, modelKeys, skills]);

// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the mounted editor's visible text anchored while its DOM width changes
useLayoutEffect(() => {
if (editor) return preserveReadingPosition(editor.view.dom);
}, [editor]);

// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores ProseMirror focus and caret scroll when the keyed editor remounts, capturing focus on teardown
useLayoutEffect(() => {
if (!editor) return;
Expand Down
42 changes: 42 additions & 0 deletions apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,48 @@ describe("MessagesTimeline messages", () => {
await vi.waitFor(() => expect(viewport.scrollTop).toBeLessThan(atEnd));
});

it("keeps the visible sentence in a long message when the chat width changes", async () => {
setup();
const size = { width: window.innerWidth, height: window.innerHeight };
onTestFinished(() => page.viewport(size.width, size.height));
await page.viewport(1200, 1400);
const props = { ...baseProps(), liveFollowEnabled: false };
const paragraphs = Array.from(
{ length: 30 },
(_, index) =>
`Paragraph ${index + 1}. ${"A side panel should not move the sentence being read out of view. ".repeat(5)}`,
);
await using screen = await renderTimeline(
[message(paragraphs.join("\n\n"), { role: "assistant" })],
props,
);
screen.container.style.width = "900px";
const viewport = props.listRef.current!.getScrollableNode()!;
const target = page.getByText(paragraphs[15]!.trim(), { exact: true }).element();
await vi.waitFor(() => {
expect(viewport.scrollHeight).toBeGreaterThan(1000);
expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeLessThan(2);
});
await props.listRef.current!.scrollToOffset({
offset:
viewport.scrollTop +
target.getBoundingClientRect().top -
viewport.getBoundingClientRect().top -
24,
animated: false,
});
viewport.dispatchEvent(new Event("scroll"));
const before = target.getBoundingClientRect().top - viewport.getBoundingClientRect().top;
expect(Math.abs(before - 24)).toBeLessThan(2);
for (const width of [500, 900]) {
screen.container.style.width = `${width}px`;
await vi.waitFor(() => {
const after = target.getBoundingClientRect().top - viewport.getBoundingClientRect().top;
expect(Math.abs(after - before)).toBeLessThan(30);
});
}
});

it("disables the minimap's next turn button at the bottom of the thread", async () => {
setup();
const props = baseProps();
Expand Down
13 changes: 13 additions & 0 deletions apps/web/src/components/chat/MessagesTimeline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor";
import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
import { observeResize } from "~/lib/observeResize";
import { preserveReadingPosition } from "~/lib/preserveReadingPosition";
import { useStableCallback } from "~/hooks/useStableCallback";

const NOOP_USE_ARTIFACT_TEMPLATE = () => {};
Expand Down Expand Up @@ -1261,6 +1262,14 @@ const ConversationTimeline = memo(function ConversationTimeline({

const canvas = useChatCanvas();
const registerTimeline = canvas?.registerTimeline;
const shouldPreserveReadingPosition = useStableCallback(
() =>
!liveFollowEnabled &&
!anchoredEndSpace &&
!findActive &&
!citationPositioning &&
!restoringThreadPosition,
);
// Stable so the list attaches once per mount, not on every render.
const setTimelineList = useStableCallback((list: LegendListRef | null) => {
listRef.current = list;
Expand All @@ -1276,6 +1285,9 @@ const ConversationTimeline = memo(function ConversationTimeline({
})
: null;
viewportRef.current = viewport;
const stopPreservingReadingPosition = scrollNode
? preserveReadingPosition(scrollNode, shouldPreserveReadingPosition)
: undefined;
const detachViewport = viewport ? onViewportAttach?.(viewport) : undefined;
const stopRememberingRelease = viewport?.onFollowReleased(rememberReleasedPosition);
const stopDisclosureReveal = viewport?.subscribe(() => {
Expand Down Expand Up @@ -1304,6 +1316,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
scheduleContentSizeChanged();
return () => {
stopListeningToContentSize?.();
stopPreservingReadingPosition?.();
stopRememberingRelease?.();
stopDisclosureReveal?.();
if (contentSizeFrame !== null) cancelAnimationFrame(contentSizeFrame);
Expand Down
115 changes: 115 additions & 0 deletions apps/web/src/lib/preserveReadingPosition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { observeResize } from "./observeResize";

/** Native anchoring keeps a paragraph's start fixed, losing the visible line in a long paragraph. */
export function preserveReadingPosition(
scroller: HTMLElement,
enabled: () => boolean = () => true,
): () => void {
let width = scroller.clientWidth;
let anchor: { range: Range; top: number } | null = null;
let frame: number | null = null;

const capture = () => {
if (frame !== null || scroller.clientWidth !== width) return;
anchor = null;
if (!enabled() || scroller.scrollTop === 0) return;
const box = scroller.getBoundingClientRect();
const selection =
scroller.isContentEditable && document.activeElement === scroller
? document.getSelection()
: null;
if (selection?.isCollapsed && selection.rangeCount > 0) {
const range = selection.getRangeAt(0).cloneRange();
const rect = range.getBoundingClientRect();
if (
scroller.contains(range.startContainer) &&
rect.top >= box.top &&
rect.bottom <= box.bottom
) {
anchor = { range, top: rect.top - box.top };
return;
}
}
// A point near the top captures text rather than the paragraph's bounding box.
const x = box.left + box.width / 2;
// The first point can land in paragraph spacing. Look only within the first few lines.
for (let inset = Math.min(24, box.height / 2); inset < Math.min(64, box.height); inset += 8) {
const y = box.top + inset;
const position = document.caretPositionFromPoint?.(x, y);
const range = document.createRange();
if (position) {
range.setStart(position.offsetNode, position.offset);
} else {
const fallback = document.caretRangeFromPoint?.(x, y);
if (!fallback) continue;
range.setStart(fallback.startContainer, fallback.startOffset);
}
range.collapse(true);
if (
!scroller.contains(range.startContainer) ||
range.startContainer.nodeType !== Node.TEXT_NODE
)
continue;
const top = range.getBoundingClientRect().top - box.top;
if (top >= 0 && top < scroller.clientHeight) {
anchor = { range, top };
break;
}
}
};
const restore = () => {
if (
!enabled() ||
!anchor ||
anchor.range.startContainer.nodeType !== Node.TEXT_NODE ||
!scroller.contains(anchor.range.startContainer)
)
return;
const delta =
anchor.range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - anchor.top;
if (Math.abs(delta) > 0.5) scroller.scrollTop += delta;
};
const stop = observeResize(scroller, () => {
const nextWidth = scroller.clientWidth;
if (nextWidth === width) {
capture();
return;
}
width = nextWidth;
restore();
if (frame !== null) cancelAnimationFrame(frame);
// Virtualized rows can finish measuring in the next frame. Keep the same text anchor then.
frame = requestAnimationFrame(() => {
restore();
frame = null;
capture();
});
});
scroller.addEventListener("scroll", capture, { passive: true });
scroller.addEventListener("input", capture);
const captureSelection = () => {
if (document.activeElement === scroller) capture();
};
if (scroller.isContentEditable) document.addEventListener("selectionchange", captureSelection);
const interrupt = () => {
if (frame !== null) cancelAnimationFrame(frame);
anchor = null;
// Scrolling wins over a pending resize correction; the next frame captures the reader's new place.
frame = requestAnimationFrame(() => {
frame = null;
width = scroller.clientWidth;
capture();
});
};
scroller.addEventListener("wheel", interrupt, { passive: true });
scroller.addEventListener("touchmove", interrupt, { passive: true });
return () => {
stop();
if (frame !== null) cancelAnimationFrame(frame);
scroller.removeEventListener("scroll", capture);
scroller.removeEventListener("input", capture);
document.removeEventListener("selectionchange", captureSelection);
scroller.removeEventListener("wheel", interrupt);
scroller.removeEventListener("touchmove", interrupt);
};
}
Loading
Loading