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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/3425-ghost-fade-end.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-ui-kit": patch
---

End the loading ghost's handoff when its fade ends, not 600ms after the data arrives, so a late first frame no longer removes the ghost from partial opacity. Where no fade runs (reduced motion, `animation: none`) the handoff still ends after 600ms.
17 changes: 17 additions & 0 deletions docs/decisions/design-kit/loading.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,23 @@ so ellipsis does not cut off blurred ends. Reduced motion hides the entire
band and disables every translation; print hides ghosts and the band. The
existing instant reduced-motion handoff and stream tail rules remain.

### D53 addendum — the handoff ends on its fades' end (#3425, 2026-11-15)

The handoff now ends when the item's own fades end, not on a 600ms timer
started at the arrival commit (`useArrival`,
`packages/ui-kit/src/internal/GhostText.tsx:216-248`). The fades start on the
first frame the browser renders after the commit. On a loaded browser that
frame can come hundreds of ms late, and the commit timer then removed the
ghost from partial opacity, part-way through its fade. Even unloaded, the timer
ended the fade a frame early. Each consumer hands its root element to the hook,
which waits on that frame's running `ghost-in` and `ghost-out` animations.

Where no fade runs, the handoff still ends after `HANDOFF_MS`. That covers
reduced motion's 0s fades, `animation: none` and a DOM without Web Animations.
A fade that has not started `FIRST_FRAME_MS` (3s) after the commit means the
document renders no frames, and the handoff ends then rather than hold the
ghost forever. The 600ms fade, its easing and its keyframes are unchanged.


<a id="2026-10-07--streaminganswer-is-the-turns-waiting-status-1144"></a>

