Skip to content

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

Colour a chat's code blocks only once they come near the screen

AdityaUmale2e753009a131
diff --git a/src/components/ChatMarkdown.test.ts b/src/components/ChatMarkdown.test.ts
index 3d7e2e5443..2739009dd1 100644
--- a/src/components/ChatMarkdown.test.ts
+++ b/src/components/ChatMarkdown.test.ts
@@ -58,6 +58,9 @@ vi.mock("shiki/core", () => ({
vi.mock("shiki/engine/javascript", () => ({
createJavaScriptRegexEngine: () => ({}),
}));
+// These tests pin how a block is coloured, not when: without an observer a block counts as near the screen at once.
+// (Removed outright rather than stubbed, since tests below undo every stubbed global.)
+delete (globalThis as { IntersectionObserver?: unknown }).IntersectionObserver;
describe("soft line breaks", () => {
it("keeps a reply's single line breaks as line breaks, outside code", () => {
@@ -1397,3 +1400,31 @@ describe("Simple mode's code block", () => {
expect(html).not.toContain('title="Mermaid diagram"');
});
});
+
+describe("a code block far from the screen", () => {
+ it("stays plain until it comes near the screen, then is coloured", async () => {
+ let report: IntersectionObserverCallback | undefined;
+ (globalThis as { IntersectionObserver?: unknown }).IntersectionObserver = class {
+ constructor(callback: IntersectionObserverCallback) { report = callback; }
+ observe() {}
+ unobserve() {}
+ };
+ shiki.codeToHtml.mockReset();
+ shiki.codeToHtml.mockImplementation(async (code: string) => `<pre class="near-probe">${code}</pre>`);
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ try {
+ await act(async () => root.render(createElement(ChatMarkdown, { text: "```ts\nconst farAway = 1;\n```" })));
+ expect(shiki.codeToHtml).not.toHaveBeenCalled();
+ expect(host.textContent).toContain("const farAway = 1;");
+ await act(async () => report!([{ target: host.querySelector(".chat-code-block")!, isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver));
+ await vi.waitFor(() => expect(host.querySelector(".near-probe")?.textContent).toBe("const farAway = 1;"));
+ } finally {
+ await act(async () => root.unmount());
+ host.remove();
+ delete (globalThis as { IntersectionObserver?: unknown }).IntersectionObserver;
+ shiki.codeToHtml.mockReset();
+ }
+ });
+});
diff --git a/src/components/CodeBlock.tsx b/src/components/CodeBlock.tsx
index 6705d229c9..56ce48677f 100644
--- a/src/components/CodeBlock.tsx
+++ b/src/components/CodeBlock.tsx
@@ -1,5 +1,5 @@
// Security: Shiki's output is generator-escaped; nothing else reaches the DOM as HTML.
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import type { HighlighterCore } from "shiki/core";
import { Check, Copy, Download, MoreHorizontal, WrapText, X } from "lucide-react";
@@ -7,6 +7,7 @@ import { cn } from "@/lib/cn";
import { useCopyFeedback } from "@/lib/copy-text";
import { t } from "@/lib/i18n";
import { useAdvancedMode } from "@/lib/interface-mode";
+import { useNearScreen } from "@/lib/on-screen";
import { countLines, downloadSnippetFile, formatLineCount, getLanguageDisplayName, getSnippetFileName } from "../lib/code-block";
import { SidebarPopoverMenu, type SidebarMenuItem } from "./SidebarPopoverMenu";
@@ -196,8 +197,12 @@ export function CodePlate({ copied, onCopy, copyLabel, items }: {
export function CodeBlock({ code, lang, initialWrap = false }: CodeBlockProps) {
const simple = !useAdvancedMode();
+ const frame = useRef<HTMLDivElement>(null);
+ // A long chat can hold dozens of blocks: coloured ones are thousands of spans to style and lay out on every switch,
+ // so a block is coloured only once it comes near the screen.
+ const near = useNearScreen(frame);
const highlightable = code.length <= HIGHLIGHT_MAX_CHARS;
- const [html, setHtml] = useState<string | null>(() => highlightable ? highlightCache.get(highlightKey(lang, code)) ?? null : null);
+ const [html, setHtml] = useState<string | null>(() => highlightable && near ? highlightCache.get(highlightKey(lang, code)) ?? null : null);
// React compares dangerouslySetInnerHTML by identity: a fresh object each render rebuilds the highlighted DOM.
const markup = useMemo(() => (html ? { __html: html } : null), [html]);
const { state: copied, copy } = useCopyFeedback(code);
@@ -208,6 +213,7 @@ export function CodeBlock({ code, lang, initialWrap = false }: CodeBlockProps) {
useEffect(() => {
if (!highlightable) return setHtml(null);
+ if (!near) return;
const key = highlightKey(lang, code);
const cached = highlightCache.get(key);
if (cached) return setHtml(cached);
@@ -223,7 +229,7 @@ export function CodeBlock({ code, lang, initialWrap = false }: CodeBlockProps) {
return () => {
alive = false;
};
- }, [code, lang, highlightable]);
+ }, [code, lang, highlightable, near]);
const download = () => {
const filename = getSnippetFileName(lang);
@@ -247,7 +253,7 @@ export function CodeBlock({ code, lang, initialWrap = false }: CodeBlockProps) {
if (simple) {
return (
- <div dir="ltr" className="chat-code-block group/code relative my-2.5 overflow-hidden rounded-lg bg-ink/[0.04]">
+ <div ref={frame} dir="ltr" className="chat-code-block group/code relative my-2.5 overflow-hidden rounded-lg bg-ink/[0.04]">
<CodePlate copied={copied} onCopy={copy} copyLabel={t("code.copyTitle")} items={[
{ key: "wrap", label: t("code.wrapLines"), icon: <WrapText size={14} aria-hidden="true" />, active: wrapLines, onSelect: () => setWrapLines((wrap) => !wrap) },
{ key: "save", label: t("code.saveAsFile"), icon: <Download size={14} aria-hidden="true" />, onSelect: download },
@@ -259,7 +265,7 @@ export function CodeBlock({ code, lang, initialWrap = false }: CodeBlockProps) {
}
return (
- <div dir="ltr" className="chat-code-block my-2 overflow-hidden rounded-lg border border-hairline/40 bg-inset">
+ <div ref={frame} dir="ltr" className="chat-code-block my-2 overflow-hidden rounded-lg border border-hairline/40 bg-inset">
<div className="flex flex-wrap items-center justify-between gap-2 border-b border-hairline/30 bg-raised/30 px-3 py-1.5 text-xs">
<div className="flex min-w-0 flex-1 items-center gap-2">
<span title={displayLanguage} className="min-w-0 truncate rounded border border-hairline/40 bg-raised px-1.5 py-0.5 text-[11px] font-medium tracking-wide text-ink select-none">
diff --git a/src/lib/on-screen.test.ts b/src/lib/on-screen.test.ts
new file mode 100644
index 0000000000..f4586fdcc9
--- /dev/null
+++ b/src/lib/on-screen.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment happy-dom
+import { act, createElement, useRef } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { useNearScreen } from "./on-screen";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+// The module makes its observer once, on first use, so only the first test that watches sees this fake's reports.
+class FakeObserver {
+ static last: FakeObserver | undefined;
+ watched = new Set<Element>();
+ constructor(
+ public report: (changes: { target: Element; isIntersecting: boolean }[]) => void,
+ public options?: IntersectionObserverInit,
+ ) {
+ FakeObserver.last = this;
+ }
+ observe(target: Element) { this.watched.add(target); }
+ unobserve(target: Element) { this.watched.delete(target); }
+}
+
+function Probe() {
+ const ref = useRef<HTMLDivElement>(null);
+ return createElement("div", { ref, "data-near": String(useNearScreen(ref)) });
+}
+
+let host: HTMLDivElement;
+let root: Root;
+const near = () => (host.firstElementChild as HTMLElement).dataset.near;
+
+beforeEach(() => {
+ vi.stubGlobal("IntersectionObserver", FakeObserver);
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ host.remove();
+ vi.unstubAllGlobals();
+});
+
+describe("useNearScreen", () => {
+ it("is false until the element comes near, then stays true and stops watching", () => {
+ act(() => root.render(createElement(Probe)));
+ const watcher = FakeObserver.last!;
+ const element = host.firstElementChild!;
+ expect([...watcher.watched]).toEqual([element]);
+ expect(watcher.options).toMatchObject({ rootMargin: "800px 0px" });
+ act(() => watcher.report([{ target: element, isIntersecting: false }]));
+ expect(near()).toBe("false");
+ act(() => watcher.report([{ target: element, isIntersecting: true }]));
+ expect(near()).toBe("true");
+ expect(watcher.watched.size).toBe(0);
+ });
+
+ it("is true at once where the browser cannot tell", () => {
+ vi.stubGlobal("IntersectionObserver", undefined);
+ act(() => root.render(createElement(Probe)));
+ expect(near()).toBe("true");
+ });
+});
diff --git a/src/lib/on-screen.ts b/src/lib/on-screen.ts
index 6f14de0e63..b3ede64bb7 100644
--- a/src/lib/on-screen.ts
+++ b/src/lib/on-screen.ts
@@ -1,17 +1,28 @@
import { useEffect, useState, type RefObject } from "react";
-const watchers = new Map<Element, (onScreen: boolean) => void>();
-let observer: IntersectionObserver | undefined;
+// One observer per margin, each with its own elements, so an element can be watched at two margins at once.
+const observers = new Map<number, { observer: IntersectionObserver; watchers: Map<Element, (onScreen: boolean) => void> }>();
-function watch(element: Element, onChange: (onScreen: boolean) => void): () => void {
- observer ??= new IntersectionObserver((entries) => {
- for (const entry of entries) watchers.get(entry.target)?.(entry.isIntersecting);
- });
+function watch(element: Element, onChange: (onScreen: boolean) => void, margin = 0): () => void {
+ let watching = observers.get(margin);
+ if (!watching) {
+ const watchers = new Map<Element, (onScreen: boolean) => void>();
+ const observer = new IntersectionObserver(
+ (entries) => {
+ for (const entry of entries) watchers.get(entry.target)?.(entry.isIntersecting);
+ },
+ // scrollMargin carries the margin into scrolling boxes (like the chat's), not only the window.
+ margin ? ({ rootMargin: `${margin}px 0px`, scrollMargin: `${margin}px 0px` } as IntersectionObserverInit) : undefined,
+ );
+ watching = { observer, watchers };
+ observers.set(margin, watching);
+ }
+ const { observer, watchers } = watching;
watchers.set(element, onChange);
observer.observe(element);
return () => {
watchers.delete(element);
- observer?.unobserve(element);
+ observer.unobserve(element);
};
}
@@ -26,3 +37,18 @@ export function useOnScreen(ref: RefObject<Element | null>): boolean {
}, [ref]);
return onScreen;
}
+
+/** How far from the screen, in pixels, an element counts as near it. */
+const NEAR_SCREEN_MARGIN = 800;
+
+/** Whether the element has come within NEAR_SCREEN_MARGIN of the screen yet. It stays true once it has, and is true at
+ * once where the browser cannot tell. */
+export function useNearScreen(ref: RefObject<Element | null>): boolean {
+ const [near, setNear] = useState(() => typeof IntersectionObserver === "undefined");
+ useEffect(() => {
+ const element = ref.current;
+ if (near || !element) return;
+ return watch(element, (nearNow) => nearNow && setNear(true), NEAR_SCREEN_MARGIN);
+ }, [ref, near]);
+ return near;
+}