fix(webui): show latest button for hidden content (#6605)
* fix(webui): show latest button for hidden content * fix(webui): preserve latest navigation after focus scroll
This commit is contained in:
1 parent
c5f2ce5089
commit
f62dfe0ee8
7 files changed
+243
-23
No files matched your search
@@ -110,7 +110,9 @@ const parameters = new URLSearchParams(location.search);
|
|||||||
const railClient = new NanobotClient({ url: "ws://127.0.0.1:8765", reconnect: false });
|
const railClient = new NanobotClient({ url: "ws://127.0.0.1:8765", reconnect: false });
|
||||||
const railHistory: UIMessage[] = Array.from({ length: 5 }, (_, index) => [
|
const railHistory: UIMessage[] = Array.from({ length: 5 }, (_, index) => [
|
||||||
{ id: `u${1995 + index}`, role: "user" as const, content: `Question ${1995 + index}`, createdAt: index + 1 },
|
{ id: `u${1995 + index}`, role: "user" as const, content: `Question ${1995 + index}`, createdAt: index + 1 },
|
||||||
{ id: `a${1995 + index}`, role: "assistant" as const, content: "A synthetic answer.\n\n".repeat(8), createdAt: index + 1 },
|
{ id: `a${1995 + index}`, role: "assistant" as const, content: parameters.has("focus-links") && index === 4
|
||||||
|
? Array.from({ length: 45 }, (_, i) => `[Reference ${i}](https://example.test/ref${i})`).join("\n")
|
||||||
|
: "A synthetic answer.\n\n".repeat(8), createdAt: index + 1 },
|
||||||
]).flat();
|
]).flat();
|
||||||
function RailFixture() {
|
function RailFixture() {
|
||||||
const [messages, setMessages] = useState(parameters.has("real") ? [] : railHistory);
|
const [messages, setMessages] = useState(parameters.has("real") ? [] : railHistory);
|
||||||
@@ -148,7 +150,9 @@ function RailFixture() {
|
|||||||
<button onClick={() => setStreaming(true)} disabled={streaming}>{streaming ? "Streaming" : "Simulate stream"}</button>
|
<button onClick={() => setStreaming(true)} disabled={streaming}>{streaming ? "Streaming" : "Simulate stream"}</button>
|
||||||
</div>}
|
</div>}
|
||||||
{parameters.has("workbench") ? <PaneWorkbench
|
{parameters.has("workbench") ? <PaneWorkbench
|
||||||
panes={[{ key: "rail", title: "Rail conversation" }]} activePaneKey="rail" layout="columns" showLayoutControl={false}
|
panes={parameters.has("focus-links")
|
||||||
|
? [{ key: "rail", title: "Rail conversation" }, { key: "other", title: "Other conversation" }]
|
||||||
|
: [{ key: "rail", title: "Rail conversation" }]} activePaneKey="rail" layout="columns" showLayoutControl={false}
|
||||||
onActivatePane={() => {}} onAddPane={() => {}} onLayoutChange={() => {}} onPaneOrderChange={() => {}}
|
onActivatePane={() => {}} onAddPane={() => {}} onLayoutChange={() => {}} onPaneOrderChange={() => {}}
|
||||||
renderPane={(_pane, context) => <>
|
renderPane={(_pane, context) => <>
|
||||||
{viewport(context.composerPortalTarget !== undefined, context.navigationFrame)}
|
{viewport(context.composerPortalTarget !== undefined, context.navigationFrame)}
|
||||||
|
|||||||
@@ -1,4 +1,21 @@
|
|||||||
import { expect, test } from "@playwright/test";
|
import { expect, test, type Page } from "@playwright/test";
|
||||||
|
|
||||||
|
async function recordBottomButtonFrames(page: Page) {
|
||||||
|
await page.evaluate(() => {
|
||||||
|
(window as unknown as { bottomButtonFrames: boolean[] }).bottomButtonFrames = [];
|
||||||
|
let start = 0;
|
||||||
|
const sample = () => {
|
||||||
|
(window as unknown as { bottomButtonFrames: boolean[] }).bottomButtonFrames.push(
|
||||||
|
Boolean(document.querySelector('button[aria-label="Scroll to bottom"]')),
|
||||||
|
);
|
||||||
|
if (performance.now() - start < 300) requestAnimationFrame(sample);
|
||||||
|
};
|
||||||
|
document.querySelector('button[aria-label="Scroll to bottom"]')!.addEventListener("click", () => {
|
||||||
|
start = performance.now();
|
||||||
|
requestAnimationFrame(sample);
|
||||||
|
}, { once: true });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
for (const { width, dark } of [{ width: 360, dark: false }, { width: 314, dark: true }, { width: 600, dark: false }]) {
|
for (const { width, dark } of [{ width: 360, dark: false }, { width: 314, dark: true }, { width: 600, dark: false }]) {
|
||||||
test.describe(`mobile transcript at ${width}px`, () => {
|
test.describe(`mobile transcript at ${width}px`, () => {
|
||||||
@@ -68,3 +85,74 @@ test.describe("desktop transcript spacing", () => {
|
|||||||
expect(await scroller.evaluate(node => getComputedStyle(node).maskImage)).toContain("calc(100% - 36px)");
|
expect(await scroller.evaluate(node => getComputedStyle(node).maskImage)).toContain("calc(100% - 36px)");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("bottom button stays hidden throughout smooth navigation", async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 360, height: 740 });
|
||||||
|
await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en"));
|
||||||
|
await page.route("**/api/**", route => route.fulfill({ json: {} }));
|
||||||
|
await page.goto("/browser/fixture.html?case=mobile-chat-layout&project");
|
||||||
|
const scroller = page.locator(".thread-message-viewport");
|
||||||
|
const button = page.getByRole("button", { name: "Scroll to bottom" });
|
||||||
|
await expect.poll(() => scroller.evaluate(el => el.scrollHeight - el.clientHeight)).toBeGreaterThan(100);
|
||||||
|
await expect(button).toBeHidden();
|
||||||
|
const readableDistance = () => scroller.evaluate(el => {
|
||||||
|
const rows = [...el.querySelectorAll<HTMLElement>(".thread-message-row")];
|
||||||
|
const row = rows.reverse().find(item => item.getBoundingClientRect().height > 0)!;
|
||||||
|
const gap = el.querySelector<HTMLElement>(".thread-message-end-gap")!;
|
||||||
|
return row.getBoundingClientRect().bottom - (el.getBoundingClientRect().bottom - gap.getBoundingClientRect().height);
|
||||||
|
});
|
||||||
|
expect(await readableDistance()).toBeLessThanOrEqual(1);
|
||||||
|
await scroller.hover();
|
||||||
|
await page.mouse.wheel(0, -120);
|
||||||
|
await expect(button).toBeVisible();
|
||||||
|
expect(await readableDistance()).toBeGreaterThan(0);
|
||||||
|
await expect(button).toBeVisible();
|
||||||
|
await recordBottomButtonFrames(page);
|
||||||
|
await button.click();
|
||||||
|
await expect(button).toBeHidden();
|
||||||
|
await expect.poll(() => scroller.evaluate(el => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(1);
|
||||||
|
await page.waitForTimeout(320);
|
||||||
|
const frames = await page.evaluate(() => (window as unknown as { bottomButtonFrames: boolean[] }).bottomButtonFrames);
|
||||||
|
expect(frames.length).toBeGreaterThan(1);
|
||||||
|
expect(frames).not.toContain(true);
|
||||||
|
await expect(button).toBeHidden();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("bottom button stays hidden after focus scrolls a following thread", async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 360, height: 740 });
|
||||||
|
await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en"));
|
||||||
|
await page.route("**/api/sessions/**", route => route.fulfill({ json: { prompts: [] } }));
|
||||||
|
await page.goto("/browser/fixture.html?case=rail&workbench=1&focus-links=1");
|
||||||
|
const scroller = page.locator(".thread-message-viewport");
|
||||||
|
const links = scroller.locator("a");
|
||||||
|
const button = page.getByRole("button", { name: "Scroll to bottom" });
|
||||||
|
await expect(links).toHaveCount(45);
|
||||||
|
await expect.poll(() => scroller.evaluate(el => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(1);
|
||||||
|
await expect(button).toBeHidden();
|
||||||
|
|
||||||
|
const index = await scroller.evaluate(el => {
|
||||||
|
const top = el.getBoundingClientRect().top;
|
||||||
|
return [...el.querySelectorAll("a")].findIndex(link => {
|
||||||
|
const offset = link.getBoundingClientRect().top - top;
|
||||||
|
return offset > 48 && offset < 100;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
expect(index).toBeGreaterThan(0);
|
||||||
|
await links.nth(index).focus();
|
||||||
|
const initialTop = await scroller.evaluate(el => el.scrollTop);
|
||||||
|
await page.keyboard.press("Shift+Tab");
|
||||||
|
await expect(links.nth(index - 1)).toBeFocused();
|
||||||
|
await expect(button).toBeVisible();
|
||||||
|
const distance = initialTop - await scroller.evaluate(el => el.scrollTop);
|
||||||
|
expect(distance).toBeGreaterThan(0);
|
||||||
|
expect(distance).toBeLessThan(48);
|
||||||
|
|
||||||
|
await recordBottomButtonFrames(page);
|
||||||
|
await button.click();
|
||||||
|
await expect.poll(() => scroller.evaluate(el => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(1);
|
||||||
|
await page.waitForTimeout(320);
|
||||||
|
const frames = await page.evaluate(() => (window as unknown as { bottomButtonFrames: boolean[] }).bottomButtonFrames);
|
||||||
|
expect(frames.length).toBeGreaterThan(1);
|
||||||
|
expect(frames).not.toContain(true);
|
||||||
|
await expect(button).toBeHidden();
|
||||||
|
});
|
||||||
@@ -313,6 +313,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
const composerLayoutChangeRef = useRef(onComposerLayoutChange);
|
const composerLayoutChangeRef = useRef(onComposerLayoutChange);
|
||||||
composerLayoutChangeRef.current = onComposerLayoutChange;
|
composerLayoutChangeRef.current = onComposerLayoutChange;
|
||||||
const bottomRef = useRef<HTMLDivElement>(null);
|
const bottomRef = useRef<HTMLDivElement>(null);
|
||||||
|
const endGapRef = useRef<HTMLDivElement>(null);
|
||||||
const lastConversationKeyRef = useRef<string | null>(conversationKey);
|
const lastConversationKeyRef = useRef<string | null>(conversationKey);
|
||||||
const conversationHandoffPendingRef = useRef(false);
|
const conversationHandoffPendingRef = useRef(false);
|
||||||
const conversationHandoffAnimationRef = useRef<Animation | null>(null);
|
const conversationHandoffAnimationRef = useRef<Animation | null>(null);
|
||||||
@@ -323,7 +324,27 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
const historyScrollAnchorRef = useRef<HistoryScrollAnchor | null>(null);
|
const historyScrollAnchorRef = useRef<HistoryScrollAnchor | null>(null);
|
||||||
const previousLoadingOlderRef = useRef(loadingOlder);
|
const previousLoadingOlderRef = useRef(loadingOlder);
|
||||||
const composerDockHeightRef = useRef(0);
|
const composerDockHeightRef = useRef(0);
|
||||||
const [atBottom, setAtBottom] = useState(true);
|
const [contentBelowViewport, setContentBelowViewport] = useState(false);
|
||||||
|
const [navigatingToBottom, setNavigatingToBottom] = useState(false);
|
||||||
|
const lastMessageRowRef = useRef<HTMLElement | null>(null);
|
||||||
|
const refreshLastMessageRow = useCallback(() => {
|
||||||
|
const rows = messageContentRef.current?.querySelectorAll<HTMLElement>(".thread-message-row");
|
||||||
|
lastMessageRowRef.current = null;
|
||||||
|
if (!rows) return;
|
||||||
|
for (let index = rows.length - 1; index >= 0; index--) {
|
||||||
|
if (rows[index].getBoundingClientRect().height > 0) {
|
||||||
|
lastMessageRowRef.current = rows[index];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
const updateContentVisibility = useCallback(() => {
|
||||||
|
const viewport = messageRegionRef.current;
|
||||||
|
const lastRow = lastMessageRowRef.current;
|
||||||
|
setContentBelowViewport(Boolean(viewport && lastRow
|
||||||
|
&& lastRow.getBoundingClientRect().bottom > viewport.getBoundingClientRect().bottom
|
||||||
|
- (endGapRef.current?.getBoundingClientRect().height ?? 0)));
|
||||||
|
}, []);
|
||||||
const [atHistoryTop, setAtHistoryTop] = useState(false);
|
const [atHistoryTop, setAtHistoryTop] = useState(false);
|
||||||
const [historyPhase, setHistoryPhase] = useState<HistoryRevealPhase>("hidden");
|
const [historyPhase, setHistoryPhase] = useState<HistoryRevealPhase>("hidden");
|
||||||
const historyPhaseRef = useRef(historyPhase);
|
const historyPhaseRef = useRef(historyPhase);
|
||||||
@@ -380,7 +401,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
useState(INITIAL_HISTORY_WINDOW);
|
useState(INITIAL_HISTORY_WINDOW);
|
||||||
const threadMotionRef = useRef<ThreadMotionCoordinator | null>(null);
|
const threadMotionRef = useRef<ThreadMotionCoordinator | null>(null);
|
||||||
if (threadMotionRef.current === null) {
|
if (threadMotionRef.current === null) {
|
||||||
const camera = new ThreadCameraController(() => scrollRef.current);
|
const camera = new ThreadCameraController(() => scrollRef.current, {
|
||||||
|
onSettled: () => threadMotionRef.current?.cameraSettled(),
|
||||||
|
});
|
||||||
threadMotionRef.current = new ThreadMotionCoordinator({
|
threadMotionRef.current = new ThreadMotionCoordinator({
|
||||||
camera,
|
camera,
|
||||||
measure: (promptId) => {
|
measure: (promptId) => {
|
||||||
@@ -408,6 +431,10 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
: null,
|
: null,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
onLatestNavigationSettled: () => {
|
||||||
|
setNavigatingToBottom(false);
|
||||||
|
updateContentVisibility();
|
||||||
|
},
|
||||||
onGeometry: (geometry: ThreadMotionGeometry) => {
|
onGeometry: (geometry: ThreadMotionGeometry) => {
|
||||||
composerLayoutChangeRef.current?.();
|
composerLayoutChangeRef.current?.();
|
||||||
if (Math.abs(composerDockHeightRef.current - geometry.composerHeight) >= 1) {
|
if (Math.abs(composerDockHeightRef.current - geometry.composerHeight) >= 1) {
|
||||||
@@ -419,7 +446,6 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
current === nextOverflow ? current : nextOverflow,
|
current === nextOverflow ? current : nextOverflow,
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
onAutoFollow: () => setAtBottom(true),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const hasTaskResults = useHasSubagentResults();
|
const hasTaskResults = useHasSubagentResults();
|
||||||
@@ -461,7 +487,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
|
|
||||||
const yieldCameraToUser = useCallback(() => {
|
const yieldCameraToUser = useCallback(() => {
|
||||||
threadMotionRef.current?.takeUserControl();
|
threadMotionRef.current?.takeUserControl();
|
||||||
}, []);
|
setNavigatingToBottom(false);
|
||||||
|
updateContentVisibility();
|
||||||
|
}, [updateContentVisibility]);
|
||||||
|
|
||||||
const captureHistoryScrollAnchor = useCallback(() => {
|
const captureHistoryScrollAnchor = useCallback(() => {
|
||||||
const scroller = scrollRef.current;
|
const scroller = scrollRef.current;
|
||||||
@@ -542,14 +570,14 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
if (el) {
|
if (el) {
|
||||||
const top = Math.max(0, el.scrollHeight - el.clientHeight);
|
const top = Math.max(0, el.scrollHeight - el.clientHeight);
|
||||||
if (smooth) {
|
if (smooth) {
|
||||||
threadMotionRef.current?.navigateLatestTo(top);
|
const result = threadMotionRef.current?.navigateLatestTo(top);
|
||||||
|
setNavigatingToBottom(result === "started" || result === "retargeted");
|
||||||
} else {
|
} else {
|
||||||
threadMotionRef.current?.jumpTo(top);
|
threadMotionRef.current?.jumpTo(top);
|
||||||
}
|
}
|
||||||
} else if (marker) {
|
} else if (marker) {
|
||||||
marker.scrollIntoView({ block: "end", behavior });
|
marker.scrollIntoView({ block: "end", behavior });
|
||||||
}
|
}
|
||||||
setAtBottom(true);
|
|
||||||
}, [resetHistoryHeader]);
|
}, [resetHistoryHeader]);
|
||||||
|
|
||||||
const scrollToBottom = useCallback(
|
const scrollToBottom = useCallback(
|
||||||
@@ -576,7 +604,6 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
threadMotionRef.current?.takeUserControl();
|
threadMotionRef.current?.takeUserControl();
|
||||||
setAtBottom(false);
|
|
||||||
if (hiddenMessageCount > 0) {
|
if (hiddenMessageCount > 0) {
|
||||||
setVisibleMessageCount((count) =>
|
setVisibleMessageCount((count) =>
|
||||||
Math.min(messages.length, count + HISTORY_WINDOW_INCREMENT),
|
Math.min(messages.length, count + HISTORY_WINDOW_INCREMENT),
|
||||||
@@ -615,7 +642,6 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
if (!scrollEl || !prompt) return false;
|
if (!scrollEl || !prompt) return false;
|
||||||
historyScrollAnchorRef.current = null;
|
historyScrollAnchorRef.current = null;
|
||||||
resetHistoryHeader();
|
resetHistoryHeader();
|
||||||
setAtBottom(false);
|
|
||||||
threadMotionRef.current?.navigateHistoryToPrompt(promptId);
|
threadMotionRef.current?.navigateHistoryToPrompt(promptId);
|
||||||
return true;
|
return true;
|
||||||
}, [resetHistoryHeader]);
|
}, [resetHistoryHeader]);
|
||||||
@@ -636,7 +662,6 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
if (historyWindow) navigation?.latest();
|
if (historyWindow) navigation?.latest();
|
||||||
threadMotionRef.current?.takeUserControl();
|
threadMotionRef.current?.takeUserControl();
|
||||||
pendingPromptJumpRef.current = promptId;
|
pendingPromptJumpRef.current = promptId;
|
||||||
setAtBottom(false);
|
|
||||||
setVisibleMessageCount((count) => Math.max(count, localMessages.length - index));
|
setVisibleMessageCount((count) => Math.max(count, localMessages.length - index));
|
||||||
}, [historyWindow, latestMessages, messages, navigateToVisiblePrompt, navigation]);
|
}, [historyWindow, latestMessages, messages, navigateToVisiblePrompt, navigation]);
|
||||||
|
|
||||||
@@ -647,7 +672,6 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
pendingConversationScrollRef.current = false;
|
pendingConversationScrollRef.current = false;
|
||||||
pendingPromptJumpRef.current = navigation.target.id;
|
pendingPromptJumpRef.current = navigation.target.id;
|
||||||
threadMotionRef.current?.takeUserControl();
|
threadMotionRef.current?.takeUserControl();
|
||||||
setAtBottom(false);
|
|
||||||
const index = messages.findIndex((message) => message.id === navigation.target!.id);
|
const index = messages.findIndex((message) => message.id === navigation.target!.id);
|
||||||
setVisibleMessageCount(Math.max(INITIAL_HISTORY_WINDOW, messages.length - Math.max(0, index)));
|
setVisibleMessageCount(Math.max(INITIAL_HISTORY_WINDOW, messages.length - Math.max(0, index)));
|
||||||
}, [navigation?.target]);
|
}, [navigation?.target]);
|
||||||
@@ -658,7 +682,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
|
|
||||||
const cancelAutoScroll = useCallback(() => {
|
const cancelAutoScroll = useCallback(() => {
|
||||||
threadMotionRef.current?.takeUserControl();
|
threadMotionRef.current?.takeUserControl();
|
||||||
}, []);
|
setNavigatingToBottom(false);
|
||||||
|
updateContentVisibility();
|
||||||
|
}, [updateContentVisibility]);
|
||||||
|
|
||||||
useImperativeHandle(
|
useImperativeHandle(
|
||||||
ref,
|
ref,
|
||||||
@@ -724,7 +750,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
historyScrollAnchorRef.current = null;
|
historyScrollAnchorRef.current = null;
|
||||||
restoreScrollAfterPrependRef.current = null;
|
restoreScrollAfterPrependRef.current = null;
|
||||||
threadMotionRef.current?.reset();
|
threadMotionRef.current?.reset();
|
||||||
setAtBottom(true);
|
setNavigatingToBottom(false);
|
||||||
setShowHistoryExhausted(false);
|
setShowHistoryExhausted(false);
|
||||||
setVisibleMessageCount(INITIAL_HISTORY_WINDOW);
|
setVisibleMessageCount(INITIAL_HISTORY_WINDOW);
|
||||||
|
|
||||||
@@ -878,8 +904,10 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
}, [conversationReady, hasMessages]);
|
}, [conversationReady, hasMessages]);
|
||||||
|
|
||||||
useLayoutEffect(() => {
|
useLayoutEffect(() => {
|
||||||
|
refreshLastMessageRow();
|
||||||
|
updateContentVisibility();
|
||||||
threadMotionRef.current?.invalidateGeometry();
|
threadMotionRef.current?.invalidateGeometry();
|
||||||
}, [composer, hasMessages, visibleMessages.length]);
|
}, [composer, hasMessages, visibleMessages, refreshLastMessageRow, updateContentVisibility]);
|
||||||
|
|
||||||
useEffect(() => () => {
|
useEffect(() => () => {
|
||||||
conversationHandoffAnimationRef.current?.cancel();
|
conversationHandoffAnimationRef.current?.cancel();
|
||||||
@@ -897,11 +925,15 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
if (!el) return;
|
if (!el) return;
|
||||||
|
|
||||||
const invalidateGeometry = () => {
|
const invalidateGeometry = () => {
|
||||||
|
refreshLastMessageRow();
|
||||||
threadMotionRef.current?.invalidateGeometry();
|
threadMotionRef.current?.invalidateGeometry();
|
||||||
|
updateContentVisibility();
|
||||||
};
|
};
|
||||||
const reconcileObservedGeometry = () => {
|
const reconcileObservedGeometry = () => {
|
||||||
|
refreshLastMessageRow();
|
||||||
reconcileHistoryScrollAnchor();
|
reconcileHistoryScrollAnchor();
|
||||||
threadMotionRef.current?.reconcileObservedGeometry();
|
threadMotionRef.current?.reconcileObservedGeometry();
|
||||||
|
updateContentVisibility();
|
||||||
};
|
};
|
||||||
reconcileObservedGeometry();
|
reconcileObservedGeometry();
|
||||||
const observer = typeof ResizeObserver === "undefined"
|
const observer = typeof ResizeObserver === "undefined"
|
||||||
@@ -911,29 +943,28 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
if (content) observer?.observe(content);
|
if (content) observer?.observe(content);
|
||||||
if (contentRegion) observer?.observe(contentRegion);
|
if (contentRegion) observer?.observe(contentRegion);
|
||||||
if (messageContent) observer?.observe(messageContent);
|
if (messageContent) observer?.observe(messageContent);
|
||||||
|
if (endGapRef.current) observer?.observe(endGapRef.current);
|
||||||
if (composerDock) observer?.observe(composerDock);
|
if (composerDock) observer?.observe(composerDock);
|
||||||
window.addEventListener("resize", invalidateGeometry);
|
window.addEventListener("resize", invalidateGeometry);
|
||||||
return () => {
|
return () => {
|
||||||
observer?.disconnect();
|
observer?.disconnect();
|
||||||
window.removeEventListener("resize", invalidateGeometry);
|
window.removeEventListener("resize", invalidateGeometry);
|
||||||
};
|
};
|
||||||
}, [hasMessages, reconcileHistoryScrollAnchor]);
|
}, [hasMessages, reconcileHistoryScrollAnchor, refreshLastMessageRow, updateContentVisibility]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const el = scrollRef.current;
|
const el = scrollRef.current;
|
||||||
if (!el) return;
|
if (!el) return;
|
||||||
|
|
||||||
const onScroll = (allowHistoryLoad = true) => {
|
const onScroll = (allowHistoryLoad = true) => {
|
||||||
|
updateContentVisibility();
|
||||||
setAtHistoryTop(el.scrollTop <= 1);
|
setAtHistoryTop(el.scrollTop <= 1);
|
||||||
if (el.scrollTop > 1) historySpringRef.current?.leaveBoundary();
|
if (el.scrollTop > 1) historySpringRef.current?.leaveBoundary();
|
||||||
const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
|
const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
|
||||||
const near = distance < NEAR_BOTTOM_PX;
|
const near = distance < NEAR_BOTTOM_PX;
|
||||||
// A detached history page's bottom is not the live tail.
|
// A detached history page's bottom is not the live tail.
|
||||||
const owner = threadMotionRef.current?.observeScroll(near && !historyWindow) ?? "automatic";
|
const owner = threadMotionRef.current?.observeScroll(near && !historyWindow) ?? "automatic";
|
||||||
const logicallyAtBottom = !historyWindow && (owner === "automatic" || (owner === "navigation" && near));
|
if (threadMotionRef.current?.snapshot().mode !== "navigating-latest") setNavigatingToBottom(false);
|
||||||
setAtBottom((current) =>
|
|
||||||
current === logicallyAtBottom ? current : logicallyAtBottom,
|
|
||||||
);
|
|
||||||
if (owner === "user") {
|
if (owner === "user") {
|
||||||
// Restoring the anchor also emits scroll. Keep that reading position
|
// Restoring the anchor also emits scroll. Keep that reading position
|
||||||
// through lazy content resizing instead of selecting a prepended row.
|
// through lazy content resizing instead of selecting a prepended row.
|
||||||
@@ -978,6 +1009,10 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
canScrollInDirection(el, direction),
|
canScrollInDirection(el, direction),
|
||||||
direction === "forward" && !historyWindow,
|
direction === "forward" && !historyWindow,
|
||||||
);
|
);
|
||||||
|
if (threadMotionRef.current?.snapshot().mode !== "navigating-latest") {
|
||||||
|
setNavigatingToBottom(false);
|
||||||
|
updateContentVisibility();
|
||||||
|
}
|
||||||
};
|
};
|
||||||
const prepareHistoryPull = () => {
|
const prepareHistoryPull = () => {
|
||||||
if (loadingOlder || navigation?.loading) return;
|
if (loadingOlder || navigation?.loading) return;
|
||||||
@@ -1149,6 +1184,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
messages.length,
|
messages.length,
|
||||||
olderError,
|
olderError,
|
||||||
yieldCameraToUser,
|
yieldCameraToUser,
|
||||||
|
updateContentVisibility,
|
||||||
historySlotKey,
|
historySlotKey,
|
||||||
historyWindow,
|
historyWindow,
|
||||||
navigation,
|
navigation,
|
||||||
@@ -1244,7 +1280,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
</DiagramScope>
|
</DiagramScope>
|
||||||
</DiffViewportContext.Provider>
|
</DiffViewportContext.Provider>
|
||||||
</div>
|
</div>
|
||||||
<div aria-hidden className="thread-message-end-gap shrink-0" />
|
<div ref={endGapRef} aria-hidden className="thread-message-end-gap shrink-0" />
|
||||||
<div ref={bottomRef} aria-hidden className="h-px shrink-0" />
|
<div ref={bottomRef} aria-hidden className="h-px shrink-0" />
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
@@ -1319,7 +1355,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{showScrollToBottomButton && (!atBottom || historyWindow) && (
|
{showScrollToBottomButton && (historyWindow || (contentBelowViewport && !navigatingToBottom)) && (
|
||||||
<div
|
<div
|
||||||
className="absolute left-1/2 z-20 -translate-x-1/2"
|
className="absolute left-1/2 z-20 -translate-x-1/2"
|
||||||
style={{ bottom: scrollButtonBottom }}
|
style={{ bottom: scrollButtonBottom }}
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ export type ThreadCameraFollowResult = "started" | "retargeted" | "settled";
|
|||||||
interface ThreadCameraOptions {
|
interface ThreadCameraOptions {
|
||||||
scheduler?: ThreadCameraScheduler;
|
scheduler?: ThreadCameraScheduler;
|
||||||
prefersReducedMotion?: () => boolean;
|
prefersReducedMotion?: () => boolean;
|
||||||
|
onSettled?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
function defaultScheduler(): ThreadCameraScheduler {
|
function defaultScheduler(): ThreadCameraScheduler {
|
||||||
@@ -38,6 +39,7 @@ export class ThreadCameraController {
|
|||||||
private readonly getViewport: () => ThreadCameraViewport | null;
|
private readonly getViewport: () => ThreadCameraViewport | null;
|
||||||
private readonly scheduler: ThreadCameraScheduler;
|
private readonly scheduler: ThreadCameraScheduler;
|
||||||
private readonly prefersReducedMotion: () => boolean;
|
private readonly prefersReducedMotion: () => boolean;
|
||||||
|
private readonly onSettled?: () => void;
|
||||||
private frameId: number | null = null;
|
private frameId: number | null = null;
|
||||||
private phase: "idle" | "following" = "idle";
|
private phase: "idle" | "following" = "idle";
|
||||||
private target = 0;
|
private target = 0;
|
||||||
@@ -50,6 +52,7 @@ export class ThreadCameraController {
|
|||||||
) {
|
) {
|
||||||
this.getViewport = getViewport;
|
this.getViewport = getViewport;
|
||||||
this.scheduler = options.scheduler ?? defaultScheduler();
|
this.scheduler = options.scheduler ?? defaultScheduler();
|
||||||
|
this.onSettled = options.onSettled;
|
||||||
this.prefersReducedMotion = options.prefersReducedMotion ?? defaultPrefersReducedMotion;
|
this.prefersReducedMotion = options.prefersReducedMotion ?? defaultPrefersReducedMotion;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -132,6 +135,7 @@ export class ThreadCameraController {
|
|||||||
if (remainingMs === 0) {
|
if (remainingMs === 0) {
|
||||||
this.write(viewport, this.target);
|
this.write(viewport, this.target);
|
||||||
this.cancel();
|
this.cancel();
|
||||||
|
this.onSettled?.();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ const THREAD_MOTION_TRANSITIONS: Readonly<
|
|||||||
"resume-follow": "current-automatic-mode",
|
"resume-follow": "current-automatic-mode",
|
||||||
},
|
},
|
||||||
"follow-latest": {
|
"follow-latest": {
|
||||||
|
"navigate-latest": "navigating-latest",
|
||||||
"navigate-history": "navigating-history",
|
"navigate-history": "navigating-history",
|
||||||
"user-scroll": "browsing-history",
|
"user-scroll": "browsing-history",
|
||||||
},
|
},
|
||||||
@@ -134,6 +135,7 @@ interface ThreadMotionCoordinatorOptions {
|
|||||||
measure: (promptId: string | null) => ThreadMotionGeometry | null;
|
measure: (promptId: string | null) => ThreadMotionGeometry | null;
|
||||||
onGeometry?: (geometry: ThreadMotionGeometry) => void;
|
onGeometry?: (geometry: ThreadMotionGeometry) => void;
|
||||||
onAutoFollow?: () => void;
|
onAutoFollow?: () => void;
|
||||||
|
onLatestNavigationSettled?: () => void;
|
||||||
scheduler?: ThreadMotionScheduler;
|
scheduler?: ThreadMotionScheduler;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,6 +161,7 @@ export class ThreadMotionCoordinator {
|
|||||||
private readonly measure: ThreadMotionCoordinatorOptions["measure"];
|
private readonly measure: ThreadMotionCoordinatorOptions["measure"];
|
||||||
private readonly onGeometry?: ThreadMotionCoordinatorOptions["onGeometry"];
|
private readonly onGeometry?: ThreadMotionCoordinatorOptions["onGeometry"];
|
||||||
private readonly onAutoFollow?: ThreadMotionCoordinatorOptions["onAutoFollow"];
|
private readonly onAutoFollow?: ThreadMotionCoordinatorOptions["onAutoFollow"];
|
||||||
|
private readonly onLatestNavigationSettled?: () => void;
|
||||||
private readonly scheduler: ThreadMotionScheduler;
|
private readonly scheduler: ThreadMotionScheduler;
|
||||||
private turn: ThreadMotionTurn = {
|
private turn: ThreadMotionTurn = {
|
||||||
id: null,
|
id: null,
|
||||||
@@ -180,6 +183,7 @@ export class ThreadMotionCoordinator {
|
|||||||
this.measure = options.measure;
|
this.measure = options.measure;
|
||||||
this.onGeometry = options.onGeometry;
|
this.onGeometry = options.onGeometry;
|
||||||
this.onAutoFollow = options.onAutoFollow;
|
this.onAutoFollow = options.onAutoFollow;
|
||||||
|
this.onLatestNavigationSettled = options.onLatestNavigationSettled;
|
||||||
this.scheduler = options.scheduler ?? defaultScheduler();
|
this.scheduler = options.scheduler ?? defaultScheduler();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -330,6 +334,13 @@ export class ThreadMotionCoordinator {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cameraSettled(): void {
|
||||||
|
if (this.mode === "navigating-latest") {
|
||||||
|
this.settleLatestNavigation();
|
||||||
|
this.onLatestNavigationSettled?.();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
isAutoFollowPaused(): boolean {
|
isAutoFollowPaused(): boolean {
|
||||||
return this.isHistoryMode();
|
return this.isHistoryMode();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -587,6 +587,34 @@ describe("ThreadMotionCoordinator", () => {
|
|||||||
expect(coordinator.snapshot().mode).toBe("browsing-history");
|
expect(coordinator.snapshot().mode).toBe("browsing-history");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("settles camera navigation without relying on a scroll event", () => {
|
||||||
|
const { coordinator } = motionHarness();
|
||||||
|
coordinator.takeUserControl();
|
||||||
|
coordinator.navigateLatestTo(1_400);
|
||||||
|
coordinator.cameraSettled();
|
||||||
|
expect(coordinator.snapshot().mode).toBe("follow-latest");
|
||||||
|
|
||||||
|
coordinator.navigateHistoryTo(200);
|
||||||
|
coordinator.cameraSettled();
|
||||||
|
expect(coordinator.snapshot().mode).toBe("navigating-history");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps explicit latest navigation in control when already following the tail", () => {
|
||||||
|
const { camera, coordinator, advanceFrame, setCameraFollowing } = motionHarness();
|
||||||
|
coordinator.resumeAutoFollow();
|
||||||
|
advanceFrame();
|
||||||
|
|
||||||
|
expect(coordinator.snapshot().mode).toBe("follow-latest");
|
||||||
|
expect(coordinator.navigateLatestTo(1_400)).toBe("started");
|
||||||
|
expect(coordinator.snapshot().mode).toBe("navigating-latest");
|
||||||
|
expect(coordinator.observeScroll(true)).toBe("navigation");
|
||||||
|
expect(camera.isFollowing()).toBe(true);
|
||||||
|
|
||||||
|
setCameraFollowing(false);
|
||||||
|
coordinator.cameraSettled();
|
||||||
|
expect(coordinator.snapshot().mode).toBe("follow-latest");
|
||||||
|
});
|
||||||
|
|
||||||
it("retargets smooth latest navigation before resuming automatic follow", () => {
|
it("retargets smooth latest navigation before resuming automatic follow", () => {
|
||||||
const {
|
const {
|
||||||
camera,
|
camera,
|
||||||
|
|||||||
@@ -201,6 +201,14 @@ function getScroller(container: HTMLElement): HTMLElement {
|
|||||||
return scroller;
|
return scroller;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function mockMessageEnd(scroller: HTMLElement) {
|
||||||
|
const rows = scroller.querySelectorAll<HTMLElement>(".thread-message-row");
|
||||||
|
const row = rows[rows.length - 1];
|
||||||
|
scroller.getBoundingClientRect = () => ({ bottom: scroller.clientHeight } as DOMRect);
|
||||||
|
row.getBoundingClientRect = () => ({ height: 100, bottom: scroller.scrollHeight - scroller.scrollTop } as DOMRect);
|
||||||
|
act(() => window.dispatchEvent(new Event("resize")));
|
||||||
|
}
|
||||||
|
|
||||||
async function renderPromptRailViewport({
|
async function renderPromptRailViewport({
|
||||||
scrollTo,
|
scrollTo,
|
||||||
messages: promptMessages = makePromptExchangeMessages(5),
|
messages: promptMessages = makePromptExchangeMessages(5),
|
||||||
@@ -922,6 +930,7 @@ describe("ThreadViewport", () => {
|
|||||||
await flushAnimationFrame();
|
await flushAnimationFrame();
|
||||||
followTo.mockClear();
|
followTo.mockClear();
|
||||||
|
|
||||||
|
mockMessageEnd(scroller);
|
||||||
act(() => {
|
act(() => {
|
||||||
fireEvent.wheel(scroller, { deltaY: -24 });
|
fireEvent.wheel(scroller, { deltaY: -24 });
|
||||||
scroller.scrollTop = 1_380;
|
scroller.scrollTop = 1_380;
|
||||||
@@ -970,6 +979,43 @@ describe("ThreadViewport", () => {
|
|||||||
.not.toBeInTheDocument();
|
.not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("tracks the message content edge independently of trailing space and motion ownership", () => {
|
||||||
|
const resizeObserver = stubResizeObserver();
|
||||||
|
try {
|
||||||
|
const { container } = render(<ThreadViewport messages={messages} isStreaming={false} composer={<div>composer</div>} />);
|
||||||
|
const scroller = getScroller(container);
|
||||||
|
const content = scroller.firstElementChild as HTMLElement;
|
||||||
|
const row = scroller.querySelector<HTMLElement>(".thread-message-row:last-child")!;
|
||||||
|
const gap = scroller.querySelector<HTMLElement>(".thread-message-end-gap")!;
|
||||||
|
let contentBottom = 565;
|
||||||
|
scroller.getBoundingClientRect = () => ({ bottom: 600 } as DOMRect);
|
||||||
|
gap.getBoundingClientRect = () => ({ height: 36 } as DOMRect);
|
||||||
|
row.getBoundingClientRect = () => ({ bottom: contentBottom, height: 100 } as DOMRect);
|
||||||
|
act(() => window.dispatchEvent(new Event("resize")));
|
||||||
|
Object.defineProperties(scroller, {
|
||||||
|
scrollHeight: { configurable: true, value: 1000 },
|
||||||
|
clientHeight: { configurable: true, value: 600 },
|
||||||
|
scrollTop: { configurable: true, writable: true, value: 300 },
|
||||||
|
});
|
||||||
|
act(() => { scroller.dispatchEvent(new Event("scroll")); });
|
||||||
|
expect(screen.getByRole("button", { name: "Scroll to bottom" })).toBeInTheDocument();
|
||||||
|
contentBottom = 564;
|
||||||
|
act(() => { scroller.dispatchEvent(new Event("scroll")); });
|
||||||
|
expect(screen.queryByRole("button", { name: "Scroll to bottom" })).not.toBeInTheDocument();
|
||||||
|
contentBottom = 570;
|
||||||
|
const observer = resizeObserver.observers.find((item) => item.elements.includes(content))!;
|
||||||
|
act(() => { observer.callback([], observer); });
|
||||||
|
expect(screen.getByRole("button", { name: "Scroll to bottom" })).toBeInTheDocument();
|
||||||
|
vi.spyOn(ThreadMotionCoordinator.prototype, "navigateLatestTo").mockReturnValue("started");
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Scroll to bottom" }));
|
||||||
|
expect(screen.queryByRole("button", { name: "Scroll to bottom" })).not.toBeInTheDocument();
|
||||||
|
fireEvent.wheel(scroller, { deltaY: -20 });
|
||||||
|
expect(screen.getByRole("button", { name: "Scroll to bottom" })).toBeInTheDocument();
|
||||||
|
} finally {
|
||||||
|
resizeObserver.restore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it("keeps the scroll-to-bottom button above a growing composer", async () => {
|
it("keeps the scroll-to-bottom button above a growing composer", async () => {
|
||||||
const resizeObserver = stubResizeObserver();
|
const resizeObserver = stubResizeObserver();
|
||||||
|
|
||||||
@@ -988,6 +1034,7 @@ describe("ThreadViewport", () => {
|
|||||||
scrollTop: { configurable: true, value: 0 },
|
scrollTop: { configurable: true, value: 0 },
|
||||||
});
|
});
|
||||||
|
|
||||||
|
mockMessageEnd(scroller);
|
||||||
act(() => {
|
act(() => {
|
||||||
dispatchUserScroll(scroller);
|
dispatchUserScroll(scroller);
|
||||||
});
|
});
|
||||||
@@ -1046,6 +1093,7 @@ describe("ThreadViewport", () => {
|
|||||||
scrollTop: { configurable: true, writable: true, value: 0 },
|
scrollTop: { configurable: true, writable: true, value: 0 },
|
||||||
});
|
});
|
||||||
|
|
||||||
|
mockMessageEnd(scroller);
|
||||||
act(() => {
|
act(() => {
|
||||||
dispatchUserScroll(scroller);
|
dispatchUserScroll(scroller);
|
||||||
});
|
});
|
||||||
@@ -2379,6 +2427,7 @@ describe("ThreadViewport", () => {
|
|||||||
clientHeight: { configurable: true, value: 600 },
|
clientHeight: { configurable: true, value: 600 },
|
||||||
scrollTop: { configurable: true, writable: true, value: 300 },
|
scrollTop: { configurable: true, writable: true, value: 300 },
|
||||||
});
|
});
|
||||||
|
mockMessageEnd(scroller);
|
||||||
act(() => {
|
act(() => {
|
||||||
dispatchUserScroll(scroller);
|
dispatchUserScroll(scroller);
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in new issue
Block a user