Expand Down
16 changes: 10 additions & 6 deletions docs/process/test-waits.md
Original file line number Diff line number Diff line change
Expand Up @@ -587,7 +587,9 @@ The nine former 640 ms settlements in `packages/ui-kit/tests/ghost-text.test.tsx
retain their assertions. The test captures every global timeout registered by
these mounted components, including a wrongly configured delay. Its independent
600 ms oracle checks the actual `useArrival` effect (`useArrival`,
`packages/ui-kit/src/internal/GhostText.tsx:181-194`). At 599 ms the same outgoing
`packages/ui-kit/src/internal/GhostText.tsx:216-248`). happy-dom computes no CSS
animations, so no fade runs and the hook ends the handoff on its 600 ms
fallback timer. Stand-in fades cover the path where a fade runs (#3425). At 599 ms the same outgoing
and incoming nodes must remain; at 600 ms the real callback runs inside React
`act`, whose committed result must remove both handoff classes. Neither an
arbitrary microtask nor immediate absence proves completion.
Expand All @@ -614,13 +616,15 @@ in the successor. The original glyph, role, style, accessibility, inertness,
interaction, ordering and loaded-state assertions stay in this file.

Native proof remains unchanged and required: `playHandoff` in
`packages/ui-kit/stories/_ghost.tsx` observes 300 ms mid-handoff opacity,
320/720 px geometry, a 600 ms fade in animation time and removal within three
rendered frames of that fade's end (#3417). LoadingToReady
`packages/ui-kit/stories/_ghost.tsx` observes mid-handoff opacity,
320/720 px geometry, a 600 ms fade in animation time, a fade that ends before
removal (#3425) and removal within three rendered frames of that fade's end
(#3417). LoadingToReady
stories run in both Storybook theme projects. Chromium's
`packages/ui-kit/tests/visual/ghost-handoff.visual.tsx` retains both themes,
input-orchestration and main-thread-stall exclusion, and the mutation holding
one width's ghost 200 ms past its fade that still fails.
input-orchestration and main-thread-stall exclusion, a long task right after
the commit that delays the fades' start (#3425), and the mutation holding one
width's ghost 400 ms past its fade that still fails.
Logical component time proves none of CSS rasterization, native elapsed
animation budgets or geometry. Production JavaScript and CSS remain 600 ms.

Expand Down
6 changes: 4 additions & 2 deletions packages/ui-kit/src/conversation/StreamingAnswer.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { GhostBand } from "../internal/GhostBand.js";
import type { CSSProperties, KeyboardEvent } from "react";
import { useRef, type CSSProperties, type KeyboardEvent } from "react";

import { GhostText, INCOMING, useArrival } from "../internal/GhostText.js";
import { StatusDot } from "../primitives/StatusDot.js";
Expand Down Expand Up @@ -78,7 +78,8 @@ export function StreamingAnswer(p: StreamingAnswerProps) {
const canStop = p.stoppable !== false;
const act = Boolean(p.onStop);
const waiting = p.bars !== false && !text;
const arriving = useArrival(waiting);
const frame = useRef<HTMLDivElement>(null);
const arriving = useArrival(waiting, frame);
// Code points, not UTF-16 units, so the tail never splits a character.
const chars = Array.from(text);
const split = Math.max(0, chars.length - TAIL);
Expand All @@ -100,6 +101,7 @@ export function StreamingAnswer(p: StreamingAnswerProps) {

return (
<div
ref={frame}
data-kit-streaming-answer=""
style={{
display: "flex",
Expand Down
6 changes: 4 additions & 2 deletions packages/ui-kit/src/decisions/ActionCard.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { GhostBand } from "../internal/GhostBand.js";
import { useId, type CSSProperties, type KeyboardEvent, type ReactNode } from "react";
import { useId, useRef, type CSSProperties, type KeyboardEvent, type ReactNode } from "react";

import { Chip } from "../primitives/Chip.js";
import {
Expand Down Expand Up @@ -171,7 +171,8 @@ export function ActionCard(p: ActionCardProps) {
const em = p.emphasis || k.em;
const st = p.state || "ready";
const loading = st === "loading";
const arriving = useArrival(loading);
const frame = useRef<HTMLDivElement>(null);
const arriving = useArrival(loading, frame);
// The ghost's seed is this instance — kept per item key, not per list
// position — so re-ranking a row never regenerates its glyphs.
const id = useId();
Expand Down Expand Up @@ -311,6 +312,7 @@ export function ActionCard(p: ActionCardProps) {

return (
<div
ref={frame}
style={{ ...box, position: "relative" }}
aria-busy={loading ? true : undefined}
className={act ? "bk-row" : undefined}
Expand Down
6 changes: 4 additions & 2 deletions packages/ui-kit/src/evidence/SearchResultCard.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { GhostBand } from "../internal/GhostBand.js";
import { useId, type CSSProperties, type KeyboardEvent } from "react";
import { useId, useRef, type CSSProperties, type KeyboardEvent } from "react";

import { Ghosted, ghostLength, useArrival, useLastLengths, useLoadingValue, type GhostTextProps } from "../internal/GhostText.js";
import { Icon, type IconName } from "../primitives/Icon.js";
Expand Down Expand Up @@ -67,7 +67,8 @@ export interface SearchResultCardProps {
export function SearchResultCard(p: SearchResultCardProps) {
const view = p.view || "ready";
const loading = view === "loading";
const arriving = useArrival(loading);
const frame = useRef<HTMLDivElement>(null);
const arriving = useArrival(loading, frame);
// The ghost's seed is this instance — kept per item key, not per list
// position — so re-ranking a row never regenerates its glyphs.
const id = useId();
Expand Down Expand Up @@ -167,6 +168,7 @@ export function SearchResultCard(p: SearchResultCardProps) {

return (
<div
ref={frame}
style={{ ...box, position: "relative" }}
data-search-result-card=""
aria-busy={loading ? true : undefined}
Expand Down
70 changes: 62 additions & 8 deletions packages/ui-kit/src/internal/GhostText.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode, type RefObject } from "react";

import { color, font } from "../tokens.js";

Expand Down Expand Up @@ -170,15 +170,50 @@ export function GhostText(p: GhostTextProps) {
/* ── The handoff ───────────────────────────────────────────────────────── */

/**
* True for the 600ms after `loading` turns false, so the item can draw its
* ghost under the arriving text. Per item: each list row calls it with its
* own flag, so each one hands off when ITS data lands.
* How long an arrival waits for its first rendered frame before it stops
* waiting for its fades. A fade starts on the first frame after the commit, so
* a document that renders none — a hidden tab, a frozen embedding — would hold
* the ghost forever. A loaded runner starts the fade a few hundred ms late,
* never seconds.
*/
export const FIRST_FRAME_MS = 3000;

/** The handoff's two fades, by keyframe name (`tokens.css`). */
const HANDOFF_FADES = new Set(["ghost-in", "ghost-out"]);

/** The frame's running handoff fades, with a duration to run. Empty where no
* fade runs: `animation: none`, reduced motion's 0s, no Web Animations. */
function handoffFades(frame: Element | null): Animation[] {
if (!frame || typeof frame.getAnimations !== "function") return [];
return frame.getAnimations({ subtree: true }).filter((a) => {
const name = (a as CSSAnimation).animationName;
const duration = Number(a.effect?.getComputedTiming().duration ?? 0);
return name !== undefined && HANDOFF_FADES.has(name) && duration > 0;
});
}

/**
* True from the commit where `loading` turns false until that item's handoff
* fades have ended, so the item can draw its ghost under the arriving text.
* Per item: each list row calls it with its own flag and its own frame, so
* each one hands off when ITS data lands.
*
* Derived during render rather than in an effect, so the first ready frame
* already carries the outgoing ghost — an effect would paint one frame of bare
* text first, and the ghost would blink back over it.
*
* The handoff ends on the fades' own end (#3425), not on a timer from the
* commit: the fades start on the first frame the browser renders after the
* commit, and on a loaded browser that frame can be hundreds of ms late. A
* timer would then remove the ghost part-way through its fade. `frame` is the
* item's root element, holding its `.bk-ghost-out` and `.bk-ghost-in` layers.
*
* Where no fade runs — reduced motion, `animation: none`, a document without
* Web Animations — the handoff ends after `HANDOFF_MS`, the fade's length. A
* fade that has not started `FIRST_FRAME_MS` after the commit means the
* document renders no frames, and the handoff ends then.
*/
export function useArrival(loading: boolean): boolean {
export function useArrival(loading: boolean, frame: RefObject<Element | null>): boolean {
const [prev, setPrev] = useState(loading);
const [arriving, setArriving] = useState(false);
if (prev !== loading) {
Expand All @@ -187,9 +222,28 @@ export function useArrival(loading: boolean): boolean {
}
useEffect(() => {
if (!arriving) return;
const timer = setTimeout(() => setArriving(false), HANDOFF_MS);
return () => clearTimeout(timer);
}, [arriving]);
let live = true;
const end = () => {
if (live) setArriving(false);
};
const fades = handoffFades(frame.current);
if (!fades.length) {
const timer = setTimeout(end, HANDOFF_MS);
return () => {
live = false;
clearTimeout(timer);
};
}
// A fade that is cancelled (its layer removed or restyled) has ended too.
void Promise.allSettled(fades.map((fade) => fade.finished)).then(end);
const frameless = setTimeout(() => {
if (fades.every((fade) => fade.startTime === null)) end();
}, FIRST_FRAME_MS);
return () => {
live = false;
clearTimeout(frameless);
};
}, [arriving, frame]);
return arriving;
}

Expand Down
6 changes: 4 additions & 2 deletions packages/ui-kit/src/rows/FileRow.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { GhostBand } from "../internal/GhostBand.js";
import { useId, type CSSProperties, type KeyboardEvent } from "react";
import { useId, useRef, type CSSProperties, type KeyboardEvent } from "react";

import { Chip } from "../primitives/Chip.js";
import { GhostIconSlot, Ghosted, ghostLength, useArrival, useLastLengths, useLoadingValue } from "../internal/GhostText.js";
Expand Down Expand Up @@ -107,7 +107,8 @@ export function FileRow(p: FileRowProps) {
const act = Boolean(p.onClick) && p.view !== "loading";
const view = p.view || "ready";
const loading = view === "loading";
const arriving = useArrival(loading);
const frame = useRef<HTMLDivElement>(null);
const arriving = useArrival(loading, frame);
// The ghost's seed is this instance — kept per item key, not per list
// position — so re-ranking a row never regenerates its glyphs.
const id = useId();
Expand Down Expand Up @@ -202,6 +203,7 @@ export function FileRow(p: FileRowProps) {

return (
<div
ref={frame}
style={{ ...box, position: "relative" }}
aria-busy={loading ? true : undefined}
className={act ? "bk-row" : undefined}
Expand Down
6 changes: 4 additions & 2 deletions packages/ui-kit/src/rows/QueueItemRow.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { GhostBand } from "../internal/GhostBand.js";
import { useId, type CSSProperties, type KeyboardEvent } from "react";
import { useId, useRef, type CSSProperties, type KeyboardEvent } from "react";

import {
GhostDot,
Expand Down Expand Up @@ -93,7 +93,8 @@ export function QueueItemRow(p: QueueItemRowProps) {
const s = STATES[state] || STATES.claimed;
const view = p.view || "ready";
const loading = view === "loading";
const arriving = useArrival(loading);
const frame = useRef<HTMLDivElement>(null);
const arriving = useArrival(loading, frame);
// The ghost's seed is this instance — kept per item key, not per list
// position — so re-ranking a row never regenerates its glyphs.
const id = useId();
Expand Down Expand Up @@ -189,6 +190,7 @@ export function QueueItemRow(p: QueueItemRowProps) {

return (
<div
ref={frame}
style={{ ...box, position: "relative" }}
aria-busy={loading ? true : undefined}
className={act ? "bk-row" : undefined}
Expand Down
7 changes: 4 additions & 3 deletions packages/ui-kit/src/states/Placeholder.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { GhostBand } from "../internal/GhostBand.js";
import { useId, type CSSProperties, type KeyboardEvent, type ReactNode } from "react";
import { useId, useRef, type CSSProperties, type KeyboardEvent, type ReactNode } from "react";

import { DEFAULT_SIZE, GhostText, INCOMING, ghostFamily, useArrival, type GhostSpec } from "../internal/GhostText.js";
import { Icon, type IconName } from "../primitives/Icon.js";
Expand Down Expand Up @@ -112,7 +112,8 @@ export function Placeholder(p: PlaceholderProps) {
const v = p.variant || "loading";
const loading = v === "loading";
const arrived = loading && p.arrived === true;
const arriving = useArrival(loading && !arrived);
const frame = useRef<HTMLDivElement>(null);
const arriving = useArrival(loading && !arrived, frame);
const err = v === "error";
const empty = v === "empty";
const skin = TONES[p.tone || (err ? "red" : "neutral")] || TONES.neutral;
Expand Down Expand Up @@ -204,7 +205,7 @@ export function Placeholder(p: PlaceholderProps) {
}

return (
<div style={{ ...box, position: "relative" }} aria-busy={loading && !arrived ? true : undefined}>
<div ref={frame} style={{ ...box, position: "relative" }} aria-busy={loading && !arrived ? true : undefined}>
{loading && !arrived ? <div style={stack}>{ghosts}</div> : null}
{arrived ? (
// One tree from arrival on: ending the handoff drops the overlay and a
Expand Down
13 changes: 7 additions & 6 deletions packages/ui-kit/stories/_ghost.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ const opacity = (el: Element | null) => (el ? Number(getComputedStyle(el).opacit
* - the ghost's lines are the ready lines: the frame is the same height
* loading and ready, at 320px and at 720px, so nothing below it moves;
* - on arrival the outgoing ghost is laid over the content, not beside it;
* - each outgoing ghost fades over the approved 600ms and is gone within
* three rendered frames of its fade's end (#3417).
* - each outgoing ghost fades over the approved 600ms, stays until that
* fade has ended (#3425) and is gone within three rendered frames of its
* end (#3417).
*/
export async function playHandoff({
canvasElement,
Expand Down Expand Up @@ -85,10 +86,9 @@ export async function playHandoff({
// click resolves up to ~375ms after the frame commits its arriving layers
// (sometimes after the whole fade), so a fixed 300ms wait from there landed
// 370-770ms into the 600ms fade, after the ghost was gone. The harness
// controls' height only shifted that by luck. A later point in the fade is
// no safer: the ghost is removed on a timer started at the commit, and a
// saturated browser can start the CSS animation 300ms late, so the window
// both clocks agree on opens with the fade itself.
// controls' height only shifted that by luck. A saturated browser can
// start the CSS animation 300ms late, so the window opens with the fade
// itself, not with the commit.
const sampledFrame = handoffs[0]!;
// React commits the arrival inside the click, so it is observable now;
// without an outgoing layer there is no handoff to wait for.
Expand Down Expand Up @@ -199,6 +199,7 @@ export async function playHandoff({
await expect(clock.fadeMs, `${width}px: the outgoing ghost's fade, in animation time`).toBeLessThanOrEqual(FADE_MS);
await expect(clock.framesAfterFade, `${width}px: frames rendered with the ghost after its fade ended`).toBeLessThanOrEqual(FRAMES_AFTER_FADE);
await expect(clock.removed, `${width}px: the outgoing ghost was removed`).toBe(true);
await expect(clock.fadeEnded, `${width}px: the outgoing ghost's fade ended before its removal`).toBe(true);
}
await expect(canvasElement.querySelectorAll(".bk-ghost, .bk-ghost-out")).toHaveLength(0);
} finally {
Expand Down
21 changes: 14 additions & 7 deletions packages/ui-kit/stories/_handoff-clock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
* that genuinely holds the ghost past its fade keeps painting frames with it.
*
* The promise this checks is D53's: the outgoing ghost fades out over the
* approved 600ms on its own animation clock and is gone within a few rendered
* frames of that fade's end. The fade's length is read from its CSS animation timing at
* approved 600ms on its own animation clock, stays until that fade has ended,
* and is gone within a few rendered frames of its end (#3425). The fade's length is read from its CSS animation timing at
* arrival; its end is the browser's own `animationend`.
*/

Expand All @@ -21,11 +21,10 @@ export const FADE_MS = 600;

/**
* At most this many frames may render after the frame in which the fade ends.
* The removal timer starts at the commit and the fade on a frame near it, so
* the two end within a vsync of each other. Normally the ghost is removed
* before its fade ends at all. The worst case observed with one CPU shared
* with six busy loops was two frames, while a ghost held 200ms past its fade
* renders about twelve at 60Hz.
* The component ends the handoff on the fade's own end (#3425), so removal
* normally lands in the next frame or two. The worst case observed with one
* CPU shared with six busy loops was two frames, while a ghost held 200ms past
* its fade renders about twelve at 60Hz.
*/
export const FRAMES_AFTER_FADE = 3;

Expand All @@ -48,6 +47,12 @@ export interface HandoffClock {
fadeMs?: number;
/** Frames rendered after the fade ended, up to removal. Zero if removal came first. */
framesAfterFade: number;
/**
* A `ghost-out` fade ended (`animationend`) before the ghost was removed. A
* ghost removed part-way through its fade, from partial opacity, leaves it
* false (#3425).
*/
fadeEnded: boolean;
/** Frames rendered after arrival, up to removal. */
framesAfterArrival: number;
/**
Expand Down Expand Up @@ -79,6 +84,7 @@ export function watchHandoff(frame: HTMLElement, isArrival: (frame: HTMLElement)
arrived: false,
removed: false,
framesAfterFade: 0,
fadeEnded: false,
framesAfterArrival: 0,
settled: new Promise<void>(resolve => { settle = resolve; }),
observe,
Expand Down Expand Up @@ -133,6 +139,7 @@ export function watchHandoff(frame: HTMLElement, isArrival: (frame: HTMLElement)
// Animation events dispatch before this frame's rAF callbacks, so the frame
// in which the fade ended is the first one counted after it.
fadeEndedAt ??= frames;
clock.fadeEnded = true;
}

const observer = new MutationObserver(observe);
Expand Down
Loading
Loading