fix(scroll): let readers scroll up in embedded and streaming chats (#38)

* fix(scroll): preserve reading in page and nested conversations

* fix(scroll): distinguish reading gestures from layout-driven scrolling

* fix(ci): reuse the actual browser revision through release verification
This commit is contained in:
Cato authored and GitHub committed 2026-10-27 04:21:16 +01:00
1 parent 15065e9fbb
commit 4e11709348
19 files changed
+647 -110

No files matched your search

+8
View File
@@ -23,6 +23,14 @@ jobs:
- run: pnpm install --frozen-lockfile
# The browser checks drive a real Chromium — the only way to prove the
# mic falls back, text is 16px and nothing overflows at 390px.
- name: Read Playwright browser revision
id: playwright
run: node -p '"version=" + require("playwright/package.json").version' >> "$GITHUB_OUTPUT"
- name: Cache the verified browser revision
uses: actions/cache@v6
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ steps.playwright.outputs.version }}
- run: pnpm exec playwright install --with-deps chromium
# Identical to what runs locally: format, lint, types, build, unit +
# render tests, browser checks.
+10
View File
@@ -79,6 +79,16 @@ jobs:
# verify includes the real-browser test (test/browser.mjs), as in ci.yml;
# without the browser the v0.2.1 publish failed before reaching npm.
- name: Read Playwright browser revision
if: steps.check.outputs.publish == 'true'
id: playwright
run: node -p '"version=" + require("playwright/package.json").version' >> "$GITHUB_OUTPUT"
- name: Cache the verified browser revision
if: steps.check.outputs.publish == 'true'
uses: actions/cache@v6
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ steps.playwright.outputs.version }}
- if: steps.check.outputs.publish == 'true'
run: pnpm exec playwright install --with-deps chromium
+8 -1
View File
@@ -123,7 +123,14 @@ jobs:
cache: pnpm
- run: pnpm install --frozen-lockfile
- name: Read Playwright browser revision
id: playwright
run: node -p '"version=" + require("playwright/package.json").version' >> "$GITHUB_OUTPUT"
- name: Cache the verified browser revision
uses: actions/cache@v6
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ steps.playwright.outputs.version }}
- name: Install Chromium when the package uses Playwright
run: |
if node -e 'const p = require("./package.json"); const d = { ...p.dependencies, ...p.devDependencies }; process.exit(d.playwright || d["@playwright/test"] ? 0 : 1)'; then
+6
View File
@@ -0,0 +1,6 @@
# Changelog
## Unreleased
- Embedded conversations now let scroll gestures reach the actual page or ancestor scroller. Reading an older answer stays stable through status updates, arriving assistant turns and resizing; a new user message or the return-to-latest action resumes following. The same behavior is covered in page, panel and nested browser fixtures.
- Release verification installs the browser required by the package's own checks.
+10 -1
View File
@@ -15,7 +15,7 @@ interface that calls them.)
## Install
```sh
pnpm add @bitbaum/chatkit@^0.13.0
pnpm add @bitbaum/chatkit
```
**Install releases from npm, never a commit or a branch.** A semver range is
@@ -508,3 +508,12 @@ track's title, creator and caption. The demo WAV is an original synthesized
fixture; it is not a commercial track or a model-generated recording.
The browser word-layout audit uses Unicode word boundaries. Chinese, Japanese and Korean may wrap between characters; those legal breaks are accepted while squeezed Latin words, including words embedded in CJK text, are still reported. Whole-page and chart overflow checks remain separate.
### Scrolling in a page or panel
`ChatThread` detects whether its own panel, an ancestor, or the page scrolls.
Upward touch, wheel and keyboard gestures pause automatic following immediately,
including close to the bottom. Status updates and incoming assistant turns keep
the reading position. Sending a new user turn or choosing return-to-latest
resumes following. Full-screen `ChatScreen` keeps its bounded scroll containment;
embedded threads allow gestures to reach their surrounding page.
+3
View File
@@ -1,3 +1,4 @@
import { mountScrollFixture } from "./scroll.js";
// The visual check: every part of the chat on one page, in light and dark.
// `pnpm run demo` builds demo/dist/; open demo/index.html. Screenshot it at
// 390px and at desktop width before calling a change to chatkit done.
@@ -386,3 +387,5 @@ for (const [id, props] of [
const el = document.getElementById(id);
if (el) createRoot(el).render(<Demo {...props} />);
}
mountScrollFixture();
+23
View File
@@ -0,0 +1,23 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Scroll regression</title>
<link rel="stylesheet" href="../styles.css" />
<style>
body {
margin: 0;
font: 16px system-ui;
}
.ck-thread-inner {
max-width: 48rem;
margin-inline: auto;
}
</style>
</head>
<body>
<div id="scroll-fixture"></div>
<script src="dist/demo.js"></script>
</body>
</html>
+96
View File
@@ -0,0 +1,96 @@
// Synthetic page-scroll and nested-scroll fixtures; no customer conversation.
import { useEffect, useRef, useState } from "react";
import { createRoot } from "react-dom/client";
import { Composer, ChatThread, type ChatMessageData } from "../src/react/index.js";
function ScrollFixture() {
const [tick, setTick] = useState(0);
const [sending, setSending] = useState(false);
const complete = useRef<(() => void) | null>(null);
const [messages, setMessages] = useState<ChatMessageData[]>([
{ id: "question", role: "user", content: "Explain the synthetic example." },
{
id: "answer",
role: "assistant",
content: "A synthetic paragraph for scroll testing.\n\n".repeat(90),
},
]);
useEffect(() => {
const timer = setInterval(() => setTick((n) => n + 1), 150);
return () => clearInterval(timer);
}, []);
const mode = new URLSearchParams(location.search).get("owner") ?? "page";
return (
<>
<div id="fixture-controls" style={{ position: "fixed", top: 0, left: 0, zIndex: 20 }}>
<button
id="assistant-turn"
onClick={() =>
setMessages((m) => [
...m,
{ id: `a${m.length}`, role: "assistant", content: "A completed answer." },
])
}
>
Complete answer
</button>
<button
id="user-turn"
onClick={() =>
setMessages((m) => [
...m,
{ id: `u${m.length}`, role: "user", content: "Another question." },
])
}
>
Send question
</button>
<button id="finish-send" onClick={() => complete.current?.()}>
Finish pending send
</button>
<output id="fixture-sending">{String(sending)}</output>
<output id="fixture-tick">{tick}</output>
</div>
<div
id="fixture-owner"
style={mode === "ancestor" ? { height: "90vh", overflowY: "auto" } : {}}
>
<div
style={
mode === "panel" ? { height: "90vh", display: "flex", flexDirection: "column" } : {}
}
>
<ChatThread messages={messages} live={{ status: `Checking details ${tick}` }} />
<Composer
placeholder="Synthetic message"
voice={false}
attach={false}
sending={sending}
onSend={(text) => {
setSending(true);
setMessages((m) => [...m, { id: `u${m.length}`, role: "user", content: text }]);
return new Promise<boolean>((resolve) => {
complete.current = () => {
setMessages((m) => [
...m,
{
id: `a${m.length}`,
role: "assistant",
content: "Completed synthetic reply.",
},
]);
setSending(false);
resolve(true);
};
});
}}
/>
</div>
</div>
</>
);
}
export function mountScrollFixture() {
const root = document.getElementById("scroll-fixture");
if (root) createRoot(root).render(<ScrollFixture />);
}
+2 -2
View File
@@ -89,7 +89,7 @@ export function ThinkingRow({ thinking, live = false, labels = DEFAULT_THREAD_LA
*/
export function ChatThread({ messages, live = null, loading = false, stopped = false, onStop, onRetry, onReply, renderLink = defaultRenderLink, renderFooter, showSpeakers, speaker, share, onFeedback, renderers, empty, children, labels: labelOverrides, }) {
const labels = { ...DEFAULT_THREAD_LABELS, ...labelOverrides };
const { scrollRef, endRef, following, onScroll, jumpToBottom } = useStickToBottom([messages.length, live?.text, live?.status, live?.steps?.length, stopped], messages.length);
const { scrollRef, endRef, following, pageScroll, onScroll, jumpToBottom } = useStickToBottom([messages.length, live?.text, live?.status, live?.steps?.length, stopped], messages.filter((message) => message.role === "user").length);
if (loading) {
return (_jsx("div", { className: "ck-thread-loading", role: "status", children: labels.loading }));
}
@@ -98,7 +98,7 @@ export function ChatThread({ messages, live = null, loading = false, stopped = f
const speakers = new Set([...messages.map((m) => m.speaker?.name), live?.speaker?.name].filter(Boolean));
const named = showSpeakers ?? speakers.size > 1;
const lastAnswer = [...messages].reverse().find((m) => m.role === "assistant");
return (_jsxs("div", { className: "ck-thread-wrap", children: [_jsx("div", { ref: scrollRef, className: "ck-thread", onScroll: onScroll, children: _jsxs("div", { className: "ck-thread-inner", children: [messages.map((m) => (_jsx(ChatMessage, { message: m, onRetry: onRetry && m.id === lastAnswer?.id && !live ? onRetry : undefined, renderLink: renderLink, showSpeaker: named, footer: renderFooter?.(m), last: m.id === lastAnswer?.id, onReply: live || stopped ? undefined : onReply, speaker: speaker, share: share, onFeedback: onFeedback, renderers: renderers, labels: labels }, m.id))), live && (_jsxs("div", { className: "ck-turn ck-turn-answer", children: [named && live.speaker && _jsx("span", { className: "ck-speaker", children: live.speaker.name }), live.steps && live.steps.length > 0 && (_jsx(ThinkingRow, { thinking: { steps: live.steps }, live: true, labels: labels })), live.text ? (_jsx(Markdown, { text: extractReplies(live.text, { streaming: true }).text, renderLink: renderLink, renderers: renderers, alertLabels: labels.alerts })) : live.steps && live.steps.length > 0 ? null : (_jsxs("p", { className: "ck-live", role: "status", "aria-live": "polite", children: [_jsxs("span", { className: "ck-dots", "aria-hidden": true, children: [_jsx("span", {}), _jsx("span", {}), _jsx("span", {})] }), live.status ?? labels.working] })), onStop && (_jsxs("button", { type: "button", className: "ck-stop", onClick: onStop, children: [_jsx(IconStop, {}), labels.stop] }))] })), stopped && !live && (_jsx("p", { className: "ck-stopped", role: "status", children: labels.stopped })), children, _jsx("div", { ref: endRef })] }) }), !following && (_jsx("button", { type: "button", className: "ck-jump", onClick: jumpToBottom, "aria-label": labels.jump, title: labels.jump, children: _jsx(IconArrowDown, {}) }))] }));
return (_jsxs("div", { className: "ck-thread-wrap", children: [_jsx("div", { ref: scrollRef, className: "ck-thread", onScroll: onScroll, children: _jsxs("div", { className: "ck-thread-inner", children: [messages.map((m) => (_jsx(ChatMessage, { message: m, onRetry: onRetry && m.id === lastAnswer?.id && !live ? onRetry : undefined, renderLink: renderLink, showSpeaker: named, footer: renderFooter?.(m), last: m.id === lastAnswer?.id, onReply: live || stopped ? undefined : onReply, speaker: speaker, share: share, onFeedback: onFeedback, renderers: renderers, labels: labels }, m.id))), live && (_jsxs("div", { className: "ck-turn ck-turn-answer", children: [named && live.speaker && _jsx("span", { className: "ck-speaker", children: live.speaker.name }), live.steps && live.steps.length > 0 && (_jsx(ThinkingRow, { thinking: { steps: live.steps }, live: true, labels: labels })), live.text ? (_jsx(Markdown, { text: extractReplies(live.text, { streaming: true }).text, renderLink: renderLink, renderers: renderers, alertLabels: labels.alerts })) : live.steps && live.steps.length > 0 ? null : (_jsxs("p", { className: "ck-live", role: "status", "aria-live": "polite", children: [_jsxs("span", { className: "ck-dots", "aria-hidden": true, children: [_jsx("span", {}), _jsx("span", {}), _jsx("span", {})] }), live.status ?? labels.working] })), onStop && (_jsxs("button", { type: "button", className: "ck-stop", onClick: onStop, children: [_jsx(IconStop, {}), labels.stop] }))] })), stopped && !live && (_jsx("p", { className: "ck-stopped", role: "status", children: labels.stopped })), children, _jsx("div", { ref: endRef })] }) }), !following && (_jsx("button", { type: "button", className: `ck-jump${pageScroll ? " ck-jump-page" : ""}`, onClick: jumpToBottom, "aria-label": labels.jump, title: labels.jump, children: _jsx(IconArrowDown, {}) }))] }));
}
/** The empty state that starts a conversation. It disappears once one has. */
export function ChatStarters({ starters, onPick, title, }) {
+1 -1
View File
@@ -1 +1 @@
{"version":3,"file":"Thread.js","sourceRoot":"","sources":["../../src/react/Thread.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAGb,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAqC,MAAM,eAAe,CAAC;AAC/F,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAG/D,OAAO,EACL,aAAa,EACb,6BAA6B,GAE9B,MAAM,oBAAoB,CAAC;AAG5B,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AA4C7E;mDACmD;AACnD,MAAM,UAAU,sBAAsB,CAAC,EAAU;IAC/C,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC;IAC7C,IAAI,CAAC,GAAG,EAAE;QAAE,OAAO,GAAG,CAAC,GAAG,CAAC;IAC3B,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;IAC7B,IAAI,CAAC,GAAG,EAAE;QAAE,OAAO,GAAG,CAAC,KAAK,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC;IAC/D,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AAG,IAAI;QAChB,CAAC,CAAC,MAAM,CAAC,QAAQ;QACjB,CAAC,CAAC,QAAQ,CAAC,UAAU,KAAK,SAAS;YACjC,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,QAAQ,EAAE,sBAAsB,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;YAClF,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC;IACrB,MAAM,IAAI,GACR,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CACrC,eAAK,SAAS,EAAC,kBAAkB,aAC9B,QAAQ,CAAC,OAAO,IAAI,sBAAI,QAAQ,CAAC,OAAO,GAAK,EAC7C,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,CACnB,aAAI,SAAS,EAAC,mBAAmB,YAC9B,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,CACtB,cAEE,SAAS,EAAE,IAAI,IAAI,CAAC,KAAK,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,SAAS,aAEzE,yBAAO,IAAI,CAAC,KAAK,GAAQ,EACxB,IAAI,CAAC,MAAM,IAAI,0BAAQ,IAAI,CAAC,MAAM,GAAS,KAJvC,CAAC,CAKH,CACN,CAAC,GACC,CACN,IACG,CACP,CAAC,CAAC,CAAC,IAAI,CAAC;IACX,IAAI,IAAI;QACN,OAAO,CACL,eAAK,SAAS,EAAC,8BAA8B,EAAC,ILine truncated
+6 -7
View File
@@ -9,18 +9,17 @@ export declare function useClipboard(resetMs?: number): {
copy: (text: string) => void;
};
/**
* Follow the conversation only while the reader is at the bottom, and offer a
* way back once they are not. Pinned in a layout effect so the view settles
* before the new token paints — in a passive effect the content lands first
* and the scroll catches up, which reads as a shudder on every chunk.
*
* `grew` should change when a NEW turn is added (message count): sending is an
* unambiguous "show me the reply", so it re-arms following.
* Follow the thread until the reader scrolls up. The scroll owner may be the
* thread, a bounded ancestor, or the document (a conversation embedded in a
* case page). Never scroll other ancestors as a side effect of following.
* `grew` counts new user turns: an arriving assistant turn is not permission
* to take the reader away from an older answer.
*/
export declare function useStickToBottom(changes: DependencyList, grew: number): {
scrollRef: RefObject<HTMLDivElement | null>;
endRef: RefObject<HTMLDivElement | null>;
following: boolean;
pageScroll: boolean;
onScroll: () => void;
jumpToBottom: () => void;
};
+1 -1
View File
@@ -1 +1 @@
{"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../../src/react/hooks.ts"],"names":[],"mappings":"AAEA,OAAO,EAML,KAAK,cAAc,EACnB,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AAGf;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,OAAO,SAAO;;iBAUhC,MAAM;EAYhB;AAED;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM;;;;;;EAgDrE;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,CAAC,EAAE,SAAS,CAAC,WAAW,GAAG,IAAI,CAAC,EAAE,OAAO,UAAO,QAqBvF;AAED;;;;;;;;gFAQgF;AAChF,wBAAgB,WAAW,CAAC,GAAG,EAAE,SAAS,CAAC,mBAAmB,GAAG,IAAI,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,SAAM,QAqB/F"}
{"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../../src/react/hooks.ts"],"names":[],"mappings":"AAEA,OAAO,EAML,KAAK,cAAc,EACnB,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AAGf;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,OAAO,SAAO;;iBAUhC,MAAM;EAYhB;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM;;;;;;;EAmKrE;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,CAAC,EAAE,SAAS,CAAC,WAAW,GAAG,IAAI,CAAC,EAAE,OAAO,UAAO,QAqBvF;AAED;;;;;;;;gFAQgF;AAChF,wBAAgB,WAAW,CAAC,GAAG,EAAE,SAAS,CAAC,mBAAmB,GAAG,IAAI,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,SAAM,QAqB/F"}
+158 -46
View File
@@ -26,63 +26,175 @@ export function useClipboard(resetMs = 1500) {
return { copied, copy };
}
/**
* Follow the conversation only while the reader is at the bottom, and offer a
* way back once they are not. Pinned in a layout effect so the view settles
* before the new token paints — in a passive effect the content lands first
* and the scroll catches up, which reads as a shudder on every chunk.
*
* `grew` should change when a NEW turn is added (message count): sending is an
* unambiguous "show me the reply", so it re-arms following.
* Follow the thread until the reader scrolls up. The scroll owner may be the
* thread, a bounded ancestor, or the document (a conversation embedded in a
* case page). Never scroll other ancestors as a side effect of following.
* `grew` counts new user turns: an arriving assistant turn is not permission
* to take the reader away from an older answer.
*/
export function useStickToBottom(changes, grew) {
const scrollRef = useRef(null);
const endRef = useRef(null);
const [following, setFollowing] = useState(true);
const [pageScroll, setPageScroll] = useState(false);
const followingRef = useRef(true);
const owner = useRef(null);
const previousTop = useRef(0);
const downwardIntent = useRef(false);
const draggingScrollbar = useRef(false);
const cleanup = useRef(null);
const follow = useCallback((value) => {
followingRef.current = value;
setFollowing(value);
}, []);
const onScroll = useCallback(() => {
const el = scrollRef.current;
if (el)
setFollowing(isFollowing(el));
}, []);
const jumpToBottom = useCallback(() => {
setFollowing(true);
endRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });
}, []);
useLayoutEffect(() => {
if (following)
endRef.current?.scrollIntoView({ block: "end" });
}, [following, ...changes]);
// Pinned through SIZE changes too, not only new tokens: a composer that
// grows (a long draft, a staged screenshot), ChatScreen measuring its insets
// after the first paint, a rotated phone — each moves the bottom away, and
// a reader who was at the bottom must still be there afterwards.
const followingRef = useRef(following);
followingRef.current = following;
const observed = useRef(null);
const observer = useRef(null);
useLayoutEffect(() => {
const el = scrollRef.current;
if (el === observed.current || typeof ResizeObserver === "undefined")
return;
observer.current?.disconnect();
observed.current = el;
const el = owner.current;
if (!el)
return;
observer.current = new ResizeObserver(() => {
if (followingRef.current)
el.scrollTop = el.scrollHeight;
});
observer.current.observe(el);
if (el.firstElementChild)
observer.current.observe(el.firstElementChild);
const top = el.scrollTop;
// An upward gesture must pause even within the near-bottom threshold.
if (draggingScrollbar.current && top < previousTop.current - 1) {
downwardIntent.current = false;
follow(false);
}
else if (top > previousTop.current + 1 &&
(downwardIntent.current || draggingScrollbar.current))
follow(isFollowing(el));
previousTop.current = top;
}, [follow]);
const pin = useCallback((smooth = false) => {
const el = owner.current, end = endRef.current;
if (!el || !end)
return;
const page = el === document.scrollingElement;
const bottom = end.getBoundingClientRect().bottom;
const top = page
? el.scrollTop + bottom - window.innerHeight
: el.scrollTop + bottom - el.getBoundingClientRect().top - el.clientTop - el.clientHeight;
// A thread-owned scroller includes its padding below the end marker.
const target = el === scrollRef.current ? el.scrollHeight : top;
el.scrollTo({ top: target, behavior: smooth ? "smooth" : "instant" });
previousTop.current = el.scrollTop;
}, []);
const jumpToBottom = useCallback(() => {
follow(true);
pin(true);
}, [follow, pin]);
// Resolve on every render: an initially empty panel may become scrollable.
useLayoutEffect(() => {
const thread = scrollRef.current;
if (!thread) {
cleanup.current?.();
cleanup.current = null;
owner.current = null;
return;
}
let selected = thread;
while (selected &&
!(selected.scrollHeight > selected.clientHeight + 1 &&
/^(auto|scroll)$/.test(getComputedStyle(selected).overflowY))) {
selected = selected.parentElement;
}
selected ??= document.scrollingElement;
if (selected === owner.current)
return;
cleanup.current?.();
owner.current = selected;
previousTop.current = selected.scrollTop;
setPageScroll(selected === document.scrollingElement);
const target = selected === document.scrollingElement ? document : selected;
const pause = () => {
downwardIntent.current = false;
follow(false);
};
const wheel = (event) => {
if (event.deltaY < 0)
pause();
else if (event.deltaY > 0)
downwardIntent.current = true;
};
let touchY;
const touchStart = (event) => {
touchY = event.touches[0]?.clientY;
};
const touchMove = (event) => {
const y = event.touches[0]?.clientY;
if (y !== undefined && touchY !== undefined) {
if (y > touchY)
pause();
else if (y < touchY)
downwardIntent.current = true;
}
touchY = y;
};
const key = (event) => {
const e = event;
const input = e.target;
if (input?.closest('input, textarea, select, [contenteditable="true"]'))
return;
if (["ArrowUp", "PageUp", "Home"].includes(e.key) || (e.key === " " && e.shiftKey))
pause();
else if (["ArrowDown", "PageDown", "End"].includes(e.key) || e.key === " ")
downwardIntent.current = true;
};
const pointer = (event) => {
const e = event;
const right = selected === document.scrollingElement
? window.innerWidth
: selected.getBoundingClientRect().right;
if (e.pointerType === "mouse" && e.clientX >= right - 20) {
draggingScrollbar.current = true;
pause();
}
};
const releasePointer = () => {
draggingScrollbar.current = false;
};
window.addEventListener("pointerup", releasePointer, { passive: true });
const events = [
["pointerdown", pointer],
["scroll", onScroll],
["wheel", wheel],
["touchstart", touchStart],
["touchmove", touchMove],
["keydown", key],
];
for (const [name, listener] of events)
target.addEventListener(name, listener, { passive: true });
const observer = typeof ResizeObserver === "undefined"
? null
: new ResizeObserver(() => {
if (followingRef.current)
pin();
});
observer?.observe(selected);
if (thread.firstElementChild)
observer?.observe(thread.firstElementChild);
cleanup.current = () => {
for (const [name, listener] of events)
target.removeEventListener(name, listener);
observer?.disconnect();
window.removeEventListener("pointerup", releasePointer);
};
});
useEffect(() => () => observer.current?.disconnect(), []);
useEffect(() => () => {
cleanup.current?.();
cleanup.current = null;
owner.current = null;
}, []);
useLayoutEffect(() => {
if (followingRef.current)
pin();
}, [following, pin, ...changes]);
const previous = useRef(grew);
useEffect(() => {
if (grew > previous.current)
setFollowing(true);
useLayoutEffect(() => {
if (grew > previous.current) {
follow(true);
pin();
}
previous.current = grew;
}, [grew]);
return { scrollRef, endRef, following, onScroll, jumpToBottom };
}, [grew, follow, pin]);
return { scrollRef, endRef, following, pageScroll, onScroll, jumpToBottom };
}
/**
* Publishes the VISUAL viewport height as `--ck-viewport-height`.
+1 -1
View File
@@ -1 +1 @@
{"version":3,"file":"hooks.js","sourceRoot":"","sources":["../../src/react/hooks.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EACL,WAAW,EACX,SAAS,EACT,eAAe,EACf,MAAM,EACN,QAAQ,GAGT,MAAM,OAAO,CAAC;AACf,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,OAAO,GAAG,IAAI;IACzC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC5C,MAAM,KAAK,GAAG,MAAM,CAAuC,IAAI,CAAC,CAAC;IACjE,SAAS,CACP,GAAG,EAAE,CAAC,GAAG,EAAE;QACT,IAAI,KAAK,CAAC,OAAO;YAAE,YAAY,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACjD,CAAC,EACD,EAAE,CACH,CAAC;IACF,MAAM,IAAI,GAAG,WAAW,CACtB,CAAC,IAAY,EAAE,EAAE;QACf,KAAK,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,SAAS,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC;aACvD,IAAI,CAAC,GAAG,EAAE;YACT,SAAS,CAAC,IAAI,CAAC,CAAC;YAChB,IAAI,KAAK,CAAC,OAAO;gBAAE,YAAY,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAC/C,KAAK,CAAC,OAAO,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;QAC9D,CAAC,CAAC;aACD,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IACrB,CAAC,EACD,CAAC,OAAO,CAAC,CACV,CAAC;IACF,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;AAC1B,CAAC;AAED;;;;;;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AAC,GAAG,MAAM;oBAAE,KAAK,EAAE,CAAC;qBACnB,IAAI,CAAC,GAAG,MAAM;oBAAE,cAAc,CAAC,OAAO,GAAG,IAAI,CAAC;YACrD,CAAC;YACD,MAAM,GAAG,CAAC,CAAC;QACb,CAAC,CAAC;QACF,MAAM,GAAG,GAAG,CAAC,KAAY,EAAE,EAAE;YAC3B,MAAM,CAAC,GAAG,KAAsB,CAAC;YACjC,MAAM,KAAK,GAAG,CAAC,CAAC,MAA4B,CAAC;YAC7C,IAAI,KAAK,EAAE,OAAO,CAAC,mDAAmD,CLine truncated
+1 -1
View File
@@ -71,7 +71,7 @@
"format": "prettier --write .",
"format:check": "prettier --check .",
"demo": "esbuild demo/demo.tsx --bundle --jsx=automatic --format=iife --define:process.env.NODE_ENV='\"production\"' --outfile=demo/dist/demo.js --log-level=warning",
"test:browser": "pnpm run demo && node test/browser.mjs"
"test:browser": "pnpm run demo && node test/browser.mjs && node test/browser-scroll.mjs"
},
"devDependencies": {
"@bitbaum/design-tokens": "github:bitbaum/design-tokens#5c31f48743dabf9294bf9380a15862b4efbc68a0",
+3 -3
View File
@@ -379,9 +379,9 @@ export function ChatThread({
labels?: Partial<ThreadLabels>;
}) {
const labels = { ...DEFAULT_THREAD_LABELS, ...labelOverrides };
const { scrollRef, endRef, following, onScroll, jumpToBottom } = useStickToBottom(
const { scrollRef, endRef, following, pageScroll, onScroll, jumpToBottom } = useStickToBottom(
[messages.length, live?.text, live?.status, live?.steps?.length, stopped],
messages.length,
messages.filter((message) => message.role === "user").length,
);
if (loading) {
@@ -463,7 +463,7 @@ export function ChatThread({
{!following && (
<button
type="button"
className="ck-jump"
className={`ck-jump${pageScroll ? " ck-jump-page" : ""}`}
onClick={jumpToBottom}
aria-label={labels.jump}
title={labels.jump}
+158 -45
View File
@@ -41,62 +41,175 @@ export function useClipboard(resetMs = 1500) {
}
/**
* Follow the conversation only while the reader is at the bottom, and offer a
* way back once they are not. Pinned in a layout effect so the view settles
* before the new token paints — in a passive effect the content lands first
* and the scroll catches up, which reads as a shudder on every chunk.
*
* `grew` should change when a NEW turn is added (message count): sending is an
* unambiguous "show me the reply", so it re-arms following.
* Follow the thread until the reader scrolls up. The scroll owner may be the
* thread, a bounded ancestor, or the document (a conversation embedded in a
* case page). Never scroll other ancestors as a side effect of following.
* `grew` counts new user turns: an arriving assistant turn is not permission
* to take the reader away from an older answer.
*/
export function useStickToBottom(changes: DependencyList, grew: number) {
const scrollRef = useRef<HTMLDivElement | null>(null);
const endRef = useRef<HTMLDivElement | null>(null);
const [following, setFollowing] = useState(true);
const [pageScroll, setPageScroll] = useState(false);
const followingRef = useRef(true);
const owner = useRef<HTMLElement | null>(null);
const previousTop = useRef(0);
const downwardIntent = useRef(false);
const draggingScrollbar = useRef(false);
const cleanup = useRef<(() => void) | null>(null);
const follow = useCallback((value: boolean) => {
followingRef.current = value;
setFollowing(value);
}, []);
const onScroll = useCallback(() => {
const el = scrollRef.current;
if (el) setFollowing(isFollowing(el));
}, []);
const jumpToBottom = useCallback(() => {
setFollowing(true);
endRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });
}, []);
useLayoutEffect(() => {
if (following) endRef.current?.scrollIntoView({ block: "end" });
}, [following, ...changes]);
// Pinned through SIZE changes too, not only new tokens: a composer that
// grows (a long draft, a staged screenshot), ChatScreen measuring its insets
// after the first paint, a rotated phone — each moves the bottom away, and
// a reader who was at the bottom must still be there afterwards.
const followingRef = useRef(following);
followingRef.current = following;
const observed = useRef<HTMLElement | null>(null);
const observer = useRef<ResizeObserver | null>(null);
useLayoutEffect(() => {
const el = scrollRef.current;
if (el === observed.current || typeof ResizeObserver === "undefined") return;
observer.current?.disconnect();
observed.current = el;
const el = owner.current;
if (!el) return;
observer.current = new ResizeObserver(() => {
if (followingRef.current) el.scrollTop = el.scrollHeight;
});
observer.current.observe(el);
if (el.firstElementChild) observer.current.observe(el.firstElementChild);
const top = el.scrollTop;
// An upward gesture must pause even within the near-bottom threshold.
if (draggingScrollbar.current && top < previousTop.current - 1) {
downwardIntent.current = false;
follow(false);
} else if (
top > previousTop.current + 1 &&
(downwardIntent.current || draggingScrollbar.current)
)
follow(isFollowing(el));
previousTop.current = top;
}, [follow]);
const pin = useCallback((smooth = false) => {
const el = owner.current,
end = endRef.current;
if (!el || !end) return;
const page = el === document.scrollingElement;
const bottom = end.getBoundingClientRect().bottom;
const top = page
? el.scrollTop + bottom - window.innerHeight
: el.scrollTop + bottom - el.getBoundingClientRect().top - el.clientTop - el.clientHeight;
// A thread-owned scroller includes its padding below the end marker.
const target = el === scrollRef.current ? el.scrollHeight : top;
el.scrollTo({ top: target, behavior: smooth ? "smooth" : "instant" });
previousTop.current = el.scrollTop;
}, []);
const jumpToBottom = useCallback(() => {
follow(true);
pin(true);
}, [follow, pin]);
// Resolve on every render: an initially empty panel may become scrollable.
useLayoutEffect(() => {
const thread = scrollRef.current;
if (!thread) {
cleanup.current?.();
cleanup.current = null;
owner.current = null;
return;
}
let selected: HTMLElement | null = thread;
while (
selected &&
!(
selected.scrollHeight > selected.clientHeight + 1 &&
/^(auto|scroll)$/.test(getComputedStyle(selected).overflowY)
)
) {
selected = selected.parentElement;
}
selected ??= document.scrollingElement as HTMLElement;
if (selected === owner.current) return;
cleanup.current?.();
owner.current = selected;
previousTop.current = selected.scrollTop;
setPageScroll(selected === document.scrollingElement);
const target = selected === document.scrollingElement ? document : selected;
const pause = () => {
downwardIntent.current = false;
follow(false);
};
const wheel = (event: Event) => {
if ((event as WheelEvent).deltaY < 0) pause();
else if ((event as WheelEvent).deltaY > 0) downwardIntent.current = true;
};
let touchY: number | undefined;
const touchStart = (event: Event) => {
touchY = (event as TouchEvent).touches[0]?.clientY;
};
const touchMove = (event: Event) => {
const y = (event as TouchEvent).touches[0]?.clientY;
if (y !== undefined && touchY !== undefined) {
if (y > touchY) pause();
else if (y < touchY) downwardIntent.current = true;
}
touchY = y;
};
const key = (event: Event) => {
const e = event as KeyboardEvent;
const input = e.target as HTMLElement | null;
if (input?.closest('input, textarea, select, [contenteditable="true"]')) return;
if (["ArrowUp", "PageUp", "Home"].includes(e.key) || (e.key === " " && e.shiftKey)) pause();
else if (["ArrowDown", "PageDown", "End"].includes(e.key) || e.key === " ")
downwardIntent.current = true;
};
const pointer = (event: Event) => {
const e = event as PointerEvent;
const right =
selected === document.scrollingElement
? window.innerWidth
: selected.getBoundingClientRect().right;
if (e.pointerType === "mouse" && e.clientX >= right - 20) {
draggingScrollbar.current = true;
pause();
}
};
const releasePointer = () => {
draggingScrollbar.current = false;
};
window.addEventListener("pointerup", releasePointer, { passive: true });
const events: [string, EventListener][] = [
["pointerdown", pointer],
["scroll", onScroll],
["wheel", wheel],
["touchstart", touchStart],
["touchmove", touchMove],
["keydown", key],
];
for (const [name, listener] of events)
target.addEventListener(name, listener, { passive: true });
const observer =
typeof ResizeObserver === "undefined"
? null
: new ResizeObserver(() => {
if (followingRef.current) pin();
});
observer?.observe(selected);
if (thread.firstElementChild) observer?.observe(thread.firstElementChild);
cleanup.current = () => {
for (const [name, listener] of events) target.removeEventListener(name, listener);
observer?.disconnect();
window.removeEventListener("pointerup", releasePointer);
};
});
useEffect(() => () => observer.current?.disconnect(), []);
useEffect(
() => () => {
cleanup.current?.();
cleanup.current = null;
owner.current = null;
},
[],
);
useLayoutEffect(() => {
if (followingRef.current) pin();
}, [following, pin, ...changes]);
const previous = useRef(grew);
useEffect(() => {
if (grew > previous.current) setFollowing(true);
useLayoutEffect(() => {
if (grew > previous.current) {
follow(true);
pin();
}
previous.current = grew;
}, [grew]);
}, [grew, follow, pin]);
return { scrollRef, endRef, following, onScroll, jumpToBottom };
return { scrollRef, endRef, following, pageScroll, onScroll, jumpToBottom };
}
/**
+11 -1
View File
@@ -462,7 +462,8 @@
flex-direction: column;
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
/* Embedded threads must allow gestures to reach the page scroll owner. */
overscroll-behavior: auto;
padding: 0.5rem 0;
}
.ck-thread-inner {
@@ -720,6 +721,7 @@
/* The thread scrolls the full width (the scrollbar sits at the screen's
edge, and a swipe anywhere moves it); its column keeps a reading measure. */
.ck-screen .ck-thread {
overscroll-behavior: contain;
padding: var(--ck-top-inset, 0px) var(--ck-gutter) calc(var(--ck-bottom-inset, 0px) + 0.75rem);
scroll-padding-top: var(--ck-top-inset, 0px);
scroll-padding-bottom: var(--ck-bottom-inset, 0px);
@@ -1928,3 +1930,11 @@ details.ck-thinking[open] > summary svg {
min-height: 44px;
overflow-wrap: anywhere;
}
/* Embedded page threads keep the return-to-latest action in the viewport. */
.ck-jump-page {
position: fixed;
right: 1rem;
bottom: 1rem;
z-index: 10;
}
+141
View File
@@ -0,0 +1,141 @@
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { extname, join, normalize } from "node:path";
import { fileURLToPath } from "node:url";
import { chromium } from "playwright";
import assert from "node:assert/strict";
const root = fileURLToPath(new URL("..", import.meta.url));
const server = createServer(async (req, res) => {
const path = normalize(join(root, new URL(req.url, "http://localhost").pathname));
if (!path.startsWith(root)) return res.writeHead(403).end();
try {
res
.writeHead(200, {
"content-type":
{ ".html": "text/html", ".js": "text/javascript", ".css": "text/css" }[extname(path)] ??
"application/octet-stream",
})
.end(await readFile(path));
} catch {
res.writeHead(404).end();
}
}).listen(0);
const browser = await chromium.launch(
process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : {},
);
try {
for (const width of [390, 1280])
for (const owner of ["page", "panel", "ancestor"]) {
const page = await browser.newPage({
viewport: { width, height: 844 },
hasTouch: width === 390,
isMobile: width === 390,
});
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.goto(`http://localhost:${server.address().port}/demo/scroll.html?owner=${owner}`);
await page.waitForSelector(".ck-live");
await page.waitForTimeout(400);
const position = () =>
page.evaluate((mode) => {
const el =
mode === "page"
? document.scrollingElement
: mode === "panel"
? document.querySelector(".ck-thread")
: document.querySelector("#fixture-owner");
return { top: el.scrollTop, height: el.scrollHeight, client: el.clientHeight };
}, owner);
const start = await position();
assert.ok(start.top > 100, `${owner} ${width}: starts at latest turn`);
await page.mouse.move(width / 2, 400);
await page.mouse.wheel(0, -450);
await page.waitForTimeout(150);
const reading = await position();
assert.ok(reading.top < start.top - 200, `${owner} ${width}: can scroll upward`);
await page.waitForTimeout(700);
assert.ok(
Math.abs((await position()).top - reading.top) < 3,
`${owner} ${width}: status ticks must not steal reading position`,
);
await page.evaluate(() => document.querySelector("#assistant-turn").click());
await page.waitForTimeout(350);
assert.ok(
Math.abs((await position()).top - reading.top) < 3,
`${owner} ${width}: completed assistant turn must not steal reading position`,
);
await page.setViewportSize({ width, height: 760 });
await page.waitForTimeout(300);
assert.ok(
(await position()).top < start.top - 150,
`${owner} ${width}: resize respects reading`,
);
// Sending a new question is an explicit request to follow the new reply.
await page.evaluate(() => document.querySelector("#user-turn").click());
await page.waitForTimeout(350);
const sent = await position();
assert.ok(
sent.top > reading.top + 200,
`${owner} ${width}: own new question resumes following`,
);
await page.mouse.wheel(0, -25);
await page.waitForTimeout(500);
assert.ok(
(await position()).top < sent.top - 10,
`${owner} ${width}: even a small upward gesture pauses following`,
);
await page.evaluate(() => document.querySelector(".ck-jump").click());
await page.waitForTimeout(650);
const jumped = await position();
assert.ok(
jumped.top > (await position()).top - 3 && jumped.top > reading.top + 200,
`${owner} ${width}: return-to-latest works`,
);
if (width === 390) {
const cdp = await page.context().newCDPSession(page);
await cdp.send("Input.dispatchTouchEvent", {
type: "touchStart",
touchPoints: [{ x: width / 2, y: 180 }],
});
for (let y = 210; y <= 570; y += 30) {
await cdp.send("Input.dispatchTouchEvent", {
type: "touchMove",
touchPoints: [{ x: width / 2, y }],
});
await page.waitForTimeout(25);
}
await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
await page.waitForTimeout(450);
assert.ok(
(await position()).top < jumped.top - 100,
`${owner}: upward touch gesture remains free while statuses change (${jumped.top} -> ${(await position()).top})`,
);
await cdp.detach();
}
await page.locator(".ck-input").fill("A pending synthetic question.");
await page.locator(".ck-input").press("Enter");
await page.waitForFunction(
() => document.getElementById("fixture-sending").textContent === "true",
);
await page.mouse.move(width / 2, 400);
await page.mouse.wheel(0, -420);
await page.waitForTimeout(400);
const pendingReading = await position();
await page.evaluate(() => document.getElementById("finish-send").click());
await page.waitForFunction(() => document.querySelector(".ck-input").value === "");
await page.waitForTimeout(400);
assert.ok(
Math.abs((await position()).top - pendingReading.top) < 4,
`${owner} ${width}: reply completion and focused draft clear preserve reading`,
);
assert.deepEqual(errors, [], `${owner} ${width}: no browser errors`);
await page.close();
console.log(
`PASS ${owner} ${width}: streaming, completed turn, resize, own send and small upward gesture`,
);
}
} finally {
await browser.close();
server.close();
}