Skip to content

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

Fade in a streaming reply's new blocks as they arrive

AdityaUmale04ceb28d7138
diff --git a/src/components/ChatMarkdown.stream-fade.test.ts b/src/components/ChatMarkdown.stream-fade.test.ts
new file mode 100644
index 0000000000..7db480c9ec
--- /dev/null
+++ b/src/components/ChatMarkdown.stream-fade.test.ts
@@ -0,0 +1,87 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } 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", () => {
+ let host: HTMLDivElement;
+ let root: Root;
+ let faded: string[];
+ let reduced: boolean;
+ const draw = (text: string, streaming = true) =>
+ act(() => root.render(createElement(StreamingReplyContext, { value: streaming }, createElement(ChatMarkdown, { text }))));
+ const take = () => faded.splice(0);
+
+ 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);
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+ });
+ 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("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("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("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([]);
+ });
+});
diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsx
index 8aed71132d..b86a3d1ee3 100644
--- a/src/components/ChatMarkdown.tsx
+++ b/src/components/ChatMarkdown.tsx
@@ -14,6 +14,7 @@ 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";
@@ -894,6 +895,7 @@ 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);
@@ -947,7 +949,7 @@ 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 data-look="bot-text" className="chat-md min-w-0 [&>*+*]:mt-2">
+ <div ref={fadeIn} data-look="bot-text" 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>
diff --git a/src/components/RichTable.tsx b/src/components/RichTable.tsx
index 638fed842f..a2d6dd1c4c 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}>
+ style={{ maxHeight: large ? "65dvh" : virtual || !wrap ? 400 : undefined }} data-fit={fit || undefined} data-virtual={virtual || 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
new file mode 100644
index 0000000000..71ef777fa9
--- /dev/null
+++ b/src/lib/stream-fade-in.ts
@@ -0,0 +1,36 @@
+// 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";
+
+/** 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)" };
+
+const reducedMotion = () => window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
+
+/** 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;
+}