Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions packages/core/embed-insert.test.ts
Original file line number Diff line number Diff line change
@@ -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('');
});
});
80 changes: 80 additions & 0 deletions packages/core/embed-insert.ts
Original file line number Diff line number Diff line change
@@ -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,
};
}
1 change: 1 addition & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
45 changes: 44 additions & 1 deletion packages/ui/HANDOFF.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down Expand Up @@ -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),
}),
];

<MarkdownEditor extensions={editorExtensions} {...editorProps} />;
```

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.
Expand Down
1 change: 1 addition & 0 deletions packages/ui/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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!
<MarkdownEditor markdown={md} documentId={docId} editorHandleRef={ref} extensions={editorExtensions} />
```
- **`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)".
Expand Down
34 changes: 34 additions & 0 deletions packages/ui/components/MarkdownEditor.embedPicker.reexport.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
Loading