Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): stop preview iframe leaking into text/html clipboard (#2880)

Nick Gomez45c3cf505d62
diff --git a/.changeset/fix-clipboard-preview-codeblock-iframe-leak.md b/.changeset/fix-clipboard-preview-codeblock-iframe-leak.md
new file mode 100644
index 000000000..b174f7e46
--- /dev/null
+++ b/.changeset/fix-clipboard-preview-codeblock-iframe-leak.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Fix copying a rendered `html preview` code block pasting broken markup into other apps. Selecting and copying a preview-active code block previously placed the preview's internal sandboxed iframe (several KB of security-policy, theme, and bootstrap markup) plus resize-handle chrome into the clipboard, so pasting into Gmail, Notion, Slack, or Docs produced bloated, non-rendering junk. The clipboard now receives the clean fenced code source instead, matching how rendered math and Mermaid diagrams already copy.
diff --git a/packages/app/src/editor/clipboard/clipboard-walker-fallback-palette.test.ts b/packages/app/src/editor/clipboard/clipboard-walker-fallback-palette.test.ts
index 90dee1393..cfcb74fda 100644
--- a/packages/app/src/editor/clipboard/clipboard-walker-fallback-palette.test.ts
+++ b/packages/app/src/editor/clipboard/clipboard-walker-fallback-palette.test.ts
@@ -8,7 +8,7 @@
* appends as a no-op — Activity-hidden copies would lose the descriptor
* entirely.
*
- * bun-test has no DOM (`document.createElement` is unavailable), so the
+ * the vitest node environment has no DOM (`document.createElement` is unavailable), so the
* DOM-shape behavior of the palette functions is covered by Playwright
* E2E. This file pins the **structural** contracts that are testable
* without a DOM:
@@ -19,10 +19,13 @@
* - `TYPE_TO_TONE` shape pins the supported callout type set.
*/
-import { describe, expect, test } from 'vitest';
+import type { Node as PmNode } from '@tiptap/pm/model';
+import { JSDOM } from 'jsdom';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { classifyUrlPortability } from './clipboard-sanitize.ts';
import {
PALETTE_DESCRIPTOR_NAMES,
+ paletteFor,
paletteUrlReason,
TYPE_TO_TONE,
toneForType,
@@ -109,10 +112,63 @@ describe('toneForType — type-to-tone lookup with prototype-pollution guard', (
// the palette-side surface — a thin `null|reason` wrapper over
// `classifyUrlPortability` that gives the palette tests a pure assertion
// target without needing a DOM (palette functions themselves create real
-// `<img>`/`<video>`/`<audio>` elements, which bun-test cannot exercise).
+// `<img>`/`<video>`/`<audio>` elements, which the vitest node environment
+// cannot exercise).
// DOM-shape coverage of the actual swap happens in the cross-app
// sanitizer-proxy fixture tests and Playwright E2E.
+// ─── paletteFor — codeBlock route (Activity-hidden preview fallback) ────
+//
+// A preview-active `html`/`xml` code block is a native PM node (not a
+// jsxComponent), so `paletteFor` routes it through
+// `nonPortableRenderSourceFallback` via a pre-switch `codeBlock` guard.
+// That guard is the ONLY thing keeping the Activity-hidden path from
+// dropping the block (a codeBlock that reached the `!== 'jsxComponent'`
+// check returns null). This describe block pins the route so removing the
+// guard fails here. `nonPortableRenderSourceFallback` builds a `<pre>`, so a
+// real DOM is installed for these cases only.
+
+function stubCodeBlock(args: { language: string; meta?: string; textContent?: string }): PmNode {
+ return {
+ type: { name: 'codeBlock' },
+ attrs: { language: args.language, meta: args.meta ?? '' },
+ textContent: args.textContent ?? '',
+ } as unknown as PmNode;
+}
+
+describe('paletteFor — preview-active codeBlock route', () => {
+ let dom: JSDOM;
+ const prevDocument = Object.getOwnPropertyDescriptor(globalThis, 'document');
+ beforeAll(() => {
+ dom = new JSDOM('<!DOCTYPE html><html><body></body></html>');
+ Object.defineProperty(globalThis, 'document', {
+ value: dom.window.document,
+ configurable: true,
+ writable: true,
+ });
+ });
+ afterAll(() => {
+ if (prevDocument) Object.defineProperty(globalThis, 'document', prevDocument);
+ else Reflect.deleteProperty(globalThis as unknown as Record<string, unknown>, 'document');
+ dom.window.close();
+ });
+
+ test('preview-active html codeBlock → non-null clean source (guard present)', () => {
+ const el = paletteFor(
+ stubCodeBlock({ language: 'html', meta: 'preview', textContent: '<h1>Hi</h1>' }),
+ );
+ expect(el).not.toBeNull();
+ expect(el?.textContent ?? '').toContain('<h1>Hi</h1>');
+ // Clean fenced source, not the live iframe render.
+ expect(el?.querySelector('iframe')).toBeNull();
+ });
+
+ test('non-preview codeBlock → null (portable clean-clone path)', () => {
+ const el = paletteFor(stubCodeBlock({ language: 'html', textContent: '<h1>Hi</h1>' }));
+ expect(el).toBeNull();
+ });
+});
+
describe('paletteUrlReason — portability decision', () => {
test('returns null for fragment-only refs', () => {
expect(paletteUrlReason('#section')).toBeNull();
diff --git a/packages/app/src/editor/clipboard/clipboard-walker-fallback-palette.ts b/packages/app/src/editor/clipboard/clipboard-walker-fallback-palette.ts
index 211991451..5d524d462 100644
--- a/packages/app/src/editor/clipboard/clipboard-walker-fallback-palette.ts
+++ b/packages/app/src/editor/clipboard/clipboard-walker-fallback-palette.ts
@@ -29,8 +29,9 @@ import { nonPortableRenderSourceFallback } from './non-portable-render-source-fa
/**
* Callout type → cross-app tone mapping. Exported so the registry-coverage
* test in `clipboard-walker-fallback-palette.test.ts` can pin the supported
- * type set without invoking the DOM-creating palette functions (bun-test
- * has no DOM; full palette DOM behavior is covered in Playwright E2E).
+ * type set without invoking the DOM-creating palette functions (the vitest
+ * node environment has no DOM; full palette DOM behavior is covered in
+ * Playwright E2E).
*/
export const TYPE_TO_TONE: Record<string, { color: string; bg: string }> = {
note: { color: '#0969da', bg: '#dbeafe' },
@@ -268,6 +269,13 @@ function audioPalette(props: Record<string, unknown>): Element {
* results as no-ops.
*/
export function paletteFor(node: PmNode): Element | null {
+ // Preview-active `html`/`xml` code blocks are native PM nodes (not
+ // jsxComponents) whose live render is a non-portable iframe. Route them
+ // through the shared helper ahead of the jsxComponent guard so the
+ // Activity-hidden path emits the same clean fenced source the mounted
+ // walker path does — `nonPortableRenderSourceFallback` returns null for
+ // non-preview code blocks, so plain fences still fall through to null.
+ if (node.type.name === 'codeBlock') return nonPortableRenderSourceFallback(node, document);
if (node.type.name !== 'jsxComponent') return null;
const componentName = node.attrs.componentName as string | undefined;
const props = (node.attrs.props as Record<string, unknown>) ?? {};
diff --git a/packages/app/src/editor/clipboard/codeblock-preview-clipboard.test.ts b/packages/app/src/editor/clipboard/codeblock-preview-clipboard.test.ts
new file mode 100644
index 000000000..46d89879c
--- /dev/null
+++ b/packages/app/src/editor/clipboard/codeblock-preview-clipboard.test.ts
@@ -0,0 +1,274 @@
+/**
+ * Clipboard fidelity contract (WYSIWYG app tier): a preview-active `html
+ * preview` code block must NOT leak its non-portable render internals into the
+ * cross-app `text/html` payload.
+ *
+ * Domain invariant: when a preview-active code-block NodeView is fully selected
+ * and copied, the live-DOM walker tier must emit the clean `<pre><code>` source
+ * representation of the block — never the `.ok-codeblock-preview` render
+ * (`<iframe srcdoc>` whose srcdoc is the CSP-meta + theme-CSS + bootstrap-JS
+ * header from buildPreviewIframeHeader, plus a duplicate of the code, plus the
+ * ResizeHandles chrome). This is the same guarantee the walker already enforces
+ * for the other non-portable live renders (block Math KaTeX, Mermaid SVG): a
+ * destination (Gmail, Notion, Slack, Docs) receives readable source, not
+ * several KB of inert `srcdoc` markup and render chrome.
+ *
+ * Mechanism-agnostic on purpose. The invariant has two candidate enforcement
+ * points — source-fallback recognition of a preview-active code block at the
+ * walker boundary, OR opt-out enrollment of the preview wrapper so the walker
+ * drops it and the clean `<pre>` sibling carries the block. Either satisfies
+ * the invariant; the oracle here asserts ONLY on the emitted fragment shape, so
+ * it does not pin which mechanism the fix uses.
+ *
+ * Substrate: drives the REAL production `walkLiveDomToInlineStyledFragment`
+ * against a `nodeDOM` that mirrors CodeBlockView's preview-active render. A bare
+ * EditorView registers no React nodeViews (it renders the default `<pre><code>`
+ * and never the preview iframe), so the NodeView DOM the walker sees in
+ * production is supplied explicitly — every transformation under test is
+ * production code. jsdom globals are installed in beforeAll and RESTORED in
+ * afterAll so sibling no-DOM unit files keep their contract. Same pattern as
+ * `clipboard-line-structure.test.ts`.
+ */
+
+import { getSchema } from '@tiptap/core';
+import type { Node as PmNode } from '@tiptap/pm/model';
+import { JSDOM } from 'jsdom';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { buildPreviewIframeHeader } from '../extensions/preview-iframe-header.ts';
+import { sharedExtensions } from '../extensions/shared.ts';
+import { OPT_OUT_ATTR } from './clipboard-sanitize.ts';
+import { type WalkerEnv, walkLiveDomToInlineStyledFragment } from './clipboard-walker.ts';
+
+function installDomGlobals(): () => void {
+ const dom = new JSDOM('<!DOCTYPE html><html><head></head><body></body></html>', {
+ url: 'http://localhost:5173',
+ pretendToBeVisual: true,
+ });
+ const win = dom.window as unknown as Window & typeof globalThis;
+ const installed: Record<string, unknown> = {
+ window: win,
+ document: win.document,
+ HTMLElement: win.HTMLElement,
+ Element: win.Element,
+ Node: win.Node,
+ Document: win.Document,
+ DocumentFragment: win.DocumentFragment,
+ Text: win.Text,
+ getComputedStyle: win.getComputedStyle.bind(win),
+ };
+ const previousDescriptors = new Map<string, PropertyDescriptor | undefined>();
+ const globalRecord = globalThis as unknown as Record<string, unknown>;
+ for (const [key, value] of Object.entries(installed)) {
+ previousDescriptors.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
+ Object.defineProperty(globalThis, key, { value, configurable: true, writable: true });
+ }
+ return () => {
+ for (const [key, descriptor] of previousDescriptors) {
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
+ else Reflect.deleteProperty(globalRecord, key);
+ }
+ dom.window.close();
+ };
+}
+
+let restore: (() => void) | null = null;
+beforeAll(() => {
+ restore = installDomGlobals();
+});
+afterAll(() => {
+ restore?.();
+ restore = null;
+});
+
+const schema = getSchema(sharedExtensions);
+const CODE = '<h1>Hi</h1>\n<script>document.title="x"</script>';
+
+/** A real one-codeBlock doc: fence `html preview` with an HTML body. */
+function previewCodeBlockDoc(): PmNode {
+ const code = schema.text(CODE);
+ const codeBlock = schema.nodes.codeBlock.create({ language: 'html', meta: 'preview' }, code);
+ return schema.nodes.doc.create(null, codeBlock);
+}
+
+/**
+ * Build a DOM subtree carrying the non-portable content of CodeBlockView's
+ * preview-active render: `.ok-codeblock` wrapper → `.ok-codeblock-preview`
+ * (iframe[srcdoc] + resize-handle chrome) + hidden `<pre>` + opted-out
+ * `.ok-codeblock-chrome`.
+ *
+ * The load-bearing property is that the preview wrapper itself carries NO
+ * clipboard opt-out — that is why the walker must recognise the block and emit
+ * source rather than drop it. This reproduces enough of that shape to make the
+ * leak assertions meaningful; it is not a byte-faithful mirror of every class
+ * name (the resize-handle markup in particular is abbreviated — the walker
+ * replaces the whole preview subtree regardless, so the assertions key on the
+ * stable `.ok-resize-handle` / `.ok-codeblock-preview` base classes). A fix
+ * that enrolls the wrapper in the opt-out instead would change this render;
+ * keep the fixture in lock-step with CodeBlockView in that case — the
+ * assertions below stay identical either way.
+ */
+function buildCodeBlockPreviewDom(): HTMLElement {
+ const wrapper = document.createElement('div');
+ wrapper.className = 'ok-codeblock relative my-3';
+ wrapper.setAttribute('data-preview', 'true');
+ wrapper.setAttribute('data-code-visible', 'false');
+
+ const preview = document.createElement('div');
+ preview.className = 'ok-codeblock-preview ok-codeblock-preview--solo';
+ preview.setAttribute('contenteditable', 'false');
+ preview.setAttribute('style', 'height: 320px; width: 480px;');
+
+ const iframe = document.createElement('iframe');
+ iframe.setAttribute('title', 'HTML preview');
+ iframe.setAttribute('sandbox', 'allow-scripts');
+ iframe.setAttribute('referrerpolicy', 'no-referrer');
+ iframe.setAttribute('srcdoc', buildPreviewIframeHeader('light') + CODE);
+ iframe.className = 'ok-codeblock-preview-frame';
+ preview.appendChild(iframe);
+
+ const handles = document.createElement('div');
+ handles.className = 'ok-resize-handles';
+ for (const dir of ['e', 's', 'se']) {
+ const h = document.createElement('div');
+ h.className = `ok-resize-handle ok-resize-handle-${dir}`;
+ handles.appendChild(h);
+ }
+ preview.appendChild(handles);
+ wrapper.appendChild(preview);
+
+ const pre = document.createElement('pre');
+ pre.className = 'ok-codeblock-pre m-0 overflow-x-auto px-5 py-4 font-mono text-sm';
+ pre.setAttribute('aria-hidden', 'true');
+ const code = document.createElement('code');
+ code.className = 'hljs block whitespace-pre bg-transparent p-0 language-html';
+ code.textContent = CODE;
+ pre.appendChild(code);
+ wrapper.appendChild(pre);
+
+ const chrome = document.createElement('div');
+ chrome.className = 'ok-codeblock-chrome';
+ chrome.setAttribute('contenteditable', 'false');
+ chrome.setAttribute(OPT_OUT_ATTR, 'true');
+ const btn = document.createElement('button');
+ btn.textContent = 'copy';
+ chrome.appendChild(btn);
+ wrapper.appendChild(chrome);
+
+ return wrapper;
+}
+
+/** Minimal EditorView stand-in — the walker only touches these members. */
+function fakeView(doc: PmNode, nodeDom: HTMLElement) {
+ const codeBlock = doc.firstChild;
+ if (!codeBlock) throw new Error('expected a codeBlock child');
+ return {
+ state: {
+ doc,
+ selection: { from: 0, to: codeBlock.nodeSize },
+ },
+ nodeDOM: (pos: number) => (pos === 0 ? nodeDom : null),
+ } as unknown as Parameters<typeof walkLiveDomToInlineStyledFragment>[1];
+}
+
+/**
+ * A view whose live DOM is unmounted for the block — `nodeDOM` returns null,
+ * the Activity-hidden case where the walker defers to `paletteFor` instead of
+ * cloning the live tree. The palette must emit the same clean source shape the
+ * mounted path does, or the block is silently dropped from the payload.
+ */
+function unmountedView(doc: PmNode) {
+ const codeBlock = doc.firstChild;
+ if (!codeBlock) throw new Error('expected a codeBlock child');
+ return {
+ state: {
+ doc,
+ selection: { from: 0, to: codeBlock.nodeSize },
+ },
+ nodeDOM: () => null,
+ } as unknown as Parameters<typeof walkLiveDomToInlineStyledFragment>[1];
+}
+
+function emitFragmentHtml(): { holder: HTMLElement; html: string } {
+ const doc = previewCodeBlockDoc();
+ const nodeDom = buildCodeBlockPreviewDom();
+ const env: WalkerEnv = {
+ getComputedStyle: () => ({ getPropertyValue: () => '' }),
+ };
+ const frag = walkLiveDomToInlineStyledFragment(
+ // slice arg is unused by the walker (it reads view.state.selection).
+ undefined as unknown as Parameters<typeof walkLiveDomToInlineStyledFragment>[0],
+ fakeView(doc, nodeDom),
+ env,
+ );
+ const holder = document.createElement('div');
+ holder.appendChild(frag);
+ return { holder, html: holder.innerHTML };
+}
+
+describe('preview-active codeBlock clipboard emission (text/html tier)', () => {
+ test('emits no iframe / srcdoc render-header into the payload', () => {
+ const { holder, html } = emitFragmentHtml();
+ expect(holder.querySelector('iframe')).toBeNull();
+ expect(html).not.toContain('srcdoc');
+ expect(html).not.toContain('Content-Security-Policy');
+ });
+
+ test('emits no preview render chrome (resize handles) into the payload', () => {
+ const { holder } = emitFragmentHtml();
+ expect(holder.querySelector('.ok-resize-handle')).toBeNull();
+ expect(holder.querySelector('.ok-codeblock-preview')).toBeNull();
+ });
+
+ test('emits the clean code source, present and not destination-hidden', () => {
+ const { holder } = emitFragmentHtml();
+ const pre = holder.querySelector('pre');
+ expect(pre).not.toBeNull();
+ // The code body survives as readable source text (either the live
+ // `<pre><code>` clone or a source-fallback `<pre class="mdx-component">`).
+ expect(pre?.textContent ?? '').toContain('<h1>Hi</h1>');
+ // Not hidden at destinations: no inline display:none rides on the block
+ // (visual hiding of the live `<pre>` is app-stylesheet-only, keyed on
+ // `data-code-visible`, and `display` is excluded from the walker's
+ // STYLE_ALLOWLIST — so the emitted clone must render).
+ expect(pre?.getAttribute('style') ?? '').not.toContain('display');
+ });
+});
+
+describe('preview-active codeBlock clipboard emission — Activity-hidden (unmounted) path', () => {
+ // When the block lives inside an `<Activity mode="hidden">` subtree its live
+ // DOM is unmounted, so `view.nodeDOM(pos)` is null and the walker defers to
+ // the static `paletteFor` fallback. The palette must emit the SAME clean
+ // fenced source the mounted path does — otherwise a preview-active code block
+ // is silently dropped from the payload (the block Math / Mermaid palette
+ // entries already guarantee this symmetry for their non-portable renders).
+ function emitFromUnmounted(): { holder: HTMLElement; html: string } {
+ const doc = previewCodeBlockDoc();
+ const env: WalkerEnv = {
+ getComputedStyle: () => ({ getPropertyValue: () => '' }),
+ };
+ const frag = walkLiveDomToInlineStyledFragment(
+ undefined as unknown as Parameters<typeof walkLiveDomToInlineStyledFragment>[0],
+ unmountedView(doc),
+ env,
+ );
+ const holder = document.createElement('div');
+ holder.appendChild(frag);
+ return { holder, html: holder.innerHTML };
+ }
+
+ test('emits the clean fenced source, not an empty (dropped) payload', () => {
+ const { holder } = emitFromUnmounted();
+ const pre = holder.querySelector('pre');
+ expect(pre).not.toBeNull();
+ expect(pre?.textContent ?? '').toContain('<h1>Hi</h1>');
+ // The authored info-string rides along so a markdown-aware destination
+ // re-parses back to a preview-active code block, not a plain fence.
+ expect(pre?.textContent ?? '').toContain('html preview');
+ });
+
+ test('emits no iframe / srcdoc render internals via the palette path', () => {
+ const { holder, html } = emitFromUnmounted();
+ expect(holder.querySelector('iframe')).toBeNull();
+ expect(html).not.toContain('srcdoc');
+ });
+});
diff --git a/packages/app/src/editor/clipboard/non-portable-render-source-fallback.test.ts b/packages/app/src/editor/clipboard/non-portable-render-source-fallback.test.ts
index d22fc6823..d12ed06d0 100644
--- a/packages/app/src/editor/clipboard/non-portable-render-source-fallback.test.ts
+++ b/packages/app/src/editor/clipboard/non-portable-render-source-fallback.test.ts
@@ -1,7 +1,7 @@
/**
* Co-located unit tests for the non-portable-render source-fallback
* helper. Mirrors the convention from `clipboard-walker-fallback-
- * palette.test.ts`: bun-test has no DOM, so the DOM-shape behaviour of
+ * palette.test.ts`: the vitest node environment has no DOM, so the DOM-shape behaviour of
* `nonPortableRenderSourceFallback` is covered by Playwright E2E. This
* file pins the **structural** dispatch contract that is testable
* without a DOM via `sourceFallbackFormFor` (the inner pure classifier).
@@ -9,11 +9,13 @@
* Coverage tiers:
* 1. Block jsxComponents (Math, Mermaid) → expected markdown-source
* bytes
- * 2. Falls through (Callout, paragraph, heading, mathInline,
+ * 2. Preview-active codeBlock → fenced-source bytes; non-preview → null
+ * 3. Falls through (Callout, paragraph, heading, mathInline,
* unknown jsxComponent) → null
- * 3. Edge cases — empty / missing / non-string props
+ * 4. Edge cases — empty / missing / non-string props
*/
+import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
import type { Node as PmNode } from '@tiptap/pm/model';
import { describe, expect, test } from 'vitest';
import { sourceFallbackFormFor } from './non-portable-render-source-fallback.ts';
@@ -28,13 +30,19 @@ function stubPmNode(args: {
typeName: string;
componentName?: string;
props?: Record<string, unknown>;
+ language?: unknown;
+ meta?: unknown;
+ textContent?: string;
}): PmNode {
return {
type: { name: args.typeName },
attrs: {
...(args.componentName !== undefined ? { componentName: args.componentName } : {}),
...(args.props !== undefined ? { props: args.props } : {}),
+ ...(args.language !== undefined ? { language: args.language } : {}),
+ ...(args.meta !== undefined ? { meta: args.meta } : {}),
},
+ textContent: args.textContent ?? '',
} as unknown as PmNode;
}
@@ -129,6 +137,165 @@ describe('sourceFallbackFormFor — MermaidFence jsxComponent', () => {
});
});
+describe('sourceFallbackFormFor — preview-active codeBlock', () => {
+ test('html + preview → fenced source with the authored info-string', () => {
+ const node = stubPmNode({
+ typeName: 'codeBlock',
+ language: 'html',
+ meta: 'preview',
+ textContent: '<h1>Hi</h1>',
+ });
+ expect(sourceFallbackFormFor(node)).toEqual({
+ source: '```html preview\n<h1>Hi</h1>\n```',
+ });
+ });
+
+ test('xml + preview → recognized via the normalize path', () => {
+ // `html` normalizes to highlight.js's `xml` key; a block authored as
+ // `xml preview` renders the same iframe and must fall back too.
+ const node = stubPmNode({
+ typeName: 'codeBlock',
+ language: 'xml',
+ meta: 'preview',
+ textContent: '<svg></svg>',
+ });
+ expect(sourceFallbackFormFor(node)).toEqual({
+ source: '```xml preview\n<svg></svg>\n```',
+ });
+ });
+
+ test('fence widens past a backtick run in the body (no early close)', () => {
+ // A body containing a ``` run would early-close a 3-backtick fence on
+ // re-parse (CommonMark §4.5); the fence widens to one longer.
+ const body = 'before\n```\ninner\n```\nafter';
+ const node = stubPmNode({
+ typeName: 'codeBlock',
+ language: 'html',
+ meta: 'preview',
+ textContent: body,
+ });
+ expect(sourceFallbackFormFor(node)).toEqual({
+ source: `\`\`\`\`html preview\n${body}\n\`\`\`\``,
+ });
+ });
+
+ test('tilde fence widens past a ~~~ run in the body (no early close)', () => {
+ // A backtick in the meta forces a tilde fence; a body containing a `~~~`
+ // run would early-close a 3-tilde fence on re-parse (CommonMark §4.5),
+ // so the tilde fence widens to one longer.
+ const body = 'before\n~~~\ninner\n~~~\nafter';
+ const node = stubPmNode({
+ typeName: 'codeBlock',
+ language: 'html',
+ meta: 'title="a`b`" preview',
+ textContent: body,
+ });
+ const source = sourceFallbackFormFor(node)?.source ?? '';
+ expect(source.startsWith('~~~~')).toBe(true);
+ expect(source.endsWith('\n~~~~')).toBe(true);
+ });
+
+ test('non-preview html code block → null (portable clean-clone path)', () => {
+ const node = stubPmNode({
+ typeName: 'codeBlock',
+ language: 'html',
+ textContent: '<h1>Hi</h1>',
+ });
+ expect(sourceFallbackFormFor(node)).toBeNull();
+ });
+
+ test('preview meta on a non-previewable language → null', () => {
+ // `js preview` renders no iframe — the preview pane only mounts for
+ // html/xml. The gate must not fire for other languages.
+ const node = stubPmNode({
+ typeName: 'codeBlock',
+ language: 'js',
+ meta: 'preview',
+ textContent: "console.log('x')",
+ });
+ expect(sourceFallbackFormFor(node)).toBeNull();
+ });
+
+ test('null language attr → null (no preview gate, no throw)', () => {
+ // Symmetric defense with the Math/Mermaid non-string prop tests — a
+ // non-string attr narrows to '' and the preview gate declines it.
+ const node = stubPmNode({
+ typeName: 'codeBlock',
+ language: null,
+ meta: 'preview',
+ textContent: '<h1>Hi</h1>',
+ });
+ expect(sourceFallbackFormFor(node)).toBeNull();
+ });
+
+ test('null meta attr → null (no preview gate, no throw)', () => {
+ const node = stubPmNode({
+ typeName: 'codeBlock',
+ language: 'html',
+ meta: null,
+ textContent: '<h1>Hi</h1>',
+ });
+ expect(sourceFallbackFormFor(node)).toBeNull();
+ });
+
+ test('meta carrying a backtick emits a valid fence (tilde), not a broken backtick fence', () => {
+ // A `title="…"` meta token may contain a backtick (setMetaTitle strips
+ // `"` and newlines but not backticks; a tilde-authored fence has no
+ // restriction). CommonMark §4.5 forbids backticks in a backtick fence's
+ // info-string, so embedding such meta after a backtick fence produces an
+ // opener that parsers reject — the block degrades to a paragraph. The
+ // emitted source must stay a valid fence so the round-trip intent holds.
+ const node = stubPmNode({
+ typeName: 'codeBlock',
+ language: 'html',
+ meta: 'title="a`b`" preview',
+ textContent: '<h1>Hi</h1>',
+ });
+ const form = sourceFallbackFormFor(node);
+ expect(form).not.toBeNull();
+ const source = form?.source ?? '';
+ expect(source).not.toBe('');
+ // The info-string line must not embed the fence character it opens with.
+ const fenceChar = source[0];
+ const infoLine = source.slice(0, source.indexOf('\n'));
+ expect(infoLine.slice(3)).not.toContain(fenceChar);
+ });
+});
+
+describe('sourceFallbackFormFor — emitted fence round-trips through OK`s parser', () => {
+ // The whole point of emitting fenced source (rather than the live iframe) is
+ // that a markdown-aware destination — OK`s own parser included — re-parses it
+ // back to a code block. Drive the REAL markdown pipeline so a fence that only
+ // LOOKS valid but degrades to prose on re-parse is caught.
+ const md = new MarkdownManager({ extensions: sharedExtensions });
+ const topNodeType = (source: string): string | undefined => {
+ const doc = md.parse(source) as { content?: Array<{ type?: string }> };
+ return doc.content?.[0]?.type;
+ };
+
+ test('plain preview meta round-trips to a codeBlock', () => {
+ const node = stubPmNode({
+ typeName: 'codeBlock',
+ language: 'html',
+ meta: 'preview',
+ textContent: '<h1>Hi</h1>',
+ });
+ const source = sourceFallbackFormFor(node)?.source ?? '';
+ expect(topNodeType(source)).toBe('codeBlock');
+ });
+
+ test('backtick-in-meta still round-trips to a codeBlock (not a paragraph)', () => {
+ const node = stubPmNode({
+ typeName: 'codeBlock',
+ language: 'html',
+ meta: 'title="a`b`" preview',
+ textContent: '<h1>Hi</h1>',
+ });
+ const source = sourceFallbackFormFor(node)?.source ?? '';
+ expect(topNodeType(source)).toBe('codeBlock');
+ });
+});
+
describe('sourceFallbackFormFor — fall-through cases', () => {
test('mathInline atom → null (handled by post-clone pass instead)', () => {
// mathInline is a PM atom (`inline: true, atom: true`) whose parent
diff --git a/packages/app/src/editor/clipboard/non-portable-render-source-fallback.ts b/packages/app/src/editor/clipboard/non-portable-render-source-fallback.ts
index be38fed78..63ca84058 100644
--- a/packages/app/src/editor/clipboard/non-portable-render-source-fallback.ts
+++ b/packages/app/src/editor/clipboard/non-portable-render-source-fallback.ts
@@ -1,11 +1,15 @@
/**
- * Source-fallback shape for top-level `jsxComponent` nodes whose live
- * React render is non-portable across destinations. Block KaTeX (Math)
- * and mermaid SVG (MermaidFence) paste as garbage in plain-text apps and
- * as broken styling in some rich apps; their markdown source bytes do
- * not. The walker swaps the live-DOM clone path entirely and emits a
+ * Source-fallback shape for top-level nodes whose live render is
+ * non-portable across destinations. Block KaTeX (Math) and mermaid SVG
+ * (MermaidFence) jsxComponents paste as garbage in plain-text apps and
+ * as broken styling in some rich apps; a preview-active `html`/`xml`
+ * code block renders its body inside a sandboxed `<iframe srcdoc>`
+ * (several KB of security-policy, theme, and bootstrap markup plus
+ * resize-handle chrome) that pastes as bloated, non-rendering junk.
+ * Their markdown source bytes do not. The walker swaps the live-DOM
+ * clone path entirely and emits a
* `<pre class="mdx-component"><code>{markdown source}</code></pre>` block
- * carrying readable LaTeX / mermaid source instead.
+ * carrying readable LaTeX / mermaid / fenced-code source instead.
*
* Constrained to top-level block nodes by the walker's `parent !==
* view.state.doc` gate. Inline atoms (`mathInline` inside paragraphs)
@@ -21,7 +25,10 @@
* the rendered shape itself doesn't survive cross-app paste.
*/
+import { selectFenceChar, widenFenceLength } from '@inkeep/open-knowledge-core';
import type { Node as PmNode } from '@tiptap/pm/model';
+import { normalizeCodeLanguage } from '../extensions/code-block-languages.ts';
+import { shouldShowPreview } from '../extensions/code-block-meta.ts';
type SourceFallbackForm = { source: string };
@@ -29,11 +36,36 @@ type SourceFallbackForm = { source: string };
* Build the markdown-source string for a node whose live render is
* non-portable. Returns `null` when the node isn't a recognised
* non-portable type — caller falls through to the live-DOM clone path.
- * Exported so the structural-classification logic can be tested
- * without a DOM (bun-test has no `document`); DOM-shape behaviour is
- * covered by Playwright E2E.
+ * Exported so the structural-classification logic can be unit-tested
+ * without a DOM. The emitted-DOM shape is exercised through the real
+ * walker in a jsdom integration test (covering the preview-active code
+ * block); the block Math / Mermaid renders are additionally covered by
+ * Playwright E2E.
*/
export function sourceFallbackFormFor(node: PmNode): SourceFallbackForm | null {
+ // A preview-active `html`/`xml` code block renders a live iframe that
+ // is non-portable; only such blocks need the swap. The gate reuses the
+ // same `shouldShowPreview(normalizeCodeLanguage(...), meta)` predicate
+ // the NodeView renders on, so the fallback fires on exactly the set of
+ // blocks that mounted the iframe — no duplicated preview logic. Plain
+ // code blocks return null and keep the portable clean-clone path.
+ if (node.type.name === 'codeBlock') {
+ const language = typeof node.attrs.language === 'string' ? node.attrs.language : '';
+ const meta = typeof node.attrs.meta === 'string' ? node.attrs.meta : '';
+ if (!shouldShowPreview(normalizeCodeLanguage(language), meta)) return null;
+ const body = node.textContent;
+ // The info-string carries the raw authored language + meta so a
+ // markdown-aware destination (OK's own parser included) re-parses it
+ // back to a preview-active code block. A `title="…"` meta token can
+ // carry a backtick, so fence-char selection and the widen-past-closer
+ // recompute route through the same core helpers the canonical code
+ // serializer uses, keeping the two byte-identical.
+ const info = meta ? `${language} ${meta}` : language;
+ const fenceChar = selectFenceChar(info);
+ const fence = fenceChar.repeat(widenFenceLength(fenceChar, body));
+ return { source: `${fence}${info}\n${body}\n${fence}` };
+ }
+
// Top-level jsxComponent dispatch by componentName. Mirrors the gate
// in `clipboard-walker-fallback-palette.ts:paletteFor` so the two
// paths stay aligned.
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 1c7d5bbdb..206eb99e2 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -439,6 +439,7 @@ export {
type UrnIpcLookup,
withSkillPointer,
} from './handoff/index.ts';
+export { selectFenceChar, widenFenceLength } from './markdown/code-fence.ts';
export {
HTML_MAX_BYTES,
HtmlPayloadTooLargeError,
diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.ts
new file mode 100644
index 000000000..9807a7e82
--- /dev/null
+++ b/packages/core/src/markdown/code-fence.ts
@@ -0,0 +1,13 @@
+export function selectFenceChar(info: string): '`' | '~' {
+ return info.includes('`') ? '~' : '`';
+}
+
+export function widenFenceLength(fenceChar: '`' | '~', body: string, minLength = 3): number {
+ const closerRe = new RegExp(`^ {0,3}(\\${fenceChar}+)[ \\t]*$`);
+ let len = Math.max(3, minLength);
+ for (const line of body.split('\n')) {
+ const run = closerRe.exec(line);
+ if (run && run[1].length >= len) len = run[1].length + 1;
+ }
+ return len;
+}
diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.ts
index 8f4e9a41c..7f6dfcfc3 100644
--- a/packages/core/src/markdown/to-markdown-handlers.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.ts
@@ -3,6 +3,7 @@ import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } fr
import type { Handle, Info, State } from 'mdast-util-to-markdown';
import { classifyCharacter } from 'micromark-util-classify-character';
import { isValidSourceLiteralRaw } from '../extensions/source-literal-mark.ts';
+import { widenFenceLength } from './code-fence.ts';
import { TO_MARKDOWN_EXT } from './remark-mdx-agnostic.ts';
import { isInlineWhitespaceNumericCharRef } from './whitespace-char-ref.ts';
@@ -272,14 +273,7 @@ export const toMarkdownHandlers = {
}
const fenceChar = node.data?.sourceFenceChar;
const char = fenceChar === '~' ? '~' : '`';
- let len = Math.max(3, node.data?.sourceFenceLength ?? 3);
- const fenceRunRe = new RegExp(`^ {0,3}(\\${char}+)[ \\t]*$`);
- for (const line of value.split('\n')) {
- const run = fenceRunRe.exec(line);
- if (run && run[1].length >= len) {
- len = run[1].length + 1;
- }
- }
+ const len = widenFenceLength(char, value, node.data?.sourceFenceLength ?? 3);
const closingCaptured = node.data?.sourceClosingFenceLength;
const closeLen =
typeof closingCaptured === 'number' && closingCaptured > len ? closingCaptured : len;