Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok-docs): reserve the real height for html preview blocks (PRD-7936) (#3406)

Andrew Mikofalvya3f25e8761c9
diff --git a/docs/package.json b/docs/package.json
index 0fbb00b65..c27100547 100644
--- a/docs/package.json
+++ b/docs/package.json
@@ -49,6 +49,7 @@
"@types/react-dom": "^19",
"fflate": "0.4.8",
"fumadocs-typescript": "~4.0.13",
+ "jsdom": "^29.1.1",
"next-validate-link": "^1.6.6",
"remark-mdx-snippets": "^0.3.3",
"schema-dts": "^2.0.0",
diff --git a/docs/src/components/html-preview.test.ts b/docs/src/components/html-preview.test.ts
new file mode 100644
index 000000000..eb0976a7e
--- /dev/null
+++ b/docs/src/components/html-preview.test.ts
@@ -0,0 +1,237 @@
+// @vitest-environment jsdom
+
+/**
+ * Layout-stability contract for `html preview` blocks.
+ *
+ * Every docs page that embeds one of these blocks reserves space for it before
+ * the sandboxed iframe can report its real height. If that reserve is a
+ * constant rather than the block's actual height, the whole page below the
+ * preview reflows the moment the measurement lands — measured at up to 593px on
+ * a single page, and visible to readers as the page "jumping" a beat after it
+ * appears.
+ *
+ * The reserve is therefore behavioral, not cosmetic, and these tests pin it at
+ * the only place a reader can observe it: the inline height the component
+ * commits to on its very first paint, before any measurement exists for that
+ * render.
+ *
+ * These run under jsdom via the per-file docblock above rather than a separate
+ * DOM tier: docs has no `test:dom` config, and the component's whole contract
+ * here is expressible through public DOM output, so the default `vitest run
+ * src` gate is the right home.
+ */
+
+import { act, createElement } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { HtmlPreview } from './html-preview.tsx';
+import {
+ DEFAULT_PREVIEW_RESERVE_PX,
+ MAX_PREVIEW_HEIGHT_PX,
+ resetPreviewHeightMemory,
+} from './preview-height-memory.ts';
+
+const actEnv = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
+
+const encode = (html: string) => Buffer.from(html, 'utf8').toString('base64');
+
+/** jsdom pins innerWidth, so width-keyed behaviour has to be driven explicitly. */
+const setViewportWidth = (width: number) => {
+ Object.defineProperty(window, 'innerWidth', {
+ value: width,
+ writable: true,
+ configurable: true,
+ });
+};
+
+const BLOCK_A = encode('<div id="a"><p>first block</p></div>');
+const BLOCK_B = encode('<div id="b"><p>a different block</p></div>');
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ // Heights are remembered in module scope, so without this each test would
+ // inherit whatever the previous one measured and the suite would depend on
+ // its own ordering.
+ resetPreviewHeightMemory();
+ // Width is part of the cache key, so a test that moved the viewport would
+ // otherwise change what the next one recalls.
+ setViewportWidth(1024);
+ actEnv.IS_REACT_ACT_ENVIRONMENT = true;
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+/** The element the component is currently reserving space with. */
+const reservedEl = () =>
+ container.querySelector<HTMLElement>('iframe[title="Interactive preview"]') ??
+ container.querySelector<HTMLElement>('div[style]');
+
+/** The inline height the component has committed to, in px. */
+const reservedHeight = () => {
+ const el = reservedEl();
+ if (!el) throw new Error('component rendered nothing to reserve space with');
+ const px = /height:\s*([\d.]+)px/.exec(el.getAttribute('style') ?? '');
+ if (!px) throw new Error(`no inline height on reserved element: ${el.outerHTML}`);
+ return Number(px[1]);
+};
+
+const render = (code: string) => {
+ act(() => {
+ root.render(createElement(HtmlPreview, { code }));
+ });
+};
+
+/**
+ * The height the component reserves on first paint, before its effects run --
+ * i.e. what a reader sees the instant the page appears. Rendering into a fresh
+ * root mirrors what React does when a client-side navigation mounts the block.
+ */
+const firstPaintReserve = (code: string) => {
+ const fresh = document.createElement('div');
+ document.body.appendChild(fresh);
+ const freshRoot = createRoot(fresh);
+ let height: number;
+ try {
+ act(() => {
+ freshRoot.render(createElement(HtmlPreview, { code }));
+ });
+ const el =
+ fresh.querySelector<HTMLElement>('iframe[title="Interactive preview"]') ??
+ fresh.querySelector<HTMLElement>('div[style]');
+ const px = /height:\s*([\d.]+)px/.exec(el?.getAttribute('style') ?? '');
+ if (!px) throw new Error(`no inline height on first paint: ${fresh.innerHTML}`);
+ height = Number(px[1]);
+ } finally {
+ act(() => freshRoot.unmount());
+ fresh.remove();
+ }
+ return height;
+};
+
+/**
+ * Deliver the height the sandboxed iframe reports back. jsdom does not execute
+ * srcDoc scripts, so the real inner script cannot run -- but it addresses its
+ * message with an id embedded in that same srcDoc, so recovering the id from
+ * the rendered attribute and posting the identical envelope exercises the
+ * component's real listener rather than a stand-in for it.
+ */
+const reportMeasuredHeight = (height: number) => {
+ const iframe = container.querySelector('iframe[title="Interactive preview"]');
+ if (!iframe) throw new Error('iframe has not mounted; cannot report a height');
+ const srcDoc = iframe.getAttribute('srcdoc') ?? '';
+ const id = /var ID=("[^"]+")/.exec(srcDoc);
+ if (!id) throw new Error('srcDoc does not carry the preview id the component listens for');
+ act(() => {
+ window.dispatchEvent(
+ new MessageEvent('message', { data: { __okpreview: JSON.parse(id[1]), h: height } }),
+ );
+ });
+};
+
+describe('HtmlPreview space reservation', () => {
+ test('adopts the height the iframe reports', () => {
+ render(BLOCK_A);
+ reportMeasuredHeight(328);
+ expect(reservedHeight()).toBe(328);
+ });
+
+ test('reserves a measured block at its measured height when it is rendered again', () => {
+ // A reader navigating away from a docs page and back -- or between two
+ // pages that both carry preview blocks -- remounts this component. The
+ // height of BLOCK_A is known by then, so the remount must not fall back to
+ // a placeholder guess and reflow the page a second time.
+ render(BLOCK_A);
+ reportMeasuredHeight(328);
+ expect(reservedHeight()).toBe(328);
+
+ expect(firstPaintReserve(BLOCK_A)).toBe(328);
+ });
+
+ test('does not lend one block its neighbour’s measured height', () => {
+ // Guards the remount fix from over-reaching: heights are per-block, so a
+ // block nobody has measured must not inherit an unrelated block's height.
+ render(BLOCK_A);
+ reportMeasuredHeight(328);
+
+ expect(firstPaintReserve(BLOCK_B)).not.toBe(328);
+ });
+
+ test('does not recall a height measured at a different viewport width', () => {
+ // The same block is legitimately a different height at a different width:
+ // one settles at 240px in a desktop column and 422px on a phone. Recalling
+ // across widths would reserve a number as wrong as the constant this
+ // replaced, so a different width has to miss rather than hit.
+ setViewportWidth(360);
+ render(BLOCK_A);
+ reportMeasuredHeight(422);
+ expect(reservedHeight()).toBe(422);
+
+ setViewportWidth(1280);
+ expect(firstPaintReserve(BLOCK_A)).toBe(DEFAULT_PREVIEW_RESERVE_PX);
+
+ // ...and returning to the original width still hits.
+ setViewportWidth(360);
+ expect(firstPaintReserve(BLOCK_A)).toBe(422);
+ });
+
+ test('drops a block’s remembered height when the code prop changes on a live root', () => {
+ // A preview on one docs page can be reconciled onto the one on the next
+ // rather than remounted. Without re-deriving during render the new block
+ // would open at the previous block's height, which is the reflow this
+ // whole change exists to remove.
+ render(BLOCK_A);
+ reportMeasuredHeight(512);
+ expect(reservedHeight()).toBe(512);
+
+ render(BLOCK_B);
+ expect(reservedHeight()).toBe(DEFAULT_PREVIEW_RESERVE_PX);
+ });
+
+ test('clamps an implausible reported height', () => {
+ render(BLOCK_A);
+ reportMeasuredHeight(MAX_PREVIEW_HEIGHT_PX + 1000);
+ expect(reservedHeight()).toBe(MAX_PREVIEW_HEIGHT_PX);
+ });
+
+ test('answers the frame even before a theme resolves', () => {
+ // The reply doubles as the acknowledgement that stops the frame
+ // announcing. The frame ships in the server HTML and starts announcing at
+ // parse time, so if the parent stayed silent until a theme resolved, a slow
+ // hydration would leave the frame retrying and its height discarded.
+ render(BLOCK_A);
+ const iframe = container.querySelector<HTMLIFrameElement>(
+ 'iframe[title="Interactive preview"]',
+ );
+ if (!iframe) throw new Error('iframe did not render');
+
+ const sent: unknown[] = [];
+ Object.defineProperty(iframe, 'contentWindow', {
+ value: { postMessage: (msg: unknown) => sent.push(msg) },
+ configurable: true,
+ });
+
+ reportMeasuredHeight(300);
+
+ expect(sent.length).toBeGreaterThan(0);
+ expect(sent.some((m) => (m as { __okpreview?: string }).__okpreview !== undefined)).toBe(true);
+ });
+
+ test('reserves the same height before and after the iframe replaces the placeholder', () => {
+ // The component renders a placeholder until it can pick a theme, then swaps
+ // in the iframe. If those two disagree on height, hydration itself becomes a
+ // second source of reflow, independent of measurement.
+ render(BLOCK_A);
+ reportMeasuredHeight(412);
+ const withIframe = reservedHeight();
+
+ expect(firstPaintReserve(BLOCK_A)).toBe(withIframe);
+ });
+});
diff --git a/docs/src/components/html-preview.tsx b/docs/src/components/html-preview.tsx
index 5b7dc4523..b62b864d2 100644
--- a/docs/src/components/html-preview.tsx
+++ b/docs/src/components/html-preview.tsx
@@ -4,21 +4,40 @@
* Renders a ` ```html preview ` block (base64'd by the remarkHtmlPreview
* plugin) as a sandboxed, auto-sizing iframe. The iframe gets the same
* OpenKnowledge theme tokens the editor injects, so one authored block looks
- * identical in the OK editor preview and here on the docs site. Height syncs
- * back over postMessage; theme follows the docs light/dark toggle.
+ * identical in the OK editor preview and here on the docs site.
+ *
+ * The document carries BOTH palettes and picks between them itself, which keeps
+ * `srcDoc` a pure function of the authored code. That matters twice over: the
+ * iframe can be rendered before the docs theme is known (so no empty card
+ * precedes it, and measuring starts as the page is parsed), and switching the
+ * docs theme no longer rewrites `srcDoc` and reloads every preview on the page.
*/
import { useTheme } from 'next-themes';
-import { useEffect, useId, useState } from 'react';
+import { useEffect, useId, useRef, useState } from 'react';
+import {
+ DEFAULT_PREVIEW_RESERVE_PX,
+ MAX_PREVIEW_HEIGHT_PX,
+ recallPreviewHeight,
+ rememberPreviewHeight,
+ restorePreviewHeights,
+} from './preview-height-memory';
const BASE =
'*{box-sizing:border-box}html,body{margin:0}body{background:transparent;color:var(--foreground);font-family:system-ui,-apple-system,sans-serif;font-size:14px;line-height:1.5}';
const LIGHT =
- ':root{--background:oklch(1 0 0);--foreground:oklch(0.145 0 0);--card:oklch(1 0 0);--card-foreground:oklch(0.145 0 0);--muted:oklch(0.97 0 0);--muted-foreground:oklch(0.556 0 0);--border:oklch(0.922 0 0);--primary:oklch(0.6321 0.1983 259.59);--accent-soft:#e6efff;--accent-ink:#00245d;--chart-1:oklch(0.62 0.19 259);--chart-2:oklch(0.58 0.14 145);--chart-3:oklch(0.62 0.15 70);--chart-4:oklch(0.55 0.18 290);--chart-5:oklch(0.58 0.21 25);--radius:0.625rem;color-scheme:light}';
+ '--background:oklch(1 0 0);--foreground:oklch(0.145 0 0);--card:oklch(1 0 0);--card-foreground:oklch(0.145 0 0);--muted:oklch(0.97 0 0);--muted-foreground:oklch(0.556 0 0);--border:oklch(0.922 0 0);--primary:oklch(0.6321 0.1983 259.59);--accent-soft:#e6efff;--accent-ink:#00245d;--chart-1:oklch(0.62 0.19 259);--chart-2:oklch(0.58 0.14 145);--chart-3:oklch(0.62 0.15 70);--chart-4:oklch(0.55 0.18 290);--chart-5:oklch(0.58 0.21 25);--radius:0.625rem;color-scheme:light';
const DARK =
- ':root{--background:oklch(0.205 0 0);--foreground:oklch(0.985 0 0);--card:oklch(0.245 0 0);--card-foreground:oklch(0.985 0 0);--muted:oklch(0.3 0 0);--muted-foreground:oklch(0.708 0 0);--border:oklch(1 0 0 / 0.14);--primary:#69a3ff;--accent-soft:#12233f;--accent-ink:#9ec3ff;--chart-1:oklch(0.72 0.14 259);--chart-2:oklch(0.73 0.13 145);--chart-3:oklch(0.77 0.14 70);--chart-4:oklch(0.72 0.16 290);--chart-5:oklch(0.72 0.2 25);--radius:0.625rem;color-scheme:dark}';
+ '--background:oklch(0.205 0 0);--foreground:oklch(0.985 0 0);--card:oklch(0.245 0 0);--card-foreground:oklch(0.985 0 0);--muted:oklch(0.3 0 0);--muted-foreground:oklch(0.708 0 0);--border:oklch(1 0 0 / 0.14);--primary:#69a3ff;--accent-soft:#12233f;--accent-ink:#9ec3ff;--chart-1:oklch(0.72 0.14 259);--chart-2:oklch(0.73 0.13 145);--chart-3:oklch(0.77 0.14 70);--chart-4:oklch(0.72 0.16 290);--chart-5:oklch(0.72 0.2 25);--radius:0.625rem;color-scheme:dark';
+
+/**
+ * The system preference is the starting point, and an explicit `data-theme` set
+ * by the parent wins over it in either direction. Defining every token on bare
+ * `:root` first means no variable exists only inside a media query.
+ */
+const THEME_CSS = `:root{${LIGHT}}@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){${DARK}}}:root[data-theme="dark"]{${DARK}}:root[data-theme="light"]{${LIGHT}}`;
function decode(b64: string): string {
if (typeof atob === 'undefined') return '';
@@ -26,45 +45,105 @@ function decode(b64: string): string {
return new TextDecoder().decode(bytes);
}
+/**
+ * How many 250ms announce ticks the document keeps trying for before giving up.
+ * 240 is a minute — far past any plausible hydration, and bounded so a page the
+ * parent never claims does not leave a timer running forever.
+ */
+const MAX_ANNOUNCE_TICKS = 240;
+
+function buildSrcDoc(code: string, domId: string): string {
+ const inner = decode(code);
+ const script =
+ '(function(){' +
+ `var ID=${JSON.stringify(domId)};` +
+ "function post(){parent.postMessage({__okpreview:ID,h:document.documentElement.scrollHeight},'*')}" +
+ "addEventListener('load',post);" +
+ "addEventListener('resize',post);" +
+ 'if(window.ResizeObserver){new ResizeObserver(post).observe(document.body)}' +
+ // Keep announcing until the parent answers, rather than for a fixed window.
+ // This document ships inside the server-rendered HTML, so it starts running
+ // as the page is parsed, while the parent only begins listening once it
+ // hydrates. A bounded window would drop the height and the theme for good
+ // on any hydration slower than the window.
+ `var n=0,t=setInterval(function(){post();if(++n>${MAX_ANNOUNCE_TICKS})clearInterval(t)},250);` +
+ "addEventListener('message',function(e){" +
+ 'var d=e.data;' +
+ 'if(!d||d.__okpreview!==ID)return;' +
+ // Any reply proves the parent is listening, so stop announcing.
+ 'clearInterval(t);' +
+ // The parent pushes the docs theme in rather than rebuilding this document,
+ // so switching theme repaints the preview instead of reloading it.
+ "if(typeof d.theme==='string'){document.documentElement.setAttribute('data-theme',d.theme)}" +
+ 'post()});' +
+ '})()';
+
+ return `<!doctype html><html><head><meta charset="utf-8"><style>${THEME_CSS}${BASE}</style></head><body>${inner}<script>${script}</script></body></html>`;
+}
+
export function HtmlPreview({ code }: { code: string }) {
const { resolvedTheme } = useTheme();
- const [mounted, setMounted] = useState(false);
- const [height, setHeight] = useState(200);
const domId = useId().replace(/[^a-zA-Z0-9]/g, '');
+ const frameRef = useRef<HTMLIFrameElement>(null);
- useEffect(() => setMounted(true), []);
+ const [height, setHeight] = useState(
+ () => recallPreviewHeight(code) ?? DEFAULT_PREVIEW_RESERVE_PX,
+ );
+ const [frameLoaded, setFrameLoaded] = useState(false);
+
+ // React may reconcile a preview on one docs page onto the one on the next.
+ // Re-deriving here keeps the reserve tied to the block being shown rather
+ // than to whatever was measured for the block it replaced.
+ const [renderedCode, setRenderedCode] = useState(code);
+ if (code !== renderedCode) {
+ setRenderedCode(code);
+ setHeight(recallPreviewHeight(code) ?? DEFAULT_PREVIEW_RESERVE_PX);
+ setFrameLoaded(false);
+ }
+
+ useEffect(() => {
+ restorePreviewHeights();
+ }, []);
useEffect(() => {
const onMessage = (e: MessageEvent) => {
const d = e.data as { __okpreview?: string; h?: number } | null;
- if (d && d.__okpreview === domId && typeof d.h === 'number') {
- setHeight(Math.min(Math.ceil(d.h), 5000));
+ if (!d || d.__okpreview !== domId) return;
+
+ // Hearing from the frame is what proves it is running and listening.
+ // The load event cannot be relied on here: the iframe ships in the
+ // server-rendered HTML, so it often finishes loading before hydration
+ // attaches an onLoad handler, and that handler then never fires.
+ setFrameLoaded(true);
+
+ if (typeof d.h === 'number') {
+ const measured = Math.min(Math.ceil(d.h), MAX_PREVIEW_HEIGHT_PX);
+ setHeight(measured);
+ rememberPreviewHeight(code, measured);
}
};
window.addEventListener('message', onMessage);
return () => window.removeEventListener('message', onMessage);
- }, [domId]);
-
- if (!mounted) {
- return (
- <div
- className="not-prose my-5 rounded-2xl border border-fd-border bg-fd-card"
- style={{ height }}
- />
- );
- }
+ }, [domId, code]);
- const vars = resolvedTheme === 'dark' ? DARK : LIGHT;
- const inner = decode(code);
- const srcDoc = `<!doctype html><html><head><meta charset="utf-8"><style>${vars}${BASE}</style></head><body>${inner}<script>(function(){var ID=${JSON.stringify(domId)};function post(){parent.postMessage({__okpreview:ID,h:document.documentElement.scrollHeight},'*')}addEventListener('load',post);addEventListener('resize',post);if(window.ResizeObserver){new ResizeObserver(post).observe(document.body)}var n=0,t=setInterval(function(){post();if(++n>24)clearInterval(t)},250)})()</script></body></html>`;
+ // Answer the frame once it has announced itself, and again whenever the theme
+ // changes. The reply is unconditional even when the theme has not resolved
+ // yet: it doubles as the acknowledgement that stops the frame announcing, so
+ // withholding it would leave the frame retrying until its cap.
+ useEffect(() => {
+ if (!frameLoaded) return;
+ frameRef.current?.contentWindow?.postMessage({ __okpreview: domId, theme: resolvedTheme }, '*');
+ }, [frameLoaded, resolvedTheme, domId]);
return (
<iframe
+ ref={frameRef}
title="Interactive preview"
sandbox="allow-scripts"
className="not-prose my-5 w-full rounded-2xl border border-fd-border bg-fd-card shadow-sm"
style={{ height }}
- srcDoc={srcDoc}
+ srcDoc={buildSrcDoc(code, domId)}
+ onLoad={() => setFrameLoaded(true)}
/>
);
}
diff --git a/docs/src/components/preview-height-memory.ts b/docs/src/components/preview-height-memory.ts
new file mode 100644
index 000000000..65fdf5103
--- /dev/null
+++ b/docs/src/components/preview-height-memory.ts
@@ -0,0 +1,132 @@
+/**
+ * Remembers how tall each `html preview` block turned out to be, so a block
+ * that has already been measured reserves its real height the next time it is
+ * rendered instead of falling back to a placeholder guess and reflowing the
+ * page underneath it.
+ *
+ * Heights are keyed by width as well as by block. The preview content is
+ * responsive, and the docs column itself changes width at layout breakpoints,
+ * so the same block legitimately settles at different heights: one block
+ * measures 240px on a desktop column and 422px on a phone. A height recalled
+ * for the wrong width would be as wrong as the constant it replaced, so a
+ * different width is a cache miss rather than a stale hit.
+ */
+
+/**
+ * What to reserve for a block nobody has measured yet. A sandboxed iframe
+ * cannot be sized without rendering it, so the very first view of a block at a
+ * given width has nothing better to go on than a guess.
+ */
+export const DEFAULT_PREVIEW_RESERVE_PX = 200;
+
+/** Ignore an implausible height rather than persisting it. */
+export const MAX_PREVIEW_HEIGHT_PX = 5000;
+
+/**
+ * Bucket width so that ordinary window resizing, scrollbar appearance, and
+ * sub-pixel layout differences do not each mint a separate entry. Coarse enough
+ * to hit on a revisit, fine enough that a real breakpoint change misses.
+ */
+const WIDTH_BUCKET_PX = 40;
+
+const STORAGE_KEY = 'ok-docs:preview-heights:v1';
+
+const memory = new Map<string, number>();
+let restored = false;
+
+/**
+ * `null` when there is no window to measure — during server rendering, and
+ * therefore also during the client's hydrating render, which keeps the reserve
+ * identical on both sides.
+ */
+function currentWidthBucket(): number | null {
+ if (typeof window === 'undefined') return null;
+ return Math.round(window.innerWidth / WIDTH_BUCKET_PX) * WIDTH_BUCKET_PX;
+}
+
+function keyFor(code: string, widthBucket: number): string {
+ return `${widthBucket}:${code}`;
+}
+
+/** The height this block last settled at, at the current width, if known. */
+export function recallPreviewHeight(code: string): number | undefined {
+ const widthBucket = currentWidthBucket();
+ if (widthBucket === null) return undefined;
+ return memory.get(keyFor(code, widthBucket));
+}
+
+/** Record what a block actually measured, so the next render can reserve it. */
+export function rememberPreviewHeight(code: string, height: number): void {
+ const widthBucket = currentWidthBucket();
+ if (widthBucket === null) return;
+ if (!Number.isFinite(height) || height <= 0 || height > MAX_PREVIEW_HEIGHT_PX) return;
+
+ const key = keyFor(code, widthBucket);
+ // The frame re-reports its height on load, on every ResizeObserver fire, and
+ // on a 250ms interval for its first six seconds. Almost all of those repeat a
+ // height already recorded, so bail before re-serialising the whole map.
+ if (memory.get(key) === height) return;
+
+ memory.set(key, height);
+ persist();
+}
+
+/**
+ * Mirror into sessionStorage so heights survive a reload within the session.
+ *
+ * Storage is unavailable or throws in private-browsing and locked-down cookie
+ * modes. That is a real boundary rather than a masked error: the memory is an
+ * optimisation, and losing it costs a one-time reflow, not correctness.
+ */
+function persist(): void {
+ try {
+ sessionStorage.setItem(STORAGE_KEY, JSON.stringify(Object.fromEntries(memory)));
+ } catch {
+ // Session storage is unavailable; in-memory recall still works for this page.
+ }
+}
+
+/**
+ * Load persisted heights into the in-memory map.
+ *
+ * MUST be called from an effect, never during render. Reading storage while
+ * rendering would let the client's first render disagree with the server's
+ * markup and produce a hydration mismatch on the reserved height. Deferring it
+ * keeps the hydrating render identical to the server's while still making the
+ * heights available to every client-side navigation that follows, which is the
+ * case that actually reflows today.
+ */
+export function restorePreviewHeights(): void {
+ if (restored) return;
+ restored = true;
+
+ try {
+ const raw = sessionStorage.getItem(STORAGE_KEY);
+ if (!raw) return;
+ for (const [key, height] of Object.entries(JSON.parse(raw) as Record<string, unknown>)) {
+ if (typeof height === 'number' && height > 0 && height <= MAX_PREVIEW_HEIGHT_PX) {
+ // A height measured in this session is more current than a stored one.
+ if (!memory.has(key)) memory.set(key, height);
+ }
+ }
+ } catch {
+ // Unreadable or malformed storage; fall back to measuring afresh.
+ }
+}
+
+/**
+ * Drop everything remembered so far, persisted copy included. Exists so tests
+ * can start from a known state; clearing storage too is what makes them
+ * independent of each other, since a leftover entry would otherwise be restored
+ * into the next test.
+ */
+export function resetPreviewHeightMemory(): void {
+ memory.clear();
+ restored = false;
+ try {
+ sessionStorage.removeItem(STORAGE_KEY);
+ } catch {
+ // Storage itself is unreachable (private mode, blocked cookies), so there is
+ // nothing persisted to clear anyway.
+ }
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 806343263..0dd726c9f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -284,6 +284,9 @@ importers:
fumadocs-typescript:
specifier: ~4.0.13
+ jsdom:
+ specifier: ^29.1.1
+ version: 29.1.1(@noble/[email protected])
next-validate-link:
specifier: ^1.6.6
version: 1.6.6(@types/[email protected])(@types/[email protected])