mirror of
https://github.com/bitbaum/chatkit.git
synced 2026-12-03 21:07:24 +01:00
On bitbaum /hire/ at 390x844 the contact box (a ChatThread, a receipt link and the Composer) sits mid-page and the document owns the scroll. The reader's first message pinned the end of the thread to the bottom of the viewport, which scrolled the page UP by about 300px and pushed the composer they were typing in below the fold. What a consumer gets: - When the document owns the scroll, following only moves the page down: with the end of the thread already on screen, nothing moves. A thread or panel that scrolls itself is unchanged, and the jump button still goes to the latest turn in either direction, because the reader asked. - --ck-follow-gap (a length, default 0) on the thread's wrapper or any ancestor leaves that much room under the latest turn when the page follows, so a composer under the thread stays in view. The browser resolves it (rem, em, px, calc); unset, negative or invalid is 0. - While the reader has sent nothing on a page, nothing moves, as before. How it is checked: test/browser-scroll.mjs gains a mid-page fixture (demo/scroll.html?owner=page&greeting&below) at 390 and 1280px. With the composer mid-screen the first message does not scroll the page up and the composer stays on screen; as the thread grows past the foot of the screen the page follows and leaves the end at 0px, 10rem, 6em, 90px and (invalid) 0px above the bottom of the viewport, within 2px. Both checks fail on the previous code; every existing scroll case passes unchanged. Claude-Session: https://claude.ai/code/session_019MDtmsSWTTpVpe4wh3v1sb Co-authored-by: Claude <noreply@anthropic.com>
349 lines
14 KiB
JavaScript
349 lines
14 KiB
JavaScript
"use client";
|
|
import { useCallback, useEffect, useLayoutEffect, useRef, useState, } from "react";
|
|
import { isAtBottom, isFollowing } from "../scroll.js";
|
|
/**
|
|
* Copy + a checkmark that resets. Failures are swallowed on purpose (insecure
|
|
* origin, denied permission): the text stays selectable, so a failed copy
|
|
* blocks nothing — `copied` simply never flips.
|
|
*/
|
|
export function useClipboard(resetMs = 1500) {
|
|
const [copied, setCopied] = useState(false);
|
|
const timer = useRef(null);
|
|
useEffect(() => () => {
|
|
if (timer.current)
|
|
clearTimeout(timer.current);
|
|
}, []);
|
|
const copy = useCallback((text) => {
|
|
void Promise.resolve(navigator.clipboard?.writeText(text))
|
|
.then(() => {
|
|
setCopied(true);
|
|
if (timer.current)
|
|
clearTimeout(timer.current);
|
|
timer.current = setTimeout(() => setCopied(false), resetMs);
|
|
})
|
|
.catch(() => { });
|
|
}, [resetMs]);
|
|
return { copied, copy };
|
|
}
|
|
/**
|
|
* `--ck-follow-gap` on the thread's wrapper (or any ancestor), in pixels. The
|
|
* browser resolves the length: a hidden probe takes it as `min-height`, whose
|
|
* computed value is absolute pixels for rem, em, px and calc(). Unset, a
|
|
* percentage, a negative or an invalid value is 0.
|
|
*/
|
|
function followGap(thread) {
|
|
const wrapper = thread?.parentElement ?? thread;
|
|
if (!wrapper)
|
|
return 0;
|
|
if (!getComputedStyle(wrapper).getPropertyValue("--ck-follow-gap").trim())
|
|
return 0;
|
|
const probe = document.createElement("div");
|
|
probe.style.display = "none";
|
|
probe.style.minHeight = "var(--ck-follow-gap)";
|
|
wrapper.appendChild(probe);
|
|
const value = getComputedStyle(probe).minHeight;
|
|
probe.remove();
|
|
const px = value.endsWith("px") ? parseFloat(value) : 0;
|
|
return Number.isFinite(px) && px > 0 ? px : 0;
|
|
}
|
|
/**
|
|
* 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.
|
|
*
|
|
* A greeting on a page is not a conversation yet. While the document owns the
|
|
* scroll and the reader has sent nothing (`grew` is 0), the thread neither
|
|
* moves the page nor offers a way back down: a contact box at the foot of a
|
|
* long page opened that page at the box, past everything above it (bitbaum
|
|
* /hire/ and /builders/, 2026-11-12). The first turn the reader sends starts
|
|
* the following.
|
|
*
|
|
* When the document owns the scroll, following only ever moves the page DOWN,
|
|
* to bring the end of the thread into view, plus `--ck-follow-gap` (a length
|
|
* on the thread's wrapper, default 0) so what the host puts under the thread
|
|
* stays in view too. The jump button may move either way: the reader asked.
|
|
*/
|
|
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 turns = useRef(grew);
|
|
turns.current = grew;
|
|
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 = owner.current;
|
|
if (!el)
|
|
return;
|
|
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));
|
|
// Arriving at the very bottom by any downward scroll (a fling that runs
|
|
// on after the finger lifted, a scroll anchored by the browser) is being
|
|
// back at the latest message, whatever the last touch event said.
|
|
else if (top > previousTop.current + 1 && isAtBottom(el))
|
|
follow(true);
|
|
previousTop.current = top;
|
|
}, [follow]);
|
|
// `asked`: the reader pressed the jump button, so the page may move either
|
|
// way. Following on its own only ever brings a new turn INTO view.
|
|
const pin = useCallback((smooth = false, asked = false) => {
|
|
const el = owner.current, end = endRef.current;
|
|
if (!el || !end)
|
|
return;
|
|
const page = el === document.scrollingElement;
|
|
if (page && turns.current === 0)
|
|
return;
|
|
const bottom = end.getBoundingClientRect().bottom;
|
|
if (page) {
|
|
// A page that scrolls is the host's page: the composer, a receipt and
|
|
// more page sit under the thread. Following never scrolls it UP: on
|
|
// bitbaum /hire/ (2026-11-12) the first message pulled the end of the
|
|
// thread down to the foot of the screen and pushed the composer the
|
|
// reader was typing in below the fold. `--ck-follow-gap` keeps room
|
|
// under the latest turn for what follows it.
|
|
const target = el.scrollTop + bottom - window.innerHeight + followGap(scrollRef.current);
|
|
if (!asked && target <= el.scrollTop)
|
|
return;
|
|
el.scrollTo({ top: target, behavior: smooth ? "smooth" : "instant" });
|
|
}
|
|
else {
|
|
// A thread-owned scroller includes its padding below the end marker.
|
|
const target = el === scrollRef.current
|
|
? el.scrollHeight
|
|
: el.scrollTop + bottom - el.getBoundingClientRect().top - el.clientTop - el.clientHeight;
|
|
el.scrollTo({ top: target, behavior: smooth ? "smooth" : "instant" });
|
|
}
|
|
previousTop.current = el.scrollTop;
|
|
}, []);
|
|
const jumpToBottom = useCallback(() => {
|
|
follow(true);
|
|
pin(true, 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;
|
|
// Some DOM implementations (including server-side test environments) do
|
|
// not expose a scrolling element. A formerly scrollable thread can become
|
|
// unscrollable after its layout changes, so do not assume the fallback
|
|
// exists when resolving its replacement.
|
|
if (!selected) {
|
|
cleanup.current?.();
|
|
cleanup.current = null;
|
|
owner.current = null;
|
|
setPageScroll(false);
|
|
return;
|
|
}
|
|
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;
|
|
};
|
|
// A finger rocks back a pixel or two as it lifts. That last touchmove
|
|
// reads as "scrolling up" and paused following at the bottom, leaving
|
|
// the jump button on screen with nowhere to jump to (OrangeCat on
|
|
// Android, 2026-11-01). Where the gesture ENDS decides: at the very
|
|
// bottom, the reader is following again.
|
|
const touchEnd = (event) => {
|
|
if (event.touches.length === 0 && isAtBottom(selected))
|
|
follow(true);
|
|
};
|
|
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],
|
|
["touchend", touchEnd],
|
|
["touchcancel", touchEnd],
|
|
["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(() => () => {
|
|
cleanup.current?.();
|
|
cleanup.current = null;
|
|
owner.current = null;
|
|
}, []);
|
|
useLayoutEffect(() => {
|
|
if (followingRef.current)
|
|
pin();
|
|
}, [following, pin, ...changes]);
|
|
const previous = useRef(grew);
|
|
useLayoutEffect(() => {
|
|
if (grew > previous.current) {
|
|
follow(true);
|
|
pin();
|
|
}
|
|
previous.current = grew;
|
|
}, [grew, follow, pin]);
|
|
return {
|
|
scrollRef,
|
|
endRef,
|
|
// Nothing to jump to before the reader has said anything on a page.
|
|
following: following || (pageScroll && grew === 0),
|
|
pageScroll,
|
|
onScroll,
|
|
jumpToBottom,
|
|
};
|
|
}
|
|
/**
|
|
* Publishes the VISUAL viewport height as `--ck-viewport-height`.
|
|
*
|
|
* `100dvh` does not shrink when the Android soft keyboard opens; only
|
|
* `visualViewport` does. A chat column sized `100dvh` keeps its height while
|
|
* the keyboard covers the bottom of it, so the composer ends up behind the
|
|
* keyboard (orangecat `ViewportHeightSync`, #1094). Rounded down: sub-pixel
|
|
* heights leave a 1px seam under the composer on some devices.
|
|
*/
|
|
export function useViewportHeight(target, enabled = true) {
|
|
useEffect(() => {
|
|
if (!enabled)
|
|
return;
|
|
const vv = window.visualViewport;
|
|
const el = target?.current ?? document.documentElement;
|
|
const sync = () => el.style.setProperty("--ck-viewport-height", `${Math.floor(vv?.height ?? window.innerHeight)}px`);
|
|
sync();
|
|
vv?.addEventListener("resize", sync);
|
|
vv?.addEventListener("scroll", sync);
|
|
window.addEventListener("orientationchange", sync);
|
|
return () => {
|
|
vv?.removeEventListener("resize", sync);
|
|
vv?.removeEventListener("scroll", sync);
|
|
window.removeEventListener("orientationchange", sync);
|
|
el.style.removeProperty("--ck-viewport-height");
|
|
};
|
|
}, [target, enabled]);
|
|
}
|
|
/** Grow a textarea to its content up to `max` px, keyed on the VALUE so a
|
|
* prefill, a dictated transcript or the clear after send resize it too.
|
|
*
|
|
* An EMPTY box is always one line. Chromium counts the placeholder in
|
|
* `scrollHeight`, so a box measured while it was narrow — mid-transition,
|
|
* inside a sheet still opening — read its wrapped placeholder as content and
|
|
* locked at `max` with nothing typed: half a phone screen of blank composer
|
|
* (Loki, 2026-10-09). And the box re-measures when its WIDTH changes, since a
|
|
* width measured once is wrong after the layout settles or the phone turns. */
|
|
export function useAutoGrow(ref, value, max = 240) {
|
|
useLayoutEffect(() => {
|
|
const el = ref.current;
|
|
if (!el)
|
|
return;
|
|
const fit = () => {
|
|
el.style.height = "auto";
|
|
if (!el.value)
|
|
return;
|
|
el.style.height = `${Math.min(el.scrollHeight, max)}px`;
|
|
};
|
|
fit();
|
|
if (typeof ResizeObserver === "undefined")
|
|
return;
|
|
// Width only: fit() changes the height, and reacting to that would loop.
|
|
let width = el.clientWidth;
|
|
const observer = new ResizeObserver(() => {
|
|
if (el.clientWidth === width)
|
|
return;
|
|
width = el.clientWidth;
|
|
fit();
|
|
});
|
|
observer.observe(el);
|
|
return () => observer.disconnect();
|
|
}, [ref, value, max]);
|
|
}
|
|
//# sourceMappingURL=hooks.js.map
|