fix(webui): stabilize earlier-history loading and reclaim space (#6349)
* fix(webui): retain smoothly revealed history loading headers * refactor(webui): simplify history loading feedback * fix(webui): keep retained history headers clear of preceding text * fix(webui): reclaim completed history loading space * refactor(webui): group history projection handoff with navigation * test(webui): synchronize history motion observations * fix(webui): collapse history completion geometry handoff
This commit is contained in:
1 parent
73a55e0b2f
commit
743c51e81f
24 files changed
+1658
-356
No files matched your search
@@ -8,14 +8,16 @@ interface ThreadHistoryStatusProps {
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
exhausted?: boolean;
|
||||
preview?: boolean;
|
||||
onRetry: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export const ThreadHistoryStatus = forwardRef<HTMLDivElement, ThreadHistoryStatusProps>(function ThreadHistoryStatus({ loading, error, exhausted = false, onRetry, className }, ref) {
|
||||
export const ThreadHistoryStatus = forwardRef<HTMLDivElement, ThreadHistoryStatusProps>(function ThreadHistoryStatus({ loading, error, exhausted = false, preview = false, onRetry, className }, ref) {
|
||||
const { t } = useTranslation();
|
||||
const state = !loading && error ? "error" : !loading && exhausted ? "exhausted" : "loading";
|
||||
const label = t(state === "error" ? "thread.history.retryLabel" : `thread.history.${state}`);
|
||||
const state = loading ? "loading" : error ? "error" : exhausted ? "exhausted" : "ready";
|
||||
const hidden = state === "ready" && !preview;
|
||||
const label = state === "ready" ? undefined : t(state === "error" ? "thread.history.retryLabel" : `thread.history.${state}`);
|
||||
// Blocks adapted from loading.dev (MIT); see THIRD_PARTY_NOTICES.md.
|
||||
const blocks = <span aria-hidden="true" className="thread-history-blocks">
|
||||
{Array.from({ length: 9 }, (_, index) => <span key={index}
|
||||
@@ -25,20 +27,21 @@ export const ThreadHistoryStatus = forwardRef<HTMLDivElement, ThreadHistoryStatu
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("thread-history-status thread-message-row pointer-events-none absolute inset-x-0 top-0 z-10 flex items-center justify-center", className)}
|
||||
className={cn("thread-history-status thread-message-row pointer-events-none absolute inset-x-0 top-0 z-10 flex items-center justify-center", hidden && "invisible", className)}
|
||||
aria-hidden={hidden || undefined}
|
||||
data-state={state}
|
||||
>
|
||||
<div role="status" aria-live="polite" aria-atomic="true">
|
||||
{state === "exhausted" ? (
|
||||
<span className="text-xs">{label}</span>
|
||||
) : (
|
||||
) : state === "ready" ? blocks : (
|
||||
<HoverHint content={state === "error" ? error : label} side="bottom">
|
||||
{loading ? (
|
||||
<div tabIndex={0} aria-label={label} className="thread-history-control pointer-events-auto rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||
{blocks}<span className="sr-only">{label}</span>
|
||||
</div>
|
||||
) : (
|
||||
<button type="button" aria-label={state === "error" ? label : t("thread.loadEarlier")} onClick={onRetry}
|
||||
<button type="button" aria-label={label} onClick={onRetry}
|
||||
className="thread-history-control pointer-events-auto rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||
{blocks}<span className="sr-only">{label}</span>
|
||||
</button>
|
||||
|
||||
@@ -23,6 +23,8 @@ import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage }
|
||||
interface ThreadMessagesProps {
|
||||
messages: UIMessage[];
|
||||
beforeMessages?: ReactNode;
|
||||
beforeUnit?: { key: string; content: ReactNode };
|
||||
topInset?: number;
|
||||
afterUserMessage?: (message: UIMessage) => ReactNode;
|
||||
afterMessages?: ReactNode;
|
||||
temporary?: boolean;
|
||||
@@ -81,6 +83,8 @@ export function assistantForkFlags(units: DisplayUnit[]): boolean[] {
|
||||
export function ThreadMessages({
|
||||
messages,
|
||||
beforeMessages,
|
||||
beforeUnit,
|
||||
topInset = 0,
|
||||
afterUserMessage,
|
||||
afterMessages,
|
||||
temporary = false,
|
||||
@@ -174,6 +178,11 @@ export function ThreadMessages({
|
||||
setOpenContextBlockKey((current) => open ? key : current === key ? null : current);
|
||||
}, []);
|
||||
let nextUserIndex = hiddenUserMessageCount;
|
||||
const preludeIndex = Math.max(0, beforeUnit ? unitKeys.indexOf(beforeUnit.key) : 0);
|
||||
const inset = topInset > 0 ? <div aria-hidden style={{ height: topInset }} /> : null;
|
||||
const preludeInset = preludeIndex === 0 ? inset : null;
|
||||
const renderPrelude = (prefix: ReactNode, marginTop?: string) => prefix || preludeInset || beforeMessages
|
||||
? <div key="thread-prelude" className={cn("flow-root", marginTop)}>{prefix}{preludeInset}{beforeMessages}</div> : null;
|
||||
|
||||
return (
|
||||
<div ref={messageListRef} className="flex w-full flex-col">
|
||||
@@ -181,8 +190,10 @@ export function ThreadMessages({
|
||||
containerRef={messageListRef}
|
||||
onQuoteSelection={onQuoteSelection}
|
||||
/>
|
||||
{beforeMessages}
|
||||
{units.map((unit, index) => {
|
||||
{[
|
||||
preludeIndex > 0 ? <Fragment key="top-inset">{inset}</Fragment> : null,
|
||||
units.length === 0 ? renderPrelude(null) : null,
|
||||
...units.flatMap((unit, index) => {
|
||||
const next = units[index + 1];
|
||||
const hasBodyBelow =
|
||||
unit.type === "activity"
|
||||
@@ -233,14 +244,17 @@ export function ThreadMessages({
|
||||
&& unit.message.deliveryStatus !== "failed"
|
||||
) nextUserIndex += 1;
|
||||
|
||||
return (
|
||||
<Fragment key={unitKeys[index]}>
|
||||
const prefix = beforeUnit?.key === unitKeys[index] ? beforeUnit.content : null;
|
||||
const prelude = index === preludeIndex ? renderPrelude(prefix, marginTop) : null;
|
||||
return [
|
||||
prelude,
|
||||
<Fragment key={`unit:${unitKeys[index]}`}>
|
||||
<ThreadDisplayUnit
|
||||
key={unitKeys[index]}
|
||||
unitKey={unitKeys[index]}
|
||||
unit={unit}
|
||||
mobileActions={mobileActions}
|
||||
marginTop={marginTop}
|
||||
marginTop={prelude ? "" : marginTop}
|
||||
userPromptId={userPromptId}
|
||||
hasBodyBelow={hasBodyBelow}
|
||||
suppressActivity={suppressActivity}
|
||||
@@ -279,9 +293,9 @@ export function ThreadMessages({
|
||||
{unit.type === "message" && unit.message.role === "user" ? (
|
||||
afterUserMessage?.(unit.message)
|
||||
) : null}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</Fragment>,
|
||||
];
|
||||
})]}
|
||||
{afterMessages}
|
||||
{pendingActivity ? (
|
||||
<div className={cn("thread-message-row", units.length > 0 && "mt-5")}>
|
||||
|
||||
@@ -900,6 +900,7 @@ export function ThreadShell({
|
||||
activeHistoryKeyRef.current = historyKey;
|
||||
const currentUiMessagesRef = useRef<UIMessage[] | null>(null);
|
||||
const uiRevisionRef = useRef(0);
|
||||
const olderPageStartRef = useRef<{ historyKey: string; client: typeof client; visibleFirstId: string | null } | null>(null);
|
||||
const showTemporaryChatControl =
|
||||
!hideHeader && !session && !loading && !!onTemporaryChatEnabledChange;
|
||||
|
||||
@@ -945,6 +946,35 @@ export function ThreadShell({
|
||||
const promptNavigation = usePromptHistory(historyKey, historyVersion, displayMessages);
|
||||
const updateNavigationMessages = promptNavigation.updateMessages;
|
||||
|
||||
const olderPageProjectionPending = Boolean(
|
||||
olderPageStartRef.current?.historyKey === historyKey
|
||||
&& olderPageStartRef.current.client === client
|
||||
&& !loadingOlder
|
||||
&& !olderError
|
||||
&& normalizedHistory[0]?.id !== olderPageStartRef.current.visibleFirstId
|
||||
&& displayMessages[0]?.id !== normalizedHistory[0]?.id,
|
||||
);
|
||||
useLayoutEffect(() => {
|
||||
const pending = olderPageStartRef.current;
|
||||
if (pending && (pending.historyKey !== historyKey || pending.client !== client)) {
|
||||
olderPageStartRef.current = null;
|
||||
}
|
||||
if (!historyKey) {
|
||||
olderPageStartRef.current = null;
|
||||
} else if (loadingOlder) {
|
||||
// The request may finish before this shell commits the rendered projection.
|
||||
if (!olderPageStartRef.current) {
|
||||
olderPageStartRef.current = {
|
||||
historyKey,
|
||||
client,
|
||||
visibleFirstId: normalizedHistory[0]?.id ?? null,
|
||||
};
|
||||
}
|
||||
} else if (olderError || !olderPageProjectionPending) {
|
||||
olderPageStartRef.current = null;
|
||||
}
|
||||
}, [client, displayMessages, historyKey, loadingOlder, olderError, olderPageProjectionPending, normalizedHistory]);
|
||||
|
||||
const loadTraceDetails = useCallback(async (refs: string[]) => {
|
||||
const requestKey = historyKey;
|
||||
if (!requestKey) return;
|
||||
@@ -2101,7 +2131,7 @@ export function ThreadShell({
|
||||
slashCommands={availableSlashCommands}
|
||||
forkBoundaryMessageCount={forkBoundaryMessageCount}
|
||||
hasMoreBefore={hasMoreBefore}
|
||||
loadingOlder={loadingOlder}
|
||||
loadingOlder={loadingOlder || olderPageProjectionPending}
|
||||
olderError={olderError}
|
||||
userMessageOffset={userMessageOffset}
|
||||
onLoadOlder={loadOlder}
|
||||
|
||||
@@ -18,7 +18,7 @@ import { DiagramScope } from "@/components/markdown-diagrams/context";
|
||||
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
|
||||
import { isAgentActivityMember } from "@/components/thread/AgentActivityCluster";
|
||||
import { ThreadCameraController } from "@/components/thread/thread-camera";
|
||||
import { ThreadHistorySpring } from "@/components/thread/thread-history-spring";
|
||||
import { HISTORY_HOLD_PX, ThreadHistorySpring, type HistoryRevealPhase } from "@/components/thread/thread-history-spring";
|
||||
import {
|
||||
ThreadMotionCoordinator,
|
||||
type ThreadMotionGeometry,
|
||||
@@ -93,7 +93,7 @@ interface HistoryScrollAnchor {
|
||||
const THREAD_DISPLAY_UNIT_SELECTOR = "[data-thread-display-unit]";
|
||||
|
||||
function promptTopInset(scroller: HTMLElement): number {
|
||||
const padding = Number.parseFloat(getComputedStyle(scroller).paddingTop);
|
||||
const padding = Number.parseFloat(getComputedStyle(scroller).scrollPaddingTop);
|
||||
return Number.isFinite(padding) ? padding : PROMPT_TOP_INSET_PX;
|
||||
}
|
||||
|
||||
@@ -236,8 +236,16 @@ function readSoftKeyboardInsetBottom(container: HTMLElement | null): number {
|
||||
return inset >= SOFT_KEYBOARD_MIN_INSET_PX ? Math.ceil(inset) : 0;
|
||||
}
|
||||
|
||||
function setHistoryStatusTravel(element: HTMLDivElement | null, distance: number): void {
|
||||
element?.style.setProperty("--history-pull", `${distance}px`);
|
||||
function setHistoryPresentation(
|
||||
scroller: HTMLDivElement | null,
|
||||
status: HTMLDivElement | null,
|
||||
slot: HTMLDivElement | null,
|
||||
distance: number,
|
||||
): void {
|
||||
// A retained inline slot replaces the same amount of presentation travel.
|
||||
const travel = distance - (slot ? HISTORY_HOLD_PX : 0);
|
||||
if (scroller) scroller.style.transform = travel ? `translateY(${travel}px)` : "";
|
||||
status?.style.setProperty("--history-pull", `${distance}px`);
|
||||
}
|
||||
|
||||
export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProps>(function ThreadViewport({
|
||||
@@ -279,8 +287,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
const activeTurnId = historyWindow ? null : liveTurnId;
|
||||
const forkBoundaryMessageCount = historyWindow ? historyWindow.forkBoundaryMessageCount : latestForkBoundary;
|
||||
const hasMoreBefore = historyWindow?.hasMoreBefore ?? latestHasMoreBefore;
|
||||
const loadingOlder = historyWindow ? navigation!.loading : latestLoadingOlder;
|
||||
const olderError = historyWindow ? navigation!.error : latestOlderError;
|
||||
const loadingOlder = historyWindow ? navigation!.operation === "older" && navigation!.loading : latestLoadingOlder;
|
||||
const olderError = historyWindow ? navigation!.operation === "older" ? navigation!.error : null : latestOlderError;
|
||||
const userMessageOffset = historyWindow?.userMessageOffset ?? latestUserOffset;
|
||||
const onLoadOlder = historyWindow ? navigation!.older : loadLatestOlder;
|
||||
const scrollRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -299,10 +307,17 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
const restoreScrollAfterPrependRef =
|
||||
useRef<{ height: number; top: number } | null>(null);
|
||||
const historyScrollAnchorRef = useRef<HistoryScrollAnchor | null>(null);
|
||||
const previousLoadingOlderRef = useRef(loadingOlder);
|
||||
const composerDockHeightRef = useRef(0);
|
||||
const [atBottom, setAtBottom] = useState(true);
|
||||
const [atHistoryTop, setAtHistoryTop] = useState(false);
|
||||
const [historyFeedbackActive, setHistoryFeedbackActive] = useState(false);
|
||||
const [historyPhase, setHistoryPhase] = useState<HistoryRevealPhase>("hidden");
|
||||
const historyPhaseRef = useRef(historyPhase);
|
||||
const [historySlotKey, setHistorySlotKey] = useState<string | null>(null);
|
||||
const historySlotCompleted = previousLoadingOlderRef.current && !loadingOlder && !olderError && historySlotKey !== null;
|
||||
const retainedHistorySlotKey = historySlotCompleted ? null : historySlotKey;
|
||||
const [showHistoryExhausted, setShowHistoryExhausted] = useState(false);
|
||||
const historySlotRef = useRef<HTMLDivElement | null>(null);
|
||||
const historyInputRef = useRef<"touch" | "other">("other");
|
||||
const historyTouchRef = useRef<{
|
||||
lastY: number; startX: number; startY: number; pulling: boolean; horizontal: boolean;
|
||||
@@ -312,15 +327,15 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
const historySpringRef = useRef<ThreadHistorySpring | null>(null);
|
||||
if (historySpringRef.current === null) {
|
||||
historySpringRef.current = new ThreadHistorySpring({
|
||||
onFeedbackChange: setHistoryFeedbackActive,
|
||||
onPhaseChange: (phase) => {
|
||||
const previous = historyPhaseRef.current;
|
||||
historyPhaseRef.current = phase;
|
||||
setHistoryPhase(phase);
|
||||
if (phase === "hidden" && previous === "feedback") setShowHistoryExhausted(false);
|
||||
},
|
||||
onUpdate: (distance) => {
|
||||
// Presentation travel never becomes a scrollTop destination or an anchor correction.
|
||||
historyDistanceRef.current = distance;
|
||||
if (messageRegionRef.current) {
|
||||
messageRegionRef.current.style.transform = distance > 0 ? `translateY(${distance}px)` : "";
|
||||
}
|
||||
// Keep animated custom properties out of the inherited message tree.
|
||||
setHistoryStatusTravel(historyStatusRef.current, distance);
|
||||
setHistoryPresentation(messageRegionRef.current, historyStatusRef.current, historySlotRef.current, distance);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -329,11 +344,15 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
// React can reuse this div for the empty state; release imperative styles with the ref.
|
||||
messageRegionRef.current?.style.removeProperty("transform");
|
||||
messageRegionRef.current = element;
|
||||
if (element && historyDistanceRef.current > 0) element.style.transform = `translateY(${historyDistanceRef.current}px)`;
|
||||
setHistoryPresentation(element, historyStatusRef.current, historySlotRef.current, historyDistanceRef.current);
|
||||
}, []);
|
||||
const setHistoryStatus = useCallback((element: HTMLDivElement | null) => {
|
||||
historyStatusRef.current = element;
|
||||
setHistoryStatusTravel(element, historyDistanceRef.current);
|
||||
setHistoryPresentation(messageRegionRef.current, element, historySlotRef.current, historyDistanceRef.current);
|
||||
}, []);
|
||||
const setHistorySlot = useCallback((element: HTMLDivElement | null) => {
|
||||
historySlotRef.current = element;
|
||||
setHistoryPresentation(messageRegionRef.current, historyStatusRef.current, element, historyDistanceRef.current);
|
||||
}, []);
|
||||
const [composerDockHeight, setComposerDockHeight] = useState(0);
|
||||
const [keyboardInsetBottom, setKeyboardInsetBottom] = useState(0);
|
||||
@@ -391,10 +410,6 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
? messageRegionRef.current
|
||||
: viewportFrameRef.current;
|
||||
}, [hasMessages]);
|
||||
useLayoutEffect(() => {
|
||||
const scroller = scrollRef.current;
|
||||
historySpringRef.current?.setLoading(Boolean(conversationReady && scroller && loadingOlder && !olderError && scroller.scrollTop <= 1));
|
||||
}, [conversationKey, conversationReady, hasMessages, loadingOlder, olderError]);
|
||||
const visibleMessages = useMemo(
|
||||
() => windowMessages(messages, visibleMessageCount),
|
||||
[messages, visibleMessageCount],
|
||||
@@ -443,7 +458,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
}
|
||||
historyScrollAnchorRef.current = {
|
||||
key,
|
||||
offsetTop: element.getBoundingClientRect().top - viewport.top,
|
||||
// Normalize out the reveal lease, even when reading above its inline slot.
|
||||
offsetTop: element.getBoundingClientRect().top - viewport.top
|
||||
- (historySlotRef.current ? HISTORY_HOLD_PX : 0),
|
||||
};
|
||||
return true;
|
||||
}, []);
|
||||
@@ -463,7 +480,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
|
||||
const nextOffset =
|
||||
element.getBoundingClientRect().top
|
||||
- scroller.getBoundingClientRect().top;
|
||||
- scroller.getBoundingClientRect().top
|
||||
- (historySlotRef.current ? HISTORY_HOLD_PX : 0);
|
||||
const delta = nextOffset - anchor.offsetTop;
|
||||
if (Math.abs(delta) < 0.5) return true;
|
||||
const maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight);
|
||||
@@ -472,8 +490,29 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
return true;
|
||||
}, []);
|
||||
|
||||
const resetHistoryHeader = useCallback(() => {
|
||||
setHistorySlotKey(null);
|
||||
historySpringRef.current?.reset();
|
||||
}, []);
|
||||
|
||||
const holdHistoryHeader = useCallback(() => {
|
||||
// A request at a new boundary supersedes the old slot. Mid-page retry
|
||||
// keeps its original boundary, never a hit-tested answer or activity row.
|
||||
if (!historySlotRef.current || (scrollRef.current && scrollRef.current.scrollTop <= 1)) {
|
||||
const unit = messageContentRef.current?.querySelector<HTMLElement>(THREAD_DISPLAY_UNIT_SELECTOR);
|
||||
if (unit?.dataset.threadDisplayUnit) setHistorySlotKey(unit.dataset.threadDisplayUnit);
|
||||
}
|
||||
historySpringRef.current?.hold();
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
// Replaced history windows cannot retain a slot for an unmounted boundary.
|
||||
if (retainedHistorySlotKey && !historySlotRef.current) resetHistoryHeader();
|
||||
}, [retainedHistorySlotKey, resetHistoryHeader, visibleMessages]);
|
||||
|
||||
const scrollToBottomNow = useCallback((smooth = false) => {
|
||||
historyScrollAnchorRef.current = null;
|
||||
resetHistoryHeader();
|
||||
const el = scrollRef.current;
|
||||
const marker = bottomRef.current;
|
||||
const behavior: ScrollBehavior = smooth ? "smooth" : "auto";
|
||||
@@ -488,7 +527,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
marker.scrollIntoView({ block: "end", behavior });
|
||||
}
|
||||
setAtBottom(true);
|
||||
}, []);
|
||||
}, [resetHistoryHeader]);
|
||||
|
||||
const scrollToBottom = useCallback(
|
||||
(smooth = false, options?: { force?: boolean }) => {
|
||||
@@ -501,6 +540,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
);
|
||||
|
||||
const loadEarlierMessages = useCallback(() => {
|
||||
if (loadingOlder || navigation?.loading) return;
|
||||
const el = scrollRef.current;
|
||||
if (el) {
|
||||
if (captureHistoryScrollAnchor()) {
|
||||
@@ -520,7 +560,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (hasMoreBefore && onLoadOlder && !loadingOlder) {
|
||||
if (hasMoreBefore && onLoadOlder) {
|
||||
holdHistoryHeader();
|
||||
setVisibleMessageCount((count) => count + HISTORY_WINDOW_INCREMENT);
|
||||
void onLoadOlder();
|
||||
}
|
||||
@@ -528,8 +569,10 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
captureHistoryScrollAnchor,
|
||||
hasMoreBefore,
|
||||
hiddenMessageCount,
|
||||
holdHistoryHeader,
|
||||
loadingOlder,
|
||||
messages.length,
|
||||
navigation?.loading,
|
||||
onLoadOlder,
|
||||
]);
|
||||
|
||||
@@ -548,16 +591,11 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
const prompt = scrollEl ? findPromptElement(scrollEl, promptId) : null;
|
||||
if (!scrollEl || !prompt) return false;
|
||||
historyScrollAnchorRef.current = null;
|
||||
resetHistoryHeader();
|
||||
setAtBottom(false);
|
||||
const maxScrollTop = Math.max(0, scrollEl.scrollHeight - scrollEl.clientHeight);
|
||||
threadMotionRef.current?.navigateHistoryTo(
|
||||
Math.min(
|
||||
maxScrollTop,
|
||||
Math.max(0, promptTop(scrollEl, prompt) - promptTopInset(scrollEl)),
|
||||
),
|
||||
);
|
||||
threadMotionRef.current?.navigateHistoryToPrompt(promptId);
|
||||
return true;
|
||||
}, []);
|
||||
}, [resetHistoryHeader]);
|
||||
|
||||
const jumpToUserPrompt = useCallback((promptId: string) => {
|
||||
// A local destination also supersedes an in-flight remote jump.
|
||||
@@ -654,7 +692,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
lastConversationKeyRef.current = conversationKey;
|
||||
historyTouchRef.current = null;
|
||||
historyInputRef.current = "other";
|
||||
historySpringRef.current?.reset();
|
||||
resetHistoryHeader();
|
||||
conversationHandoffAnimationRef.current?.cancel();
|
||||
conversationHandoffAnimationRef.current = null;
|
||||
conversationHandoffPendingRef.current = true;
|
||||
@@ -663,6 +701,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
restoreScrollAfterPrependRef.current = null;
|
||||
threadMotionRef.current?.reset();
|
||||
setAtBottom(true);
|
||||
setShowHistoryExhausted(false);
|
||||
setVisibleMessageCount(INITIAL_HISTORY_WINDOW);
|
||||
|
||||
const surface = hasMessages ? messageRegionRef.current : emptyStateRef.current;
|
||||
@@ -677,7 +716,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
fill: "forwards",
|
||||
},
|
||||
);
|
||||
}, [conversationKey, hasMessages]);
|
||||
}, [conversationKey, hasMessages, resetHistoryHeader]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!conversationReady) {
|
||||
@@ -722,6 +761,18 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
});
|
||||
}, [activeTurnId, activeTurnStartedHere, conversationReady, messages]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const wasLoading = previousLoadingOlderRef.current;
|
||||
previousLoadingOlderRef.current = loadingOlder;
|
||||
if (!wasLoading || loadingOlder || olderError || !historySlotKey) return;
|
||||
// The completed render already removed the slot. Rebase the saved anchor
|
||||
// by its live presentation travel before the single final-geometry read.
|
||||
const anchor = historyScrollAnchorRef.current;
|
||||
if (anchor) anchor.offsetTop += historyDistanceRef.current;
|
||||
setShowHistoryExhausted(historyExhausted);
|
||||
resetHistoryHeader();
|
||||
}, [loadingOlder, olderError, historySlotKey, historyExhausted, resetHistoryHeader]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const pending = restoreScrollAfterPrependRef.current;
|
||||
const el = scrollRef.current;
|
||||
@@ -735,7 +786,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
Math.max(0, pending.top + delta),
|
||||
);
|
||||
threadMotionRef.current?.jumpTo(nextTop);
|
||||
}, [reconcileHistoryScrollAnchor, visibleMessages.length, messages]);
|
||||
}, [reconcileHistoryScrollAnchor, visibleMessages.length, messages, loadingOlder]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const promptId = pendingPromptJumpRef.current;
|
||||
@@ -768,6 +819,13 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
scrollToBottom,
|
||||
]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
// A request commits temporary space; successful completion reclaims it below.
|
||||
if (conversationReady && loadingOlder && scrollRef.current?.scrollTop === 0 && !historySlotRef.current) {
|
||||
holdHistoryHeader();
|
||||
}
|
||||
}, [conversationReady, loadingOlder, holdHistoryHeader]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!conversationReady || !conversationHandoffPendingRef.current) return;
|
||||
conversationHandoffPendingRef.current = false;
|
||||
@@ -843,7 +901,6 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
const onScroll = (allowHistoryLoad = true) => {
|
||||
setAtHistoryTop(el.scrollTop <= 1);
|
||||
if (el.scrollTop > 1) historySpringRef.current?.leaveBoundary();
|
||||
else historySpringRef.current?.setLoading(conversationReady && loadingOlder && !olderError);
|
||||
const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
|
||||
const near = distance < NEAR_BOTTOM_PX;
|
||||
const owner = threadMotionRef.current?.observeScroll(near) ?? "automatic";
|
||||
@@ -865,15 +922,15 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
const handleScroll = () => onScroll(true);
|
||||
const atHistoryBoundary = () => el.scrollTop <= 1 && messages.length > 0 && conversationReady
|
||||
&& !pendingConversationScrollRef.current;
|
||||
const canLoadAtTop = () => atHistoryBoundary() && !loadingOlder
|
||||
&& (hiddenMessageCount > 0 || (hasMoreBefore && !olderError));
|
||||
const canLoadAtTop = () => atHistoryBoundary() && !loadingOlder && !navigation?.loading
|
||||
&& (hiddenMessageCount > 0 || hasMoreBefore);
|
||||
const handleDirectionalInput = (
|
||||
direction: ThreadScrollDirection | null,
|
||||
) => {
|
||||
if (!direction) return;
|
||||
if (direction === "forward" && historyWindow?.hasMoreAfter
|
||||
&& el.scrollHeight - el.scrollTop - el.clientHeight < HISTORY_PREFETCH_MIN_PX
|
||||
&& !navigation?.loading && !navigation?.error) {
|
||||
&& !navigation?.loading) {
|
||||
captureHistoryScrollAnchor();
|
||||
navigation?.newer();
|
||||
}
|
||||
@@ -888,6 +945,13 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
direction === "forward",
|
||||
);
|
||||
};
|
||||
const prepareHistoryPull = () => {
|
||||
if (loadingOlder || navigation?.loading) return;
|
||||
const first = messageContentRef.current?.querySelector<HTMLElement>(THREAD_DISPLAY_UNIT_SELECTOR);
|
||||
// A retained header belongs to the page boundary where it was opened,
|
||||
// not to a newer boundary reached by scrolling through prepended history.
|
||||
if (historySlotKey && first?.dataset.threadDisplayUnit !== historySlotKey) resetHistoryHeader();
|
||||
};
|
||||
const handleWheel = (event: WheelEvent) => {
|
||||
if (
|
||||
event.defaultPrevented
|
||||
@@ -901,13 +965,13 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
const unit = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? 16
|
||||
: event.deltaMode === WheelEvent.DOM_DELTA_PAGE ? el.clientHeight : 1;
|
||||
if (event.deltaY < 0) {
|
||||
prepareHistoryPull();
|
||||
yieldCameraToUser();
|
||||
setAtHistoryTop(true);
|
||||
const first = historySpringRef.current?.wheel(-event.deltaY * unit);
|
||||
if (first && canLoadAtTop()) loadEarlierMessages();
|
||||
if ((first || olderError) && canLoadAtTop()) loadEarlierMessages();
|
||||
return;
|
||||
}
|
||||
if (historyDistanceRef.current > 0) historySpringRef.current?.wheel(-event.deltaY * unit);
|
||||
}
|
||||
handleDirectionalInput(directionFromDelta(event.deltaY));
|
||||
};
|
||||
@@ -952,6 +1016,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
if (gesture.horizontal) return;
|
||||
if (gesture.pulling || (atHistoryBoundary() && delta < 0 && hiddenMessageCount === 0)) {
|
||||
if (!gesture.pulling) {
|
||||
prepareHistoryPull();
|
||||
historySpringRef.current?.startTouch();
|
||||
gesture.pulling = true;
|
||||
}
|
||||
@@ -991,7 +1056,6 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
}
|
||||
if (isKeyboardControl(event.target as Element | null)) return;
|
||||
historyInputRef.current = "other";
|
||||
historySpringRef.current?.leaveBoundary();
|
||||
handleDirectionalInput(keyboardScrollDirection(event));
|
||||
};
|
||||
el.addEventListener("scroll", handleScroll, { passive: true });
|
||||
@@ -1024,10 +1088,27 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
messages.length,
|
||||
olderError,
|
||||
yieldCameraToUser,
|
||||
historySlotKey,
|
||||
historyWindow,
|
||||
navigation,
|
||||
resetHistoryHeader,
|
||||
]);
|
||||
|
||||
const navigationStatus = navigation?.operation !== "older" && Boolean(navigation?.loading || navigation?.error);
|
||||
const showHistoryStatus = !historySlotCompleted && !navigationStatus && messages.length > 0 && conversationReady
|
||||
&& (atHistoryTop && (!historyExhausted || showHistoryExhausted) || historyPhase !== "hidden" || loadingOlder);
|
||||
const historyStatus = showHistoryStatus ? (
|
||||
<ThreadHistoryStatus
|
||||
ref={setHistoryStatus}
|
||||
loading={loadingOlder}
|
||||
error={olderError}
|
||||
exhausted={historyExhausted}
|
||||
preview={historyPhase === "feedback"}
|
||||
onRetry={loadEarlierMessages}
|
||||
className={!retainedHistorySlotKey && !(historyExhausted && showHistoryExhausted) ? cn("thread-history-reveal", historyPhase === "feedback" && "thread-history-feedback") : undefined}
|
||||
/>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<div className="thread-viewport relative flex min-h-0 flex-1 overflow-hidden">
|
||||
<div
|
||||
@@ -1062,7 +1143,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
data-testid="thread-message-region"
|
||||
className={cn(
|
||||
"thread-message-viewport thread-viewport-scrollbar row-start-1 flex min-h-0 min-w-0 flex-col",
|
||||
"scroll-auto justify-start overflow-x-hidden overscroll-y-none pb-0 pt-12",
|
||||
"scroll-auto justify-start overflow-x-hidden overscroll-y-none pb-0 scroll-pt-12",
|
||||
"[overflow-anchor:none] [scrollbar-width:none]",
|
||||
"[&::-webkit-scrollbar]:hidden",
|
||||
hasVerticalOverflow ? "overflow-y-auto" : "overflow-hidden",
|
||||
@@ -1072,6 +1153,12 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
<DiagramScope identity={conversationKey}>
|
||||
<SubagentThreadMessages
|
||||
messages={visibleMessages}
|
||||
topInset={PROMPT_TOP_INSET_PX}
|
||||
beforeUnit={retainedHistorySlotKey ? { key: retainedHistorySlotKey, content: (
|
||||
<div ref={setHistorySlot} className="thread-history-slot relative" style={{ height: HISTORY_HOLD_PX }}>
|
||||
{historyStatus}
|
||||
</div>
|
||||
) } : undefined}
|
||||
temporary={temporary}
|
||||
isStreaming={isStreaming}
|
||||
activeTurnId={activeTurnId}
|
||||
@@ -1147,17 +1234,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
{navigation && (navigation.loading || navigation.error) ? (
|
||||
<ThreadHistoryStatus ref={setHistoryStatus} loading={navigation.loading} error={navigation.error} onRetry={navigation.retry} />
|
||||
) : messages.length > 0 && conversationReady && ((atHistoryTop && (!historyExhausted || historyFeedbackActive)) || loadingOlder || olderError) ? (
|
||||
<ThreadHistoryStatus
|
||||
ref={setHistoryStatus}
|
||||
loading={loadingOlder}
|
||||
exhausted={historyExhausted}
|
||||
error={olderError}
|
||||
onRetry={loadEarlierMessages}
|
||||
/>
|
||||
) : null}
|
||||
{!retainedHistorySlotKey ? historyStatus : null}
|
||||
{navigationStatus && navigation ? <ThreadHistoryStatus loading={navigation.loading}
|
||||
error={navigation.error} onRetry={navigation.retry} /> : null}
|
||||
{!hasMessages ? <div ref={bottomRef} aria-hidden className="h-px" /> : null}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,168 +1,170 @@
|
||||
import type { ThreadCameraScheduler } from "@/components/thread/thread-camera";
|
||||
import { animate, motionValue, type AnimationPlaybackControls, type MotionValue } from "motion";
|
||||
|
||||
export const HISTORY_PULL_LIMIT_PX = 80;
|
||||
export const HISTORY_PULL_TRIGGER_PX = 42;
|
||||
const LOADING_POCKET_PX = 20;
|
||||
export const HISTORY_HOLD_PX = 48;
|
||||
export const HISTORY_PULL_TRIGGER_PX = 56;
|
||||
const RESISTANCE_LENGTH_PX = 120;
|
||||
const FREQUENCY = 22;
|
||||
const DAMPING_RATIO = 0.78;
|
||||
|
||||
export type HistoryRevealPhase = "hidden" | "feedback" | "held";
|
||||
|
||||
interface HistorySpringOptions {
|
||||
onUpdate: (distance: number) => void;
|
||||
onFeedbackChange: (active: boolean) => void;
|
||||
scheduler?: ThreadCameraScheduler;
|
||||
onPhaseChange: (phase: HistoryRevealPhase) => void;
|
||||
prefersReducedMotion?: () => boolean;
|
||||
}
|
||||
|
||||
/** Presentation only: the thread camera remains the sole scroll-position owner. */
|
||||
/** Presentation only: Motion owns spring integration; the thread camera remains the sole scroll-position owner. */
|
||||
export class ThreadHistorySpring {
|
||||
private readonly options: HistorySpringOptions;
|
||||
private readonly scheduler: ThreadCameraScheduler;
|
||||
private readonly reducedMotion: () => boolean;
|
||||
private frame: number | null = null;
|
||||
private timestamp: number | null = null;
|
||||
private distance = 0;
|
||||
private velocity = 0;
|
||||
private loading = false;
|
||||
private readonly value: MotionValue<number> = motionValue(0);
|
||||
private animation: AnimationPlaybackControls | null = null;
|
||||
private destination: number | null = null;
|
||||
private animationGeneration = 0;
|
||||
private phase: HistoryRevealPhase = "hidden";
|
||||
private dragging = false;
|
||||
private travel = 0;
|
||||
private wheelLatched = false;
|
||||
private feedbackActive = false;
|
||||
|
||||
constructor(options: HistorySpringOptions) {
|
||||
this.options = options;
|
||||
this.scheduler = options.scheduler ?? {
|
||||
request: (callback) => window.requestAnimationFrame(callback),
|
||||
cancel: (id) => window.cancelAnimationFrame(id),
|
||||
now: () => performance.now(),
|
||||
};
|
||||
const motionPreference = typeof window !== "undefined" && typeof window.matchMedia === "function"
|
||||
const preference = typeof window !== "undefined" && typeof window.matchMedia === "function"
|
||||
? window.matchMedia("(prefers-reduced-motion: reduce)") : null;
|
||||
this.reducedMotion = options.prefersReducedMotion ?? (() => motionPreference?.matches ?? false);
|
||||
this.reducedMotion = options.prefersReducedMotion ?? (() => preference?.matches ?? false);
|
||||
this.value.on("change", this.publish);
|
||||
}
|
||||
|
||||
setLoading(loading: boolean): void {
|
||||
if (this.loading === loading) return;
|
||||
this.loading = loading;
|
||||
if (!this.dragging) this.animate();
|
||||
hold(): void {
|
||||
this.wheelLatched = true;
|
||||
this.setPhase("held");
|
||||
this.animateTo(HISTORY_HOLD_PX);
|
||||
}
|
||||
|
||||
wheel(travel: number): boolean {
|
||||
if (this.dragging) return false;
|
||||
if (this.dragging || travel === 0) return false;
|
||||
const first = !this.wheelLatched && travel > 0;
|
||||
this.wheelLatched = true;
|
||||
if (travel > 0) this.setFeedbackActive(true);
|
||||
// Wheel packets add pressure to one live spring, without a position jump.
|
||||
const speed = FREQUENCY * (travel > 0
|
||||
? HISTORY_PULL_LIMIT_PX - Math.max(0, this.distance)
|
||||
: -Math.max(0, this.distance));
|
||||
this.velocity += (speed - this.velocity) * (1 - Math.exp(-Math.abs(travel) / RESISTANCE_LENGTH_PX));
|
||||
this.animate();
|
||||
if (travel > 0) {
|
||||
this.wheelLatched = true;
|
||||
if (this.phase !== "held") this.setPhase("feedback");
|
||||
}
|
||||
const pressure = 1 - Math.exp(-Math.abs(travel) / RESISTANCE_LENGTH_PX);
|
||||
const current = this.boundedValue();
|
||||
const pressured = current + ((travel > 0 ? HISTORY_PULL_LIMIT_PX : 0) - current) * pressure;
|
||||
// Each packet retargets the same MotionValue; interruption keeps the live spring velocity.
|
||||
this.animateTo(Math.max(0, Math.min(HISTORY_PULL_LIMIT_PX, pressured)));
|
||||
return first;
|
||||
}
|
||||
|
||||
startTouch(): void {
|
||||
this.stopFrame();
|
||||
this.stopAnimation();
|
||||
const visible = this.boundedValue();
|
||||
this.value.set(visible);
|
||||
this.dragging = true;
|
||||
this.setFeedbackActive(true);
|
||||
this.velocity = 0;
|
||||
this.travel = -RESISTANCE_LENGTH_PX
|
||||
* Math.log(Math.max(Number.EPSILON, 1 - Math.max(0, this.distance) / HISTORY_PULL_LIMIT_PX));
|
||||
if (this.phase !== "held") this.setPhase("feedback");
|
||||
this.travel = -RESISTANCE_LENGTH_PX * Math.log(Math.max(Number.EPSILON, 1 - visible / HISTORY_PULL_LIMIT_PX));
|
||||
}
|
||||
|
||||
moveTouch(travel: number): void {
|
||||
if (!this.dragging) return;
|
||||
this.travel = Math.max(0, this.travel + travel);
|
||||
this.distance = HISTORY_PULL_LIMIT_PX * (1 - Math.exp(-this.travel / RESISTANCE_LENGTH_PX));
|
||||
this.publish();
|
||||
this.value.set(HISTORY_PULL_LIMIT_PX * (1 - Math.exp(-this.travel / RESISTANCE_LENGTH_PX)));
|
||||
}
|
||||
|
||||
endTouch(cancelled = false): boolean {
|
||||
const triggered = this.dragging && !cancelled && this.distance >= HISTORY_PULL_TRIGGER_PX;
|
||||
if (!this.dragging) return false;
|
||||
const triggered = !cancelled && this.boundedValue() >= HISTORY_PULL_TRIGGER_PX;
|
||||
this.dragging = false;
|
||||
this.travel = 0;
|
||||
this.publish();
|
||||
this.animate();
|
||||
this.animateTo(this.restPosition());
|
||||
return triggered;
|
||||
}
|
||||
|
||||
/** Native scrolling releases this input round, not the committed reveal. */
|
||||
leaveBoundary(): void {
|
||||
this.loading = false;
|
||||
this.dragging = false;
|
||||
this.wheelLatched = false;
|
||||
this.setFeedbackActive(false);
|
||||
this.animate();
|
||||
if (this.reducedMotion() && this.phase !== "held") {
|
||||
this.stopAnimation();
|
||||
this.value.set(0);
|
||||
this.setPhase("hidden");
|
||||
return;
|
||||
}
|
||||
this.animateTo(this.restPosition());
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.stopFrame();
|
||||
this.distance = 0;
|
||||
this.velocity = 0;
|
||||
this.travel = 0;
|
||||
this.loading = false;
|
||||
this.stopAnimation();
|
||||
this.dragging = false;
|
||||
this.travel = 0;
|
||||
this.wheelLatched = false;
|
||||
this.setFeedbackActive(false);
|
||||
this.publish();
|
||||
this.setPhase("hidden");
|
||||
this.value.set(0);
|
||||
}
|
||||
|
||||
private setFeedbackActive(active: boolean): void {
|
||||
if (this.feedbackActive === active) return;
|
||||
this.feedbackActive = active;
|
||||
this.options.onFeedbackChange(active);
|
||||
private readonly publish = (distance: number): void => {
|
||||
const bounded = Math.max(0, Math.min(HISTORY_PULL_LIMIT_PX, distance));
|
||||
this.options.onUpdate(this.phase !== "held" && this.reducedMotion() ? 0 : bounded);
|
||||
};
|
||||
|
||||
private boundedValue(): number {
|
||||
return Math.max(0, Math.min(HISTORY_PULL_LIMIT_PX, this.value.get()));
|
||||
}
|
||||
|
||||
private publish(): void {
|
||||
// Reduced motion suppresses travel, not the input/settlement lifecycle.
|
||||
this.options.onUpdate(this.reducedMotion() ? 0 : Math.max(0, this.distance));
|
||||
private restPosition(): number {
|
||||
return this.phase === "held" ? HISTORY_HOLD_PX : 0;
|
||||
}
|
||||
|
||||
private stopFrame(): void {
|
||||
if (this.frame !== null) this.scheduler.cancel(this.frame);
|
||||
this.frame = null;
|
||||
this.timestamp = null;
|
||||
private setPhase(phase: HistoryRevealPhase): void {
|
||||
if (this.phase === phase) return;
|
||||
this.phase = phase;
|
||||
this.options.onPhaseChange(phase);
|
||||
}
|
||||
|
||||
private animate(): void {
|
||||
if (this.frame !== null) return;
|
||||
if (this.distance === (this.loading ? LOADING_POCKET_PX : 0) && this.velocity === 0) {
|
||||
if (!this.loading) {
|
||||
this.wheelLatched = false;
|
||||
this.setFeedbackActive(false);
|
||||
}
|
||||
private stopAnimation(): void {
|
||||
this.animationGeneration++;
|
||||
this.animation?.stop();
|
||||
this.animation = null;
|
||||
this.destination = null;
|
||||
}
|
||||
|
||||
private animateTo(target: number): void {
|
||||
if (this.dragging) return;
|
||||
const next = Math.max(0, Math.min(HISTORY_PULL_LIMIT_PX, target));
|
||||
if (this.destination === next && this.animation) return;
|
||||
if (this.reducedMotion() && this.phase === "held") {
|
||||
this.stopAnimation();
|
||||
this.value.set(HISTORY_HOLD_PX);
|
||||
return;
|
||||
}
|
||||
this.timestamp = this.scheduler.now();
|
||||
this.frame = this.scheduler.request(this.advance);
|
||||
if (Math.abs(this.value.get() - next) < 0.01) {
|
||||
this.stopAnimation();
|
||||
this.value.set(next);
|
||||
this.finish(next, this.animationGeneration);
|
||||
return;
|
||||
}
|
||||
const generation = ++this.animationGeneration;
|
||||
this.destination = next;
|
||||
this.animation = animate(this.value, next, {
|
||||
type: "spring",
|
||||
stiffness: 484,
|
||||
damping: 34,
|
||||
mass: 1,
|
||||
onComplete: () => this.finish(next, generation),
|
||||
});
|
||||
}
|
||||
|
||||
private readonly advance = (timestamp: number): void => {
|
||||
this.frame = null;
|
||||
const seconds = Math.max(0, timestamp - (this.timestamp ?? timestamp)) / 1000;
|
||||
this.timestamp = timestamp;
|
||||
const target = this.loading ? LOADING_POCKET_PX : 0;
|
||||
// Exact damped-oscillator solution stays stable across slow or suspended frames.
|
||||
const decay = FREQUENCY * DAMPING_RATIO;
|
||||
const frequency = FREQUENCY * Math.sqrt(1 - DAMPING_RATIO ** 2);
|
||||
const displacement = this.distance - target;
|
||||
const sine = (this.velocity + decay * displacement) / frequency;
|
||||
const phase = frequency * seconds;
|
||||
const envelope = Math.exp(-decay * seconds);
|
||||
this.distance = target + envelope * (displacement * Math.cos(phase) + sine * Math.sin(phase));
|
||||
this.velocity = envelope * (
|
||||
(sine * frequency - decay * displacement) * Math.cos(phase)
|
||||
- (displacement * frequency + decay * sine) * Math.sin(phase)
|
||||
);
|
||||
const settled = Math.abs(this.distance - target) < 0.08 && Math.abs(this.velocity) < 0.8;
|
||||
if (settled) {
|
||||
this.distance = target;
|
||||
this.velocity = 0;
|
||||
this.timestamp = null;
|
||||
if (!this.loading) {
|
||||
this.wheelLatched = false;
|
||||
this.setFeedbackActive(false);
|
||||
}
|
||||
private finish(destination: number, generation: number): void {
|
||||
if (generation !== this.animationGeneration) return;
|
||||
this.animation = null;
|
||||
this.destination = null;
|
||||
this.value.set(destination);
|
||||
if (destination !== this.restPosition()) {
|
||||
this.animateTo(this.restPosition());
|
||||
return;
|
||||
}
|
||||
this.publish();
|
||||
if (!settled) this.frame = this.scheduler.request(this.advance);
|
||||
};
|
||||
if (destination === 0 && this.phase !== "held") {
|
||||
this.wheelLatched = false;
|
||||
this.setPhase("hidden");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,6 +71,7 @@ const THREAD_MOTION_TRANSITIONS: Readonly<
|
||||
"navigation-settled": "current-automatic-mode",
|
||||
"user-scroll": "browsing-history",
|
||||
"boundary-scroll": "browsing-history",
|
||||
"composer-input": "idle",
|
||||
"resume-follow": "current-automatic-mode",
|
||||
},
|
||||
"navigating-history": {
|
||||
@@ -79,6 +80,7 @@ const THREAD_MOTION_TRANSITIONS: Readonly<
|
||||
"navigation-settled": "browsing-history",
|
||||
"user-scroll": "browsing-history",
|
||||
"boundary-scroll": "browsing-history",
|
||||
"composer-input": "browsing-history",
|
||||
"resume-follow": "current-automatic-mode",
|
||||
},
|
||||
"browsing-history": {
|
||||
@@ -164,6 +166,7 @@ export class ThreadMotionCoordinator {
|
||||
hasOutput: false,
|
||||
};
|
||||
private mode: ThreadMotionMode = "idle";
|
||||
private historyNavigationPromptId: string | null = null;
|
||||
private promptPositioned = false;
|
||||
private measurementFrameId: number | null = null;
|
||||
private geometryDirty = false;
|
||||
@@ -309,12 +312,21 @@ export class ThreadMotionCoordinator {
|
||||
}
|
||||
|
||||
navigateHistoryTo(top: number): ThreadCameraFollowResult | null {
|
||||
this.camera.cancel();
|
||||
return this.beginHistoryNavigation(top, null);
|
||||
}
|
||||
|
||||
navigateHistoryToPrompt(promptId: string): ThreadCameraFollowResult | null {
|
||||
const geometry = this.measure(promptId);
|
||||
if (!geometry || geometry.promptTop === null) return null;
|
||||
return this.beginHistoryNavigation(geometry.promptTop, promptId);
|
||||
}
|
||||
|
||||
private beginHistoryNavigation(top: number, promptId: string | null): ThreadCameraFollowResult | null {
|
||||
if (this.mode !== "navigating-history") this.camera.cancel();
|
||||
this.transition("navigate-history");
|
||||
this.historyNavigationPromptId = promptId;
|
||||
const result = this.camera.navigateTo(top);
|
||||
if (!result || result === "settled") {
|
||||
this.transition("navigation-settled");
|
||||
}
|
||||
if (!result || result === "settled") this.transition("navigation-settled");
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -378,6 +390,7 @@ export class ThreadMotionCoordinator {
|
||||
this.composerInputDuringTurn = false;
|
||||
this.resumeFollowArmed = false;
|
||||
this.mode = "idle";
|
||||
this.historyNavigationPromptId = null;
|
||||
this.promptPositioned = false;
|
||||
}
|
||||
|
||||
@@ -410,6 +423,7 @@ export class ThreadMotionCoordinator {
|
||||
: transition;
|
||||
if (nextMode === this.mode) return false;
|
||||
this.mode = nextMode;
|
||||
if (nextMode !== "navigating-history") this.historyNavigationPromptId = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -434,14 +448,23 @@ export class ThreadMotionCoordinator {
|
||||
if (!this.geometryDirty) return;
|
||||
this.geometryDirty = false;
|
||||
|
||||
const navigationPromptId = this.mode === "navigating-history"
|
||||
? this.historyNavigationPromptId
|
||||
: null;
|
||||
const needsPromptGeometry =
|
||||
!this.isHistoryMode()
|
||||
&& this.turn.id !== null
|
||||
&& !this.promptPositioned;
|
||||
const geometry = this.measure(needsPromptGeometry ? this.turn.promptId : null);
|
||||
navigationPromptId !== null
|
||||
|| (!this.isHistoryMode() && this.turn.id !== null && !this.promptPositioned);
|
||||
const geometry = this.measure(navigationPromptId ?? (needsPromptGeometry ? this.turn.promptId : null));
|
||||
if (!geometry) return;
|
||||
this.onGeometry?.(geometry);
|
||||
|
||||
if (this.mode === "navigating-history" && navigationPromptId !== null) {
|
||||
if (geometry.promptTop !== null) {
|
||||
const result = this.camera.navigateTo(geometry.promptTop);
|
||||
if (!result || result === "settled") this.transition("navigation-settled");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.mode === "navigating-latest") {
|
||||
const result = this.camera.navigateTo(geometry.maxScrollTop);
|
||||
if (!result || result === "settled") {
|
||||
|
||||
Reference in new issue
Block a user