Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Streaming fade: CSS on the reply's root while it streams, once per block

milind-soni75a49328633c
diff --git a/DESIGN.md b/DESIGN.md
index 252b87eb05..92648f2b5c 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -286,7 +286,8 @@ Motion explains a change. It never decorates.
while the room it takes grows or shrinks, so the chat glides and nothing in
the panel rewraps. Words leaving a control fade, drift a few pixels and soften
rather than being cut off; they never wrap mid-way.
-- **300ms ceiling.** Only first-run onboarding may run longer.
+- **300ms ceiling.** Only first-run onboarding and a streaming reply's blocks
+ fading in (600ms, `ease-out`, once per block) may run longer.
- **Nothing scales in from zero.** Things grow from about 96% and fade.
- **Hover and press transitions are 120ms** on colour and opacity only. Don't
animate layout. One exception: buttons (`.ui-button`, `.ui-icon-button`)
diff --git a/src/components/ChatMarkdown.stream-fade.test.ts b/src/components/ChatMarkdown.stream-fade.test.ts
index ffbb6a932b..1816136c81 100644
--- a/src/components/ChatMarkdown.stream-fade.test.ts
+++ b/src/components/ChatMarkdown.stream-fade.test.ts
@@ -1,38 +1,38 @@
// @vitest-environment happy-dom
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
import { act, createElement } from "react";
import { createRoot, type Root } from "react-dom/client";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { setLocale } from "../lib/i18n";
import { StreamingReplyContext } from "@/state/live-reply";
-vi.mock("@/lib/interface-mode", async (importOriginal) => ({
- ...await importOriginal<typeof import("@/lib/interface-mode")>(),
- useAdvancedMode: () => true,
- readAdvancedMode: () => true,
-}));
-
const { ChatMarkdown } = await import("./ChatMarkdown");
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-describe("a streaming reply fades in what arrives", () => {
+// The fade is CSS: a block fades in when it is first put on the page while the reply streams. So each block must be put
+// on the page once, and stay the same element as it grows and finishes, or a shown block would blink.
+describe("a streaming reply's blocks fade in once", () => {
let host: HTMLDivElement;
let root: Root;
- let faded: string[];
- let reduced: boolean;
+ let shown: Set<Element>;
const draw = (text: string, streaming = true) =>
act(() => root.render(createElement(StreamingReplyContext, { value: streaming }, createElement(ChatMarkdown, { text }))));
- const take = () => faded.splice(0);
+ const markdown = () => host.querySelector(".chat-md")!;
+ /** What this draw put on the page that was not there before: top-level blocks, list items, table rows, code blocks. */
+ const added = (text: string) => {
+ draw(text);
+ const now = [...markdown().querySelectorAll(":scope > *, li, tr, .chat-code-block")];
+ const fresh = now.filter((element) => !shown.has(element)).map((element) => `${element.tagName.toLowerCase()}:${(element.textContent ?? "").trim().slice(0, 12)}`);
+ shown = new Set(now);
+ return fresh;
+ };
beforeEach(() => {
setLocale("en");
- faded = [];
- reduced = false;
- vi.spyOn(HTMLElement.prototype, "animate").mockImplementation(function (this: HTMLElement) {
- faded.push(`${this.tagName.toLowerCase()}:${this.textContent}`);
- return {} as Animation;
- });
- vi.spyOn(window, "matchMedia").mockImplementation((query: string) => ({ matches: reduced && query.includes("reduce") }) as MediaQueryList);
+ shown = new Set();
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
@@ -40,58 +40,44 @@ describe("a streaming reply fades in what arrives", () => {
afterEach(() => {
act(() => root.unmount());
host.remove();
- vi.restoreAllMocks();
- });
-
- it("fades each new block in once, as it arrives", () => {
- draw("First paragraph ");
- expect(take(), "the reply's first draw fades in as one").toEqual(["div:First paragraph"]);
- draw("First paragraph grows ");
- expect(take(), "words added to a shown block do not play it again").toEqual([]);
- draw("First paragraph grows\n\nSecond ");
- expect(take(), "the first block, now finished and drawn anew, does not play again").toEqual(["p:Second"]);
});
- it("fades a list in item by item and a table row by row", () => {
- draw("Steps:\n\n");
- expect(take()).toEqual(["div:Steps:"]);
- draw("Steps:\n\n- one\n");
- expect(take()).toEqual(["li:one"]);
- draw("Steps:\n\n- one\n- two\n");
- expect(take()).toEqual(["li:two"]);
- draw("Steps:\n\n- one\n- two\n\n| a | b |\n|---|---|\n| 1 | 2 |\n");
- expect(take().filter((each) => each.startsWith("tr:"))).toEqual(["tr:ab", "tr:12"]);
+ it("marks the reply as streaming only while it streams", () => {
+ draw("Here is the plan");
+ expect(markdown().hasAttribute("data-streaming")).toBe(true);
+ draw("Here is the plan.", false);
+ expect(markdown().hasAttribute("data-streaming"), "a finished reply never plays the fade").toBe(false);
});
- it("fades a new block in before the footnotes, not the footnotes again", () => {
- draw("A claim.[^1]\n\n[^1]: The source.\n");
- take();
- draw("A claim.[^1]\n\nMore detail.\n\n[^1]: The source.\n");
- expect(take()).toEqual(["p:More detail."]);
+ it("keeps a paragraph the same element as words arrive and as it finishes", () => {
+ expect(added("First ")).toEqual(["p:First"]);
+ expect(added("First grows ")).toEqual([]);
+ expect(added("First grows\n\nSecond ")).toEqual(["p:Second"]);
+ expect(added("First grows\n\nSecond part\n\nThird")).toEqual(["p:Third"]);
});
- it("fades a reply opened mid-stream in once as a whole, not block by block", () => {
- draw("One.\n\nTwo.\n\n- three\n- four\n");
- expect(take().map((each) => each.split(":")[0]), "one fade for the reply, none for its blocks").toEqual(["div"]);
+ it("keeps a list and a table when they finish", () => {
+ expect(added("Lead:\n\n- one\n")).toEqual(["p:Lead:", "ul:one", "li:one"]);
+ expect(added("Lead:\n\n- one\n- two\n")).toEqual(["li:two"]);
+ expect(added("Lead:\n\n- one\n- two\n\n| a | b |\n|---|---|\n| 1 | 2 |\n")).toEqual(["div:ab12", "tr:ab", "tr:12"]);
+ expect(added("Lead:\n\n- one\n- two\n\n| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n")).toEqual(["tr:34"]);
+ expect(added("Lead:\n\n- one\n- two\n\n| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n\nAfter")).toEqual(["p:After"]);
});
- it("leaves a finished reply, and anyone who asks for less motion, without a fade", () => {
- draw("A saved reply.\n\nWith two blocks.", false);
- expect(take()).toEqual([]);
- reduced = true;
- act(() => root.unmount());
- root = createRoot(host);
- draw("Streaming for someone who asked for less motion ");
- expect(take()).toEqual([]);
+ it("keeps a code block when its fence closes", () => {
+ expect(added("Code:\n\n```js\nconst a = 1;\n")).toEqual(["p:Code:", "div:const a = 1;"]);
+ expect(added("Code:\n\n```js\nconst a = 1;\nconst b = 2;\n")).toEqual([]);
+ expect(added("Code:\n\n```js\nconst a = 1;\nconst b = 2;\n```\n"), "the closing fence keeps the block").toEqual([]);
+ expect(added("Code:\n\n```js\nconst a = 1;\nconst b = 2;\n```\n\nAfter ")).toEqual(["p:After"]);
});
- it("leaves the reply still when the app is set to less motion, whatever the system asks", () => {
- document.documentElement.dataset.reducedMotion = "true";
- try {
- draw("Streaming with the app set to less motion ");
- expect(take()).toEqual([]);
- } finally {
- delete document.documentElement.dataset.reducedMotion;
- }
+ it("fades with opacity only, once, while streaming, and not with reduced motion", () => {
+ const css = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "../styles.css"), "utf8");
+ const media = css.match(/@media \(prefers-reduced-motion: no-preference\) \{\n {2}\.chat-md\[data-streaming\] > \*,[\s\S]*?\n\}\n/)?.[0];
+ expect(media, "the fade sits inside prefers-reduced-motion: no-preference").toBeDefined();
+ expect(media).toContain("transition: opacity 600ms ease-out;");
+ expect(media).toMatch(/@starting-style \{\s*\.chat-md\[data-streaming\] > \*,\s*\.chat-md\[data-streaming\] \[data-stream-fade\] \{\s*opacity: 0;\s*\}\s*\}/);
+ expect(media, "no keyframes: nothing runs after a block is in").not.toMatch(/animation|@keyframes|infinite/);
+ expect(css.match(/\.chat-md\[data-streaming\]/g)?.length, "the rule exists only in this block").toBe(4);
});
});
diff --git a/src/components/ChatMarkdown.stream-identity.test.ts b/src/components/ChatMarkdown.stream-identity.test.ts
index 6d65bafcdb..6d898fa042 100644
--- a/src/components/ChatMarkdown.stream-identity.test.ts
+++ b/src/components/ChatMarkdown.stream-identity.test.ts
@@ -175,13 +175,16 @@ describe("a streamed reply drawn block by block and piece by piece", () => {
hosts.forEach((host) => host.remove());
});
+ /** A reply's page without its streaming mark, which only gates the fade-in. */
+ const page = (host: HTMLDivElement) => host.innerHTML.replace(' data-streaming=""', "");
+
/** The cut where drawing `text` in parts first differs from drawing it whole, or null. */
const firstDifference = (text: string, cuts: number[]): string | null => {
for (const cut of cuts) {
const prefix = text.slice(0, cut);
draw(streamed, prefix, true, false);
draw(whole, prefix, true, true);
- const [parts, all] = [hosts[0]!.innerHTML, hosts[1]!.innerHTML];
+ const [parts, all] = [page(hosts[0]!), page(hosts[1]!)];
if (parts === all) continue;
let at = 0;
while (parts[at] === all[at]) at++;
@@ -195,7 +198,7 @@ describe("a streamed reply drawn block by block and piece by piece", () => {
expect(firstDifference(text, Array.from({ length: text.length }, (_, index) => index + 1))).toBeNull();
if (OPEN_AT_THE_END.includes(name)) return;
draw(whole, text, false, true);
- expect(hosts[0]!.innerHTML, "the finished reply").toBe(hosts[1]!.innerHTML);
+ expect(page(hosts[0]!), "the finished reply").toBe(page(hosts[1]!));
});
it("random documents: every sampled prefix draws as the whole text does", () => {
diff --git a/src/components/ChatMarkdown.streaming.test.ts b/src/components/ChatMarkdown.streaming.test.ts
index b2445ad54e..2e1ddecdae 100644
--- a/src/components/ChatMarkdown.streaming.test.ts
+++ b/src/components/ChatMarkdown.streaming.test.ts
@@ -42,7 +42,8 @@ describe("a reply's Markdown while it streams", () => {
let root: Root;
const draw = (text: string, streaming: boolean) =>
act(() => root.render(createElement(StreamingReplyContext, { value: streaming }, createElement(ChatMarkdown, { text }))));
- const markup = () => host.innerHTML;
+ // The streaming mark only gates the fade-in; the page under it is what is compared.
+ const markup = () => host.innerHTML.replace(' data-streaming=""', "");
beforeEach(() => {
setLocale("en");
diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsx
index b86a3d1ee3..660a098407 100644
--- a/src/components/ChatMarkdown.tsx
+++ b/src/components/ChatMarkdown.tsx
@@ -14,7 +14,6 @@ import { createMarkdownRenderCache } from "@/lib/markdown-render-cache";
import { closedFence, mayHoldMath, openFence, splitMarkdownBlocks, splitStreamPieces, type StreamPieces } from "@/lib/markdown-stream-blocks";
import { drawStreamPieces, type ItemScope, type ParsePiece } from "@/lib/markdown-stream-pieces";
import { StreamingReplyContext } from "@/state/live-reply";
-import { useStreamFadeIn } from "@/lib/stream-fade-in";
import { parseFenceInfo } from "../lib/code-block";
import { markdownImageName, markdownImageOpenUrl } from "../lib/markdown-image";
@@ -290,7 +289,7 @@ export function MermaidDiagram({ code }: MermaidDiagramProps) {
{t("chat.mermaid.failed", { error })}
</p>
)}
- {markup && <div className="overflow-x-auto p-3 [&_svg]:!max-w-full" dangerouslySetInnerHTML={markup} />}
+ {markup && <div data-stream-fade className="overflow-x-auto p-3 [&_svg]:!max-w-full" dangerouslySetInnerHTML={markup} />}
{(showSource || !svg || error) && (
<pre className={cn("overflow-x-auto text-[13px]", simple ? "px-3 py-2 leading-5 text-ink-secondary" : "p-3 leading-relaxed text-ink")}>{code}</pre>
)}
@@ -660,7 +659,12 @@ const MessageScopeContext = createContext<MessageScope>({ threads: [] });
/** The source of the block still being written, whose last fence may be open; null for finished text. */
const StreamSourceContext = createContext<string | null>(null);
-function MarkdownCode({ node, children }: BlockProps) {
+/** A fence still being written, drawn without parsing in the place its parsed `pre` takes, so it stays the same block. */
+type OpenFence = NonNullable<MarkdownPart["fence"]>;
+const OPEN_FENCE_KEY = "pre-0";
+
+function MarkdownCode({ node, children, fence }: BlockProps & { fence?: OpenFence }) {
+ if (fence) return <CodeBlock code={fence.code} lang={fence.lang} initialWrap={fence.wrap} open />;
const streamSource = use(StreamSourceContext);
const position = (node as { position?: { start: { offset?: number }; end: { offset?: number } } } | undefined)?.position;
const open = streamSource !== null && !closedFence(streamSource, position?.start.offset, position?.end.offset);
@@ -895,7 +899,6 @@ function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS,
const { threads, currentBotId } = MAY_LINK_THREAD.test(text) ? use(ThreadRefsContext) : NO_THREAD_REFS;
const streaming = use(StreamingReplyContext);
const parts = useMemo(() => markdownParts(text, streaming), [text, streaming]);
- const fadeIn = useStreamFadeIn(streaming, parts);
// One answer for the whole text, as a finished message gets: a block alone may hold half of a pair.
const needsMath = useMemo(() => normalizedSourceHasMath(parts.length === 1 ? parts[0]!.source : parts.map((part) => part.source).join("")), [parts]);
const [katexReady, setKatexReady] = useState(() => katexPlugin !== null);
@@ -932,16 +935,17 @@ function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS,
};
const piece: ParsePiece = (source, cacheKey, loose) => parse(source, cacheKey, loose);
const itemScope: ItemScope = (nodes, index, open) => <StreamSourceContext key={index} value={open}>{nodes}</StreamSourceContext>;
+ // A block keeps one tree shape from its first words to its end, so its elements stay the same ones on the page.
const draw = ({ text: partText, source, finished, pieces, repair }: MarkdownPart): ReactNode => {
if (finished) {
- return parse(source, partText, false, () => {
+ return <StreamSourceContext value={null}>{parse(source, partText, false, () => {
const split = splitStreamPieces(partText);
const joined = split && drawStreamPieces(split, false, piece, itemScope);
return joined ? <>{joined}</> : null;
- });
+ })}</StreamSourceContext>;
}
const joined = pieces && drawStreamPieces(pieces, true, piece, itemScope);
- if (joined) return joined;
+ if (joined) return <StreamSourceContext value={null}><>{joined}</></StreamSourceContext>;
const whole = pieces ? normalizeMarkdown(partText, repair).source : source;
return <StreamSourceContext value={whole}>{parse(whole, null)}</StreamSourceContext>;
};
@@ -949,10 +953,10 @@ function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS,
const scope = { message: streaming ? undefined : message, imageOffsets: streaming ? undefined : parts[0]?.imageOffsets, threads, currentBotId, delivered, originals };
return (
<MessageScopeContext.Provider value={scope}>
- <div ref={fadeIn} data-look="bot-text" className="chat-md min-w-0 [&>*+*]:mt-2">
+ <div data-look="bot-text" data-streaming={streaming ? "" : undefined} className="chat-md min-w-0 [&>*+*]:mt-2">
{parts.map((part, index) => (
// The whole text's tree puts a line break between its top-level blocks; the parts keep it.
- <Fragment key={index}>{index > 0 && "\n"}{part.fence ? <CodeBlock code={part.fence.code} lang={part.fence.lang} initialWrap={part.fence.wrap} open /> : draw(part)}</Fragment>
+ <Fragment key={index}>{index > 0 && "\n"}{part.fence ? <StreamSourceContext value={part.text}><>{[<MarkdownCode key={OPEN_FENCE_KEY} fence={part.fence} />]}</></StreamSourceContext> : draw(part)}</Fragment>
))}
</div>
</MessageScopeContext.Provider>
diff --git a/src/components/RichTable.tsx b/src/components/RichTable.tsx
index a2d6dd1c4c..638fed842f 100644
--- a/src/components/RichTable.tsx
+++ b/src/components/RichTable.tsx
@@ -186,7 +186,7 @@ function TableViewport({ columns, rows, order, name, wrap, large, sort, onSort,
const cardArrow = (index: number) => arrow(index, cn("shrink-0 text-ink-tertiary transition-opacity", sort?.column === index ? "opacity-100" : "opacity-0 group-hover/th:opacity-100 group-focus-within/th:opacity-100 touch:opacity-100"));
return <div ref={scroll} tabIndex={0} role="region" aria-label={name}
className={cn("overflow-auto overscroll-x-contain focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent/60", card && !fit && "[mask-image:linear-gradient(90deg,#000_calc(100%-40px),transparent)]")}
- style={{ maxHeight: large ? "65dvh" : virtual || !wrap ? 400 : undefined }} data-fit={fit || undefined} data-virtual={virtual || undefined}>
+ style={{ maxHeight: large ? "65dvh" : virtual || !wrap ? 400 : undefined }} data-fit={fit || undefined}>
<table dir={direction} aria-label={name} aria-rowcount={order.length + 1} className={cn("w-full border-separate border-spacing-0 text-[14px]", fit ? "table-auto" : "table-fixed", card && "leading-5")} style={fit ? undefined : { minWidth: widths.reduce((a, b) => a + b, 0) }}>
{!fit && <colgroup>{widths.map((width, index) => <col key={index} style={{ width }} />)}</colgroup>}
<thead ref={heading} hidden={headless} className={cn("sticky top-0 z-10", look === "panel" ? "bg-raised" : look === "card" ? "bg-card" : "bg-composer")}><tr aria-rowindex={1}>
diff --git a/src/lib/stream-fade-in.ts b/src/lib/stream-fade-in.ts
deleted file mode 100644
index 1befa6e61f..0000000000
--- a/src/lib/stream-fade-in.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-// A streaming reply's new blocks, list items and table rows fade in as they arrive instead of appearing at once. The
-// fade lives on the elements' animations, never in the markup, so the streamed page stays the page the saved message
-// draws.
-import { useLayoutEffect, useRef, type RefObject } from "react";
-import { reducedMotion } from "@/lib/onboarding";
-
-/** What fades in: the reply's top-level blocks (a list by its items), list items and table rows. */
-const STREAM_FADE_TARGETS = ":scope > :not(ul, ol), li, tr";
-const FADE: Keyframe[] = [{ opacity: 0 }, { opacity: 1 }];
-const FADE_TIMING: KeyframeAnimationOptions = { duration: 320, easing: "cubic-bezier(0.22, 1, 0.36, 1)" };
-
-/** Footnotes sit at the reply's end and a long table draws only the rows in view, so neither keeps page order. */
-const keepsPageOrder = (target: Element) => !target.closest("[data-footnotes], [data-virtual]");
-
-/**
- * Fades in what a streaming reply drew since `content` last changed: the whole reply on its first draw, then each new
- * target. Targets are counted in page order, so one already shown does not play again when a finished block is drawn
- * anew.
- */
-export function useStreamFadeIn(streaming: boolean, content: unknown): RefObject<HTMLDivElement | null> {
- const ref = useRef<HTMLDivElement>(null);
- const shown = useRef<number | null>(null);
- useLayoutEffect(() => {
- const host = ref.current;
- if (!streaming || !host) {
- shown.current = null;
- return;
- }
- const targets = [...host.querySelectorAll(STREAM_FADE_TARGETS)].filter(keepsPageOrder);
- const fresh = shown.current === null ? [host] : targets.slice(shown.current);
- if (!reducedMotion()) for (const target of fresh) target.animate?.(FADE, FADE_TIMING);
- shown.current = targets.length;
- }, [streaming, content]);
- return ref;
-}
diff --git a/src/styles.css b/src/styles.css
index fa7b44e25a..f1104deb46 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -1337,6 +1337,22 @@
line-height: 1.75;
}
+/* A streaming reply's blocks fade in as each one arrives, so a chunk of text does not pop in. @starting-style applies
+ only when an element is first put on the page, and the rule holds only while the reply streams, so opening a
+ finished reply never plays it. Opacity only, once per block, no layout change, nothing running after the stream. */
+@media (prefers-reduced-motion: no-preference) {
+ .chat-md[data-streaming] > *,
+ .chat-md[data-streaming] [data-stream-fade] {
+ transition: opacity 600ms ease-out;
+ }
+ @starting-style {
+ .chat-md[data-streaming] > *,
+ .chat-md[data-streaming] [data-stream-fade] {
+ opacity: 0;
+ }
+ }
+}
+
.chat-code-actions > button:focus-visible {
outline: 2px solid var(--color-focus);
outline-offset: 2px;