From cb931855e554a256fd3d7f36ce11bb0dcabcb83d Mon Sep 17 00:00:00 2001 From: olibaron Date: Fri, 11 Sep 2026 11:32:47 +0200 Subject: [PATCH 1/3] fix: settle a finished block to a plain render, animation and all MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A streamed block wore the animated shape for its whole life, and the closed render then replaced it with markup that carried no animation at all. For the words that was invisible — they had finished fading — but the swap itself was not. The code gutter was rebuilt from scratch, every entry restarting its fade, and a table's last row jumped from partial opacity to full in a single frame. Every block kind now makes that swap once, after the fade it started has run, one pass per closed block: - `MarkdownCode` books the pass on a timer instead of swapping children during render, and the guard is a flag rather than the children, so a settle that produced nothing to adopt cannot re-arm it; - the pass is skipped when the animation is off, where the closed shape is already the plain one, and `reset()` cancels one that is still booked; - line numbers take the code cache's tally in both phases — the settled tree holds the same lines — and remember the last tally, so a caller that withdraws it can no longer collapse the gutter and remount every entry; - tables and markup get the same pass from the renderer, rebuilt from a cache of its own so a later block cannot race it; - a finished block carries no `data-animate-word`, `data-animate-key` or `data-animate-marker`: its frame is byte-identical to the same document streamed with the animation off, and blocks already settled are never re-passed when new ones stream. Coverage stays at 100%, including the guards these passes added. --- lib/code/index.tsx | 48 +++++++++-- lib/code/line-numbers.tsx | 17 +++- lib/renderer.tsx | 109 +++++++++++++++++++++++-- tests/coverage/renderer-edges.test.tsx | 56 +++++++++++++ 4 files changed, 214 insertions(+), 16 deletions(-) diff --git a/lib/code/index.tsx b/lib/code/index.tsx index 7010251..9ee08b7 100644 --- a/lib/code/index.tsx +++ b/lib/code/index.tsx @@ -22,7 +22,11 @@ export interface CodeBlockProps { events?: Emitter | undefined; ui?: UiConfig | undefined; scrollDown?: unknown; - /** Line total from the streaming cache, when it is the one rendering. */ + /** + * Line total from the code cache. It is passed in both phases: the settled + * tree holds the same lines, and withdrawing the tally at the settle is what + * made the gutter rebuild every entry it had. + */ lineCount?: number | undefined; } @@ -37,6 +41,8 @@ class MarkdownCode extends PureComponent { private currentScrollHeight = 0; private readonly codeRef = React.createRef(); private readonly wrapperRef = React.createRef(); + /** Whether the settle has been decided; kept apart from what it produced. */ + private settled = false; private settledChildren: ReactNode | undefined; private settleTimeout: ReturnType | undefined; @@ -75,6 +81,7 @@ class MarkdownCode extends PureComponent { ) { clearTimeout(vm.settleTimeout); vm.settleTimeout = undefined; + vm.settled = false; vm.settledChildren = undefined; vm.scheduleSettledChildren(); } @@ -204,9 +211,17 @@ class MarkdownCode extends PureComponent { fullscreen = " fullscreen"; } + // The settle is the final render, so the gutter stops animating with it — + // while it is still streaming, and during the wait before the settled tree + // is adopted, the entries keep fading in as their lines arrive. + const lineAnimation = vm.settled === true ? false : props.animation; + children = props.children; - if (vm.settledChildren) { + // The flag is the decision, the content is only the payload: a settle that + // came back with nothing to adopt must leave the cached tree on screen + // rather than blank the block. + if (vm.settled === true && vm.settledChildren) { children = vm.settledChildren; } @@ -237,8 +252,8 @@ class MarkdownCode extends PureComponent { {ui.lineNumbers === false ? null : ( )} @@ -258,24 +273,39 @@ class MarkdownCode extends PureComponent { const vm = this; const props = vm.props; - if (props.stream === true || vm.settleTimeout !== undefined) { + if ( + props.stream === true || + vm.settled === true || + vm.settleTimeout !== undefined + ) { return; } delay = props.animation === true ? 1000 : 0; if (delay === 0) { - vm.settledChildren = props.preChildren; - vm.setState({ finalStream: true }); + vm.applySettledChildren(); return; } vm.settleTimeout = setTimeout(() => { - vm.settledChildren = vm.props.preChildren; vm.settleTimeout = undefined; - vm.setState({ finalStream: true }); + vm.applySettledChildren(); }, delay); } + + /** + * Adopt the settled tree, once. The flag — not the children — is what stops + * a second pass, so a settle that produced nothing to adopt cannot put the + * block back on the timer or leave the guard re-evaluating on every render. + */ + private applySettledChildren(): void { + const vm = this; + + vm.settled = true; + vm.settledChildren = vm.props.preChildren; + vm.setState({ finalStream: true }); + } } export default MarkdownCode; diff --git a/lib/code/line-numbers.tsx b/lib/code/line-numbers.tsx index 1141a75..fa22699 100644 --- a/lib/code/line-numbers.tsx +++ b/lib/code/line-numbers.tsx @@ -9,6 +9,10 @@ interface LineNumberProps { * `textContent` back off the DOM — that re-serialises the whole fence on * every chunk, so a long block spends more time counting its gutter than * rendering its code. + * + * The caller may stop passing it — there is nothing left to count once the + * block has settled, and a host with no cache never passes it at all. The + * last tally is kept, so a withdrawn tally cannot take the gutter with it. */ lineCount?: number | undefined; } @@ -29,6 +33,9 @@ class LineNumber extends Component { private cachedGroups: ReactNode[] = []; private cachedAnimation: boolean | undefined; + /** The last tally the caller gave, kept for when it is withdrawn. */ + private lastKnownTotal = 0; + /** Lines per memoised group. Small enough that the tail stays cheap. */ private static readonly groupSize = 64; @@ -69,15 +76,21 @@ class LineNumber extends Component { * state only catches up in componentDidUpdate, which would render the gutter * from the previous count and leave every line number one pass behind the * line it belongs to. + * + * It is remembered as well as returned, because the caller may withdraw it. + * Nothing has been counted while the prop was there, so state would still be + * zero, and that zero renders the empty-state span for a pass — unmounting + * every entry and restarting the fade on all of them. */ private total(): number { const vm = this; if (typeof vm.props.lineCount === "number") { - return vm.props.lineCount; + vm.lastKnownTotal = vm.props.lineCount; + return vm.lastKnownTotal; } - return vm.state.lineNumberTotal; + return vm.state.lineNumberTotal || vm.lastKnownTotal; } lineNumberCount() { diff --git a/lib/renderer.tsx b/lib/renderer.tsx index 4213ba2..2a46db1 100644 --- a/lib/renderer.tsx +++ b/lib/renderer.tsx @@ -104,6 +104,8 @@ class Renderer { private codeCache = new CodeCache(); private tableCache = new TableCache(); private listCache = new ListCache(); + /** Pending settled passes, one per closed block; dropped on reset. */ + private settleTimers = new Map>(); private components!: ReturnType & RendererComponents; /** Host-supplied component overrides, applied to every component map. */ private componentOverrides!: RendererComponents; @@ -275,6 +277,13 @@ class Renderer { this.cachedFootnotes = null; this.resetLineCache(); + + this.settleTimers.forEach((timer) => { + clearTimeout(timer); + }); + + this.settleTimers.clear(); + this.applyState({}); } @@ -825,6 +834,14 @@ class Renderer { } } + // Only a live block has animation to strip: when the message is not + // streaming, processMd() already rendered it through the plain shape. + if (streaming === true) { + vm.scheduleSettle(blockId, animation, () => + vm.settledMarkupBlock(mdBuffer, streaming), + ); + } + vm.mdBuffer = closeObject.mdNext; vm.applyState({ md: mdState }, () => { @@ -1080,14 +1097,19 @@ class Renderer { } // Both the streaming frames and the closed one are built here, so React - // sees the same shape throughout and never remounts the table. - private tableElement(stream: boolean): ReactElement { + // sees the same shape throughout and never remounts the table. The settled + // pass brings a cache of its own: the same rows, built without the word + // spans the streaming shape wraps them in. + private tableElement( + stream: boolean, + cache: TableCache = this.tableCache, + ): ReactElement { let hasRows; const vm = this; // Only whether any row exists matters; filtering copies the whole array. - hasRows = vm.tableCache.data.some((row) => row); + hasRows = cache.data.some((row) => row); return ( - {vm.tableCache.head} - {hasRows ? {vm.tableCache.data} : null} + {cache.head} + {hasRows ? {cache.data} : null} ); } + /** + * Book a settled pass for a closed block. + * + * Nothing is deferred when the animation is off: the shape it closed in is + * already the settled one, so the pass would re-render identical markup. + */ + private scheduleSettle( + blockId: number, + animation: boolean, + rebuild: () => ReactNode, + ): void { + const vm = this; + + if (animation !== true) { + return; + } + + vm.settleTimers.set( + blockId, + setTimeout(() => { + vm.settleTimers.delete(blockId); + vm.settleBlock(blockId, rebuild); + }, 1000), + ); + } + + /** + * Replace a closed block's element once its fades have run, so the finished + * block is a plain render. Waiting is what makes it invisible: content caught + * mid-fade would jump from its partial opacity to full the moment the + * animated spans and markers go. + */ + private settleBlock(blockId: number, rebuild: () => ReactNode): void { + const vm = this; + const block = vm.streamDataMap.get(blockId); + const element = rebuild(); + + if (!block || !element) { + return; + } + + block.time = runtime.timeNow(); + block.element = element; + vm.applyState({ md: vm.mdState }); + } + + /** A closed table's rows again, built without the streaming word spans. */ + private settledTableBlock(mdBuffer: string): ReactElement { + const vm = this; + const cache = new TableCache(); + + cache.append(mdBuffer, vm.processorFor("cached-table"), { + ...cellComponents(vm), + ...vm.componentOverrides, + }); + + return vm.tableElement(false, cache); + } + + /** + * The same markup again, through the same pipeline minus the animation + * stage: prose, lists and maths lose their word spans, links their + * `data-animate-key`, and items their fading marker. + */ + private settledMarkupBlock( + mdBuffer: string, + streaming: boolean, + ): ReactNode { + return this.processMd(mdBuffer, streaming, false); + } + // The list wrapper. Its attributes follow from the items themselves: the // start number from the first marker, the task-list class from whether any // item rendered a checkbox. @@ -1248,6 +1341,12 @@ class Renderer { } } + if (vm.tableCache.head) { + vm.scheduleSettle(blockId, animation, () => + vm.settledTableBlock(mdBuffer), + ); + } + vm.mdBuffer = closeObject.mdNext; vm.applyState({ md: mdState }, () => { diff --git a/tests/coverage/renderer-edges.test.tsx b/tests/coverage/renderer-edges.test.tsx index 5bc533b..c24becd 100644 --- a/tests/coverage/renderer-edges.test.tsx +++ b/tests/coverage/renderer-edges.test.tsx @@ -200,6 +200,62 @@ describe("renderer defensive and callback paths", () => { expect(scrollDown).toHaveBeenCalled(); }); + it("drops a booked settled pass when the renderer resets", () => { + vi.useFakeTimers(); + + try { + const renderer: any = new Renderer({ streaming: true, animation: true }); + + // Finalizing closes the block, which books its settled pass. + renderer.streamMd("text\n\n", true, true, true); + expect(renderer.settleTimers.size).toBe(1); + + const settle = vi.spyOn(renderer, "settleBlock"); + + renderer.reset(); + + expect(renderer.settleTimers.size).toBe(0); + + // The cancelled pass must not run against the reset state. + vi.advanceTimersByTime(5000); + expect(settle).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } + }); + + it("ignores a settled pass whose block, or rebuild, is gone", () => { + const renderer: any = new Renderer({ streaming: true, animation: true }); + + // The block is not in the map any more: nothing to replace, nothing added. + expect(() => renderer.settleBlock(404, () =>
gone
)).not.toThrow(); + expect(renderer.streamDataMap.size).toBe(0); + + // The block is there, but its rebuild came back with nothing to show. + renderer.streamDataMap.set(7, { + key: 7, + time: 0, + element:
streamed
, + }); + + renderer.settleBlock(7, () => null); + + expect(renderer.streamDataMap.get(7).element).toBeTruthy(); + }); + + it("books no settled pass for a close that was never streaming", () => { + const renderer: any = new Renderer({ streaming: false, animation: true }); + + renderer.streamMd("text\n\n", false, true, true); + + // The block did close... + expect(renderer.streamData.length).toBe(1); + + // ...but a non-streaming close already rendered through the plain shape, + // so there is nothing to strip and no pass is booked. + expect(renderer.settleTimers.size).toBe(0); + }); + it("falls back to the regular processor for an unknown internal shape", () => { const processor = createProcessor("unknown" as any, {} as any); expect(processor.processSync("text").result).toBeTruthy(); From a50bf6c382bfdcce4f9e292347c8fd91731454ab Mon Sep 17 00:00:00 2001 From: olibaron Date: Fri, 11 Sep 2026 11:32:52 +0200 Subject: [PATCH 2/3] fix: let the host import tippy's stylesheet, the way it imports KaTeX's MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tippy.js became an optional peer so that a consumer which never renders a toolbar would not pay for it, but the stylesheet still inlined tippy's base CSS: every consumer shipped it, and the build in turn needed the package installed, which nothing did — so `npm run build` could not pass from a clean `npm ci`. The main stylesheet now carries only the toolbar skin and no longer imports from `node_modules`. A host that renders toolbars imports tippy's own sheet beside the one it already imports for KaTeX: import "tippy.js/dist/tippy.css"; Documented in `styling.md` and the README, and applied to the site demo, the playground and the example page. The built stylesheet drops by the 1.4 kB tippy sheet, and the build assertion still guards the skin. tippy.js stays a peer and a devDependency, exactly as KaTeX does: `tsc` needs its types and the tooltip loader test needs the runtime. Also comments out `will-change: opacity` on the word and marker fades, which promoted a compositor layer per word for no measured gain. --- README.md | 7 ++++++ example/index.html | 9 +++++++ package-lock.json | 10 ++++++-- package.json | 1 + scripts/build-css.mjs | 4 ++- styles/hypermarkdown.scss | 25 ++++++++++--------- website/docs/styling.md | 8 ++++++ website/src/components/home/LiveDemo.tsx | 1 + .../components/playground/PlaygroundApp.tsx | 1 + 9 files changed, 51 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 47430b3..209f120 100644 --- a/README.md +++ b/README.md @@ -124,6 +124,13 @@ Import the component stylesheet once in your application entry point: import "@aeven-ai/hypermarkdown/styles.css"; ``` +If you render the code or diagram toolbars, tippy.js — an optional peer — also +needs its stylesheet, the same way KaTeX does: + +```tsx +import "tippy.js/dist/tippy.css"; +``` + Then import the component: ```tsx diff --git a/example/index.html b/example/index.html index 933e64b..28e78e7 100644 --- a/example/index.html +++ b/example/index.html @@ -80,6 +80,15 @@ href="./katex.css" /> + + +