diff --git a/lib/code/header.tsx b/lib/code/header.tsx index 693c7aa..f090e8e 100644 --- a/lib/code/header.tsx +++ b/lib/code/header.tsx @@ -19,13 +19,12 @@ interface HeaderProps { } class Header extends Component { - private ticking = false; private tippyCopyTimeout: ReturnType | undefined; private readonly guid = runtime.guid(); private readonly headerRef = React.createRef(); private readonly tippyFullScreenRef = React.createRef(); private readonly tippyCopyContentRef = React.createRef(); - private stopWatchingScroll: (() => void) | undefined; + private stickyHeader: runtime.StickyHeaderWatch | undefined; constructor(props: HeaderProps) { super(props); @@ -41,9 +40,10 @@ class Header extends Component { override componentDidMount() { const vm = this; - vm.updateHeaderScrollClass(); - vm.stopWatchingScroll = runtime.onViewportScroll( - vm.updateHeaderScrollClass, + vm.stickyHeader = runtime.watchStickyHeader( + () => vm.props.wrapperRef.current, + () => vm.headerRef.current, + () => vm.props.fullscreen === true, ); } @@ -171,41 +171,7 @@ class Header extends Component { } updateHeaderScrollClass() { - const vm = this; - - if (vm.ticking !== true) { - requestAnimationFrame(() => { - let rec; - let top; - let height; - - const wrapper = vm.props.wrapperRef?.current; - - if (vm.props.fullscreen === true) { - vm.headerRef?.current?.classList?.remove("scroll"); - } else { - if (wrapper) { - rec = wrapper.getBoundingClientRect(); - top = rec?.top || 0; - height = rec?.height || 0; - - if (top >= 56) { - vm.headerRef?.current?.classList?.remove("scroll"); - } else { - if (height + top > 106) { - vm.headerRef?.current?.classList?.add("scroll"); - } else { - vm.headerRef?.current?.classList?.remove("scroll"); - } - } - } - } - - vm.ticking = false; - }); - - vm.ticking = true; - } + this.stickyHeader?.update(); } previewButtonComponent(props: HeaderProps) { @@ -248,7 +214,7 @@ class Header extends Component { override componentWillUnmount() { const vm = this; - vm.stopWatchingScroll?.(); + vm.stickyHeader?.stop(); } override render() { diff --git a/lib/mermaid/header.tsx b/lib/mermaid/header.tsx index ec268a9..7022b6a 100644 --- a/lib/mermaid/header.tsx +++ b/lib/mermaid/header.tsx @@ -18,12 +18,11 @@ interface HeaderProps { } class Header extends Component { - private ticking = false; private tippyCopyTimeout: ReturnType | undefined; private readonly headerRef = React.createRef(); private readonly tippyFullScreenRef = React.createRef(); private readonly tippyCopyContentRef = React.createRef(); - private stopWatchingScroll: (() => void) | undefined; + private stickyHeader: runtime.StickyHeaderWatch | undefined; constructor(props: HeaderProps) { super(props); @@ -35,9 +34,10 @@ class Header extends Component { override componentDidMount() { const vm = this; - vm.updateHeaderScrollClass(); - vm.stopWatchingScroll = runtime.onViewportScroll( - vm.updateHeaderScrollClass, + vm.stickyHeader = runtime.watchStickyHeader( + () => vm.props.wrapperRef.current, + () => vm.headerRef.current, + () => vm.props.fullscreen === true, ); } @@ -106,46 +106,12 @@ class Header extends Component { } updateHeaderScrollClass() { - const vm = this; - - if (vm.ticking !== true) { - requestAnimationFrame(() => { - let rec; - let top; - let height; - - const wrapper = vm.props?.wrapperRef?.current; - - if (vm.props.fullscreen === true) { - vm.headerRef?.current?.classList?.remove("scroll"); - } else { - if (wrapper) { - rec = wrapper.getBoundingClientRect(); - top = rec?.top || 0; - height = rec?.height || 0; - - if (top >= 56) { - vm.headerRef?.current?.classList?.remove("scroll"); - } else { - if (height + top > 106) { - vm.headerRef?.current?.classList?.add("scroll"); - } else { - vm.headerRef?.current?.classList?.remove("scroll"); - } - } - } - } - - vm.ticking = false; - }); - - vm.ticking = true; - } + this.stickyHeader?.update(); } override componentWillUnmount() { const vm = this; - vm.stopWatchingScroll?.(); + vm.stickyHeader?.stop(); } override render() { diff --git a/lib/runtime.ts b/lib/runtime.ts index f6b68cb..d0dcf23 100644 --- a/lib/runtime.ts +++ b/lib/runtime.ts @@ -148,3 +148,148 @@ export function onViewportScroll(handler: () => void): () => void { window.removeEventListener("resize", handler); }; } + +/** Distance from the host's sticky chat header at which a block toolbar goes flat. */ +const STICKY_HEADER_OFFSET = 56; + +/** Below this the block is nearly scrolled past, so the toolbar drops away. */ +const STICKY_HEADER_MIN_VISIBLE = 106; + +interface StickyHeader { + readonly wrapper: () => HTMLElement | null; + readonly header: () => HTMLElement | null; + readonly fullscreen: () => boolean; + target: HTMLElement | null; + stuck: boolean; +} + +/** Handle for one block toolbar registered with {@link watchStickyHeader}. */ +export interface StickyHeaderWatch { + /** Recompute this toolbar now, for changes no scroll reports (fullscreen). */ + update(): void; + /** Stop watching and clear the class, so a later registration starts from the element's real state. */ + stop(): void; +} + +const stickyPending = new Set(); +const stickyOnScreen = new Set(); +const stickyByTarget = new Map(); +let stickyObserver: IntersectionObserver | undefined; +let stopStickyScroll: (() => void) | undefined; + +function isStuck(entry: StickyHeader): boolean { + if (entry.target === null || entry.fullscreen()) return false; + const rect = entry.target.getBoundingClientRect(); + const top = rect.top || 0; + return top < STICKY_HEADER_OFFSET && top + (rect.height || 0) > STICKY_HEADER_MIN_VISIBLE; +} + +function setStuck(entry: StickyHeader, stuck: boolean): void { + if (entry.stuck === stuck) return; + entry.stuck = stuck; + entry.header()?.classList.toggle("scroll", stuck); +} + +/** Reads every on-screen block before writing any class, so one pass lays out once. */ +function updateOnScreen(): void { + const next = [...stickyOnScreen].map((entry) => [entry, isStuck(entry)] as const); + for (const [entry, stuck] of next) setStuck(entry, stuck); +} + +/** Scroll and resize are watched only while some block is on screen. */ +function syncStickyScroll(): void { + if (stickyOnScreen.size > 0) { + stopStickyScroll ??= onViewportScroll(updateOnScreen); + } else { + stopStickyScroll?.(); + stopStickyScroll = undefined; + } +} + +function onStickyIntersection(entries: IntersectionObserverEntry[]): void { + for (const change of entries) { + const entry = stickyByTarget.get(change.target); + if (entry === undefined) continue; + if (change.isIntersecting) { + stickyOnScreen.add(entry); + setStuck(entry, isStuck(entry)); + } else { + // Off screen the block cannot span the toolbar band. + stickyOnScreen.delete(entry); + setStuck(entry, false); + } + } + syncStickyScroll(); +} + +/** Attach registrations whose wrapper ref has committed since they were made. */ +function attachPending(): void { + for (const entry of stickyPending) { + const target = entry.wrapper(); + if (target === null) continue; + stickyPending.delete(entry); + entry.target = target; + stickyByTarget.set(target, entry); + if (typeof IntersectionObserver === "undefined") { + stickyOnScreen.add(entry); + setStuck(entry, isStuck(entry)); + } else { + stickyObserver ??= new IntersectionObserver(onStickyIntersection); + stickyObserver.observe(target); + } + } + syncStickyScroll(); +} + +/** + * Keep a block toolbar's "scroll" class in step with its block's position: + * set while the block spans the band below the host's sticky header, cleared + * otherwise and in fullscreen. + * + * One IntersectionObserver and one capturing scroll listener serve every + * block on the page, and the listener measures only blocks on screen, so an + * idle transcript with hundreds of blocks costs nothing per scroll frame. The + * class is written only when the state changes: `classList` add and remove + * rewrite the attribute, and so queue a mutation record, even when the token + * is already in the requested state. + * + * The wrapper is read on the next frame, after the host commits its ref; + * without IntersectionObserver every block counts as on screen. + * @param wrapper - reads the block element whose position decides the state. + * @param header - reads the toolbar element that carries the class. + * @param fullscreen - reads whether the block is fullscreen. + * @returns the registration's update and stop handle. + */ +export function watchStickyHeader( + wrapper: () => HTMLElement | null, + header: () => HTMLElement | null, + fullscreen: () => boolean, +): StickyHeaderWatch { + const entry: StickyHeader = { wrapper, header, fullscreen, target: null, stuck: false }; + + if (typeof window === "undefined") { + return { update() {}, stop() {} }; + } + + stickyPending.add(entry); + requestAnimationFrame(attachPending); + + return { + update() { + if (entry.target !== null && (fullscreen() || stickyOnScreen.has(entry))) { + setStuck(entry, isStuck(entry)); + } + }, + stop() { + setStuck(entry, false); + stickyPending.delete(entry); + stickyOnScreen.delete(entry); + if (entry.target !== null) { + stickyByTarget.delete(entry.target); + stickyObserver?.unobserve(entry.target); + entry.target = null; + } + syncStickyScroll(); + }, + }; +} diff --git a/lib/table/header.tsx b/lib/table/header.tsx index 6f4c83f..9a48a07 100644 --- a/lib/table/header.tsx +++ b/lib/table/header.tsx @@ -12,12 +12,6 @@ import { defaultUi } from "../config"; import type { UiConfig } from "../config"; import Tooltip, { type TooltipHandle } from "../tooltip"; -/** Distance from the sticky chat header at which the toolbar goes flat. */ -const HEADER_OFFSET = 56; - -/** Below this the table is nearly scrolled past, so the toolbar drops away. */ -const HEADER_MIN_VISIBLE = 106; - interface TableHeaderProps { /** This renderer's own bus, so blocks report only to the renderer that made them. */ events?: Emitter | undefined; @@ -42,51 +36,31 @@ function TableHeaderComponent(props: TableHeaderProps) { const headerRef = useRef(null); const tippyCopyRef = useRef(null); - // The scroll handler is registered once but reads the current fullscreen - // value, so it goes through a ref rather than the closed-over state. - const tickingRef = useRef(false); + // The watch is registered once but reads the current fullscreen value, so + // it goes through a ref rather than the closed-over prop. + const fullscreenRef = useRef(fullscreen); + fullscreenRef.current = fullscreen; + const stickyHeaderRef = useRef(null); const copyTimeoutRef = useRef | undefined>( undefined, ); - const updateHeaderScrollClass = useCallback(() => { - if (tickingRef.current === true) { - return; - } - - tickingRef.current = true; - - requestAnimationFrame(() => { - const header = headerRef.current; - const wrapper = wrapperRef.current; - - tickingRef.current = false; - - if (!header) { - return; - } - - if (fullscreen === true || !wrapper) { - header.classList.remove("scroll"); - return; - } - - const rect = wrapper.getBoundingClientRect(); - const top = rect?.top || 0; - const height = rect?.height || 0; - - if (top < HEADER_OFFSET && height + top > HEADER_MIN_VISIBLE) { - header.classList.add("scroll"); - } else { - header.classList.remove("scroll"); - } - }); - }, [fullscreen, wrapperRef]); + useEffect(() => { + const watch = runtime.watchStickyHeader( + () => wrapperRef.current, + () => headerRef.current, + () => fullscreenRef.current === true, + ); + stickyHeaderRef.current = watch; + return () => { + stickyHeaderRef.current = null; + watch.stop(); + }; + }, [wrapperRef]); useEffect(() => { - updateHeaderScrollClass(); - return runtime.onViewportScroll(updateHeaderScrollClass); - }, [updateHeaderScrollClass]); + stickyHeaderRef.current?.update(); + }, [fullscreen]); useEffect(() => { return () => { diff --git a/package-lock.json b/package-lock.json index a9b82c7..16641c7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@aeven-ai/hypermarkdown", - "version": "0.4.2", + "version": "0.4.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@aeven-ai/hypermarkdown", - "version": "0.4.2", + "version": "0.4.3", "license": "MIT", "dependencies": { "hast-util-to-jsx-runtime": "^2.3.6", diff --git a/package.json b/package.json index 7d8f623..447c6ad 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@aeven-ai/hypermarkdown", - "version": "0.4.2", + "version": "0.4.3", "description": "Ridiculously fast Markdown for React and AI. Streaming-native renderer that caches settled code lines, table rows, and list items so growing LLM output does not re-parse finished work.", "author": "Aeven", "repository": { diff --git a/tests/coverage/final-branches.test.tsx b/tests/coverage/final-branches.test.tsx index 9f65d55..f72592f 100644 --- a/tests/coverage/final-branches.test.tsx +++ b/tests/coverage/final-branches.test.tsx @@ -93,14 +93,11 @@ describe("remaining component branches", () => { }); expect(() => diagramHeader.copyContent(clickEvent)).not.toThrow(); - const frame = vi - .spyOn(globalThis, "requestAnimationFrame") - .mockImplementation((callback) => { - callback(0); - return 1; - }); - diagramHeader.updateHeaderScrollClass(); - expect(frame).toHaveBeenCalled(); + // An unmounted header holds no sticky watch, so an update schedules nothing. + const frame = vi.spyOn(globalThis, "requestAnimationFrame"); + expect(() => diagramHeader.updateHeaderScrollClass()).not.toThrow(); + expect(() => codeHeader.updateHeaderScrollClass()).not.toThrow(); + expect(frame).not.toHaveBeenCalled(); }); it("covers defensive diagram cleanup without a parent or mounted wrapper", () => { diff --git a/tests/coverage/runtime-server.test.ts b/tests/coverage/runtime-server.test.ts index 4cdbfad..5d25472 100644 --- a/tests/coverage/runtime-server.test.ts +++ b/tests/coverage/runtime-server.test.ts @@ -2,7 +2,7 @@ import { readFileSync } from "node:fs"; import { describe, expect, it, vi } from "vitest"; -import { currentPath, onViewportScroll } from "../../lib/runtime"; +import { currentPath, onViewportScroll, watchStickyHeader } from "../../lib/runtime"; import MermaidDiagram from "../../lib/mermaid"; import PanZoom from "../../lib/mermaid/pan-zoom"; import "../../index"; @@ -19,6 +19,11 @@ describe("runtime SSR adapters", () => { const stop = onViewportScroll(handler); expect(() => stop()).not.toThrow(); expect(handler).not.toHaveBeenCalled(); + const watch = watchStickyHeader(() => null, () => null, () => false); + expect(() => { + watch.update(); + watch.stop(); + }).not.toThrow(); }); it("renders diagrams without a DOM sandbox during SSR", async () => { diff --git a/tests/coverage/sticky-header.test.ts b/tests/coverage/sticky-header.test.ts new file mode 100644 index 0000000..f2df70d --- /dev/null +++ b/tests/coverage/sticky-header.test.ts @@ -0,0 +1,138 @@ +// @vitest-environment jsdom +import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"; + +import { watchStickyHeader } from "../../lib/runtime"; + +let frames: FrameRequestCallback[] = []; +const observed = new Set(); +let deliver: (target: Element, isIntersecting: boolean) => void = () => {}; + +beforeAll(() => { + window.requestAnimationFrame = ((callback: FrameRequestCallback) => { + frames.push(callback); + return frames.length; + }) as typeof window.requestAnimationFrame; + class FakeIntersectionObserver { + constructor(callback: IntersectionObserverCallback) { + deliver = (target, isIntersecting) => { + callback([{ target, isIntersecting } as IntersectionObserverEntry], this as never); + }; + } + observe(target: Element) { observed.add(target); } + unobserve(target: Element) { observed.delete(target); } + disconnect() { observed.clear(); } + } + (globalThis as { IntersectionObserver?: unknown }).IntersectionObserver = FakeIntersectionObserver; +}); + +afterEach(() => { + frames = []; + vi.restoreAllMocks(); +}); + +function flushFrames() { + const pending = frames; + frames = []; + pending.forEach((callback) => callback(performance.now())); +} + +function block(rect: { top: number; height: number }) { + const wrapper = document.createElement("div"); + const header = document.createElement("div"); + header.className = "codeblock-header"; + const measure = vi.fn(() => rect as DOMRect); + Object.defineProperty(wrapper, "getBoundingClientRect", { configurable: true, value: measure }); + const watch = watchStickyHeader(() => wrapper, () => header, () => false); + return { wrapper, header, measure, rect, watch }; +} + +describe("watchStickyHeader", () => { + it("measures only on-screen blocks and writes the class only when the state flips", () => { + const visible = block({ top: 0, height: 400 }); + const offscreen = block({ top: -5_000, height: 400 }); + flushFrames(); + expect(observed.has(visible.wrapper) && observed.has(offscreen.wrapper)).toBe(true); + + const records: MutationRecord[] = []; + const recorder = new MutationObserver((batch) => { records.push(...batch); }); + recorder.observe(visible.header, { attributes: true }); + recorder.observe(offscreen.header, { attributes: true }); + + deliver(visible.wrapper, true); + deliver(offscreen.wrapper, false); + expect(visible.header.classList.contains("scroll")).toBe(true); + for (let index = 0; index < 20; index += 1) window.dispatchEvent(new Event("scroll")); + + expect(offscreen.measure).not.toHaveBeenCalled(); + expect(visible.measure).toHaveBeenCalledTimes(21); + expect(recorder.takeRecords().length + records.length).toBe(1); + + visible.rect.top = 80; + visible.watch.update(); + expect(visible.header.classList.contains("scroll")).toBe(false); + + visible.watch.stop(); + offscreen.watch.stop(); + recorder.disconnect(); + }); + + it("clears a stuck toolbar when its block leaves the screen and detaches the scroll listener", () => { + const listening = vi.spyOn(window, "removeEventListener"); + const only = block({ top: 0, height: 400 }); + flushFrames(); + deliver(only.wrapper, true); + expect(only.header.classList.contains("scroll")).toBe(true); + + deliver(only.wrapper, false); + expect(only.header.classList.contains("scroll")).toBe(false); + expect(listening).toHaveBeenCalledWith("scroll", expect.any(Function), true); + + only.measure.mockClear(); + window.dispatchEvent(new Event("scroll")); + expect(only.measure).not.toHaveBeenCalled(); + only.watch.stop(); + expect(observed.has(only.wrapper)).toBe(false); + }); + + it("waits for the wrapper ref and clears the class on stop", () => { + let wrapper: HTMLElement | null = null; + const header = document.createElement("div"); + const watch = watchStickyHeader(() => wrapper, () => header, () => false); + flushFrames(); + watch.update(); + expect(observed.size).toBe(0); + + const element = document.createElement("div"); + Object.defineProperty(element, "getBoundingClientRect", { + configurable: true, + value: () => ({ top: 0, height: 400 }), + }); + wrapper = element; + const other = block({ top: 900, height: 10 }); + flushFrames(); + expect(observed.has(element)).toBe(true); + deliver(element, true); + expect(header.classList.contains("scroll")).toBe(true); + + watch.stop(); + expect(header.classList.contains("scroll")).toBe(false); + other.watch.stop(); + }); + + it("ignores a stopped block's queued intersection and stops a registration that never attached", () => { + const stopped = block({ top: 0, height: 400 }); + flushFrames(); + // Off screen, an explicit update measures nothing. + deliver(stopped.wrapper, false); + stopped.watch.update(); + expect(stopped.measure).not.toHaveBeenCalled(); + stopped.watch.stop(); + deliver(stopped.wrapper, true); + expect(stopped.header.classList.contains("scroll")).toBe(false); + + const neverAttached = watchStickyHeader(() => null, () => null, () => false); + neverAttached.stop(); + flushFrames(); + expect(observed.size).toBe(0); + }); +}); diff --git a/website/package-lock.json b/website/package-lock.json index 9796786..54ccd47 100644 --- a/website/package-lock.json +++ b/website/package-lock.json @@ -38,7 +38,7 @@ }, "..": { "name": "@aeven-ai/hypermarkdown", - "version": "0.4.2", + "version": "0.4.3", "license": "MIT", "dependencies": { "hast-util-to-jsx-runtime": "^2.3.6",