diff --git a/packages/core/embed-insert.test.ts b/packages/core/embed-insert.test.ts
new file mode 100644
index 0000000000..727edded6d
--- /dev/null
+++ b/packages/core/embed-insert.test.ts
@@ -0,0 +1,67 @@
+// These tests pin the splice planner's own-paragraph guarantee. A regression
+// would leave an otherwise valid host-built embed line inline with prose,
+// indented as code, or with the caret trapped on the embed line.
+import { describe, expect, it } from 'bun:test';
+
+import { planEmbedInsert } from './embed-insert';
+
+describe('planEmbedInsert - the own-paragraph guarantee', () => {
+ const EMBED_LINE = '[Report](report.html#embed)';
+
+ /** Apply a splice plan the way CodeMirror would. */
+ function applied(body: string, from: number, to: number): string {
+ const plan = planEmbedInsert(body, from, to, EMBED_LINE);
+ return body.slice(0, plan.from) + plan.insert + body.slice(plan.to);
+ }
+
+ it('keeps an embed typed on the only line terminated and puts the caret on the fresh last line', () => {
+ const body = '/embed rep';
+ const plan = planEmbedInsert(body, 0, body.length, EMBED_LINE);
+ const result = applied(body, 0, body.length);
+ expect(result).toBe(`${EMBED_LINE}\n`);
+ expect(plan.cursor).toBe(result.length);
+ });
+
+ it('opens a blank line above an embed typed under a text line', () => {
+ const body = 'Intro paragraph.\n/embed rep';
+ const start = body.indexOf('/embed');
+ const result = applied(body, start, body.length);
+ expect(result).toBe(`Intro paragraph.\n\n${EMBED_LINE}\n`);
+ });
+
+ it('opens a blank line below an embed typed above existing text', () => {
+ const body = '/embed rep\nNext paragraph.\n';
+ const result = applied(body, 0, '/embed rep'.length);
+ expect(result).toBe(`${EMBED_LINE}\n\nNext paragraph.\n`);
+ });
+
+ it('moves text after the cursor on the same line to its own paragraph', () => {
+ const body = '/embed reptrailing words';
+ const result = applied(body, 0, '/embed rep'.length);
+ expect(result).toBe(`${EMBED_LINE}\n\ntrailing words`);
+ });
+
+ it('does not double already-blank surroundings', () => {
+ const body = 'Intro.\n\n/embed rep\n\nOutro.\n';
+ const start = body.indexOf('/embed');
+ const result = applied(body, start, start + '/embed rep'.length);
+ expect(result).toBe(`Intro.\n\n${EMBED_LINE}\n\nOutro.\n`);
+ });
+
+ it('swallows leading whitespace that would turn the embed into an indented code block', () => {
+ const body = 'Intro.\n /embed rep';
+ const start = body.indexOf('/embed');
+ const result = applied(body, start, body.length);
+ expect(result).toBe(`Intro.\n\n${EMBED_LINE}\n`);
+ });
+
+ it('puts the caret on the blank line after the embed instead of on its link line', () => {
+ const body = 'Intro.\n/embed rep\nOutro.\n';
+ const start = body.indexOf('/embed');
+ const plan = planEmbedInsert(body, start, start + '/embed rep'.length, EMBED_LINE);
+ const result = body.slice(0, plan.from) + plan.insert + body.slice(plan.to);
+ expect(result[plan.cursor - 1]).toBe('\n');
+ const caretLineEnd = result.indexOf('\n', plan.cursor);
+ expect(result.slice(plan.cursor, caretLineEnd === -1 ? undefined : caretLineEnd)).toBe('');
+ });
+});
diff --git a/packages/core/embed-insert.ts b/packages/core/embed-insert.ts
new file mode 100644
index 0000000000..bbe8be7c7a
--- /dev/null
+++ b/packages/core/embed-insert.ts
@@ -0,0 +1,80 @@
+/**
+ * A text splice that inserts an embed line as its own markdown paragraph.
+ */
+export interface EmbedInsertPlan {
+ /**
+ * Replacement start at the beginning of the line that holds the typed
+ * `/embed` query. Leading whitespace is swallowed so the embed does not
+ * become an indented code block.
+ */
+ readonly from: number;
+ /**
+ * Replacement end. Trailing text on the trigger line is preserved and
+ * moved to its own paragraph.
+ */
+ readonly to: number;
+ /** Text inserted in place of the replacement range. */
+ readonly insert: string;
+ /** Caret destination at the start of the line after the embed. */
+ readonly cursor: number;
+}
+
+/**
+ * Plan the splice that replaces a typed `/embed` query with an embed line.
+ *
+ * The embed line is normalized into its own blank-line-delimited paragraph.
+ * The caller owns the embed grammar and supplies the exact line to insert.
+ *
+ * @param body - Current document text.
+ * @param from - Start of the typed query, after any leading line whitespace.
+ * @param to - End of the typed query.
+ * @param embedLine - Exact host-built embed line.
+ * @returns The replacement range, inserted text, and caret destination.
+ */
+export function planEmbedInsert(
+ body: string,
+ from: number,
+ to: number,
+ embedLine: string,
+): EmbedInsertPlan {
+ // Extend the replacement to the start of the line. The picker only fires
+ // when everything before the typed query is whitespace.
+ let lineStart = body.lastIndexOf('\n', from - 1) + 1;
+ if (from === 0) lineStart = 0;
+
+ // No blank line is needed before an embed at the document start or when
+ // the previous line is already blank (including whitespace-only lines).
+ let prefix = '';
+ if (lineStart > 0) {
+ const previousLineStart = body.lastIndexOf('\n', lineStart - 2) + 1;
+ const previousLine = body.slice(previousLineStart, lineStart - 1);
+ if (!/^\s*$/.test(previousLine)) prefix = '\n';
+ }
+
+ // Normalize the paragraph after the embed according to what follows the
+ // replaced range. Existing blank lines are retained instead of doubled.
+ let lineEnd = body.indexOf('\n', to);
+ if (lineEnd === -1) lineEnd = body.length;
+ const restOfLine = body.slice(to, lineEnd);
+ let suffix: string;
+ if (!/^\s*$/.test(restOfLine)) {
+ suffix = '\n\n';
+ } else if (lineEnd >= body.length) {
+ suffix = '\n';
+ } else {
+ let nextLineEnd = body.indexOf('\n', lineEnd + 1);
+ if (nextLineEnd === -1) nextLineEnd = body.length;
+ const nextLine = body.slice(lineEnd + 1, nextLineEnd);
+ suffix = /^\s*$/.test(nextLine) ? '' : '\n';
+ }
+
+ const embedEnd = lineStart + prefix.length + embedLine.length;
+ return {
+ from: lineStart,
+ // Swallow a whitespace-only rest of line. Leaving it behind would add
+ // trailing spaces to the embed line and break exact-line host grammars.
+ to: /^\s*$/.test(restOfLine) ? lineEnd : to,
+ insert: prefix + embedLine + suffix,
+ cursor: embedEnd + 1,
+ };
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index 06ca3843cc..66fd6260be 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -15,6 +15,7 @@
"./code-file": "./code-file.ts",
"./compress": "./compress.ts",
"./crypto": "./crypto.ts",
+ "./embed-insert": "./embed-insert.ts",
"./external-annotation": "./external-annotation.ts",
"./extract-code-paths": "./extract-code-paths.ts",
"./favicon": "./favicon.ts",
diff --git a/packages/ui/HANDOFF.md b/packages/ui/HANDOFF.md
index 83f757974e..b11b28af35 100644
--- a/packages/ui/HANDOFF.md
+++ b/packages/ui/HANDOFF.md
@@ -189,7 +189,7 @@ We deliberately did **not** restructure the exports map in this PR (move-don't-r
| `components/BlockRenderer` + the block components it renders (`TableBlock`, `HtmlBlock`, `Callout`, `MermaidBlock`, `MathBlock`, …) | Pure rendering. |
| `components/InlineMarkdown` | Code-file hover previews route through the `docPreviewFetcher` seam. Wiki-link rendering takes the sync `resolveLinkedDoc` prop (live labels + deleted-doc treatment; see "Wiki-link seams (0.27.0)"). |
| `components/Viewer` | The full annotatable document. Required props: `markdown` and `taterMode` (pass `false`). **Pass `disableCodePathValidation` unless you implement `/api/doc/exists`** — code-path validation is a prop-level opt-out, not a `configure` seam. |
-| `components/MarkdownEditor` | Theme-bridging wrapper over `@plannotator/markdown-editor`. Takes CM6 extensions via the `extensions` prop (captured ONCE per `documentId` — see "Wiki-link seams (0.27.0)") and re-exports `wikiLinks` + its config types. |
+| `components/MarkdownEditor` | Theme-bridging wrapper over `@plannotator/markdown-editor`. Takes CM6 extensions via the `extensions` prop (captured ONCE per `documentId` — see "Wiki-link seams (0.27.0)") and re-exports `wikiLinks`, `embedPicker`, `embedSlashItem`, `planEmbedInsert`, and their public types. |
| `components/MarkdownDiff` | Theme-bridging wrapper over `@plannotator/markdown-editor`'s frozen two-revision diff. Same shim pattern as `components/MarkdownEditor` (ThemeProvider bridge, `extensions` passthrough, grid card chrome); never editable. See "Frozen markdown diff (0.28.0)". |
| `components/CommentPopover` | Anchor capture + comment entry. Ask-AI UI renders only if you pass `onAskAI`. |
| `components/AnnotationPanel` | Renders from your annotation state; no fetches of its own. |
@@ -395,6 +395,49 @@ Consumer-enablement round for wiki-links (Workspaces' `[[doc_01XYZ|label]]` link
---
+## Embed media picker (unreleased)
+
+The package now owns the reusable two-stage `/embed` authoring flow. The host still owns its target catalog, serialized embed grammar, and upload UI/API. This is a per-editor extension seam, not a `configurePlannotatorUI()` backend seam.
+
+1. **Single supported import.** `components/MarkdownEditor` re-exports `embedSlashItem()`, `embedPicker(config)`, `EmbedKind`, `EmbedTarget`, `EmbedPickerConfig`, `planEmbedInsert()`, and `EmbedInsertPlan`. Do not import the nested picker module, `@plannotator/atomic-editor`, or `@plannotator/core` directly from a host.
+
+2. **Compose both stages.** Add the static item to `slashCommands()` and register the picker beside it:
+
+ ```tsx
+ import {
+ MarkdownEditor,
+ embedPicker,
+ embedSlashItem,
+ slashCommands,
+ } from "@plannotator/ui/components/MarkdownEditor";
+
+ const editorExtensions = [
+ slashCommands({ items: [embedSlashItem()] }),
+ embedPicker({
+ getTargets: () => currentTargets,
+ buildInsertLine: (target) => buildHostEmbedLine(target),
+ uploadTarget: async (kind) => uploadHostTarget(kind),
+ getNotice: (docBody) => currentEmbedNotice(docBody),
+ }),
+ ];
+
+ ;
+ ```
+
+ The static item rewrites `/query` to `/embed ` and reopens completion. The picker then performs case-insensitive substring matching over target titles and paths. It deliberately returns `filter: false` so multi-word titles remain in the session.
+
+3. **Captured once, callbacks stay live.** The `extensions` array is still captured once per `documentId`. Keep the extension reference stable and close `getTargets`, `buildInsertLine`, `uploadTarget`, and `getNotice` over live refs or route state. Do not rebuild the array merely because target data changed.
+
+4. **Grammar belongs to the host; splicing belongs to the package.** `buildInsertLine(target)` returns the exact line the host wants stored. `planEmbedInsert()` then normalizes that line into its own blank-line-delimited paragraph and places the caret on the following line. Host-specific path resolution, label escaping, and embed-fragment grammar stay outside the package.
+
+5. **Upload is optional and single-flight.** When `uploadTarget` is absent, no upload row is rendered. When present, every picker state includes `Upload HTML...`. While its promise is pending, the typed `/embed` text stays visible and a reopened picker shows an inert `Uploading...` row. Resolving with a target inserts it through `buildInsertLine` and the same splice as an existing target; resolving `null` or rejecting leaves the typed command untouched. The package maps the anchor through CodeMirror transactions and silently drops the insert if the command was edited away. The host owns all failure UI.
+
+6. **One CodeMirror dependency graph.** The picker imports `@codemirror/autocomplete`, `@codemirror/state`, and `@codemirror/view` from `@plannotator/ui`'s declared dependencies. `@plannotator/atomic-editor` declares these as peers, so a consumer must resolve one shared copy. A second live copy of `@codemirror/state` breaks extensions just as it does for `wikiLinks`.
+
+Behavior is pinned by `components/MarkdownEditor.embedPicker.test.ts`, the supported re-export by `components/MarkdownEditor.embedPicker.reexport.test.ts`, and the pure splice planner by `../core/embed-insert.test.ts`.
+
+---
+
## Frozen markdown diff (0.28.0)
One additive component for the Workspaces versions/approvals surface: `components/MarkdownDiff`, a theme-bridging shim over `@plannotator/markdown-editor@0.4.0`'s `MarkdownDiff` — a **frozen two-revision markdown comparison**. The newer revision renders as the real document (uncollapsed, full length); deletions are projected struck-through at their original positions; changed spans get character/word emphasis; a toolbar shows the change count with prev/next navigation; a clickable, keyboard-accessible overview rail and a changed-line gutter complete the review chrome. Every 0.27.0 surface is unchanged.
diff --git a/packages/ui/README.md b/packages/ui/README.md
index f5c6aeac95..1611ffa356 100644
--- a/packages/ui/README.md
+++ b/packages/ui/README.md
@@ -60,6 +60,7 @@ Building your own tooltip and removing the built-in double-click reset are host-
const editorExtensions = [wikiLinks({ suggest, resolve, onOpen })]; // stable reference!
```
+- **`embedPicker(config)` and `embedSlashItem()` are re-exported from the same surface.** Compose the static item into `slashCommands({ items: [...] })` and pass the picker beside it in the stable `extensions` array. `getTargets`, `buildInsertLine`, optional `uploadTarget`, and optional `getNotice` stay live through callbacks. The host owns embed grammar and upload error UI; the package owns filtering, async anchor mapping, single-flight upload state, and paragraph-safe insertion through the re-exported `planEmbedInsert()`.
- **The viewer resolves wiki-links synchronously.** `InlineMarkdown` takes `resolveLinkedDoc?: (target) => { label?; status?: 'active' | 'deleted' } | null` — called with the raw stored target (opaque ids like `doc_01XYZ`, no `.md` normalization). Return a `label` to display live titles (stored label is the fallback, target the last resort); return `status: 'deleted'` for a muted non-link ("Document deleted") instead of a live link. Absent or `null` → rendering is unchanged. Sync-only by design: back it with an in-memory cache.
Requires `@plannotator/markdown-editor ^0.3.2` and `@plannotator/atomic-editor ^0.7.0`. See HANDOFF.md § "Wiki-link seams (0.27.0)".
diff --git a/packages/ui/components/MarkdownEditor.embedPicker.reexport.test.ts b/packages/ui/components/MarkdownEditor.embedPicker.reexport.test.ts
new file mode 100644
index 0000000000..14bdc93f5d
--- /dev/null
+++ b/packages/ui/components/MarkdownEditor.embedPicker.reexport.test.ts
@@ -0,0 +1,34 @@
+// This test guards the supported consumer surface. A regression would force a
+// host to import package internals or @plannotator/core directly.
+import { describe, expect, test } from 'bun:test';
+import { planEmbedInsert as corePlanEmbedInsert } from '@plannotator/core/embed-insert';
+
+import {
+ embedPicker,
+ embedSlashItem,
+ planEmbedInsert,
+ type EmbedKind,
+ type EmbedPickerConfig,
+ type EmbedTarget,
+ type EmbedInsertPlan,
+} from './MarkdownEditor';
+
+describe('MarkdownEditor module: embed picker re-exports', () => {
+ test('exposes the picker and core planner through the supported UI import', () => {
+ const kind: EmbedKind = 'html';
+ const target: EmbedTarget = { kind, path: 'report.html', title: 'Report' };
+ const config: EmbedPickerConfig = {
+ getTargets: () => [target],
+ buildInsertLine: (entry) => `[${entry.title ?? entry.path}](${entry.path}#embed)`,
+ uploadTarget: async (uploadKind) => (uploadKind === kind ? target : null),
+ getNotice: () => null,
+ };
+ const plan: EmbedInsertPlan = planEmbedInsert('/embed report', 0, 13, '[Report](report)');
+
+ expect(typeof embedPicker).toBe('function');
+ expect(typeof embedSlashItem).toBe('function');
+ expect(embedPicker(config)).toBeDefined();
+ expect(plan.insert).toContain('[Report](report)');
+ expect(planEmbedInsert).toBe(corePlanEmbedInsert);
+ });
+});
diff --git a/packages/ui/components/MarkdownEditor.embedPicker.test.ts b/packages/ui/components/MarkdownEditor.embedPicker.test.ts
new file mode 100644
index 0000000000..7712227d93
--- /dev/null
+++ b/packages/ui/components/MarkdownEditor.embedPicker.test.ts
@@ -0,0 +1,405 @@
+/**
+ * Regression coverage for the mount-scoped `/embed` picker.
+ *
+ * Requires DOM_TESTS=1 (happy-dom preload). Run:
+ * DOM_TESTS=1 bun test packages/ui/components/MarkdownEditor.embedPicker.test.ts
+ */
+import {
+ CompletionContext,
+ completionStatus,
+ type Completion,
+ type CompletionResult,
+ type CompletionSource,
+} from '@codemirror/autocomplete';
+import { EditorState } from '@codemirror/state';
+import { EditorView } from '@codemirror/view';
+import { afterEach, describe, expect, test } from 'bun:test';
+
+import {
+ embedPicker,
+ embedSlashItem,
+ slashCommands,
+ type EmbedPickerConfig,
+ type EmbedTarget,
+} from './MarkdownEditor';
+
+const hasDom = typeof document !== 'undefined';
+const REPORT: EmbedTarget = { kind: 'html', path: 'report.html', title: 'Report' };
+const mountedViews: EditorView[] = [];
+
+afterEach(() => {
+ while (mountedViews.length > 0) {
+ const view = mountedViews.pop();
+ view?.destroy();
+ }
+});
+
+function buildInsertLine(target: EmbedTarget): string {
+ return `[${target.title ?? target.path}](${target.path}#embed)`;
+}
+
+function createView(doc: string, config: EmbedPickerConfig, includeSlashMenu = false): EditorView {
+ const extensions = includeSlashMenu
+ ? [slashCommands({ items: [embedSlashItem()] }), embedPicker(config)]
+ : [embedPicker(config)];
+ const state = EditorState.create({
+ doc,
+ selection: { anchor: doc.length },
+ extensions,
+ });
+ const parent = document.createElement('div');
+ document.body.appendChild(parent);
+ const view = new EditorView({ state, parent });
+ mountedViews.push(view);
+ return view;
+}
+
+async function pickerResult(view: EditorView): Promise {
+ const pos = view.state.selection.main.head;
+ const sources = view.state.languageDataAt('autocomplete', pos);
+ // `slashCommands()` may contribute the first source. The embed source is the
+ // one whose completion range begins at the `/` for an `/embed` query.
+ for (const source of sources) {
+ const result = await source(new CompletionContext(view.state, pos, true, view));
+ if (result?.filter === false) return result;
+ }
+ return null;
+}
+
+async function requirePickerResult(view: EditorView): Promise {
+ const result = await pickerResult(view);
+ if (result === null) throw new Error('Expected the embed picker to return completions');
+ return result;
+}
+
+function requireOption(result: CompletionResult, label: string): Completion {
+ const option = result.options.find((entry) => entry.label === label);
+ if (option === undefined) throw new Error(`Expected completion option: ${label}`);
+ return option;
+}
+
+function applyOption(view: EditorView, result: CompletionResult, option: Completion): void {
+ if (typeof option.apply !== 'function') {
+ throw new Error(`Expected ${option.label} to have an apply function`);
+ }
+ option.apply(
+ view,
+ option,
+ result.from,
+ result.to ?? view.state.selection.main.head,
+ );
+}
+
+function hasSlashCommandIcon(
+ completion: Completion,
+): completion is Completion & { readonly slashCommandIcon: string } {
+ return (
+ 'slashCommandIcon' in completion && typeof completion.slashCommandIcon === 'string'
+ );
+}
+
+function deferred(): {
+ readonly promise: Promise;
+ readonly resolve: (value: T) => void;
+} {
+ let resolvePromise: ((value: T) => void) | null = null;
+ const promise = new Promise((resolve) => {
+ resolvePromise = resolve;
+ });
+ return {
+ promise,
+ resolve: (value) => {
+ if (resolvePromise === null) throw new Error('Deferred promise was not initialized');
+ resolvePromise(value);
+ },
+ };
+}
+
+async function settleUpload(): Promise {
+ await Promise.resolve();
+ await Promise.resolve();
+}
+
+describe('embed picker: two-stage completion flow', () => {
+ test.skipIf(!hasDom)('rewrites the static slash query and immediately reopens completion', async () => {
+ const view = createView('/emb', { getTargets: () => [REPORT], buildInsertLine }, true);
+ const item = embedSlashItem();
+ if (item.apply === undefined) throw new Error('Expected Embed HTML to define apply');
+
+ item.apply(view, { label: item.label }, 0, view.state.doc.length);
+ await Promise.resolve();
+
+ expect(view.state.doc.toString()).toBe('/embed ');
+ expect(view.state.selection.main.head).toBe('/embed '.length);
+ expect(completionStatus(view.state)).not.toBeNull();
+ });
+
+ test.skipIf(!hasDom)('does not answer an /embed query that starts after prose on a line', async () => {
+ const view = createView('Prose /embed report', {
+ getTargets: () => [REPORT],
+ buildInsertLine,
+ });
+ expect(await pickerResult(view)).toBeNull();
+ });
+});
+
+describe('embed picker: target rows and filtering', () => {
+ test.skipIf(!hasDom)(
+ 'keeps multi-word title queries alive with filter false and matches title case-insensitively',
+ async () => {
+ const view = createView('/embed QUARTER PLAN', {
+ getTargets: () => [
+ { kind: 'html', path: 'reports/q1.html', title: 'Quarter Plan' },
+ { kind: 'html', path: 'reports/q2.html', title: 'Roadmap' },
+ ],
+ buildInsertLine,
+ });
+
+ const result = await requirePickerResult(view);
+ expect(result.filter).toBe(false);
+ expect(result.options.map((option) => option.label)).toEqual(['Quarter Plan']);
+ },
+ );
+
+ test.skipIf(!hasDom)('matches a query against target paths as well as titles', async () => {
+ const view = createView('/embed LAUNCH-NOTES', {
+ getTargets: () => [
+ { kind: 'html', path: 'memos/launch-notes.html', title: 'Release brief' },
+ REPORT,
+ ],
+ buildInsertLine,
+ });
+
+ const result = await requirePickerResult(view);
+ expect(result.options.map((option) => option.label)).toEqual(['Release brief']);
+ });
+
+ test.skipIf(!hasDom)('reads target changes live without rebuilding the captured extension', async () => {
+ let targets: readonly EmbedTarget[] = [];
+ const view = createView('/embed ', {
+ getTargets: () => targets,
+ buildInsertLine,
+ });
+ expect((await requirePickerResult(view)).options.map((option) => option.label)).toEqual([
+ 'No HTML files in this workspace',
+ ]);
+
+ targets = [REPORT];
+ expect((await requirePickerResult(view)).options.map((option) => option.label)).toEqual([
+ 'Report',
+ ]);
+ });
+
+ test.skipIf(!hasDom)('inserts a picked target through the host builder and paragraph splice', async () => {
+ const view = createView('Intro.\n/embed report', {
+ getTargets: () => [REPORT],
+ buildInsertLine,
+ });
+ const result = await requirePickerResult(view);
+ applyOption(view, result, requireOption(result, 'Report'));
+
+ expect(view.state.doc.toString()).toBe('Intro.\n\n[Report](report.html#embed)\n');
+ });
+});
+
+describe('embed picker: empty states', () => {
+ test.skipIf(!hasDom)('distinguishes no HTML targets from no query matches and clears either row', async () => {
+ const noTargetsView = createView('/embed report', {
+ getTargets: () => [],
+ buildInsertLine,
+ });
+ const noTargets = await requirePickerResult(noTargetsView);
+ // These labels are deliberate UX states from the design contract.
+ const noTargetsRow = requireOption(noTargets, 'No HTML files in this workspace');
+ applyOption(noTargetsView, noTargets, noTargetsRow);
+ expect(noTargetsView.state.doc.toString()).toBe('');
+
+ const noMatchesView = createView('/embed missing', {
+ getTargets: () => [REPORT],
+ buildInsertLine,
+ });
+ const noMatches = await requirePickerResult(noMatchesView);
+ const noMatchesRow = requireOption(noMatches, 'No HTML files match “missing”');
+ applyOption(noMatchesView, noMatches, noMatchesRow);
+ expect(noMatchesView.state.doc.toString()).toBe('');
+ });
+});
+
+describe('embed picker: upload row availability', () => {
+ test.skipIf(!hasDom)('shows Upload HTML in populated and empty menus only when configured', async () => {
+ const uploadTarget = async (): Promise => null;
+ const cases: ReadonlyArray<{
+ readonly targets: readonly EmbedTarget[];
+ readonly configured: boolean;
+ }> = [
+ { targets: [REPORT], configured: true },
+ { targets: [], configured: true },
+ { targets: [REPORT], configured: false },
+ { targets: [], configured: false },
+ ];
+
+ for (const entry of cases) {
+ const view = createView('/embed ', {
+ getTargets: () => entry.targets,
+ buildInsertLine,
+ ...(entry.configured ? { uploadTarget } : {}),
+ });
+ const result = await requirePickerResult(view);
+ // The explicit action label is part of the public picker contract.
+ expect(result.options.some((option) => option.label === 'Upload HTML...')).toBe(
+ entry.configured,
+ );
+ }
+ });
+
+ test.skipIf(!hasDom)('carries the package 16x16 icon on the ordinary upload completion', async () => {
+ const view = createView('/embed ', {
+ getTargets: () => [],
+ buildInsertLine,
+ uploadTarget: async () => null,
+ });
+ const result = await requirePickerResult(view);
+ const uploadRow = requireOption(result, 'Upload HTML...');
+
+ expect(hasSlashCommandIcon(uploadRow)).toBe(true);
+ if (!hasSlashCommandIcon(uploadRow)) return;
+ expect(uploadRow.slashCommandIcon).toContain('viewBox="0 0 16 16"');
+ expect(uploadRow.slashCommandIcon).toContain('stroke-width="1.5"');
+ expect(uploadRow.slashCommandIcon).toContain('stroke="currentColor"');
+ });
+});
+
+describe('embed picker: upload lifecycle', () => {
+ test.skipIf(!hasDom)('leaves the typed anchor visible, then inserts a resolved upload through the splice', async () => {
+ const upload = deferred();
+ const view = createView('Intro.\n/embed report', {
+ getTargets: () => [],
+ buildInsertLine,
+ uploadTarget: () => upload.promise,
+ });
+ const result = await requirePickerResult(view);
+ applyOption(view, result, requireOption(result, 'Upload HTML...'));
+ expect(view.state.doc.toString()).toBe('Intro.\n/embed report');
+
+ upload.resolve(REPORT);
+ await settleUpload();
+ expect(view.state.doc.toString()).toBe('Intro.\n\n[Report](report.html#embed)\n');
+ });
+
+ test.skipIf(!hasDom)('leaves the typed command unchanged when upload is cancelled', async () => {
+ const upload = deferred();
+ const view = createView('/embed report', {
+ getTargets: () => [],
+ buildInsertLine,
+ uploadTarget: () => upload.promise,
+ });
+ const result = await requirePickerResult(view);
+ applyOption(view, result, requireOption(result, 'Upload HTML...'));
+
+ upload.resolve(null);
+ await settleUpload();
+ expect(view.state.doc.toString()).toBe('/embed report');
+ });
+
+ test.skipIf(!hasDom)('leaves the typed command unchanged when the host upload rejects', async () => {
+ const view = createView('/embed report', {
+ getTargets: () => [],
+ buildInsertLine,
+ uploadTarget: async () => {
+ throw new Error('host surfaced upload failure');
+ },
+ });
+ const result = await requirePickerResult(view);
+ applyOption(view, result, requireOption(result, 'Upload HTML...'));
+
+ await settleUpload();
+ expect(view.state.doc.toString()).toBe('/embed report');
+ });
+
+ test.skipIf(!hasDom)('single-flights a pending upload and renders an inert Uploading row', async () => {
+ const upload = deferred();
+ let calls = 0;
+ const view = createView('/embed report', {
+ getTargets: () => [],
+ buildInsertLine,
+ uploadTarget: () => {
+ calls += 1;
+ return upload.promise;
+ },
+ });
+ const initial = await requirePickerResult(view);
+ const uploadOption = requireOption(initial, 'Upload HTML...');
+ applyOption(view, initial, uploadOption);
+
+ const pending = await requirePickerResult(view);
+ const uploadingOption = requireOption(pending, 'Uploading...');
+ applyOption(view, pending, uploadingOption);
+ // A stale copy of the original option is also unable to start a second call.
+ applyOption(view, initial, uploadOption);
+ expect(calls).toBe(1);
+
+ upload.resolve(null);
+ await settleUpload();
+ });
+
+ test.skipIf(!hasDom)('drops the resolved insert when the /embed anchor line was deleted', async () => {
+ const upload = deferred();
+ const view = createView('Keep\n/embed report\nTail', {
+ getTargets: () => [],
+ buildInsertLine,
+ uploadTarget: () => upload.promise,
+ });
+ const anchorFrom = view.state.doc.toString().indexOf('/embed');
+ view.dispatch({ selection: { anchor: anchorFrom + '/embed report'.length } });
+ const result = await requirePickerResult(view);
+ applyOption(view, result, requireOption(result, 'Upload HTML...'));
+
+ view.dispatch({ changes: { from: anchorFrom, to: anchorFrom + '/embed report'.length } });
+ const editedBody = view.state.doc.toString();
+ upload.resolve(REPORT);
+ await settleUpload();
+
+ expect(view.state.doc.toString()).toBe(editedBody);
+ });
+
+ test.skipIf(!hasDom)('maps the pending anchor when text is inserted above its line', async () => {
+ const upload = deferred();
+ const view = createView('/embed report', {
+ getTargets: () => [],
+ buildInsertLine,
+ uploadTarget: () => upload.promise,
+ });
+ const result = await requirePickerResult(view);
+ applyOption(view, result, requireOption(result, 'Upload HTML...'));
+
+ view.dispatch({ changes: { from: 0, insert: 'Intro\n' } });
+ upload.resolve(REPORT);
+ await settleUpload();
+
+ expect(view.state.doc.toString()).toBe('Intro\n\n[Report](report.html#embed)\n');
+ });
+});
+
+describe('embed picker: notice row', () => {
+ test.skipIf(!hasDom)('renders a host notice when present and omits it when null', async () => {
+ const notice = 'NOTICE_SENTINEL';
+ const withNotice = createView('/embed report', {
+ getTargets: () => [REPORT],
+ buildInsertLine,
+ getNotice: (body) => (body.includes('/embed') ? notice : null),
+ });
+ const withoutNotice = createView('/embed report', {
+ getTargets: () => [REPORT],
+ buildInsertLine,
+ getNotice: () => null,
+ });
+
+ // Sentinel assertion: this guards conditional row presence, not host copy.
+ expect((await requirePickerResult(withNotice)).options.some((row) => row.label === notice)).toBe(
+ true,
+ );
+ expect(
+ (await requirePickerResult(withoutNotice)).options.some((row) => row.label === notice),
+ ).toBe(false);
+ });
+});
diff --git a/packages/ui/components/MarkdownEditor.tsx b/packages/ui/components/MarkdownEditor.tsx
index 22b350bc07..571edc5420 100644
--- a/packages/ui/components/MarkdownEditor.tsx
+++ b/packages/ui/components/MarkdownEditor.tsx
@@ -34,6 +34,18 @@ export type { SlashCommandItem, SlashCommandsConfig } from '@plannotator/atomic-
export { selectionToolbar } from '@plannotator/atomic-editor';
export type { SelectionToolbarConfig, InlineFormat } from '@plannotator/atomic-editor';
+/* Host-configured embed media authoring. The picker is per editor mount so its
+ callbacks can close over live route state; nothing enters configurePlannotatorUI.
+ The package owns paragraph-safe splicing while the host owns embed grammar. */
+export { embedPicker, embedSlashItem } from './MarkdownEditor/embedPicker';
+export type {
+ EmbedKind,
+ EmbedPickerConfig,
+ EmbedTarget,
+} from './MarkdownEditor/embedPicker';
+export { planEmbedInsert } from '@plannotator/core/embed-insert';
+export type { EmbedInsertPlan } from '@plannotator/core/embed-insert';
+
/* Grid-mode card utilities stay here (not in the package): they're Plannotator
design-system Tailwind classes, and this file is @source-scanned. */
const GRID_CARD_CLASSES = 'px-5 md:px-8 lg:px-10 xl:px-12 shadow-xl border border-border/50';
diff --git a/packages/ui/components/MarkdownEditor/embedPicker.ts b/packages/ui/components/MarkdownEditor/embedPicker.ts
new file mode 100644
index 0000000000..14700e1dd8
--- /dev/null
+++ b/packages/ui/components/MarkdownEditor/embedPicker.ts
@@ -0,0 +1,349 @@
+import {
+ pickedCompletion,
+ startCompletion,
+ type Completion,
+ type CompletionSource,
+} from '@codemirror/autocomplete';
+import {
+ EditorState,
+ MapMode,
+ StateEffect,
+ StateField,
+ type Extension,
+ type StateEffectType,
+} from '@codemirror/state';
+import type { EditorView } from '@codemirror/view';
+import type { SlashCommandItem } from '@plannotator/atomic-editor';
+import { planEmbedInsert } from '@plannotator/core/embed-insert';
+
+/** What an embed can point at. The union grows as new media kinds ship. */
+export type EmbedKind = 'html';
+
+/** One embeddable target supplied by the host. */
+export interface EmbedTarget {
+ /** Media kind represented by this target. */
+ readonly kind: EmbedKind;
+ /** Host-meaningful target identifier or path. */
+ readonly path: string;
+ /** Display title. Blank and absent titles fall back to {@link path}. */
+ readonly title?: string | null;
+}
+
+/** Per-editor host callbacks for the `/embed` picker. */
+export interface EmbedPickerConfig {
+ /** Live read of embeddable targets. Dynamic data belongs behind this callback. */
+ readonly getTargets: () => readonly EmbedTarget[];
+ /** Build the exact host-owned embed line for a picked target. */
+ readonly buildInsertLine: (target: EmbedTarget) => string;
+ /**
+ * Optionally upload a target. Resolve with a target to insert it, or `null`
+ * when the user cancels. The host owns error presentation.
+ */
+ readonly uploadTarget?: (kind: EmbedKind) => Promise;
+ /** Return an optional informational row for the current document text. */
+ readonly getNotice?: (docBody: string) => string | null;
+}
+
+type IconCompletion = Completion & {
+ readonly slashCommandIcon?: string;
+};
+
+type UploadAnchor = {
+ readonly from: number;
+ readonly to: number;
+ readonly text: string;
+};
+
+type UploadState =
+ | { readonly _tag: 'idle' }
+ | { readonly _tag: 'uploading'; readonly anchor: UploadAnchor | null };
+
+type UploadStateEffect =
+ | { readonly _tag: 'start'; readonly anchor: UploadAnchor }
+ | { readonly _tag: 'finish' };
+
+type UploadStateEffectType = StateEffectType;
+
+const IDLE_UPLOAD_STATE: UploadState = { _tag: 'idle' };
+const EMBED_PREFIX = '/embed ';
+const HTML_KIND: EmbedKind = 'html';
+
+// Framed `>` for an HTML document rendered in place. This follows the
+// editor package convention: 16x16 viewBox, currentColor, 1.5 stroke.
+const EMBED_ICON =
+ '';
+
+// A document with an upward arrow. `slashCommands()` owns the shared menu's
+// icon renderer; its completion metadata lets this picker use the same gutter.
+const UPLOAD_ICON =
+ '';
+
+/**
+ * Build the static slash-menu item that hands completion to the `/embed` picker.
+ *
+ * @returns A slash command that rewrites the typed query to `/embed ` and
+ * immediately reopens completion.
+ */
+export function embedSlashItem(): SlashCommandItem {
+ return {
+ label: 'Embed HTML',
+ detail: 'live preview',
+ icon: EMBED_ICON,
+ apply: (view, completion, from, to) => {
+ view.dispatch({
+ changes: { from, to, insert: EMBED_PREFIX },
+ selection: { anchor: from + EMBED_PREFIX.length },
+ annotations: pickedCompletion.of(completion),
+ });
+ startCompletion(view);
+ },
+ };
+}
+
+/**
+ * Build the `/embed` target picker extension for one editor mount.
+ *
+ * The editor captures extensions once per document mount. Keep the returned
+ * extension stable and feed changing target data through the config callbacks.
+ *
+ * @param config - Host target, serialization, upload, and notice callbacks.
+ * @returns A CodeMirror extension that composes with `slashCommands()`.
+ */
+export function embedPicker(config: EmbedPickerConfig): Extension {
+ const uploadStateEffect = StateEffect.define();
+ const uploadStateField = StateField.define({
+ create: () => IDLE_UPLOAD_STATE,
+ update: (current, transaction) => {
+ let next = current;
+ if (next._tag === 'uploading' && next.anchor !== null && transaction.docChanged) {
+ const mappedFrom = transaction.changes.mapPos(next.anchor.from, 1, MapMode.TrackAfter);
+ const mappedTo = transaction.changes.mapPos(next.anchor.to, -1, MapMode.TrackBefore);
+ next = {
+ _tag: 'uploading',
+ anchor:
+ mappedFrom === null || mappedTo === null || mappedFrom > mappedTo
+ ? null
+ : { ...next.anchor, from: mappedFrom, to: mappedTo },
+ };
+ }
+
+ for (const effect of transaction.effects) {
+ if (!effect.is(uploadStateEffect)) continue;
+ next =
+ effect.value._tag === 'start'
+ ? { _tag: 'uploading', anchor: effect.value.anchor }
+ : IDLE_UPLOAD_STATE;
+ }
+ return next;
+ },
+ });
+
+ const source = createEmbedPickerSource(config, uploadStateField, uploadStateEffect);
+ return [uploadStateField, EditorState.languageData.of(() => [{ autocomplete: source }])];
+}
+
+function createEmbedPickerSource(
+ config: EmbedPickerConfig,
+ uploadStateField: StateField,
+ uploadStateEffect: UploadStateEffectType,
+): CompletionSource {
+ return (context) => {
+ const match = context.matchBefore(/\/embed +[^\n]*$/);
+ if (match === null) return null;
+
+ // Like the package slash source, the trigger must open its line. An embed
+ // is a block insertion and belongs in its own paragraph.
+ const line = context.state.doc.lineAt(match.from);
+ if (!/^\s*$/.test(line.text.slice(0, match.from - line.from))) return null;
+
+ const query = match.text.replace(/^\/embed +/, '');
+ const targets = config.getTargets().filter((target) => target.kind === HTML_KIND);
+ const matches = filterTargets(targets, query);
+ const options: IconCompletion[] = [];
+ const notice = config.getNotice?.(context.state.doc.toString()) ?? null;
+ if (notice !== null) {
+ options.push({
+ label: notice,
+ apply: () => {
+ // Informational row: selection closes the menu and leaves the typed
+ // command in place so the author can keep deciding.
+ },
+ });
+ }
+
+ if (matches.length === 0) {
+ options.push({
+ label:
+ targets.length === 0
+ ? 'No HTML files in this workspace'
+ : `No HTML files match “${query.trim()}”`,
+ apply: (view, completion, _from, to) => {
+ view.dispatch({
+ changes: { from: line.from, to, insert: '' },
+ annotations: pickedCompletion.of(completion),
+ });
+ },
+ });
+ } else {
+ for (const target of matches) {
+ options.push({
+ label: targetLabel(target),
+ detail: target.path,
+ apply: (view, completion, from, to) => {
+ applyTargetInsert(view, completion, from, to, target, config.buildInsertLine);
+ },
+ });
+ }
+ }
+
+ const uploadTarget = config.uploadTarget;
+ if (uploadTarget !== undefined) {
+ const uploadState = context.state.field(uploadStateField);
+ options.push(
+ uploadState._tag === 'uploading'
+ ? {
+ label: 'Uploading...',
+ slashCommandIcon: UPLOAD_ICON,
+ apply: () => {
+ // Inert while the existing host callback is still pending.
+ },
+ }
+ : {
+ label: 'Upload HTML...',
+ slashCommandIcon: UPLOAD_ICON,
+ apply: (view, completion, from, to) => {
+ startUpload(
+ view,
+ completion,
+ from,
+ to,
+ config,
+ uploadTarget,
+ uploadStateField,
+ uploadStateEffect,
+ );
+ },
+ },
+ );
+ }
+
+ return {
+ // The entire `/embed query` is the completion range. Our case-insensitive
+ // substring matcher owns filtering because CM's fuzzy matcher closes a
+ // completion session when a title query contains spaces.
+ from: match.from,
+ options,
+ filter: false,
+ };
+ };
+}
+
+function filterTargets(targets: readonly EmbedTarget[], query: string): readonly EmbedTarget[] {
+ const needle = query.trim().toLowerCase();
+ if (needle === '') return targets;
+ return targets.filter((target) => {
+ const title = (target.title ?? '').toLowerCase();
+ return title.includes(needle) || target.path.toLowerCase().includes(needle);
+ });
+}
+
+function targetLabel(target: EmbedTarget): string {
+ const title = target.title ?? '';
+ return title.trim() === '' ? target.path : title;
+}
+
+function applyTargetInsert(
+ view: EditorView,
+ completion: Completion,
+ from: number,
+ to: number,
+ target: EmbedTarget,
+ buildInsertLine: EmbedPickerConfig['buildInsertLine'],
+): void {
+ const body = view.state.doc.toString();
+ const plan = planEmbedInsert(body, from, to, buildInsertLine(target));
+ view.dispatch({
+ changes: { from: plan.from, to: plan.to, insert: plan.insert },
+ selection: { anchor: plan.cursor },
+ scrollIntoView: true,
+ annotations: pickedCompletion.of(completion),
+ });
+}
+
+function startUpload(
+ view: EditorView,
+ completion: Completion,
+ from: number,
+ to: number,
+ config: EmbedPickerConfig,
+ uploadTarget: NonNullable,
+ uploadStateField: StateField,
+ uploadStateEffect: UploadStateEffectType,
+): void {
+ const uploadState = view.state.field(uploadStateField, false);
+ if (uploadState?._tag === 'uploading') return;
+
+ const anchor: UploadAnchor = {
+ from,
+ to,
+ text: view.state.doc.sliceString(from, to),
+ };
+ view.dispatch({
+ effects: uploadStateEffect.of({ _tag: 'start', anchor }),
+ annotations: pickedCompletion.of(completion),
+ });
+
+ void (async () => {
+ try {
+ const target = await uploadTarget(HTML_KIND);
+ finishUpload(view, completion, target, config, uploadStateField, uploadStateEffect);
+ } catch {
+ clearUpload(view, uploadStateField, uploadStateEffect);
+ }
+ })();
+}
+
+function finishUpload(
+ view: EditorView,
+ completion: Completion,
+ target: EmbedTarget | null,
+ config: EmbedPickerConfig,
+ uploadStateField: StateField,
+ uploadStateEffect: UploadStateEffectType,
+): void {
+ const uploadState = view.state.field(uploadStateField, false);
+ if (uploadState?._tag !== 'uploading') return;
+
+ const anchor = uploadState.anchor;
+ if (target === null || anchor === null || !isLiveAnchor(view, anchor)) {
+ clearUpload(view, uploadStateField, uploadStateEffect);
+ return;
+ }
+
+ const body = view.state.doc.toString();
+ const plan = planEmbedInsert(body, anchor.from, anchor.to, config.buildInsertLine(target));
+ view.dispatch({
+ changes: { from: plan.from, to: plan.to, insert: plan.insert },
+ selection: { anchor: plan.cursor },
+ scrollIntoView: true,
+ effects: uploadStateEffect.of({ _tag: 'finish' }),
+ annotations: pickedCompletion.of(completion),
+ });
+}
+
+function isLiveAnchor(view: EditorView, anchor: UploadAnchor): boolean {
+ if (anchor.from > anchor.to || anchor.to > view.state.doc.length) return false;
+ if (view.state.doc.sliceString(anchor.from, anchor.to) !== anchor.text) return false;
+ const line = view.state.doc.lineAt(anchor.from);
+ return /^\s*$/.test(line.text.slice(0, anchor.from - line.from));
+}
+
+function clearUpload(
+ view: EditorView,
+ uploadStateField: StateField,
+ uploadStateEffect: UploadStateEffectType,
+): void {
+ const uploadState = view.state.field(uploadStateField, false);
+ if (uploadState?._tag !== 'uploading') return;
+ view.dispatch({ effects: uploadStateEffect.of({ _tag: 'finish' }) });
+}
diff --git a/packages/ui/tsconfig.strict-consumer.json b/packages/ui/tsconfig.strict-consumer.json
index 47d9cc310d..8d7ad73df6 100644
--- a/packages/ui/tsconfig.strict-consumer.json
+++ b/packages/ui/tsconfig.strict-consumer.json
@@ -30,6 +30,7 @@
"components/InlineMarkdown.tsx",
"components/Viewer.tsx",
"components/MarkdownEditor.tsx",
+ "components/MarkdownEditor/embedPicker.ts",
"components/MarkdownDiff.tsx",
"components/CommentPopover.tsx",
"components/AnnotationPanel.tsx",