Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Use one name prop for Mirror blocks and suggest sources (#7774)
Abrahame8cb46455866
diff --git a/.changeset/mirror-name-prop-and-pickers.md b/.changeset/mirror-name-prop-and-pickers.mdnew file mode 100644index 000000000..c74b0c71b--- /dev/null+++ b/.changeset/mirror-name-prop-and-pickers.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': patch+---++`<Mirror>` and `<MirrorSource>` now share one `name` prop, Mirror Sources added from the slash menu are named for you, and the Mirror panel suggests documents and source names. Update collaborators first: earlier versions do not read `name`, though this version still reads `anchor` and `id`.diff --git a/.changeset/prop-panel-non-text-values.md b/.changeset/prop-panel-non-text-values.mdnew file mode 100644index 000000000..7ab8372a4--- /dev/null+++ b/.changeset/prop-panel-non-text-values.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': patch+---++The properties panel no longer breaks the document view when a text field holds a number or no value, such as Width on `<Embed width={300} />` under Advanced; numbers show as text.diff --git a/PRECEDENTS.md b/PRECEDENTS.mdindex 6d5cea6c8..90fd38996 100644--- a/PRECEDENTS.md+++ b/PRECEDENTS.md@@ -2,7 +2,7 @@Titles index for the architectural precedents that Open Knowledge code cites as `precedent #N`. Numbers are a stability contract: a slot is never renumbered and never reused, so a citation resolves to the same rule for as long as the code carries it. A rule that was withdrawn keeps its slot and is marked below.-60 numbered slots, 57 active, 3 retracted.+61 numbered slots, 58 active, 3 retracted.## Convention & discipline (precedents 1–8)@@ -141,3 +141,7 @@ Titles index for the architectural precedents that Open Knowledge code cites as## Native-handoff transport carries path and prompt only (precedent 60)60. **A native-handoff deep link carries a folder or workspace path plus a short directive prompt — never a `file=` attach param and never whole-doc bytes; the receiving agent grounds by reading the doc through the OpenKnowledge MCP server.**++## JSX prop renames (precedent 61)++61. **Rename a JSX prop by listing its old spelling in the new prop's `legacyNames`; old spellings stay readable.**diff --git a/docs/content/reference/components/mirror.mdx b/docs/content/reference/components/mirror.mdxindex 1a643b431..83953d4c5 100644--- a/docs/content/reference/components/mirror.mdx+++ b/docs/content/reference/components/mirror.mdx@@ -7,15 +7,15 @@ keywords: "mirror, sync, synced, transclude, embed, reference, shared block"## Example<ComponentPreview>- <MirrorPreview src="specs/architecture" anchor="overview-diagram">- This body renders live from wherever the `<MirrorSource id="overview-diagram">`- with a matching id lives — edits there ripple here without a copy step.+ <MirrorPreview src="specs/architecture" name="overview-diagram">+ This body renders live from wherever the `<MirrorSource name="overview-diagram">`+ with a matching name lives — edits there ripple here without a copy step.</MirrorPreview></ComponentPreview>````text```mdx-<Mirror src="specs/architecture" anchor="overview-diagram" />+<Mirror src="specs/architecture" name="overview-diagram" />```````@@ -28,8 +28,8 @@ keywords: "mirror, sync, synced, transclude, embed, reference, shared block"type: "string",required: true,},- "anchor": {- description: "Id of the \\`<MirrorSource>\\` block within the source doc.",+ "name": {+ description: "Name of the \\`<MirrorSource>\\` block in the source doc. Also read as \\`anchor\\`; write \\`name\\` instead.",type: "string",required: true,},@@ -38,25 +38,25 @@ keywords: "mirror, sync, synced, transclude, embed, reference, shared block"## Also: `<MirrorSource>`-Mark a block as the source of truth for content that appears in multiple docs. Wrap any block content; `<Mirror src="…" anchor="<id>">` references render this verbatim read-only at every call-site. Edit here, propagate everywhere.+Mark a block as the source of truth for content that appears in multiple docs. Wrap any block content; `<Mirror src="…" name="…">` references render this verbatim read-only at every call-site. Edit here, propagate everywhere.<ComponentPreview>- <MirrorSourcePreview id="overview-diagram">+ <MirrorSourcePreview name="overview-diagram">The canonical content this block owns. Every `<Mirror>` that references- this id anywhere in the project reads from here.+ this name anywhere in the project reads from here.</MirrorSourcePreview></ComponentPreview>```mdx-<MirrorSource id="demo-1">- Authoritative content lives inside this block — edits here propagate to every `<Mirror>` that references this id.+<MirrorSource name="overview-diagram">+ Authoritative content lives inside this block — edits here propagate to every `<Mirror>` that references this name.</MirrorSource>```<TypeTabletype={{- "id": {- description: "Stable id agents and authors use to reference this block from \\`<Mirror>\\` elsewhere.",+ "name": {+ description: "Stable name a \\`<Mirror>\\` uses to reference this block. Also read as \\`id\\`; write \\`name\\` instead.",type: "string",required: true,},@@ -73,3 +73,5 @@ _Also matches:_ `mirror`, `sync`, `synced`, `transclude`, `embed`, `reference`,## Author itType `/mirror` in the editor to insert it from the slash menu, or write the tag directly in source mode. The Properties panel on the right of the editor exposes every prop above as a form field once the block is selected.++A Mirror Source inserted from the slash menu takes its name from the nearest heading above it, as a slug of at most 40 characters cut at a word: `## Pricing Plans` gives `pricing-plans`. With no heading above it the name is `source`, and `-1`, `-2` and so on are added when another Mirror Source in the doc already has that name. In a Mirror's Properties panel, `src` suggests documents and `name` suggests the Mirror Source names in the chosen document.diff --git a/docs/scripts/generate-component-docs.ts b/docs/scripts/generate-component-docs.tsindex 75862bef4..656033542 100644--- a/docs/scripts/generate-component-docs.ts+++ b/docs/scripts/generate-component-docs.ts@@ -4,7 +4,7 @@ import { mkdir, writeFile } from 'node:fs/promises';import path from 'node:path';import { fileURLToPath } from 'node:url';import type { PropDef } from '@inkeep/open-knowledge-core';-import { builtInComponents } from '@inkeep/open-knowledge-core';+import { builtInComponents, propDescription } from '@inkeep/open-knowledge-core';const HERE = path.dirname(fileURLToPath(import.meta.url));const OUT_DIR = path.resolve(HERE, '../content/reference/components');@@ -34,6 +34,11 @@ const COMPOSITION_CHILDREN: Partial<Record<string, string>> = {const COMPOSITION_CHILD_NAMES = new Set(Object.values(COMPOSITION_CHILDREN));+const AUTHORING_NOTES: Partial<Record<string, string>> = {+ Mirror:+ "A Mirror Source inserted from the slash menu takes its name from the nearest heading above it, as a slug of at most 40 characters cut at a word: `## Pricing Plans` gives `pricing-plans`. With no heading above it the name is `source`, and `-1`, `-2` and so on are added when another Mirror Source in the doc already has that name. In a Mirror's Properties panel, `src` suggests documents and `name` suggests the Mirror Source names in the chosen document.",+};+const CANONICAL_SYNTAX: Partial<Record<string, { language: string; code: string }>> = {Callout: {language: 'md',@@ -73,7 +78,7 @@ $$`,},Mirror: {language: 'mdx',- code: `<Mirror src="specs/architecture" anchor="overview-diagram" />`,+ code: `<Mirror src="specs/architecture" name="overview-diagram" />`,},};@@ -117,7 +122,8 @@ function renderTypeTable(props: PropDef[]): string {if (visible.length === 0) return '_No public props._';const entries = visible.map((p) => {- const description = p.description ? escapeMdx(p.description) : '';+ const text = propDescription(p);+ const description = text ? escapeMdx(text) : '';const type = typeLabel(p);const defaultLine ='defaultValue' in p && p.defaultValue !== undefined@@ -174,6 +180,7 @@ function renderExample(meta: (typeof builtInComponents)[number]): string {const PLACEHOLDER_OVERRIDES: Partial<Record<string, string>> = {'Excalidraw.src': 'diagrams/board.excalidraw',+ 'MirrorSource.name': 'overview-diagram',};const GENERIC_PLACEHOLDERS: Record<string, string> = {@@ -284,15 +291,15 @@ const PREVIEWS: Partial<Record<string, string>> = {/></ComponentPreview>`,Mirror: `<ComponentPreview>- <MirrorPreview src="specs/architecture" anchor="overview-diagram">- This body renders live from wherever the \`<MirrorSource id="overview-diagram">\`- with a matching id lives — edits there ripple here without a copy step.+ <MirrorPreview src="specs/architecture" name="overview-diagram">+ This body renders live from wherever the \`<MirrorSource name="overview-diagram">\`+ with a matching name lives — edits there ripple here without a copy step.</MirrorPreview></ComponentPreview>`,MirrorSource: `<ComponentPreview>- <MirrorSourcePreview id="overview-diagram">+ <MirrorSourcePreview name="overview-diagram">The canonical content this block owns. Every \`<Mirror>\` that references- this id anywhere in the project reads from here.+ this name anywhere in the project reads from here.</MirrorSourcePreview></ComponentPreview>`,};@@ -331,6 +338,9 @@ function renderPage(const canonical = CANONICAL_SYNTAX[meta.name];const codeSample = canonical ? renderCodeSample(canonical) : `\`\`\`mdx\n${example}\n\`\`\``;+ const authoringNote = AUTHORING_NOTES[meta.name];+ const authoringNoteBlock = authoringNote ? `\n${authoringNote}\n` : '';+return `---title: ${JSON.stringify(title)}description: ${JSON.stringify(frontmatterDescription)}${keywords ? `\nkeywords: ${JSON.stringify(keywords)}` : ''}@@ -347,7 +357,7 @@ ${propsTable}${childBlock}${searchTermsLine}## Author itType \`/${(meta.searchTerms?.[0] ?? meta.name).toLowerCase()}\` in the editor to insert it from the slash menu, or write the tag directly in source mode. The Properties panel on the right of the editor exposes every prop above as a form field once the block is selected.-`;+${authoringNoteBlock}`;}function renderChildSection(child: (typeof builtInComponents)[number]): string {diff --git a/docs/src/components/previews/mirror-previews.tsx b/docs/src/components/previews/mirror-previews.tsxindex 973b5051d..f3e9f53d5 100644--- a/docs/src/components/previews/mirror-previews.tsx+++ b/docs/src/components/previews/mirror-previews.tsx@@ -1,12 +1,12 @@import { Copy, Link } from 'lucide-react';import type { ReactNode } from 'react';-export function MirrorSourcePreview({ id, children }: { id: string; children?: ReactNode }) {+export function MirrorSourcePreview({ name, children }: { name: string; children?: ReactNode }) {return (<div className="rounded-md border border-fd-border border-l-4 border-l-fd-primary bg-fd-card/50 px-4 py-3 text-fd-foreground text-sm"><div className="mb-2 flex items-center gap-2 text-fd-muted-foreground text-xs"><Copy size={12} aria-hidden />- <span className="font-mono">source id={id}</span>+ <span className="font-mono">source name={name}</span></div><div className="flex flex-col gap-2">{children}</div></div>@@ -15,11 +15,11 @@ export function MirrorSourcePreview({ id, children }: { id: string; children?: Rexport function MirrorPreview({src,- anchor,+ name,children,}: {src: string;- anchor: string;+ name: string;children?: ReactNode;}) {return (@@ -29,7 +29,7 @@ export function MirrorPreview({<span>Mirror of <span className="font-mono">{src}</span>{' → '}- <span className="font-mono">#{anchor}</span> — read-only+ <span className="font-mono">#{name}</span> — read-only</span></div><div className="flex flex-col gap-2 opacity-90">{children}</div>diff --git a/lint-plugins/no-comments/precedent-numbers.generated.json b/lint-plugins/no-comments/precedent-numbers.generated.jsonindex d5c6d9888..a1fe258b2 100644--- a/lint-plugins/no-comments/precedent-numbers.generated.json+++ b/lint-plugins/no-comments/precedent-numbers.generated.json@@ -300,6 +300,11 @@"number": 60,"form": "list","retracted": false+ },+ {+ "number": 61,+ "form": "list",+ "retracted": false}]}diff --git a/packages/app/src/components/RenderedDiffView.dom.test.tsx b/packages/app/src/components/RenderedDiffView.dom.test.tsxindex 8bd37ce4e..b89b7b505 100644--- a/packages/app/src/components/RenderedDiffView.dom.test.tsx+++ b/packages/app/src/components/RenderedDiffView.dom.test.tsx@@ -158,19 +158,28 @@ describe('RenderedDiffView', () => {expect(callout.textContent).toContain('Mind the gap.');});- test('a Mirror renders as a static reference to its source, not a live embed', async () => {- const pane = await mountDiff(- 'Intro.',- 'Intro.\n\n<Mirror src="specs/shared-intro" anchor="overview" />',- );-- const reference = await waitFor(() => {- const el = pane.querySelector('.ok-diff-ins-block [data-diff-jsx-reference]');- if (!el) throw new Error('reference not rendered');- return el;- });- expect(reference.textContent).toContain('specs/shared-intro#overview');- });+ test.each([+ ['name', '<Mirror src="specs/shared-intro" name="overview" />', 'specs/shared-intro#overview'],+ [+ 'the older anchor spelling',+ '<Mirror src="specs/shared-intro" anchor="overview" />',+ 'specs/shared-intro#overview',+ ],+ ['a numeric name', '<Mirror src="specs/shared-intro" name={7} />', 'specs/shared-intro#7'],+ ['a numeric src', '<Mirror src={42} name="overview" />', '42#overview'],+ ])(+ 'a Mirror written with %s renders as a static reference to its source, not a live embed',+ async (_spelling, mirror, target) => {+ const pane = await mountDiff('Intro.', `Intro.\n\n${mirror}`);++ const reference = await waitFor(() => {+ const el = pane.querySelector('.ok-diff-ins-block [data-diff-jsx-reference]');+ if (!el) throw new Error('reference not rendered');+ return el;+ });+ expect(reference.textContent).toContain(target);+ },+ );test('an unregistered component renders its source', async () => {const pane = await mountDiff('Intro.', 'Intro.\n\n<Widget size="2" />');diff --git a/packages/app/src/editor/anchor-target.dom.test.ts b/packages/app/src/editor/anchor-target.dom.test.tsindex 26a890660..6358d932b 100644--- a/packages/app/src/editor/anchor-target.dom.test.ts+++ b/packages/app/src/editor/anchor-target.dom.test.ts@@ -1,5 +1,9 @@+import { cleanup, render } from '@testing-library/react';+import { createElement, Fragment } from 'react';import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest';+import { anchorFromHash, hashFromMirrorSource } from '@/lib/doc-hash';import { findAnchorTarget } from './anchor-target';+import { MirrorSource } from './components/MirrorSource';function mount(html: string): HTMLElement {const root = document.createElement('div');@@ -19,6 +23,7 @@ afterAll(() => {});afterEach(() => {+ cleanup();document.body.replaceChildren();});@@ -28,9 +33,41 @@ describe('findAnchorTarget', () => {expect(findAnchorTarget(root, 'data-model-v2')?.textContent).toBe('Data model: v2');});- test('finds a mirror source by its source id', () => {- const root = mount('<div data-mirror-source-id="block-1">Mirrored</div>');- expect(findAnchorTarget(root, 'block-1')?.textContent).toBe('Mirrored');+ test('finds a rendered Mirror Source block by its name', () => {+ const root = mount('');+ render(createElement(MirrorSource, { name: 'block-1' }, 'Mirrored'), { container: root });+ expect(findAnchorTarget(root, 'block-1')?.textContent).toContain('Mirrored');+ });++ test('a Mirror link lands on its source block even where a heading has the same id', () => {+ const root = mount('');+ render(+ createElement(+ Fragment,+ null,+ createElement('h2', { id: 'plans' }, 'Plans'),+ createElement(MirrorSource, { name: 'plans' }, 'First source'),+ createElement(MirrorSource, { name: 'plans-1' }, 'Second source'),+ createElement('h2', { id: 'plans-1' }, 'Plans'),+ ),+ { container: root },+ );+ const mirrorLinkAnchor = (name: string) =>+ anchorFromHash(hashFromMirrorSource('pricing', name)) ?? '';++ expect(findAnchorTarget(root, mirrorLinkAnchor('plans'))?.textContent).toContain(+ 'First source',+ );+ expect(findAnchorTarget(root, mirrorLinkAnchor('plans-1'))?.textContent).toContain(+ 'Second source',+ );+ expect(findAnchorTarget(root, 'plans')?.tagName).toBe('H2');+ expect(findAnchorTarget(root, 'plans-1')?.tagName).toBe('H2');+ });++ test('a heading anchor that happens to start with `source:` still finds the heading', () => {+ const root = mount('<h2 id="source-notes">Source: notes</h2>');+ expect(findAnchorTarget(root, 'source: notes')?.textContent).toBe('Source: notes');});test('finds a Korean heading from an anchor written as decomposed jamo', () => {diff --git a/packages/app/src/editor/anchor-target.ts b/packages/app/src/editor/anchor-target.tsindex 3cd4bfbb4..96713537c 100644--- a/packages/app/src/editor/anchor-target.ts+++ b/packages/app/src/editor/anchor-target.ts@@ -1,13 +1,19 @@import { toWikiLinkSlug } from '@inkeep/open-knowledge-core/utils/slug';+import { mirrorSourceNameFromAnchor } from '@/lib/doc-hash';function findById(root: ParentNode, id: string): HTMLElement | null {return root.querySelector<HTMLElement>(`#${CSS.escape(id)}`);}+function findMirrorSource(root: ParentNode, name: string): HTMLElement | null {+ return root.querySelector<HTMLElement>(`[data-mirror-source-name="${CSS.escape(name)}"]`);+}+export function findAnchorTarget(root: ParentNode, anchor: string): HTMLElement | null {- const exact =- findById(root, anchor) ??- root.querySelector<HTMLElement>(`[data-mirror-source-id="${CSS.escape(anchor)}"]`);+ const sourceName = mirrorSourceNameFromAnchor(anchor);+ const linkedSource = sourceName === null ? null : findMirrorSource(root, sourceName);+ if (linkedSource) return linkedSource;+ const exact = findById(root, anchor) ?? findMirrorSource(root, anchor);if (exact) return exact;const slug = toWikiLinkSlug(anchor);return slug && slug !== anchor ? findById(root, slug) : null;diff --git a/packages/app/src/editor/components/DocumentAutocomplete.tsx b/packages/app/src/editor/components/DocumentAutocomplete.tsxnew file mode 100644index 000000000..a93e5d564--- /dev/null+++ b/packages/app/src/editor/components/DocumentAutocomplete.tsx@@ -0,0 +1,29 @@+import { useLingui } from '@lingui/react/macro';+import type { ReactNode } from 'react';+import { useOptionalPageList } from '@/components/PageListContext';+import { filterPages, type PageItem } from '../extensions/wiki-link-suggestion.ts';+import { type Suggestion, type SuggestionFieldProps, SuggestionInput } from './SuggestionInput.tsx';++export function DocumentAutocomplete({ value, ...fieldProps }: SuggestionFieldProps): ReactNode {+ const { t } = useLingui();+ const pageList = useOptionalPageList();+ const pages: PageItem[] = [...(pageList?.pages ?? [])].map((docName) => ({+ kind: 'page',+ docName,+ title: pageList?.pageTitles.get(docName) ?? docName.split('/').pop() ?? docName,+ }));+ const suggestions: readonly Suggestion[] = filterPages(pages, value.trim()).map((page) => ({+ value: page.docName,+ label: page.title,+ detail: page.title !== page.docName ? page.docName : undefined,+ }));++ return (+ <SuggestionInput+ {...fieldProps}+ value={value}+ suggestions={suggestions}+ listLabel={t`Document suggestions`}+ />+ );+}diff --git a/packages/app/src/editor/components/Mirror.tsx b/packages/app/src/editor/components/Mirror.tsxindex 2a894c774..9c7712a57 100644--- a/packages/app/src/editor/components/Mirror.tsx+++ b/packages/app/src/editor/components/Mirror.tsx@@ -1,10 +1,11 @@import { Trans } from '@lingui/react/macro';import { Copy, Link2, Link2Off } from 'lucide-react';+import { authoredText } from '../utils/authored-text.ts';import { useMirrorSource } from './use-mirror-source.ts';interface MirrorProps {- src?: string;- anchor?: string;+ src?: unknown;+ name?: unknown;}function StatusFrame(props: { tone: 'placeholder' | 'error'; children: React.ReactNode }) {@@ -27,16 +28,16 @@ function StatusFrame(props: { tone: 'placeholder' | 'error'; children: React.Rea}export function Mirror(props: MirrorProps) {- const src = props.src ?? '';- const anchor = props.anchor ?? '';- const status = useMirrorSource(src, anchor);+ const src = authoredText(props.src);+ const name = authoredText(props.name);+ const status = useMirrorSource(src, name);if (status.kind === 'empty-props') {return (<StatusFrame tone="placeholder"><Trans><span className="font-medium">Mirror — pick a source.</span> Set <code>src</code> +{' '}- <code>anchor</code> via the property panel to point at a <code>{'<MirrorSource>'}</code>{' '}+ <code>name</code> via the property panel to point at a <code>{'<MirrorSource>'}</code>{' '}elsewhere.</Trans></StatusFrame>@@ -44,7 +45,7 @@ export function Mirror(props: MirrorProps) {}if (status.kind === 'loading') {- const mirrorRef = src && anchor ? `${src}#${anchor}` : '';+ const mirrorRef = src && name ? `${src}#${name}` : '';return (<StatusFrame tone="placeholder"><Trans>@@ -76,12 +77,12 @@ export function Mirror(props: MirrorProps) {);}- if (status.kind === 'anchor-not-found') {- const mirrorSourceTag = `<MirrorSource id="${anchor}">`;+ if (status.kind === 'name-not-found') {+ const mirrorSourceTag = `<MirrorSource name="${name}">`;return (<StatusFrame tone="error"><Trans>- <span className="font-medium">Mirror anchor not found.</span> No{' '}+ <span className="font-medium">Mirror name not found.</span> No{' '}<code>{mirrorSourceTag}</code> exists in <code>{src}</code>.</Trans></StatusFrame>@@ -92,7 +93,7 @@ export function Mirror(props: MirrorProps) {<divclassName='ok-mirror-resolved relative -mx-3 prose-no-margin rounded-md border border-dashed border-transparent px-3 py-2 transition-colors [.jsx-component-wrapper:hover_&]:border-border/40 [.jsx-component-wrapper[data-selected="true"]_&]:border-border/40'data-mirror-src={src}- data-mirror-anchor={anchor}+ data-mirror-name={name}><divclassName='ok-mirror-badge pointer-events-none absolute -top-2.5 left-2 flex items-center gap-1 rounded-md bg-background px-1.5 text-xs text-muted-foreground opacity-0 transition-opacity [.jsx-component-wrapper:hover_&]:opacity-100 [.jsx-component-wrapper[data-selected="true"]_&]:opacity-100'diff --git a/packages/app/src/editor/components/MirrorSource.dom.test.tsx b/packages/app/src/editor/components/MirrorSource.dom.test.tsxnew file mode 100644index 000000000..60e78b83c--- /dev/null+++ b/packages/app/src/editor/components/MirrorSource.dom.test.tsx@@ -0,0 +1,15 @@+import { cleanup, render } from '@testing-library/react';+import { afterEach, describe, expect, test } from 'vitest';+import { MirrorSource } from './MirrorSource.tsx';++afterEach(() => {+ cleanup();+});++describe('a Mirror Source block', () => {+ test('written with a name that has no value, is labelled as unnamed', () => {+ const { container } = render(<MirrorSource name={true}>Body</MirrorSource>);+ expect(container.textContent).toContain('(no name)');+ expect(container.querySelector('[data-mirror-source-name="true"]')).toBeNull();+ });+});diff --git a/packages/app/src/editor/components/MirrorSource.tsx b/packages/app/src/editor/components/MirrorSource.tsxindex c01110779..294d9c045 100644--- a/packages/app/src/editor/components/MirrorSource.tsx+++ b/packages/app/src/editor/components/MirrorSource.tsx@@ -1,19 +1,20 @@import { Trans, useLingui } from '@lingui/react/macro';import { CopyPlus } from 'lucide-react';+import { authoredText } from '../utils/authored-text.ts';interface MirrorSourceProps {- id?: string;+ name?: unknown;children?: React.ReactNode;}export function MirrorSource(props: MirrorSourceProps) {const { t } = useLingui();- const id = props.id ?? '';- const label = id || t`(no id)`;+ const name = authoredText(props.name);+ const label = name || t`(no name)`;return (<divclassName='ok-mirror-source relative -mx-3 rounded-md border border-dashed border-transparent px-3 py-1 transition-colors [.jsx-component-wrapper:hover_&]:border-border/50 [.jsx-component-wrapper[data-selected="true"]_&]:border-border/50'- data-mirror-source-id={id}+ data-mirror-source-name={name}><div className='ok-mirror-source-badge pointer-events-none absolute -top-2.5 left-2 flex items-center gap-1 rounded-md bg-background px-1.5 text-xs text-muted-foreground opacity-0 transition-opacity [.jsx-component-wrapper:hover_&]:opacity-100 [.jsx-component-wrapper[data-selected="true"]_&]:opacity-100'><CopyPlus className="size-3" aria-hidden="true" />diff --git a/packages/app/src/editor/components/MirrorSourceAutocomplete.tsx b/packages/app/src/editor/components/MirrorSourceAutocomplete.tsxnew file mode 100644index 000000000..9030462a2--- /dev/null+++ b/packages/app/src/editor/components/MirrorSourceAutocomplete.tsx@@ -0,0 +1,49 @@+import { useLingui } from '@lingui/react/macro';+import type { ReactNode } from 'react';+import { useMirrorSourceNames } from './mirror-source-names.ts';+import { type Suggestion, type SuggestionFieldProps, SuggestionInput } from './SuggestionInput.tsx';++const MAX_SUGGESTIONS = 8;++interface MirrorSourceAutocompleteProps extends SuggestionFieldProps {+ docName: string;+}++export function MirrorSourceAutocomplete({+ docName,+ value,+ ...fieldProps+}: MirrorSourceAutocompleteProps): ReactNode {+ const { t } = useLingui();+ const sourceNames = useMirrorSourceNames(docName);+ const entries = sourceNames.kind === 'ready' ? sourceNames.entries : [];+ const query = value.trim().toLowerCase();+ const suggestions: readonly Suggestion[] = entries+ .filter(+ (entry) =>+ entry.name.toLowerCase().includes(query) || entry.preview.toLowerCase().includes(query),+ )+ .slice(0, MAX_SUGGESTIONS)+ .map((entry) => ({+ value: entry.name,+ label: entry.name,+ detail: entry.preview === '' ? undefined : entry.preview,+ }));++ let emptyMessage: string | undefined;+ if (sourceNames.kind === 'ready' && entries.length === 0) {+ emptyMessage = t`No Mirror Source blocks in ${docName}`;+ } else if (sourceNames.kind === 'ready' && suggestions.length === 0) {+ emptyMessage = t`No Mirror Source block in ${docName} matches the text in this field. Clear it to see them all.`;+ }++ return (+ <SuggestionInput+ {...fieldProps}+ value={value}+ suggestions={suggestions}+ listLabel={t`Mirror source names`}+ emptyMessage={emptyMessage}+ />+ );+}diff --git a/packages/app/src/editor/components/PropPanel.dom.test.tsx b/packages/app/src/editor/components/PropPanel.dom.test.tsxindex fee2c44b3..2c7ed49d6 100644--- a/packages/app/src/editor/components/PropPanel.dom.test.tsx+++ b/packages/app/src/editor/components/PropPanel.dom.test.tsx@@ -127,6 +127,49 @@ test.each(['cover', 'property'] as const)(},);+describe('PropPanel — a string prop written with a non-text value', () => {+ const cases: [string, PropDef, unknown, string][] = [+ [+ 'a valueless media src as an empty field',+ { name: 'src', type: 'string', required: true, accept: ALLOWED_IMAGE_MIME_TYPES },+ true,+ '',+ ],+ [+ 'a numeric media src as its text',+ { name: 'src', type: 'string', required: true, accept: ALLOWED_IMAGE_MIME_TYPES },+ 42,+ '42',+ ],+ [+ 'a numeric CSS length as its text',+ { name: 'width', type: 'string', required: false, cssLengthInput: true },+ 300,+ '300',+ ],+ [+ 'a numeric plain string as its text',+ { name: 'title', type: 'string', required: false },+ 2024,+ '2024',+ ],+ ];++ test.each(cases)('shows %s instead of failing', (_case, prop, value, shown) => {+ stubAssetPaths.clear();+ const { container } = render(+ <PropPanel+ descriptor={makeDescriptor([prop])}+ values={{ [prop.name]: value }}+ onChange={() => {}}+ />,+ );+ expect((container.querySelector(`input#prop-${prop.name}`) as HTMLInputElement).value).toBe(+ shown,+ );+ });+});+describe('PropPanel — Enter on a single-line string input dismisses', () => {test('Enter on a plain string Input (no autocomplete) calls onDismiss', () => {const onDismiss = vi.fn(() => {});diff --git a/packages/app/src/editor/components/PropPanel.mirror.dom.test.tsx b/packages/app/src/editor/components/PropPanel.mirror.dom.test.tsxnew file mode 100644index 000000000..56420b997--- /dev/null+++ b/packages/app/src/editor/components/PropPanel.mirror.dom.test.tsx@@ -0,0 +1,287 @@+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { useState } from 'react';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import type * as Y from 'yjs';++type GlobalShims = typeof globalThis & { ResizeObserver?: unknown };+const g = globalThis as GlobalShims;+if (g.ResizeObserver === undefined) {+ class NoopResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ g.ResizeObserver = NoopResizeObserver;+}++class FakeProvider {+ static instances: FakeProvider[] = [];+ document: Y.Doc;+ name: string;+ private syncedListeners: Array<() => void> = [];++ constructor(opts: { url: string; name: string; document: Y.Doc }) {+ this.document = opts.document;+ this.name = opts.name;+ FakeProvider.instances.push(this);+ }++ on(event: string, cb: () => void) {+ if (event === 'synced') this.syncedListeners.push(cb);+ }++ emitSynced() {+ for (const cb of this.syncedListeners) cb();+ }++ destroy() {}+}++vi.doMock('@hocuspocus/provider', () => ({ HocuspocusProvider: FakeProvider }));+vi.doMock('@/lib/use-collab-url', () => ({+ useCollabUrl: () => ({ collabUrl: 'ws://test/collab' }),+}));++const pageTitles = new Map([+ ['pricing', 'Pricing'],+ ['team/handbook', 'Handbook'],+]);+const stubPageListValue = {+ pages: new Set(pageTitles.keys()),+ pagesBySlug: new Map<string, string>(),+ pagesByBasename: new Map<string, string>(),+ pageTitles,+ pageMeta: new Map<string, unknown>(),+ folderPaths: new Set<string>(),+ assetPaths: new Set<string>(),+ loading: false,+ error: null,+ refetch: () => {},+ addPage: () => {},+};+vi.doMock('@/components/PageListContext', () => ({+ usePageList: () => stubPageListValue,+ useOptionalPageList: () => stubPageListValue,+}));++const { PropPanel } = await import('./PropPanel');+const { getDescriptor } = await import('../registry/index.ts');+const { disposeLiveDocPool } = await import('./live-doc-pool.ts');++const PRICING_SOURCE = [+ '# Pricing',+ '',+ '<MirrorSource name="plans">',+ '',+ 'Starter is free. Team is $8 per seat.',+ '',+ '</MirrorSource>',+ '',+ '<MirrorSource id="faq">',+ '',+ 'Can I switch plans?',+ '',+ '</MirrorSource>',+].join('\n');++function MirrorPanel({+ initial,+ onChange,+}: {+ initial: Record<string, unknown>;+ onChange: (propName: string, value: unknown) => void;+}) {+ const [values, setValues] = useState(initial);+ return (+ <PropPanel+ descriptor={getDescriptor('Mirror')}+ values={values}+ onChange={(propName, value) => {+ onChange(propName, value);+ setValues((current) => ({ ...current, [propName]: value }));+ }}+ />+ );+}++function optionTexts(): string[] {+ return screen.queryAllByTestId('suggestion-option').map((option) => option.textContent ?? '');+}++function serveDoc(docName: string, markdown: string) {+ const provider = FakeProvider.instances.find((candidate) => candidate.name === docName);+ if (!provider) throw new Error(`no live provider opened for ${docName}`);+ act(() => {+ const source = provider.document.getText('source');+ provider.document.transact(() => source.insert(0, markdown));+ provider.emitSynced();+ });+}++beforeEach(() => {+ FakeProvider.instances = [];+});++afterEach(() => {+ cleanup();+ disposeLiveDocPool();+});++describe('the Mirror property panel', () => {+ test('suggests documents for Src and picks the bare document name', () => {+ const onChange = vi.fn();+ render(<MirrorPanel initial={{}} onChange={onChange} />);++ fireEvent.click(document.getElementById('prop-src') as HTMLInputElement);+ expect(optionTexts()).toEqual(['Pricingpricing', 'Handbookteam/handbook']);++ fireEvent.change(document.getElementById('prop-src') as HTMLInputElement, {+ target: { value: 'hand' },+ });+ expect(optionTexts()).toEqual(['Handbookteam/handbook']);+ onChange.mockClear();+ fireEvent.mouseDown(screen.getByTestId('suggestion-option'));+ expect(onChange).toHaveBeenCalledWith('src', 'team/handbook');+ });++ test('suggests the Mirror Source names in the chosen document', () => {+ const onChange = vi.fn();+ render(<MirrorPanel initial={{ src: 'pricing' }} onChange={onChange} />);+ serveDoc('pricing', PRICING_SOURCE);++ fireEvent.click(document.getElementById('prop-name') as HTMLInputElement);+ expect(optionTexts()).toEqual([+ 'plansStarter is free. Team is $8 per seat.',+ 'faqCan I switch plans?',+ ]);++ const faq = screen.getAllByTestId('suggestion-option')[1];+ fireEvent.mouseDown(faq as HTMLElement);+ expect(onChange).toHaveBeenCalledWith('name', 'faq');+ });++ test('narrows the name suggestions to what is typed, by name or by content', () => {+ render(<MirrorPanel initial={{ src: 'pricing' }} onChange={() => {}} />);+ serveDoc('pricing', PRICING_SOURCE);+ const nameField = document.getElementById('prop-name') as HTMLInputElement;++ fireEvent.change(nameField, { target: { value: 'fa' } });+ expect(optionTexts()).toEqual(['faqCan I switch plans?']);++ fireEvent.change(nameField, { target: { value: 'seat' } });+ expect(optionTexts()).toEqual(['plansStarter is free. Team is $8 per seat.']);+ });++ test.each([+ ['a numeric Src as its text', { src: 42, name: 'plans' }, 'prop-src', '42'],+ ['a valueless Name as an empty field', { src: 'pricing', name: true }, 'prop-name', ''],+ ])('shows %s instead of failing', (_case, initial, fieldId, shown) => {+ render(<MirrorPanel initial={initial} onChange={() => {}} />);+ expect((document.getElementById(fieldId) as HTMLInputElement).value).toBe(shown);+ });++ test('lets an IME confirm its text without picking a suggestion', () => {+ const onChange = vi.fn();+ render(<MirrorPanel initial={{}} onChange={onChange} />);+ const srcField = document.getElementById('prop-src') as HTMLInputElement;+ fireEvent.change(srcField, { target: { value: 'pri' } });+ onChange.mockClear();++ fireEvent.keyDown(srcField, { key: 'Enter', isComposing: true });+ fireEvent.keyDown(srcField, { key: 'Enter', keyCode: 229 });+ expect(onChange).not.toHaveBeenCalled();++ fireEvent.keyDown(srcField, { key: 'Enter' });+ expect(onChange).toHaveBeenCalledWith('src', 'pricing');+ });++ test('says so once the chosen document turns out to have no Mirror Sources', () => {+ render(<MirrorPanel initial={{ src: 'pricing' }} onChange={() => {}} />);+ const nameField = document.getElementById('prop-name') as HTMLInputElement;+ const announcement = within(nameField.parentElement as HTMLElement).getByRole('status');+ fireEvent.click(nameField);+ expect(announcement.textContent).toBe('');+ expect(screen.queryByText(/No Mirror Source blocks/)).toBeNull();++ serveDoc('pricing', '# Pricing\n\nStarter is free.\n');+ expect(announcement.textContent).toBe('No Mirror Source blocks in pricing');+ expect(screen.getByText('No Mirror Source blocks in pricing', { selector: 'p' })).toBeTruthy();+ expect(screen.queryByRole('listbox')).toBeNull();+ expect(nameField.getAttribute('aria-expanded')).toBe('false');+ });++ test.each([+ ['with Mirror Sources', PRICING_SOURCE],+ ['without Mirror Sources', '# Pricing\n\nStarter is free.\n'],+ ])(+ 'stays closed for a Src document %s once focus has moved from Name to Src',+ (_case, markdown) => {+ render(<MirrorPanel initial={{}} onChange={() => {}} />);+ const nameField = document.getElementById('prop-name') as HTMLInputElement;+ const srcField = document.getElementById('prop-src') as HTMLInputElement;+ act(() => nameField.focus());+ fireEvent.click(nameField);+ act(() => srcField.focus());+ fireEvent.change(srcField, { target: { value: 'pricing' } });+ serveDoc('pricing', markdown);++ expect(nameField.getAttribute('aria-expanded')).toBe('false');+ expect(within(nameField.parentElement as HTMLElement).getByRole('status').textContent).toBe(+ '',+ );+ },+ );++ test('reads a numeric Src as the document its text names', () => {+ stubPageListValue.pages.add('42');+ try {+ render(<MirrorPanel initial={{ src: 42 }} onChange={() => {}} />);+ fireEvent.click(document.getElementById('prop-name') as HTMLInputElement);+ serveDoc('42', '<MirrorSource name="answer">\n\nForty-two.\n\n</MirrorSource>');+ expect(optionTexts()).toEqual(['answerForty-two.']);+ } finally {+ stubPageListValue.pages.delete('42');+ }+ });++ test('keeps focus in Name when a press lands on the popup outside an option', async () => {+ const user = userEvent.setup();+ render(<MirrorPanel initial={{ src: 'pricing' }} onChange={() => {}} />);+ const nameField = document.getElementById('prop-name') as HTMLInputElement;+ await user.click(nameField);+ serveDoc('pricing', '# Pricing\n\nStarter is free.\n');++ await user.pointer({+ keys: '[MouseLeft]',+ target: screen.getByText('No Mirror Source blocks in pricing', { selector: 'p' }),+ });+ expect(document.activeElement).toBe(nameField);+ expect(screen.getByText('No Mirror Source blocks in pricing', { selector: 'p' })).toBeTruthy();+ });++ test('says once when the stored name matches none of the document’s Mirror Sources', () => {+ render(<MirrorPanel initial={{ src: 'pricing', name: 'pricnig' }} onChange={() => {}} />);+ serveDoc('pricing', PRICING_SOURCE);+ const nameField = document.getElementById('prop-name') as HTMLInputElement;+ const announcement = within(nameField.parentElement as HTMLElement).getByRole('status');+ fireEvent.click(nameField);++ const message =+ 'No Mirror Source block in pricing matches the text in this field. Clear it to see them all.';+ expect(announcement.textContent).toBe(message);+ expect(screen.getByText(message, { selector: 'p' })).toBeTruthy();+ expect(screen.queryByRole('listbox')).toBeNull();++ fireEvent.change(nameField, { target: { value: 'pricnigx' } });+ expect(announcement.textContent).toBe(message);+ });++ test('opens no live document for a Src that names no document', () => {+ render(<MirrorPanel initial={{ src: 'pric' }} onChange={() => {}} />);++ fireEvent.click(document.getElementById('prop-name') as HTMLInputElement);+ expect(FakeProvider.instances).toEqual([]);+ expect(optionTexts()).toEqual([]);+ });+});diff --git a/packages/app/src/editor/components/PropPanel.tsx b/packages/app/src/editor/components/PropPanel.tsxindex 10f376315..e75da4dfd 100644--- a/packages/app/src/editor/components/PropPanel.tsx+++ b/packages/app/src/editor/components/PropPanel.tsx@@ -19,11 +19,14 @@ import {import { Spinner } from '@/components/ui/spinner';import { Switch } from '@/components/ui/switch';import { ColorPickerInput } from '@/editor/components/ColorPickerInput.tsx';+import { DocumentAutocomplete } from '@/editor/components/DocumentAutocomplete.tsx';import { IconPickerInput } from '@/editor/components/IconPickerInput.tsx';+import { MirrorSourceAutocomplete } from '@/editor/components/MirrorSourceAutocomplete.tsx';import { SrcAutocomplete } from '@/editor/components/SrcAutocomplete.tsx';import { UploadFailedError, UploadRejectedError } from '@/editor/image-upload/upload-failure.ts';import { uploadFile } from '@/editor/image-upload/upload-file.ts';import type { JsxComponentDescriptor } from '@/editor/registry/types.ts';+import { authoredText } from '@/editor/utils/authored-text.ts';import { getAutoFocusedPropName, humanizePropName } from '@/editor/utils/editor-strings.ts';import {cssLengthValidationMessage,@@ -118,6 +121,7 @@ export function PropPanel({ descriptor, values, onChange, onDismiss }: PropPanelkey={propDef.name}propDef={propDef}value={values[propDef.name]}+ values={values}onChange={(v) => onChange(propDef.name, v)}onDismiss={onDismiss}isAutoFocused={propDef.name === autoFocusedPropName}@@ -153,6 +157,7 @@ export function PropPanel({ descriptor, values, onChange, onDismiss }: PropPanelkey={propDef.name}propDef={propDef}value={values[propDef.name]}+ values={values}onChange={(v) => onChange(propDef.name, v)}onDismiss={onDismiss}isAutoFocused={propDef.name === autoFocusedPropName}@@ -173,12 +178,14 @@ function assertUnreachable(x: never): never {function PropControl({propDef,value,+ values,onChange,onDismiss,isAutoFocused,}: {propDef: PropDef;value: unknown;+ values: Record<string, unknown>;onChange: (value: unknown) => void;onDismiss?: () => void;isAutoFocused: boolean;@@ -199,6 +206,7 @@ function PropControl({const accept = propDef.accept;const showUpload = accept !== undefined && accept.length > 0;const treatEmptyAsUndefined = !propDef.required && propDef.defaultValue === undefined;+ const stringValue = authoredText(value);if (propDef.language) {const labelId = `${stringId}-label`;@@ -210,7 +218,7 @@ function PropControl({<CodeMirrorPropInputid={stringId}ariaLabelledBy={labelId}- value={(value as string) ?? ''}+ value={stringValue}language={propDef.language}onChange={(next) => {if (next === '' && treatEmptyAsUndefined) {@@ -226,7 +234,6 @@ function PropControl({}if (propDef.iconPicker) {- const currentIconValue = (value as string) ?? '';return (<div className="flex flex-col gap-1"><label htmlFor={stringId} className="text-xs text-muted-foreground">@@ -234,7 +241,7 @@ function PropControl({</label><IconPickerInputid={stringId}- value={currentIconValue}+ value={stringValue}onChange={(next) => {if (next === '' && treatEmptyAsUndefined) {onChange(undefined);@@ -249,7 +256,6 @@ function PropControl({}if (propDef.colorPicker) {- const currentColorValue = (value as string) ?? '';return (<div className="flex flex-col gap-1"><label htmlFor={stringId} className="text-xs text-muted-foreground">@@ -257,7 +263,7 @@ function PropControl({</label><ColorPickerInputid={stringId}- value={currentColorValue}+ value={stringValue}onChange={(next) => {if (next === '' && treatEmptyAsUndefined) {onChange(undefined);@@ -271,9 +277,51 @@ function PropControl({);}+ const emitString = (next: string) => {+ onChange(next === '' && treatEmptyAsUndefined ? undefined : next);+ };++ if (propDef.documentPicker) {+ return (+ <div className="flex flex-col gap-1">+ <label htmlFor={stringId} className="text-xs text-muted-foreground">+ {humanizePropName(propDef.name)}+ </label>+ <DocumentAutocomplete+ id={stringId}+ value={stringValue}+ onChange={emitString}+ onSubmit={onDismiss}+ autoFocus={isAutoFocused}+ dataPropAutofocus={isAutoFocused ? '' : undefined}+ className="h-7 text-sm"+ />+ </div>+ );+ }++ if (propDef.mirrorSourcePicker !== undefined) {+ return (+ <div className="flex flex-col gap-1">+ <label htmlFor={stringId} className="text-xs text-muted-foreground">+ {humanizePropName(propDef.name)}+ </label>+ <MirrorSourceAutocomplete+ id={stringId}+ docName={authoredText(values[propDef.mirrorSourcePicker])}+ value={stringValue}+ onChange={emitString}+ onSubmit={onDismiss}+ autoFocus={isAutoFocused}+ dataPropAutofocus={isAutoFocused ? '' : undefined}+ className="h-7 text-sm"+ />+ </div>+ );+ }+if (propDef.cssLengthInput) {- const currentCssLength = (value as string) ?? '';- const cssValidation = validateCssLength(currentCssLength);+ const cssValidation = validateCssLength(stringValue);const cssError = cssValidation.valid ? null : cssLengthValidationMessage(cssValidation);return (<div className="flex flex-col gap-1">@@ -283,7 +331,7 @@ function PropControl({<Inputid={stringId}type="text"- value={currentCssLength}+ value={stringValue}placeholder="100px, 50%, 26rem, auto"onChange={(e) => {const raw = e.target.value;@@ -316,14 +364,13 @@ function PropControl({}const mediaKind = accept !== undefined ? mediaKindForAccept(accept) : undefined;- const currentStringValue = (value as string) ?? '';const mediaValidation =- mediaKind !== undefined ? validateMediaUrl(currentStringValue, mediaKind) : null;+ mediaKind !== undefined ? validateMediaUrl(stringValue, mediaKind) : null;const mediaErrorMessage =mediaValidation !== null &&!mediaValidation.valid &&mediaKind !== undefined &&- currentStringValue.trim().length > 0+ stringValue.trim().length > 0? mediaUrlValidationMessage(mediaValidation, mediaKind): null;const mediaPlaceholder = mediaKind !== undefined ? mediaUrlPlaceholder(mediaKind) : undefined;@@ -337,7 +384,7 @@ function PropControl({{accept !== undefined ? (<SrcAutocompleteid={stringId}- value={currentStringValue}+ value={stringValue}onChange={(raw) => {if (raw === '' && treatEmptyAsUndefined) {onChange(undefined);@@ -358,7 +405,7 @@ function PropControl({<Inputid={stringId}type="text"- value={currentStringValue}+ value={stringValue}placeholder={mediaPlaceholder}onChange={(e) => {const raw = e.target.value;diff --git a/packages/app/src/editor/components/SrcAutocomplete.dom.test.tsx b/packages/app/src/editor/components/SrcAutocomplete.dom.test.tsxindex f541d91bc..84ad1ca5b 100644--- a/packages/app/src/editor/components/SrcAutocomplete.dom.test.tsx+++ b/packages/app/src/editor/components/SrcAutocomplete.dom.test.tsx@@ -54,7 +54,7 @@ afterEach(() => {});function getOptions(): HTMLButtonElement[] {- return screen.queryAllByTestId('src-autocomplete-option') as HTMLButtonElement[];+ return screen.queryAllByTestId('suggestion-option') as HTMLButtonElement[];}describe('SrcAutocomplete — open behavior', () => {@@ -267,7 +267,7 @@ describe('SrcAutocomplete — popover width tracks the trigger', () => {const input = document.getElementById('prop-src') as HTMLInputElement;fireEvent.click(input);- const option = screen.getAllByTestId('src-autocomplete-option')[0];+ const option = screen.getAllByTestId('suggestion-option')[0];expect(option).toBeDefined();const content = option?.closest('[data-slot="popover-content"]') as HTMLElement | null;expect(content).not.toBeNull();diff --git a/packages/app/src/editor/components/SrcAutocomplete.tsx b/packages/app/src/editor/components/SrcAutocomplete.tsxindex 1ba053cfa..946de6e9a 100644--- a/packages/app/src/editor/components/SrcAutocomplete.tsx+++ b/packages/app/src/editor/components/SrcAutocomplete.tsx@@ -6,29 +6,16 @@ import {} from '@inkeep/open-knowledge-core/search/workspace-search';import { useLingui } from '@lingui/react/macro';import type { ReactNode } from 'react';-import { useEffect, useId, useRef, useState } from 'react';import { useOptionalPageList } from '@/components/PageListContext';-import { Input } from '@/components/ui/input';-import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';-import { cn } from '@/lib/utils';import { filterAssetsByAccept } from '../utils/filter-assets-by-accept';+import { type Suggestion, type SuggestionFieldProps, SuggestionInput } from './SuggestionInput.tsx';const MAX_ITEMS = 8;const EMPTY_ASSET_SET: ReadonlySet<string> = new Set();-interface SrcAutocompleteProps {- value: string;- onChange: (value: string) => void;+interface SrcAutocompleteProps extends SuggestionFieldProps {accept: readonly string[];- id: string;- placeholder?: string;- autoFocus?: boolean;- ariaInvalid?: boolean;- ariaDescribedBy?: string;- dataPropAutofocus?: string;- className?: string;- onSubmit?: () => void;}interface AssetItem {@@ -87,19 +74,7 @@ function selectSuggestions(corpus: AutocompleteCorpus, rawQuery: string): readon.filter((item): item is AssetItem => Boolean(item));}-export function SrcAutocomplete({- value,- onChange,- accept,- id,- placeholder,- autoFocus,- ariaInvalid,- ariaDescribedBy,- dataPropAutofocus,- className,- onSubmit,-}: SrcAutocompleteProps): ReactNode {+export function SrcAutocomplete({ value, accept, ...inputProps }: SrcAutocompleteProps): ReactNode {const { t } = useLingui();const pageList = useOptionalPageList();const assetPaths: ReadonlySet<string> = pageList?.assetPaths ?? EMPTY_ASSET_SET;@@ -107,155 +82,18 @@ export function SrcAutocomplete({const matchingPaths = filterAssetsByAccept(assetPaths, accept);const assetItems: readonly AssetItem[] = matchingPaths.map(makeAssetItem);const corpus = getCachedCorpus(assetItems);- const suggestions = selectSuggestions(corpus, value);-- const [open, setOpen] = useState(false);- const [highlight, setHighlight] = useState(0);-- useEffect(() => {- if (highlight >= suggestions.length) setHighlight(0);- }, [highlight, suggestions.length]);-- const listboxId = useId();- const inputRef = useRef<HTMLInputElement | null>(null);-- const wantOpen = open && suggestions.length > 0;-- const selectSuggestion = (item: AssetItem) => {- onChange(`/${item.path}`);- setOpen(false);- setHighlight(0);- inputRef.current?.focus();- };+ const suggestions: readonly Suggestion[] = selectSuggestions(corpus, value).map((item) => ({+ value: `/${item.path}`,+ label: item.basename,+ detail: item.basename !== item.path ? item.path : undefined,+ }));return (- <Popover open={wantOpen} onOpenChange={(next) => setOpen(next)}>- <PopoverAnchor asChild>- <Input- ref={inputRef}- id={id}- type="text"- value={value}- placeholder={placeholder}- autoFocus={autoFocus}- data-prop-autofocus={dataPropAutofocus}- aria-invalid={ariaInvalid}- aria-describedby={ariaDescribedBy}- role="combobox"- aria-autocomplete="list"- aria-expanded={wantOpen}- aria-controls={wantOpen ? listboxId : undefined}- aria-activedescendant={- wantOpen && suggestions[highlight] ? `${listboxId}-opt-${highlight}` : undefined- }- className={className}- onChange={(e) => {- onChange(e.target.value);- setOpen(true);- setHighlight(0);- }}- onClick={() => {- setOpen(true);- }}- onKeyDown={(e) => {- if (e.key === 'ArrowDown') {- if (suggestions.length === 0) return;- e.preventDefault();- setOpen(true);- setHighlight((h) => (h + 1) % suggestions.length);- return;- }- if (e.key === 'ArrowUp') {- if (suggestions.length === 0) return;- e.preventDefault();- setOpen(true);- setHighlight((h) => (h - 1 + suggestions.length) % suggestions.length);- return;- }- if (e.key === 'Enter') {- if (wantOpen) {- const item = suggestions[highlight];- if (item) {- e.preventDefault();- selectSuggestion(item);- return;- }- }- if (onSubmit) {- e.preventDefault();- onSubmit();- }- return;- }- if (e.key === 'Escape') {- if (!wantOpen) return;- e.preventDefault();- e.stopPropagation();- setOpen(false);- return;- }- if (e.key === 'Tab') {- setOpen(false);- }- }}- />- </PopoverAnchor>- <PopoverContent- align="start"- sideOffset={4}- className="z-70 w-(--radix-popover-trigger-width) p-1"- data-ok-declines-keyboard=""- onOpenAutoFocus={(e) => {- e.preventDefault();- }}- onCloseAutoFocus={(e) => {- e.preventDefault();- }}- onInteractOutside={(e) => {- const target = e.target;- if (target instanceof Node && inputRef.current?.contains(target)) {- e.preventDefault();- }- }}- >- <div- id={listboxId}- role="listbox"- aria-label={t`Asset suggestions`}- className="flex flex-col gap-px"- >- {suggestions.map((item, idx) => {- const optionId = `${listboxId}-opt-${idx}`;- const isHighlighted = idx === highlight;- return (- <button- key={item.path}- id={optionId}- type="button"- role="option"- aria-selected={isHighlighted}- data-testid="src-autocomplete-option"- data-highlighted={isHighlighted ? '' : undefined}- className={cn(- 'flex w-full flex-col items-start gap-0.5 rounded-sm px-2 py-1 text-left text-xs',- 'transition-colors',- isHighlighted ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50',- )}- onMouseEnter={() => setHighlight(idx)}- onMouseDown={(e) => {- e.preventDefault();- selectSuggestion(item);- }}- >- <span className="font-medium">{item.basename}</span>- {item.basename !== item.path && (- <span className="text-muted-foreground/70">{item.path}</span>- )}- </button>- );- })}- </div>- </PopoverContent>- </Popover>+ <SuggestionInput+ {...inputProps}+ value={value}+ suggestions={suggestions}+ listLabel={t`Asset suggestions`}+ />);}diff --git a/packages/app/src/editor/components/SuggestionInput.tsx b/packages/app/src/editor/components/SuggestionInput.tsxnew file mode 100644index 000000000..f1a7fd956--- /dev/null+++ b/packages/app/src/editor/components/SuggestionInput.tsx@@ -0,0 +1,226 @@+import type { ReactNode } from 'react';+import { useEffect, useId, useRef, useState } from 'react';+import { Input } from '@/components/ui/input';+import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';+import { isImeCompositionKey } from '@/lib/ime-composition';+import { cn } from '@/lib/utils';++export interface Suggestion {+ readonly value: string;+ readonly label: string;+ readonly detail?: string;+}++interface SuggestionInputProps {+ id: string;+ value: string;+ onChange: (value: string) => void;+ suggestions: readonly Suggestion[];+ listLabel: string;+ emptyMessage?: string;+ placeholder?: string;+ autoFocus?: boolean;+ ariaInvalid?: boolean;+ ariaDescribedBy?: string;+ dataPropAutofocus?: string;+ className?: string;+ onSubmit?: () => void;+}++export type SuggestionFieldProps = Omit<+ SuggestionInputProps,+ 'suggestions' | 'listLabel' | 'emptyMessage'+>;++export function SuggestionInput({+ id,+ value,+ onChange,+ suggestions,+ listLabel,+ emptyMessage,+ placeholder,+ autoFocus,+ ariaInvalid,+ ariaDescribedBy,+ dataPropAutofocus,+ className,+ onSubmit,+}: SuggestionInputProps): ReactNode {+ const [open, setOpen] = useState(false);+ const [highlight, setHighlight] = useState(0);++ useEffect(() => {+ if (highlight >= suggestions.length) setHighlight(0);+ }, [highlight, suggestions.length]);++ const listboxId = useId();+ const inputRef = useRef<HTMLInputElement | null>(null);++ const listOpen = open && suggestions.length > 0;+ const showEmptyMessage = open && suggestions.length === 0 && emptyMessage !== undefined;++ const selectSuggestion = (item: Suggestion) => {+ onChange(item.value);+ setOpen(false);+ setHighlight(0);+ inputRef.current?.focus();+ };++ return (+ <>+ <Popover open={listOpen || showEmptyMessage} onOpenChange={(next) => setOpen(next)}>+ <PopoverAnchor asChild>+ <Input+ ref={inputRef}+ id={id}+ type="text"+ value={value}+ placeholder={placeholder}+ autoFocus={autoFocus}+ data-prop-autofocus={dataPropAutofocus}+ aria-invalid={ariaInvalid}+ aria-describedby={ariaDescribedBy}+ role="combobox"+ aria-autocomplete="list"+ aria-expanded={listOpen}+ aria-controls={listOpen ? listboxId : undefined}+ aria-activedescendant={+ listOpen && suggestions[highlight] ? `${listboxId}-opt-${highlight}` : undefined+ }+ className={className}+ onChange={(e) => {+ onChange(e.target.value);+ setOpen(true);+ setHighlight(0);+ }}+ onClick={() => {+ setOpen(true);+ }}+ onBlur={() => {+ setOpen(false);+ }}+ onKeyDown={(e) => {+ if (isImeCompositionKey(e)) return;+ if (e.key === 'ArrowDown') {+ if (suggestions.length === 0) return;+ e.preventDefault();+ setOpen(true);+ setHighlight((h) => (h + 1) % suggestions.length);+ return;+ }+ if (e.key === 'ArrowUp') {+ if (suggestions.length === 0) return;+ e.preventDefault();+ setOpen(true);+ setHighlight((h) => (h - 1 + suggestions.length) % suggestions.length);+ return;+ }+ if (e.key === 'Enter') {+ if (listOpen) {+ const item = suggestions[highlight];+ if (item) {+ e.preventDefault();+ selectSuggestion(item);+ return;+ }+ }+ if (onSubmit) {+ e.preventDefault();+ onSubmit();+ }+ return;+ }+ if (e.key === 'Escape') {+ if (!listOpen && !showEmptyMessage) return;+ e.preventDefault();+ e.stopPropagation();+ setOpen(false);+ return;+ }+ if (e.key === 'Tab') {+ setOpen(false);+ }+ }}+ />+ </PopoverAnchor>+ <PopoverContent+ align="start"+ sideOffset={4}+ className="z-70 w-(--radix-popover-trigger-width) p-1"+ data-ok-declines-keyboard=""+ onMouseDown={(e) => {+ e.preventDefault();+ }}+ onOpenAutoFocus={(e) => {+ e.preventDefault();+ }}+ onCloseAutoFocus={(e) => {+ e.preventDefault();+ }}+ onInteractOutside={(e) => {+ const target = e.target;+ if (target instanceof Node && inputRef.current?.contains(target)) {+ e.preventDefault();+ }+ }}+ >+ {suggestions.length === 0 ? (+ emptyMessage !== undefined && (+ <p className="px-2 py-1 text-xs text-muted-foreground wrap-break-word">+ {emptyMessage}+ </p>+ )+ ) : (+ <div+ id={listboxId}+ role="listbox"+ aria-label={listLabel}+ className="flex flex-col gap-px"+ >+ {suggestions.map((item, idx) => {+ const optionId = `${listboxId}-opt-${idx}`;+ const isHighlighted = idx === highlight;+ return (+ <button+ key={item.value}+ id={optionId}+ type="button"+ role="option"+ aria-selected={isHighlighted}+ data-testid="suggestion-option"+ data-highlighted={isHighlighted ? '' : undefined}+ className={cn(+ 'flex w-full flex-col items-start gap-0.5 rounded-sm px-2 py-1 text-left text-xs',+ 'transition-colors',+ isHighlighted ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50',+ )}+ onMouseEnter={() => setHighlight(idx)}+ onMouseDown={(e) => {+ e.preventDefault();+ selectSuggestion(item);+ }}+ >+ <span className="font-medium">{item.label}</span>+ {item.detail !== undefined && (+ <span+ className={+ isHighlighted ? 'text-accent-foreground/70' : 'text-muted-foreground'+ }+ >+ {item.detail}+ </span>+ )}+ </button>+ );+ })}+ </div>+ )}+ </PopoverContent>+ </Popover>+ <span role="status" aria-live="polite" className="sr-only">+ {showEmptyMessage ? emptyMessage : ''}+ </span>+ </>+ );+}diff --git a/packages/app/src/editor/components/mirror-source-names.test.ts b/packages/app/src/editor/components/mirror-source-names.test.tsnew file mode 100644index 000000000..1c37e76ae--- /dev/null+++ b/packages/app/src/editor/components/mirror-source-names.test.ts@@ -0,0 +1,67 @@+import { describe, expect, test } from 'vitest';+import { getSharedMarkdownManager } from '../utils/md-singleton.ts';+import { listMirrorSources } from './mirror-source-names.ts';+import type { MdastNodeLike } from './use-mirror-source.ts';++function treeOf(markdown: string): MdastNodeLike {+ return getSharedMarkdownManager().parseToMdast(markdown) as MdastNodeLike;+}++describe('listMirrorSources', () => {+ test('lists each source in document order with a plain-text preview', () => {+ const tree = treeOf(+ [+ '# Pricing',+ '',+ '<MirrorSource name="plans">',+ '',+ 'Starter is **free**. Team is $8 per seat.',+ '',+ '</MirrorSource>',+ '',+ '<MirrorSource name="faq">',+ '',+ '- Can I switch plans?',+ '',+ '</MirrorSource>',+ ].join('\n'),+ );+ expect(listMirrorSources(tree)).toEqual([+ { name: 'plans', preview: 'Starter is free. Team is $8 per seat.' },+ { name: 'faq', preview: 'Can I switch plans?' },+ ]);+ });++ test('includes a source written with the older `id` spelling', () => {+ const tree = treeOf('<MirrorSource id="plans">\n\nStarter is free.\n\n</MirrorSource>\n');+ expect(listMirrorSources(tree)).toEqual([{ name: 'plans', preview: 'Starter is free.' }]);+ });++ test('lists a repeated name once, as the first source carrying it', () => {+ const tree = treeOf(+ '<MirrorSource name="plans">\n\nFirst.\n\n</MirrorSource>\n\n<MirrorSource name="plans">\n\nSecond.\n\n</MirrorSource>\n',+ );+ expect(listMirrorSources(tree)).toEqual([{ name: 'plans', preview: 'First.' }]);+ });++ test('reads a name written as an expression the way the editor does', () => {+ const tree = treeOf(+ '<MirrorSource name={42}>\n\nForty-two.\n\n</MirrorSource>\n\n<MirrorSource name={"plans"}>\n\nStarter is free.\n\n</MirrorSource>\n',+ );+ expect(listMirrorSources(tree).map((entry) => entry.name)).toEqual(['42', 'plans']);+ });++ test('skips a source without a name', () => {+ const tree = treeOf('<MirrorSource>\n\nNameless.\n\n</MirrorSource>\n');+ expect(listMirrorSources(tree)).toEqual([]);+ });++ test('shortens a long preview', () => {+ const long = 'word '.repeat(40).trim();+ const tree = treeOf(`<MirrorSource name="long">\n\n${long}\n\n</MirrorSource>\n`);+ const [entry] = listMirrorSources(tree);+ expect(entry?.preview.endsWith('…')).toBe(true);+ expect(entry?.preview.length).toBeLessThanOrEqual(81);+ expect(long.startsWith(entry?.preview.slice(0, -1) ?? '')).toBe(true);+ });+});diff --git a/packages/app/src/editor/components/mirror-source-names.ts b/packages/app/src/editor/components/mirror-source-names.tsnew file mode 100644index 000000000..8300f8c23--- /dev/null+++ b/packages/app/src/editor/components/mirror-source-names.ts@@ -0,0 +1,91 @@+import { graphemePrefix } from '@inkeep/open-knowledge-core/utils/grapheme-clip';+import { useOptionalPageList } from '@/components/PageListContext';+import { getSharedMarkdownManager } from '../utils/md-singleton.ts';+import { useLiveDocText } from './live-doc-pool.ts';+import {+ type MdastNodeLike,+ type MdxJsxFlowElementLike,+ mirrorSourceNameOf,+} from './use-mirror-source.ts';++export interface MirrorSourceEntry {+ readonly name: string;+ readonly preview: string;+}++export type MirrorSourceNames =+ | { readonly kind: 'unavailable' }+ | { readonly kind: 'ready'; readonly entries: readonly MirrorSourceEntry[] };++const PREVIEW_LENGTH = 80;+const UNAVAILABLE_SOURCE_NAMES: MirrorSourceNames = { kind: 'unavailable' };+const EMPTY_SOURCE_NAMES: MirrorSourceNames = { kind: 'ready', entries: [] };+const PHRASING_PARENTS: ReadonlySet<string> = new Set([+ 'paragraph',+ 'heading',+ 'emphasis',+ 'strong',+ 'delete',+ 'link',+ 'linkReference',+ 'tableCell',+ 'mdxJsxTextElement',+]);++function plainTextOf(node: MdastNodeLike): string {+ if (typeof node.value === 'string') return node.value;+ const separator = PHRASING_PARENTS.has(node.type) ? '' : ' ';+ return (node.children ?? []).map(plainTextOf).join(separator);+}++function previewOf(element: MdxJsxFlowElementLike): string {+ const text = (element.children ?? []).map(plainTextOf).join(' ').replace(/\s+/g, ' ').trim();+ if (text.length <= PREVIEW_LENGTH) return text;+ return `${graphemePrefix(text, PREVIEW_LENGTH).trimEnd()}…`;+}++export function listMirrorSources(tree: MdastNodeLike): readonly MirrorSourceEntry[] {+ const entries: MirrorSourceEntry[] = [];+ const seen = new Set<string>();+ const visit = (node: MdastNodeLike) => {+ if (node.type === 'mdxJsxFlowElement' && node.name === 'MirrorSource') {+ const element = node as MdxJsxFlowElementLike;+ const name = mirrorSourceNameOf(element);+ if (name && !seen.has(name)) {+ seen.add(name);+ entries.push({ name, preview: previewOf(element) });+ }+ }+ for (const child of node.children ?? []) visit(child);+ };+ visit(tree);+ return entries;+}++function mirrorSourcesIn(docName: string, markdown: string): MirrorSourceNames {+ let tree: MdastNodeLike;+ try {+ tree = getSharedMarkdownManager().parseToMdast(markdown) as MdastNodeLike;+ } catch (err) {+ console.warn('[Mirror] parseToMdast failed while listing source names', { docName, err });+ return UNAVAILABLE_SOURCE_NAMES;+ }+ return { kind: 'ready', entries: listMirrorSources(tree) };+}++export function useMirrorSourceNames(docName: string): MirrorSourceNames {+ const pageList = useOptionalPageList();+ const isKnownDoc = docName !== '' && pageList?.pages.has(docName) === true;+ const status = useLiveDocText(isKnownDoc ? docName : null);+ if (!isKnownDoc) return UNAVAILABLE_SOURCE_NAMES;+ switch (status.kind) {+ case 'empty':+ return EMPTY_SOURCE_NAMES;+ case 'ready':+ return mirrorSourcesIn(docName, status.text);+ case 'loading':+ case 'unreachable':+ case 'at-capacity':+ return UNAVAILABLE_SOURCE_NAMES;+ }+}diff --git a/packages/app/src/editor/components/use-mirror-source.dom.test.tsx b/packages/app/src/editor/components/use-mirror-source.dom.test.tsxindex 922eaa2e8..408601202 100644--- a/packages/app/src/editor/components/use-mirror-source.dom.test.tsx+++ b/packages/app/src/editor/components/use-mirror-source.dom.test.tsx@@ -1,4 +1,4 @@-import { act, cleanup, renderHook } from '@testing-library/react';+import { act, cleanup, render, renderHook, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import type * as Y from 'yjs';@@ -36,6 +36,7 @@ const { acquireLiveDocProvider, disposeLiveDocPool, LIVE_DOC_POOL_MAX } = await'./live-doc-pool.ts');const { useMirrorSource } = await import('./use-mirror-source.ts');+const { Mirror } = await import('./Mirror.tsx');const SOURCE_MD = ['<MirrorSource id="intro">',@@ -68,6 +69,18 @@ describe('useMirrorSource', () => {disposeLiveDocPool();});+ test('a Mirror whose name was written as a number finds the source with that name', async () => {+ const { container } = render(<Mirror src="numbers" name={42} />);+ act(() => {+ const provider = lastProvider();+ setSource(provider, '<MirrorSource name="42">\n\nForty-two.\n\n</MirrorSource>');+ provider.emitSynced();+ });+ await waitFor(() => {+ expect(container.textContent).toContain('Forty-two.');+ });+ });+test('a pool capacity refusal maps to at-capacity, never source-removed', () => {const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});try {diff --git a/packages/app/src/editor/components/use-mirror-source.test.ts b/packages/app/src/editor/components/use-mirror-source.test.tsindex 11e6b3801..b46023090 100644--- a/packages/app/src/editor/components/use-mirror-source.test.ts+++ b/packages/app/src/editor/components/use-mirror-source.test.ts@@ -1,11 +1,15 @@import { describe, expect, test } from 'vitest';import { findMirrorSource, renderMirrorSubtree } from './use-mirror-source.ts';-function mirrorSourceNode(id: string, children: Array<Record<string, unknown>> = []) {+function mirrorSourceNode(+ name: string,+ children: Array<Record<string, unknown>> = [],+ attributeName: 'name' | 'id' = 'name',+) {return {type: 'mdxJsxFlowElement' as const,name: 'MirrorSource',- attributes: [{ type: 'mdxJsxAttribute', name: 'id', value: id }],+ attributes: [{ type: 'mdxJsxAttribute', name: attributeName, value: name }],children,};}@@ -24,16 +28,35 @@ describe('findMirrorSource', () => {).toBeNull();});- test('returns null when name matches but id does not', () => {+ test('returns null when no MirrorSource carries the requested name', () => {expect(findMirrorSource(root([mirrorSourceNode('a')]), 'b')).toBeNull();});- test('matches by exact id', () => {+ test('matches by exact name', () => {const node = mirrorSourceNode('banner', [{ type: 'paragraph' }]);expect(findMirrorSource(root([node]), 'banner')).toBe(node);});- test('first match wins when an id appears twice in the same doc', () => {+ test('reads an older `id` attribute as the name', () => {+ const node = mirrorSourceNode('banner', [{ type: 'paragraph' }], 'id');+ expect(findMirrorSource(root([node]), 'banner')).toBe(node);+ });++ test('`name` wins over an older `id` on the same source', () => {+ const node = {+ type: 'mdxJsxFlowElement' as const,+ name: 'MirrorSource',+ attributes: [+ { type: 'mdxJsxAttribute', name: 'id', value: 'old' },+ { type: 'mdxJsxAttribute', name: 'name', value: 'new' },+ ],+ children: [],+ };+ expect(findMirrorSource(root([node]), 'new')).toBe(node);+ expect(findMirrorSource(root([node]), 'old')).toBeNull();+ });++ test('first match wins when a name appears twice in the same doc', () => {const first = mirrorSourceNode('dup', [{ type: 'text', value: 'first' }]);const second = mirrorSourceNode('dup', [{ type: 'text', value: 'second' }]);expect(findMirrorSource(root([first, second]), 'dup')).toBe(first);@@ -52,7 +75,7 @@ describe('findMirrorSource', () => {expect(findMirrorSource(tree, 'nested')).toBe(target);});- test('ignores non-MirrorSource JSX flow elements named MirrorSource at a deeper level only by id check', () => {+ test('a MirrorSource without a name matches no requested name', () => {const stray = {type: 'mdxJsxFlowElement',name: 'MirrorSource',@@ -62,7 +85,7 @@ describe('findMirrorSource', () => {expect(findMirrorSource(root([stray]), 'x')).toBeNull();});- test('id with empty-string value still matches an empty anchor query (precise equality)', () => {+ test('an empty name still matches an empty requested name (precise equality)', () => {const node = mirrorSourceNode('', [{ type: 'paragraph' }]);expect(findMirrorSource(root([node]), '')).toBe(node);});diff --git a/packages/app/src/editor/components/use-mirror-source.ts b/packages/app/src/editor/components/use-mirror-source.tsindex 092f65d7c..72a99bede 100644--- a/packages/app/src/editor/components/use-mirror-source.ts+++ b/packages/app/src/editor/components/use-mirror-source.ts@@ -1,6 +1,14 @@import { mdastToHtml } from '@inkeep/open-knowledge-core/markdown/mdast-to-html';+import {+ builtInComponents,+ type JsxAttributeValueSource,+ jsxAttributeValue,+ resolveLegacyProps,+} from '@inkeep/open-knowledge-core/registry';+import type { PropDef } from '@inkeep/open-knowledge-core/registry/types';import { useEffect, useRef, useState } from 'react';import { useCollabUrl } from '@/lib/use-collab-url';+import { authoredText } from '../utils/authored-text.ts';import { getSharedMarkdownManager } from '../utils/md-singleton.ts';import {type AcquireLiveDocResult,@@ -13,15 +21,15 @@ import {interface MdxJsxAttrLike {type: string;name?: string;- value?: unknown;+ value?: JsxAttributeValueSource;}-interface MdxJsxFlowElementLike {+export interface MdxJsxFlowElementLike {type: 'mdxJsxFlowElement';name?: string | null;attributes?: MdxJsxAttrLike[];children?: MdastNodeLike[];}-interface MdastNodeLike {+export interface MdastNodeLike {type: string;children?: MdastNodeLike[];[key: string]: unknown;@@ -35,33 +43,41 @@ type MirrorSourceStatus =| { kind: 'loading' }| { kind: 'ready'; html: string }| { kind: 'source-removed' }- | { kind: 'anchor-not-found' }+ | { kind: 'name-not-found' }| { kind: 'empty-props' }| { kind: 'at-capacity' };-export function findMirrorSource(- tree: MdastNodeLike,- anchor: string,-): MdxJsxFlowElementLike | null {+function builtInPropsOf(componentName: string): readonly PropDef[] {+ const meta = builtInComponents.find((component) => component.name === componentName);+ if (!meta) throw new Error(`No built-in component descriptor named '${componentName}'`);+ return meta.props;+}++const MIRROR_SOURCE_PROPS = builtInPropsOf('MirrorSource');++export function mirrorSourceNameFromProps(values: Readonly<Record<string, unknown>>): string {+ return authoredText(resolveLegacyProps(MIRROR_SOURCE_PROPS, values).name);+}++export function mirrorSourceNameOf(node: MdxJsxFlowElementLike): string {+ const values: Record<string, unknown> = {};+ for (const attr of node.attributes ?? []) {+ if (attr.type === 'mdxJsxAttribute' && attr.name !== undefined) {+ values[attr.name] = jsxAttributeValue(attr.value);+ }+ }+ return mirrorSourceNameFromProps(values);+}++export function findMirrorSource(tree: MdastNodeLike, name: string): MdxJsxFlowElementLike | null {if (tree.type === 'mdxJsxFlowElement') {const node = tree as MdxJsxFlowElementLike;- if (node.name === 'MirrorSource') {- for (const attr of node.attributes ?? []) {- if (- attr.type === 'mdxJsxAttribute' &&- attr.name === 'id' &&- typeof attr.value === 'string' &&- attr.value === anchor- ) {- return node;- }- }- }+ if (node.name === 'MirrorSource' && mirrorSourceNameOf(node) === name) return node;}const children = tree.children;if (Array.isArray(children)) {for (const child of children) {- const found = findMirrorSource(child, anchor);+ const found = findMirrorSource(child, name);if (found) return found;}}@@ -90,11 +106,11 @@ function refusedMirrorStatus(}}-export function useMirrorSource(src: string, anchor: string): MirrorSourceStatus {+export function useMirrorSource(src: string, name: string): MirrorSourceStatus {const { collabUrl } = useCollabUrl();const acquireLiveDoc = useLiveDocAcquirer();const [status, setStatus] = useState<MirrorSourceStatus>({ kind: 'loading' });- const anchorRef = useRef(anchor);+ const nameRef = useRef(name);const recomputeRef = useRef<(() => void) | null>(null);useEffect(() => {@@ -119,8 +135,8 @@ export function useMirrorSource(src: string, anchor: string): MirrorSourceStatusconst { entry } = acquired;const recomputeNow = () => {- const currentAnchor = anchorRef.current;- if (!currentAnchor) {+ const currentName = nameRef.current;+ if (!currentName) {setStatus({ kind: 'empty-props' });return;}@@ -134,21 +150,21 @@ export function useMirrorSource(src: string, anchor: string): MirrorSourceStatus// biome-ignore lint/suspicious/noExplicitAny: structural type match across the core boundarytree = getSharedMarkdownManager().parseToMdast(markdown) as any;} catch (err) {- console.warn('[Mirror] parseToMdast failed', { src, anchor: currentAnchor, err });+ console.warn('[Mirror] parseToMdast failed', { src, name: currentName, err });setStatus({ kind: 'source-removed' });return;}- const node = findMirrorSource(tree, currentAnchor);+ const node = findMirrorSource(tree, currentName);if (!node) {- setStatus({ kind: 'anchor-not-found' });+ setStatus({ kind: 'name-not-found' });return;}let html: string;try {html = renderMirrorSubtree(node);} catch (err) {- console.warn('[Mirror] renderMirrorSubtree failed', { src, anchor: currentAnchor, err });- setStatus({ kind: 'anchor-not-found' });+ console.warn('[Mirror] renderMirrorSubtree failed', { src, name: currentName, err });+ setStatus({ kind: 'name-not-found' });return;}setStatus((prev) =>@@ -195,9 +211,9 @@ export function useMirrorSource(src: string, anchor: string): MirrorSourceStatus}, [collabUrl, src, acquireLiveDoc]);useEffect(() => {- anchorRef.current = anchor;+ nameRef.current = name;recomputeRef.current?.();- }, [anchor]);+ }, [name]);return status;}diff --git a/packages/app/src/editor/extensions/JsxComponentView.mirror.dom.test.tsx b/packages/app/src/editor/extensions/JsxComponentView.mirror.dom.test.tsxnew file mode 100644index 000000000..d04b2dd7d--- /dev/null+++ b/packages/app/src/editor/extensions/JsxComponentView.mirror.dom.test.tsx@@ -0,0 +1,97 @@+import { cleanup, render, screen } from '@testing-library/react';+import type { NodeViewProps } from '@tiptap/react';+import { afterEach, describe, expect, test, vi } from 'vitest';++vi.doMock('@/lib/use-collab-url', () => ({+ useCollabUrl: () => ({ collabUrl: null }),+}));++afterEach(() => {+ cleanup();+});++function mirrorNodeProps(authored: Record<string, string | number>): NodeViewProps {+ return {+ editor: {+ isEditable: true,+ isDestroyed: false,+ commands: { setNodeSelection: () => {} },+ state: { doc: { resolve: () => ({ depth: 0 }) }, selection: { from: 0, to: 0 } },+ on: () => {},+ off: () => {},+ },+ node: {+ type: { name: 'jsxComponent' },+ attrs: {+ componentName: 'Mirror',+ kind: 'element',+ attributes: Object.entries(authored).map(([name, value]) => ({+ type: 'mdxJsxAttribute',+ name,+ value:+ typeof value === 'number'+ ? { type: 'mdxJsxAttributeValueExpression', value: String(value) }+ : value,+ })),+ props: { ...authored },+ sourceRaw: '',+ sourceDirty: false,+ },+ content: { size: 0 },+ nodeSize: 1,+ },+ getPos: () => 5,+ selected: false,+ updateAttributes: () => {},+ deleteNode: () => {},+ decorations: [],+ extension: { options: {} },+ view: {},+ } as unknown as NodeViewProps;+}++async function mountMirror(authored: Record<string, string | number>) {+ const { JsxComponentView } = await import('./JsxComponentView.tsx');+ return render(<JsxComponentView {...mirrorNodeProps(authored)} />);+}++describe('a Mirror block in the editor', () => {+ test.each([+ ['name', { src: 'pricing', name: 'plans' }],+ ['the older anchor spelling', { src: 'pricing', anchor: 'plans' }],+ ])('written with %s, points at its source block', async (_spelling, authored) => {+ const { container } = await mountMirror(authored);++ expect(+ screen.getByRole('link', { name: 'Open source doc: pricing' }).getAttribute('href'),+ ).toBe('#/pricing#source:plans');+ expect(container.textContent).toContain('pricing#plans');+ const wrapper = container.querySelector('[data-jsx-component]');+ expect(wrapper).not.toBeNull();+ expect(wrapper?.hasAttribute('data-needs-config')).toBe(false);+ });++ test('written with a numeric name, links to the source with that name as text', async () => {+ await mountMirror({ src: 'pricing', name: 7 });++ expect(+ screen.getByRole('link', { name: 'Open source doc: pricing' }).getAttribute('href'),+ ).toBe('#/pricing#source:7');+ });++ test('written with a numeric src, links to the document with that src as text', async () => {+ await mountMirror({ src: 42, name: 'plans' });++ expect(screen.getByRole('link', { name: 'Open source doc: 42' }).getAttribute('href')).toBe(+ '#/42#source:plans',+ );+ });++ test('without a name, asks to be set up', async () => {+ const { container } = await mountMirror({ src: 'pricing' });++ expect(container.querySelector('[data-jsx-component]')?.getAttribute('data-needs-config')).toBe(+ 'true',+ );+ });+});diff --git a/packages/app/src/editor/extensions/JsxComponentView.test.ts b/packages/app/src/editor/extensions/JsxComponentView.test.tsindex 54bf0d3cc..8f6d4bf9c 100644--- a/packages/app/src/editor/extensions/JsxComponentView.test.ts+++ b/packages/app/src/editor/extensions/JsxComponentView.test.ts@@ -1,24 +1,28 @@import { readFileSync } from 'node:fs';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';+import { builtInComponents } from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';-import { getElementJsxAttrs, stableHash } from './JsxComponentView.tsx';+import type { JsxComponentDescriptor } from '../registry/types.ts';+import { attrsWithChangedProp, getElementJsxAttrs, stableHash } from './JsxComponentView.tsx';import { extractPrimitiveProps } from './jsx-render-contract.ts';-function reactNodes(...names: string[]): ReadonlySet<string> {- return new Set(names);+function descriptorWith(+ ...reactNodeNames: string[]+): Pick<JsxComponentDescriptor, 'props' | 'reactNodePropNames'> {+ return { props: [], reactNodePropNames: new Set(reactNodeNames) };}describe('extractPrimitiveProps', () => {test('passes through declared non-reactnode props', () => {const attrs = { props: { type: 'warning', title: 'Heads up' } };- const result = extractPrimitiveProps(attrs, reactNodes());+ const result = extractPrimitiveProps(attrs, descriptorWith());expect(result).toEqual({ type: 'warning', title: 'Heads up' });});test('excludes reactnode-typed prop names (content holes are NOT render-time props)', () => {const attrs = { props: { title: 'Hi', children: 'shouldnt be here' } };- const result = extractPrimitiveProps(attrs, reactNodes('children'));+ const result = extractPrimitiveProps(attrs, descriptorWith('children'));expect(result).toEqual({ title: 'Hi' });expect(result).not.toHaveProperty('children');});@@ -32,7 +36,7 @@ describe('extractPrimitiveProps', () => {],},};- const result = extractPrimitiveProps(attrs, reactNodes('children'));+ const result = extractPrimitiveProps(attrs, descriptorWith('children'));expect(result).toHaveProperty('items');expect(Array.isArray(result.items)).toBe(true);@@ -48,7 +52,7 @@ describe('extractPrimitiveProps', () => {external: true,},};- const result = extractPrimitiveProps(attrs, reactNodes());+ const result = extractPrimitiveProps(attrs, descriptorWith());expect(result).toEqual({title: 'Custom Card',description: 'With extras',@@ -58,18 +62,18 @@ describe('extractPrimitiveProps', () => {});test('handles empty props', () => {- const result = extractPrimitiveProps({ props: {} }, reactNodes());+ const result = extractPrimitiveProps({ props: {} }, descriptorWith());expect(result).toEqual({});});test('handles missing props attr', () => {- const result = extractPrimitiveProps({}, reactNodes());+ const result = extractPrimitiveProps({}, descriptorWith());expect(result).toEqual({});});test('XSS: strips javascript: URL from href before it reaches live React', () => {const attrs = { props: { href: 'javascript:alert(1)', title: 'bad' } };- const result = extractPrimitiveProps(attrs, reactNodes());+ const result = extractPrimitiveProps(attrs, descriptorWith());expect(result.href).toBe('#');expect(result.title).toBe('bad');});@@ -81,7 +85,7 @@ describe('extractPrimitiveProps', () => {title: 'safe',},};- const result = extractPrimitiveProps(attrs, reactNodes());+ const result = extractPrimitiveProps(attrs, descriptorWith());expect(result).not.toHaveProperty('dangerouslySetInnerHTML');expect(result.title).toBe('safe');});@@ -90,7 +94,7 @@ describe('extractPrimitiveProps', () => {const attrs = {props: { onClick: 'alert(1)', onError: 'alert(2)', title: 'safe' },};- const result = extractPrimitiveProps(attrs, reactNodes());+ const result = extractPrimitiveProps(attrs, descriptorWith());expect(result).not.toHaveProperty('onClick');expect(result).not.toHaveProperty('onError');expect(result.title).toBe('safe');@@ -105,17 +109,38 @@ describe('extractPrimitiveProps', () => {],},};- const result = extractPrimitiveProps(attrs, reactNodes());+ const result = extractPrimitiveProps(attrs, descriptorWith());const items = result.items as Array<{ title: string; url: string }>;expect(items[0].url).toBe('#');expect(items[1].url).toBe('https://ok.example.com');});+ test('reads a prop written under its older spelling as the current name', () => {+ const mirror = builtInComponents.find((component) => component.name === 'Mirror');+ if (!mirror) throw new Error('no Mirror descriptor');+ const result = extractPrimitiveProps(+ { props: { src: 'pricing', anchor: 'plans' } },+ { props: mirror.props, reactNodePropNames: new Set() },+ );+ expect(result).toEqual({ src: 'pricing', name: 'plans' });+ });++ test('XSS: sanitizes a URL prop written under an older spelling', () => {+ const result = extractPrimitiveProps(+ { props: { destination: 'javascript:alert(1)' } },+ {+ props: [{ name: 'href', type: 'string', required: false, legacyNames: ['destination'] }],+ reactNodePropNames: new Set(),+ },+ );+ expect(result).toEqual({ href: '#' });+ });+test('XSS: drops style with url(javascript:…)', () => {const attrs = {props: { style: 'background: url(javascript:alert(1)); color: red' },};- const result = extractPrimitiveProps(attrs, reactNodes());+ const result = extractPrimitiveProps(attrs, descriptorWith());expect(result.style).toBe('');});});@@ -146,6 +171,99 @@ describe('getElementJsxAttrs', () => {});});+function componentMeta(componentName: string) {+ const meta = builtInComponents.find((component) => component.name === componentName);+ if (!meta) throw new Error(`no built-in component named ${componentName}`);+ return meta;+}++function authoredElement(componentName: string, authored: Record<string, string>) {+ const attrs = getElementJsxAttrs({+ kind: 'element',+ componentName,+ attributes: Object.entries(authored).map(([name, value]) => ({+ type: 'mdxJsxAttribute',+ name,+ value,+ })),+ props: { ...authored },+ sourceRaw: '',+ sourceDirty: false,+ });+ if (!attrs) throw new Error('expected element attrs');+ return attrs;+}++function serializedAttributes(componentName: string, attrs: Record<string, unknown>) {+ const out = componentMeta(componentName).serialize(+ { attrs } as never,+ {+ all: () => [],+ } as never,+ ) as unknown as { attributes: Array<{ name: string; value: unknown }> };+ return out.attributes.map((attribute) => [attribute.name, attribute.value]);+}++describe('attrsWithChangedProp', () => {+ test('editing the name of a Mirror written with `anchor` writes `name` and drops `anchor`', () => {+ const next = attrsWithChangedProp(+ authoredElement('Mirror', { src: 'pricing', anchor: 'plans' }),+ componentMeta('Mirror'),+ 'name',+ 'faq',+ );+ expect(next.sourceDirty).toBe(true);+ expect(serializedAttributes('Mirror', next)).toEqual([+ ['src', 'pricing'],+ ['name', 'faq'],+ ]);+ });++ test('editing the name of a MirrorSource written with `id` writes `name` and drops `id`', () => {+ const next = attrsWithChangedProp(+ authoredElement('MirrorSource', { id: 'plans' }),+ componentMeta('MirrorSource'),+ 'name',+ 'plans',+ );+ expect(serializedAttributes('MirrorSource', next)).toEqual([['name', 'plans']]);+ });++ test('editing another prop keeps an older spelling as authored', () => {+ const next = attrsWithChangedProp(+ authoredElement('Mirror', { src: 'pricing', anchor: 'plans' }),+ componentMeta('Mirror'),+ 'src',+ 'billing',+ );+ expect(serializedAttributes('Mirror', next)).toEqual([+ ['src', 'billing'],+ ['anchor', 'plans'],+ ]);+ });++ test('clearing a prop removes its attribute', () => {+ const next = attrsWithChangedProp(+ authoredElement('Callout', { type: 'note', title: 'Heads up' }),+ componentMeta('Callout'),+ 'title',+ undefined,+ );+ expect(serializedAttributes('Callout', next)).toEqual([['type', 'note']]);+ });++ test('changing an image src forgets the URL the image was authored with', () => {+ const authored = authoredElement('CommonMarkImage', { src: 'chart.png', alt: 'Chart' });+ const next = attrsWithChangedProp(+ { ...authored, props: { ...authored.props, sourceUrl: 'chart.png' } },+ componentMeta('CommonMarkImage'),+ 'src',+ 'other.png',+ );+ expect(next.props).toEqual({ src: 'other.png', alt: 'Chart' });+ });+});+describe('stableHash', () => {test('key-order independence — primary load-bearing invariant', () => {expect(stableHash({ a: 1, b: 2 })).toBe(stableHash({ b: 2, a: 1 }));diff --git a/packages/app/src/editor/extensions/JsxComponentView.tsx b/packages/app/src/editor/extensions/JsxComponentView.tsxindex 4d437cf98..97382291c 100644--- a/packages/app/src/editor/extensions/JsxComponentView.tsx+++ b/packages/app/src/editor/extensions/JsxComponentView.tsx@@ -37,7 +37,7 @@ import { toast } from 'sonner';import { emitStartComment } from '@/comments/store';import { Button } from '@/components/ui/button';import { useIsEmbedded } from '@/hooks/use-is-embedded';-import { hashFromDocName } from '@/lib/doc-hash';+import { hashFromDocName, hashFromMirrorSource } from '@/lib/doc-hash';import {Popover,PopoverAnchor,@@ -59,12 +59,14 @@ import {resolveDescriptorPlaceholder,shouldRenderPlaceholder,} from '../registry/resolve-descriptor-placeholder.ts';+import type { JsxComponentDescriptor } from '../registry/types.ts';import { moveCaretAfterNode, placeGapCursorAfterNode } from '../selection/place-caret.ts';import {consumeAutoOpen,createChildNode,focusInsertedComponent,} from '../slash-command/component-items.tsx';+import { authoredText } from '../utils/authored-text.ts';import { formatContainerAriaLabel } from '../utils/editor-strings.ts';import { getEditorView } from '../utils/get-editor-view.ts';import { reconstructSource } from '../utils/reconstruct-source.ts';@@ -133,6 +135,42 @@ export function getElementJsxAttrs(attrs: Record<string, unknown>): ElementJsxAtreturn attrs.kind === 'element' ? (attrs as ElementJsxAttrs) : null;}+function isMdxJsxAttributeNamed(attribute: unknown, names: ReadonlySet<string>): boolean {+ if (attribute == null || typeof attribute !== 'object') return false;+ const { type, name } = attribute as Record<string, unknown>;+ return type === 'mdxJsxAttribute' && typeof name === 'string' && names.has(name);+}++export function attrsWithChangedProp(+ elementAttrs: ElementJsxAttrs,+ descriptor: Pick<JsxComponentDescriptor, 'props'>,+ propName: string,+ value: unknown,+): ElementJsxAttrs {+ const legacyNames = descriptor.props.find((prop) => prop.name === propName)?.legacyNames ?? [];+ const removedNames = new Set(value === undefined ? [propName, ...legacyNames] : legacyNames);+ const nextProps: Record<string, unknown> = { ...elementAttrs.props };+ for (const removedName of removedNames) delete nextProps[removedName];+ if (value !== undefined) nextProps[propName] = value;+ if (+ propName === 'src' &&+ elementAttrs.componentName === 'CommonMarkImage' &&+ value !== elementAttrs.props.src+ ) {+ delete nextProps.sourceUrl;+ }+ const attributes = Array.isArray(elementAttrs.attributes) ? elementAttrs.attributes : [];+ return {+ ...elementAttrs,+ attributes:+ removedNames.size === 0+ ? attributes+ : attributes.filter((attribute) => !isMdxJsxAttributeNamed(attribute, removedNames)),+ props: nextProps,+ sourceDirty: true,+ };+}+const MAX_AUTO_CONVERT_ATTEMPTS = 3;export function JsxComponentView({ node, editor, extension, getPos, selected }: NodeViewProps) {@@ -185,13 +223,14 @@ export function JsxComponentView({ node, editor, extension, getPos, selected }:);const currentProps = (node.attrs.props as Record<string, unknown>) ?? {};+ const primitiveProps = extractPrimitiveProps(node.attrs, descriptor);const needsConfig =hasEditableProps &&descriptor.props.some((p) => {if (p.type !== 'string') return false;if (!p.required) return false;if ('hidden' in p && p.hidden) return false;- return !Object.hasOwn(currentProps, p.name);+ return !Object.hasOwn(primitiveProps, p.name);});const showPlaceholder = shouldRenderPlaceholder(descriptor, currentProps);@@ -236,7 +275,6 @@ export function JsxComponentView({ node, editor, extension, getPos, selected }:wasSelected.current = selected;}, [selected, hasEditableProps, isSourceBearing, pos]);- const primitiveProps = extractPrimitiveProps(node.attrs, descriptor.reactNodePropNames);const renderProps = resolveJsxRenderProps(descriptor,primitiveProps,@@ -628,18 +666,17 @@ export function JsxComponentView({ node, editor, extension, getPos, selected }:)}{descriptor.name === 'Mirror' &&- typeof primitiveProps.src === 'string' &&- primitiveProps.src.length > 0 &&+ authoredText(primitiveProps.src) !== '' &&(() => {- const mirrorSrc = primitiveProps.src as string;+ const mirrorSrc = authoredText(primitiveProps.src);+ const mirrorName = authoredText(primitiveProps.name);return (<a- href={hashFromDocName(- mirrorSrc,- typeof primitiveProps.anchor === 'string' && primitiveProps.anchor.length > 0- ? primitiveProps.anchor- : null,- )}+ href={+ mirrorName !== ''+ ? hashFromMirrorSource(mirrorSrc, mirrorName)+ : hashFromDocName(mirrorSrc)+ }className="jsx-chrome-btn"aria-label={t`Open source doc: ${mirrorSrc}`}title={t`Open source: ${mirrorSrc}`}@@ -1047,40 +1084,12 @@ export function JsxComponentView({ node, editor, extension, getPos, selected }:const { pos: p, node: curNode } = target;const elementAttrs = getElementJsxAttrs(curNode.attrs);if (!elementAttrs) return;- const currentNodeProps = elementAttrs.props;- const nextProps: Record<string, unknown> = { ...currentNodeProps };- const currentAttributes = Array.isArray(curNode.attrs.attributes)- ? (curNode.attrs.attributes as unknown[])- : [];- let nextAttributes = currentAttributes;- if (value === undefined) {- delete nextProps[propName];- nextAttributes = currentAttributes.filter(- (a) =>- !(- a != null &&- typeof a === 'object' &&- (a as Record<string, unknown>).type === 'mdxJsxAttribute' &&- (a as Record<string, unknown>).name === propName- ),- );- } else {- nextProps[propName] = value;- }- if (- propName === 'src' &&- elementAttrs.componentName === 'CommonMarkImage' &&- value !== currentNodeProps.src- ) {- delete nextProps.sourceUrl;- }editor.view.dispatch(- editor.state.tr.setNodeMarkup(p, null, {- ...elementAttrs,- attributes: nextAttributes,- props: nextProps,- sourceDirty: true,- }),+ editor.state.tr.setNodeMarkup(+ p,+ null,+ attrsWithChangedProp(elementAttrs, descriptor, propName, value),+ ),);markUserTyping();}}diff --git a/packages/app/src/editor/extensions/JsxInlineView.dom.test.tsx b/packages/app/src/editor/extensions/JsxInlineView.dom.test.tsxindex fbfec8ae4..d30926d82 100644--- a/packages/app/src/editor/extensions/JsxInlineView.dom.test.tsx+++ b/packages/app/src/editor/extensions/JsxInlineView.dom.test.tsx@@ -3,9 +3,14 @@ import type { Editor } from '@tiptap/core';import { EditorContent, useEditor } from '@tiptap/react';import { useEffect, useState } from 'react';import { createPortal } from 'react-dom';-import { afterEach, describe, expect, test } from 'vitest';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { getSharedMarkdownManager } from '../utils/md-singleton.ts';import { sharedExtensions } from './shared';+vi.mock('@/lib/use-collab-url', () => ({+ useCollabUrl: () => ({ collabUrl: null }),+}));+function Host({ content, onEditor }: { content: object; onEditor: (e: Editor) => void }) {const editor = useEditor({extensions: sharedExtensions.map((extension) =>@@ -126,6 +131,36 @@ describe('JsxInlineView', () => {});});+ test('an inline Mirror written with the older anchor spelling resolves, and an edit writes name', async () => {+ const { getEditor } = mountEditor(+ docWithInline({+ componentName: 'Mirror',+ sourceRaw: '<Mirror src="pricing" anchor="plans" />',+ attributes: [+ { type: 'mdxJsxAttribute', name: 'src', value: 'pricing' },+ { type: 'mdxJsxAttribute', name: 'anchor', value: 'plans' },+ ],+ props: { src: 'pricing', anchor: 'plans' },+ }),+ );+ await waitFor(() => {+ expect(document.querySelector('[data-jsx-inline-widget]')?.textContent).toContain(+ 'pricing#plans',+ );+ });+ const editor = getEditor();+ editor.commands.setNodeSelection(1 + 'before '.length);++ const nameField = await screen.findByDisplayValue('plans');+ fireEvent.change(nameField, { target: { value: 'faq' } });++ await waitFor(() => {+ const saved = getSharedMarkdownManager().serialize(editor.getJSON());+ expect(saved).toContain('<Mirror src="pricing" name="faq" />');+ expect(saved).not.toContain('anchor=');+ });+ });+test('NodeSelection opens the PropPanel popover and a commit stamps sourceDirty', async () => {const { getEditor } = mountEditor(docWithInline({diff --git a/packages/app/src/editor/extensions/JsxInlineView.tsx b/packages/app/src/editor/extensions/JsxInlineView.tsxindex 0792a6239..93087d96e 100644--- a/packages/app/src/editor/extensions/JsxInlineView.tsx+++ b/packages/app/src/editor/extensions/JsxInlineView.tsx@@ -9,7 +9,7 @@ import { Button } from '../../components/ui/button.tsx';import { Popover, PopoverContent, PopoverTrigger } from '../../components/ui/popover.tsx';import { PropPanel } from '../components/PropPanel.tsx';import { getDescriptor } from '../registry/index.ts';-import { stableHash } from './JsxComponentView.tsx';+import { attrsWithChangedProp, getElementJsxAttrs, stableHash } from './JsxComponentView.tsx';import { extractPrimitiveProps, resolveJsxSourceDocName } from './jsx-render-contract.ts';import { normalizeDocRelativeMediaRenderProps } from './media-render-props.ts';@@ -41,7 +41,7 @@ function RegisteredInlineView({const [popoverOpen, setPopoverOpen] = useState(false);const wasSelected = useRef(false);- const primitiveProps = extractPrimitiveProps(node.attrs, descriptor.reactNodePropNames);+ const primitiveProps = extractPrimitiveProps(node.attrs, descriptor);const bodyText = (node.attrs.props as Record<string, unknown> | undefined)?.children;if (typeof bodyText === 'string' && bodyText !== '') {(primitiveProps as Record<string, unknown>).children = bodyText;@@ -69,8 +69,7 @@ function RegisteredInlineView({};}, [editor, getPos]);- const structuredProps = (node.attrs.props ?? {}) as Record<string, unknown>;- const { children: _body, ...panelValues } = structuredProps;+ const { children: _body, ...panelValues } = primitiveProps;return (<NodeViewWrapper@@ -143,12 +142,13 @@ function RegisteredInlineView({if (typeof p !== 'number') return;const curNode = editor.state.doc.nodeAt(p);if (curNode?.type.name !== 'jsxInline') return;- const nextProps = { ...curNode.attrs.props, [propName]: value };- const tr = editor.state.tr.setNodeMarkup(p, null, {- ...curNode.attrs,- props: nextProps,- sourceDirty: true,- });+ const elementAttrs = getElementJsxAttrs(curNode.attrs);+ if (!elementAttrs) return;+ const tr = editor.state.tr.setNodeMarkup(+ p,+ null,+ attrsWithChangedProp(elementAttrs, descriptor, propName, value),+ );tr.setSelection(NodeSelection.create(tr.doc, p));editor.view.dispatch(tr);}}diff --git a/packages/app/src/editor/extensions/jsx-render-contract.ts b/packages/app/src/editor/extensions/jsx-render-contract.tsindex 726d1028e..4f0c12e3c 100644--- a/packages/app/src/editor/extensions/jsx-render-contract.ts+++ b/packages/app/src/editor/extensions/jsx-render-contract.ts@@ -1,4 +1,5 @@import { incrementJsxRenderFailure } from '@inkeep/open-knowledge-core/metrics/parse-health';+import { resolveLegacyProps } from '@inkeep/open-knowledge-core/registry';import type { Editor } from '@tiptap/core';import type { Node as PmNode } from '@tiptap/pm/model';import type { ErrorInfo } from 'react';@@ -12,12 +13,15 @@ export const JSX_WRAPPER_CLASS = 'jsx-component-wrapper my-2';export function extractPrimitiveProps(attrs: Record<string, unknown>,- reactNodeNames: ReadonlySet<string>,+ descriptor: Pick<JsxComponentDescriptor, 'props' | 'reactNodePropNames'>,): Record<string, unknown> {- const propsObj = (attrs.props ?? {}) as Record<string, unknown>;+ const propsObj = resolveLegacyProps(+ descriptor.props,+ (attrs.props ?? {}) as Record<string, unknown>,+ );const result: Record<string, unknown> = {};for (const [key, value] of Object.entries(propsObj)) {- if (reactNodeNames.has(key)) continue;+ if (descriptor.reactNodePropNames.has(key)) continue;result[key] = value;}return sanitizeComponentProps(result);diff --git a/packages/app/src/editor/slash-command/component-items.tsx b/packages/app/src/editor/slash-command/component-items.tsxindex 686c7fae3..72e51d7df 100644--- a/packages/app/src/editor/slash-command/component-items.tsx+++ b/packages/app/src/editor/slash-command/component-items.tsx@@ -12,6 +12,7 @@ import { resolveIcon } from '../registry/icons.ts';import { getDescriptor, getRegisteredDescriptors } from '../registry/index.ts';import type { JsxComponentDescriptor } from '../registry/types.ts';import type { SlashCommandContext, SlashCommandItem } from './items';+import { nextMirrorSourceName } from './mirror-source-name.ts';import imagePreview from './preview-assets/image-preview.png';import videoPreview from './preview-assets/video-preview.png';@@ -393,6 +394,13 @@ function createInsertCommand(tab2Attrs.props = { ...(tab2Attrs.props as Record<string, unknown>), label: 'Tab 2' };(inserted as Record<string, unknown>).content = [tab1, tab2];}+ if (descriptor.name === 'MirrorSource') {+ const insertedAttrs = inserted.attrs as Record<string, unknown>;+ insertedAttrs.props = {+ ...(insertedAttrs.props as Record<string, unknown>),+ name: nextMirrorSourceName(state.doc, state.selection.from),+ };+ }chain().insertContent(inserted).run();afterCommit(() => {diff --git a/packages/app/src/editor/slash-command/mirror-source-insert.dom.test.tsx b/packages/app/src/editor/slash-command/mirror-source-insert.dom.test.tsxnew file mode 100644index 000000000..df498f03a--- /dev/null+++ b/packages/app/src/editor/slash-command/mirror-source-insert.dom.test.tsx@@ -0,0 +1,80 @@+import { cleanup } from '@testing-library/react';+import { Editor } from '@tiptap/core';+import { afterEach, describe, expect, test } from 'vitest';+import { sharedExtensions } from '../extensions/shared';+import { getSharedMarkdownManager } from '../utils/md-singleton.ts';+import { applySlashCommandItem } from './apply-item';+import { getComponentItems } from './component-items';++function mountEditor(headingText: string | null): { editor: Editor; container: HTMLDivElement } {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const content = [+ ...(headingText === null+ ? []+ : [{ type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: headingText }] }]),+ { type: 'paragraph' },+ ];+ const editor = new Editor({+ element: container,+ extensions: sharedExtensions,+ editable: true,+ content: { type: 'doc', content },+ });+ return { editor, container };+}++async function insertMirrorSourceAtEnd(editor: Editor): Promise<void> {+ const item = getComponentItems().find((candidate) => candidate.name === 'component-MirrorSource');+ if (!item) throw new Error('no Mirror Source slash item');+ editor.commands.insertContentAt(editor.state.doc.content.size, { type: 'paragraph' });+ editor.commands.focus('end');+ const from = editor.state.selection.from;+ editor.commands.insertContent('/mirrorsource');+ applySlashCommandItem({ editor, item, range: { from, to: editor.state.selection.from } });+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+}++function savedMarkdown(editor: Editor): string {+ return getSharedMarkdownManager().serialize(editor.getJSON());+}++afterEach(() => {+ cleanup();+ document.body.replaceChildren();+});++describe('inserting a Mirror Source from the slash menu', () => {+ test('names it after the heading above', async () => {+ const { editor } = mountEditor('Plans');+ try {+ await insertMirrorSourceAtEnd(editor);+ expect(savedMarkdown(editor)).toContain('<MirrorSource name="plans">');+ } finally {+ editor.destroy();+ }+ });++ test('a second one under the same heading gets its own name', async () => {+ const { editor } = mountEditor('Plans');+ try {+ await insertMirrorSourceAtEnd(editor);+ await insertMirrorSourceAtEnd(editor);+ const saved = savedMarkdown(editor);+ expect(saved).toMatch(/^<MirrorSource name="plans">$/m);+ expect(saved).toMatch(/^<MirrorSource name="plans-1">$/m);+ } finally {+ editor.destroy();+ }+ });++ test('without a heading above, it is named `source`', async () => {+ const { editor } = mountEditor(null);+ try {+ await insertMirrorSourceAtEnd(editor);+ expect(savedMarkdown(editor)).toContain('<MirrorSource name="source">');+ } finally {+ editor.destroy();+ }+ });+});diff --git a/packages/app/src/editor/slash-command/mirror-source-name.test.ts b/packages/app/src/editor/slash-command/mirror-source-name.test.tsnew file mode 100644index 000000000..3576091f7--- /dev/null+++ b/packages/app/src/editor/slash-command/mirror-source-name.test.ts@@ -0,0 +1,69 @@+import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';+import { getSchema } from '@tiptap/core';+import type { Node as PmNode } from '@tiptap/pm/model';+import { describe, expect, test } from 'vitest';+import { nextMirrorSourceName } from './mirror-source-name.ts';++const mdManager = new MarkdownManager({ extensions: sharedExtensions });+const schema = getSchema(sharedExtensions);++function docFor(markdown: string): PmNode {+ return schema.nodeFromJSON(mdManager.parse(markdown));+}++function nameAtEnd(markdown: string): string {+ const doc = docFor(markdown);+ return nextMirrorSourceName(doc, doc.content.size);+}++function endOfParagraph(doc: PmNode, text: string): number {+ let end = -1;+ doc.descendants((node, pos) => {+ if (node.type.name === 'paragraph' && node.textContent === text) end = pos + node.nodeSize;+ });+ if (end < 0) throw new Error(`no paragraph reading ${text}`);+ return end;+}++describe('nextMirrorSourceName', () => {+ test('names a new source after the heading above it', () => {+ expect(nameAtEnd('# Pricing\n\n## Plans\n\nWhat each plan includes.\n')).toBe('plans');+ });++ test('only a heading above the insertion point counts', () => {+ const doc = docFor('## Above\n\nFirst.\n\n## Below\n\nSecond.\n');+ expect(nextMirrorSourceName(doc, endOfParagraph(doc, 'First.'))).toBe('above');+ });++ test('falls back to `source` when no heading comes before it', () => {+ expect(nameAtEnd('Just a paragraph.\n')).toBe('source');+ });++ test('numbers a name another source in the doc already uses', () => {+ expect(+ nameAtEnd('## Plans\n\n<MirrorSource name="plans">\n\nStarter is free.\n\n</MirrorSource>\n'),+ ).toBe('plans-1');+ });++ test('counts a source written with the older `id` spelling as taken', () => {+ expect(+ nameAtEnd(+ '## Plans\n\n<MirrorSource id="plans">\n\nStarter is free.\n\n</MirrorSource>\n\n<MirrorSource name="plans-1">\n\nTeam is $8.\n\n</MirrorSource>\n',+ ),+ ).toBe('plans-2');+ });++ test('keeps a name from a long heading short, cutting at a word', () => {+ expect(nameAtEnd('## Compare enterprise licensing and procurement options\n\nText.\n')).toBe(+ 'compare-enterprise-licensing-and',+ );+ });++ test('counts a source whose name is written as a number as taken', () => {+ expect(nameAtEnd('## 7\n\n<MirrorSource name={7}>\n\nSeven.\n\n</MirrorSource>\n')).toBe('7-1');+ });++ test('keeps letters from any script', () => {+ expect(nameAtEnd('## 常见问题\n\nText.\n')).toBe('常见问题');+ });+});diff --git a/packages/app/src/editor/slash-command/mirror-source-name.ts b/packages/app/src/editor/slash-command/mirror-source-name.tsnew file mode 100644index 000000000..ebcaa9cbf--- /dev/null+++ b/packages/app/src/editor/slash-command/mirror-source-name.ts@@ -0,0 +1,42 @@+import { graphemePrefix } from '@inkeep/open-knowledge-core/utils/grapheme-clip';+import { toWikiLinkSlug } from '@inkeep/open-knowledge-core/utils/slug';+import type { Node as PmNode } from '@tiptap/pm/model';+import { mirrorSourceNameFromProps } from '../components/use-mirror-source.ts';++const FALLBACK_NAME = 'source';+const MAX_NAME_LENGTH = 40;++function headingAbove(doc: PmNode, pos: number): string {+ let text = '';+ doc.nodesBetween(0, pos, (node, nodePos) => {+ if (node.type.name === 'heading' && nodePos + node.nodeSize <= pos) text = node.textContent;+ });+ return text;+}++function shortName(slug: string): string {+ if (slug.length <= MAX_NAME_LENGTH) return slug;+ const clipped = graphemePrefix(slug, MAX_NAME_LENGTH);+ const lastBreak = clipped.lastIndexOf('-');+ return lastBreak > 0 ? clipped.slice(0, lastBreak) : clipped;+}++function namesInUse(doc: PmNode): ReadonlySet<string> {+ const names = new Set<string>();+ doc.descendants((node) => {+ if (node.type.name !== 'jsxComponent' || node.attrs.componentName !== 'MirrorSource') return;+ const authored = (node.attrs.props as Record<string, unknown> | null) ?? {};+ const name = mirrorSourceNameFromProps(authored);+ if (name !== '') names.add(name);+ });+ return names;+}++export function nextMirrorSourceName(doc: PmNode, pos: number): string {+ const base = shortName(toWikiLinkSlug(headingAbove(doc, pos))) || FALLBACK_NAME;+ const taken = namesInUse(doc);+ if (!taken.has(base)) return base;+ let suffix = 1;+ while (taken.has(`${base}-${suffix}`)) suffix += 1;+ return `${base}-${suffix}`;+}diff --git a/packages/app/src/editor/utils/authored-text.ts b/packages/app/src/editor/utils/authored-text.tsnew file mode 100644index 000000000..dee0c75a3--- /dev/null+++ b/packages/app/src/editor/utils/authored-text.ts@@ -0,0 +1,4 @@+export function authoredText(value: unknown): string {+ if (typeof value === 'string') return value;+ return typeof value === 'number' ? String(value) : '';+}diff --git a/packages/app/src/lib/doc-hash.ts b/packages/app/src/lib/doc-hash.tsindex db3ad389c..1f2911847 100644--- a/packages/app/src/lib/doc-hash.ts+++ b/packages/app/src/lib/doc-hash.ts@@ -54,6 +54,18 @@ export function hashFromDocName(docName: string, anchor?: string | null): stringreturn anchor ? `${base}#${encodeSegment(anchor)}` : base;}+const MIRROR_SOURCE_ANCHOR_PREFIX = 'source:';++export function hashFromMirrorSource(docName: string, sourceName: string): string {+ return `${hashFromDocName(docName)}#${MIRROR_SOURCE_ANCHOR_PREFIX}${encodeSegment(sourceName)}`;+}++export function mirrorSourceNameFromAnchor(anchor: string): string | null {+ if (!anchor.startsWith(MIRROR_SOURCE_ANCHOR_PREFIX)) return null;+ const sourceName = anchor.slice(MIRROR_SOURCE_ANCHOR_PREFIX.length);+ return sourceName === '' ? null : sourceName;+}+export function isSameHash(a: string, b: string): boolean {return a === b || decodeHashForComparison(a) === decodeHashForComparison(b);}diff --git a/packages/app/src/lib/rendered-diff/diff-jsx-block.tsx b/packages/app/src/lib/rendered-diff/diff-jsx-block.tsxindex ea194eaf9..71fa2fc7f 100644--- a/packages/app/src/lib/rendered-diff/diff-jsx-block.tsx+++ b/packages/app/src/lib/rendered-diff/diff-jsx-block.tsx@@ -30,6 +30,7 @@ import {shouldRenderPlaceholder,} from '@/editor/registry/resolve-descriptor-placeholder';import type { JsxComponentDescriptor } from '@/editor/registry/types';+import { authoredText } from '@/editor/utils/authored-text';import { reconstructSource } from '@/editor/utils/reconstruct-source';export interface RenderedJsxBlock {@@ -51,9 +52,9 @@ function opensLiveDocument(}function referenceTarget(renderProps: Record<string, unknown>): string {- const src = typeof renderProps.src === 'string' ? renderProps.src : '';- const anchor = typeof renderProps.anchor === 'string' ? renderProps.anchor : '';- return anchor ? `${src}#${anchor}` : src;+ const src = authoredText(renderProps.src);+ const name = authoredText(renderProps.name);+ return name ? `${src}#${name}` : src;}function diffRenderProps(@@ -133,7 +134,7 @@ function DiffJsxBlock({);}- const primitiveProps = extractPrimitiveProps(node.attrs, descriptor.reactNodePropNames);+ const primitiveProps = extractPrimitiveProps(node.attrs, descriptor);const renderProps = resolveJsxRenderProps(descriptor, primitiveProps, docName);if (diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.poindex 857434738..be5e07055 100644--- a/packages/app/src/locales/ar/messages.po+++ b/packages/app/src/locales/ar/messages.po@@ -94,8 +94,8 @@ msgstr "(منفصل)"msgid "(inline)"msgstr "(مضمَّن)"-msgid "(no id)"-msgstr "(بدون معرّف)"+msgid "(no name)"+msgstr "(بدون اسم)"msgid "(opens in new tab)"msgstr "(يفتح في تبويب جديد)"@@ -892,11 +892,11 @@ msgstr "<0>{cliCommand}</0> لن يعمل في الوحدات الطرفية اmsgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."msgstr "تعذّر دمج <0>{filePath}</0> هنا. اختر النسخة التي تريد الاحتفاظ بها."-msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."-msgstr "<0>مرآة — اختر مصدرًا.</0> اضبط <1>src</1> + <2>anchor</2> من لوحة الخصائص للإشارة إلى <3><MirrorSource></3> في مكان آخر."+msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>name</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."+msgstr "<0>مرآة — اختر مصدرًا.</0> اضبط <1>src</1> + <2>name</2> من لوحة الخصائص للإشارة إلى <3><MirrorSource></3> في مكان آخر."-msgid "<0>Mirror anchor not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."-msgstr "<0>لم يُعثر على مرساة المرآة.</0> لا يوجد <1>{mirrorSourceTag}</1> في <2>{src}</2>."+msgid "<0>Mirror name not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."+msgstr "<0>لم يُعثر على اسم المرآة.</0> لا يوجد <1>{mirrorSourceTag}</1> في <2>{src}</2>."msgid "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."msgstr "<0>تمت إزالة مصدر المرآة.</0> لم يعد المستند <1>{src}</1> متاحًا."@@ -3792,6 +3792,9 @@ msgstr "إحصاءات المستند"msgid "Document structure"msgstr "هيكل الوثيقة"+msgid "Document suggestions"+msgstr "اقتراحات المستندات"+msgid "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."msgstr "وثّق بنية هذا المستودع: أنشئ صفحة نظرة عامة ترتبط بصفحة لكل وحدة رئيسية تصف مسؤولياتها ونقاط دخولها."@@ -6294,6 +6297,9 @@ msgstr "مصدر المرآة <0>{label}</0>"msgid "Mirror source <0>api-spec</0>"msgstr "مصدر المرآة <0>api-spec</0>"+msgid "Mirror source names"+msgstr "أسماء مصادر المرآة"+msgid "Missing"msgstr "مفقود"@@ -6921,6 +6927,12 @@ msgstr "لا توجد مستودعات مطابقة."msgid "No matching worktrees or branches."msgstr "لا توجد أشجار عمل أو فروع مطابقة."+msgid "No Mirror Source block in {docName} matches the text in this field. Clear it to see them all."+msgstr "لا توجد كتلة مصدر مرآة في {docName} تطابق النص في هذا الحقل. أفرغه لعرضها كلها."++msgid "No Mirror Source blocks in {docName}"+msgstr "لا توجد كتل مصدر المرآة في {docName}"+msgid "No Outgoing"msgstr "لا روابط صادرة"diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.poindex bea574b31..b56a65214 100644--- a/packages/app/src/locales/bn/messages.po+++ b/packages/app/src/locales/bn/messages.po@@ -94,8 +94,8 @@ msgstr "(বিচ্ছিন্ন)"msgid "(inline)"msgstr "(ইনলাইন)"-msgid "(no id)"-msgstr "(কোনো id নেই)"+msgid "(no name)"+msgstr "(কোনো নাম নেই)"msgid "(opens in new tab)"msgstr "(নতুন ট্যাবে খোলে)"@@ -888,11 +888,11 @@ msgstr "পরে File মেনু থেকে যোগ না করা পmsgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."msgstr "<0>{filePath}</0> এখানে মার্জ করা যাবে না। কোন সংস্করণটি রাখবেন বেছে নিন।"-msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."-msgstr "<0>মিরর — একটি উৎস বাছুন।</0> অন্য কোথাও থাকা কোনো <3><MirrorSource></3>-এর দিকে নির্দেশ করতে প্রপার্টি প্যানেল থেকে <1>src</1> + <2>anchor</2> নির্ধারণ করুন।"+msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>name</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."+msgstr "<0>মিরর — একটি উৎস বাছুন।</0> অন্য কোথাও থাকা কোনো <3><MirrorSource></3>-এর দিকে নির্দেশ করতে প্রপার্টি প্যানেল থেকে <1>src</1> + <2>name</2> নির্ধারণ করুন।"-msgid "<0>Mirror anchor not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."-msgstr "<0>মিরর অ্যাংকর পাওয়া যায়নি।</0> <2>{src}</2>-এ কোনো <1>{mirrorSourceTag}</1> নেই।"+msgid "<0>Mirror name not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."+msgstr "<0>মিররের নাম পাওয়া যায়নি।</0> <2>{src}</2>-এ কোনো <1>{mirrorSourceTag}</1> নেই।"msgid "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."msgstr "<0>মিরর উৎস সরানো হয়েছে।</0> <1>{src}</1> নথিটি আর নেই।"@@ -3788,6 +3788,9 @@ msgstr "নথির পরিসংখ্যান"msgid "Document structure"msgstr "নথি কাঠামো"+msgid "Document suggestions"+msgstr "নথির পরামর্শ"+msgid "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."msgstr "এই রিপোজিটরির স্থাপত্য নথিভুক্ত করুন: একটি সংক্ষিপ্তসার পাতা তৈরি করুন যা প্রতিটি প্রধান মডিউলের পাতার সঙ্গে যুক্ত থাকে এবং তার দায়িত্ব ও প্রবেশবিন্দু বর্ণনা করে।"@@ -6290,6 +6293,9 @@ msgstr "মিরর উৎস <0>{label}</0>"msgid "Mirror source <0>api-spec</0>"msgstr "মিরর উৎস <0>api-spec</0>"+msgid "Mirror source names"+msgstr "মিরর উৎসের নাম"+msgid "Missing"msgstr "অনুপস্থিত"@@ -6917,6 +6923,12 @@ msgstr "মিলে যাওয়া কোনো রিপোজিটরিmsgid "No matching worktrees or branches."msgstr "মিলে যাওয়া কোনো ওয়ার্কট্রি বা ব্রাঞ্চ নেই।"+msgid "No Mirror Source block in {docName} matches the text in this field. Clear it to see them all."+msgstr "{docName}-এ এই ঘরের লেখার সাথে মেলে এমন কোনো মিরর উৎস ব্লক নেই। সবগুলো দেখতে এটি খালি করুন।"++msgid "No Mirror Source blocks in {docName}"+msgstr "{docName}-এ কোনো মিরর উৎস ব্লক নেই"+msgid "No Outgoing"msgstr "কোনো বহির্গামী নেই"diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex e246b59b2..faebc9f6c 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -94,8 +94,8 @@ msgstr "(detached)"msgid "(inline)"msgstr "(inline)"-msgid "(no id)"-msgstr "(no id)"+msgid "(no name)"+msgstr "(no name)"msgid "(opens in new tab)"msgstr "(opens in new tab)"@@ -892,11 +892,11 @@ msgstr "<0>{cliCommand}</0> won't run in external terminals until you add it latmsgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."msgstr "<0>{filePath}</0> can't be merged here. Pick the version to keep."-msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."-msgstr "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."+msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>name</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."+msgstr "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>name</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."-msgid "<0>Mirror anchor not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."-msgstr "<0>Mirror anchor not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."+msgid "<0>Mirror name not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."+msgstr "<0>Mirror name not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."msgid "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."msgstr "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."@@ -3792,6 +3792,9 @@ msgstr "Document statistics"msgid "Document structure"msgstr "Document structure"+msgid "Document suggestions"+msgstr "Document suggestions"+msgid "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."msgstr "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."@@ -6294,6 +6297,9 @@ msgstr "Mirror source <0>{label}</0>"msgid "Mirror source <0>api-spec</0>"msgstr "Mirror source <0>api-spec</0>"+msgid "Mirror source names"+msgstr "Mirror source names"+msgid "Missing"msgstr "Missing"@@ -6921,6 +6927,12 @@ msgstr "No matching repositories."msgid "No matching worktrees or branches."msgstr "No matching worktrees or branches."+msgid "No Mirror Source block in {docName} matches the text in this field. Clear it to see them all."+msgstr "No Mirror Source block in {docName} matches the text in this field. Clear it to see them all."++msgid "No Mirror Source blocks in {docName}"+msgstr "No Mirror Source blocks in {docName}"+msgid "No Outgoing"msgstr "No Outgoing"diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.poindex 88f6ef9ac..5851e3134 100644--- a/packages/app/src/locales/es/messages.po+++ b/packages/app/src/locales/es/messages.po@@ -94,8 +94,8 @@ msgstr "(desacoplado)"msgid "(inline)"msgstr "(en línea)"-msgid "(no id)"-msgstr "(sin id)"+msgid "(no name)"+msgstr "(sin nombre)"msgid "(opens in new tab)"msgstr "(se abre en una pestaña nueva)"@@ -892,11 +892,11 @@ msgstr "<0>{cliCommand}</0> no funcionará en terminales externas hasta que lo amsgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."msgstr "<0>{filePath}</0> no se puede combinar aquí. Elige la versión que quieres conservar."-msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."-msgstr "<0>Espejo: elige una fuente.</0> Define <1>src</1> + <2>anchor</2> desde el panel de propiedades para apuntar a un <3><MirrorSource></3> de otro sitio."+msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>name</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."+msgstr "<0>Espejo: elige una fuente.</0> Define <1>src</1> + <2>name</2> desde el panel de propiedades para apuntar a un <3><MirrorSource></3> de otro sitio."-msgid "<0>Mirror anchor not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."-msgstr "<0>No se encontró el ancla del espejo.</0> No existe ningún <1>{mirrorSourceTag}</1> en <2>{src}</2>."+msgid "<0>Mirror name not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."+msgstr "<0>No se encontró el nombre del espejo.</0> No existe ningún <1>{mirrorSourceTag}</1> en <2>{src}</2>."msgid "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."msgstr "<0>Se eliminó la fuente del espejo.</0> El documento <1>{src}</1> ya no está disponible."@@ -3792,6 +3792,9 @@ msgstr "Estadísticas del documento"msgid "Document structure"msgstr "Estructura del documento"+msgid "Document suggestions"+msgstr "Sugerencias de documentos"+msgid "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."msgstr "Documenta la arquitectura de este repositorio: crea una página general que enlace a una página por cada módulo principal describiendo sus responsabilidades y sus puntos de entrada."@@ -6294,6 +6297,9 @@ msgstr "Origen del espejo <0>{label}</0>"msgid "Mirror source <0>api-spec</0>"msgstr "Origen del espejo <0>api-spec</0>"+msgid "Mirror source names"+msgstr "Nombres de orígenes del espejo"+msgid "Missing"msgstr "Ausente"@@ -6921,6 +6927,12 @@ msgstr "Ningún repositorio coincide."msgid "No matching worktrees or branches."msgstr "Ningún worktree ni rama coincide."+msgid "No Mirror Source block in {docName} matches the text in this field. Clear it to see them all."+msgstr "Ningún bloque de origen del espejo en {docName} coincide con el texto de este campo. Vacíalo para verlos todos."++msgid "No Mirror Source blocks in {docName}"+msgstr "No hay bloques de origen del espejo en {docName}"+msgid "No Outgoing"msgstr "Sin salientes"diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.poindex 47a8d335a..dec873295 100644--- a/packages/app/src/locales/fr/messages.po+++ b/packages/app/src/locales/fr/messages.po@@ -94,8 +94,8 @@ msgstr "(détaché)"msgid "(inline)"msgstr "(en ligne)"-msgid "(no id)"-msgstr "(aucun id)"+msgid "(no name)"+msgstr "(aucun nom)"msgid "(opens in new tab)"msgstr "(s'ouvre dans un nouvel onglet)"@@ -892,11 +892,11 @@ msgstr "<0>{cliCommand}</0> ne fonctionnera pas dans les terminaux externes tantmsgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."msgstr "<0>{filePath}</0> ne peut pas être fusionné ici. Choisissez la version à garder."-msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."-msgstr "<0>Miroir — choisissez une source.</0> Définissez <1>src</1> + <2>anchor</2> dans le panneau des propriétés pour pointer vers un <3><MirrorSource></3> ailleurs."+msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>name</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."+msgstr "<0>Miroir — choisissez une source.</0> Définissez <1>src</1> + <2>name</2> dans le panneau des propriétés pour pointer vers un <3><MirrorSource></3> ailleurs."-msgid "<0>Mirror anchor not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."-msgstr "<0>Ancre de miroir introuvable.</0> Aucun <1>{mirrorSourceTag}</1> n'existe dans <2>{src}</2>."+msgid "<0>Mirror name not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."+msgstr "<0>Nom de miroir introuvable.</0> Aucun <1>{mirrorSourceTag}</1> n'existe dans <2>{src}</2>."msgid "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."msgstr "<0>Source du miroir supprimée.</0> Le document <1>{src}</1> n'est plus disponible."@@ -3792,6 +3792,9 @@ msgstr "Statistiques du document"msgid "Document structure"msgstr "Structure du document"+msgid "Document suggestions"+msgstr "Suggestions de documents"+msgid "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."msgstr "Documente l'architecture de ce dépôt : crée une page de synthèse qui renvoie vers une page par module principal décrivant ses responsabilités et ses points d'entrée."@@ -6294,6 +6297,9 @@ msgstr "Source du miroir <0>{label}</0>"msgid "Mirror source <0>api-spec</0>"msgstr "Source du miroir <0>api-spec</0>"+msgid "Mirror source names"+msgstr "Noms des sources du miroir"+msgid "Missing"msgstr "Manquant"@@ -6921,6 +6927,12 @@ msgstr "Aucun dépôt correspondant."msgid "No matching worktrees or branches."msgstr "Aucun worktree ni branche correspondant."+msgid "No Mirror Source block in {docName} matches the text in this field. Clear it to see them all."+msgstr "Aucun bloc source du miroir dans {docName} ne correspond au texte de ce champ. Videz-le pour tous les voir."++msgid "No Mirror Source blocks in {docName}"+msgstr "Aucun bloc source du miroir dans {docName}"+msgid "No Outgoing"msgstr "Aucun lien sortant"diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.poindex 4e13f9e29..157098a3b 100644--- a/packages/app/src/locales/hi/messages.po+++ b/packages/app/src/locales/hi/messages.po@@ -94,8 +94,8 @@ msgstr "(अलग किया हुआ)"msgid "(inline)"msgstr "(इनलाइन)"-msgid "(no id)"-msgstr "(कोई id नहीं)"+msgid "(no name)"+msgstr "(कोई नाम नहीं)"msgid "(opens in new tab)"msgstr "(नए टैब में खुलता है)"@@ -888,11 +888,11 @@ msgstr "<0>{cliCommand}</0> तब तक बाहरी टर्मिनलmsgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."msgstr "<0>{filePath}</0> को यहाँ मर्ज नहीं किया जा सकता। रखने के लिए संस्करण चुनें।"-msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."-msgstr "<0>मिरर — एक स्रोत चुनें।</0> कहीं और मौजूद किसी <3><MirrorSource></3> की ओर इंगित करने के लिए प्रॉपर्टी पैनल से <1>src</1> + <2>anchor</2> सेट करें।"+msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>name</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."+msgstr "<0>मिरर — एक स्रोत चुनें।</0> कहीं और मौजूद किसी <3><MirrorSource></3> की ओर इंगित करने के लिए प्रॉपर्टी पैनल से <1>src</1> + <2>name</2> सेट करें।"-msgid "<0>Mirror anchor not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."-msgstr "<0>मिरर एंकर नहीं मिला।</0> <2>{src}</2> में कोई <1>{mirrorSourceTag}</1> मौजूद नहीं है।"+msgid "<0>Mirror name not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."+msgstr "<0>मिरर का नाम नहीं मिला।</0> <2>{src}</2> में कोई <1>{mirrorSourceTag}</1> मौजूद नहीं है।"msgid "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."msgstr "<0>मिरर स्रोत हटा दिया गया।</0> दस्तावेज़ <1>{src}</1> अब उपलब्ध नहीं है।"@@ -3788,6 +3788,9 @@ msgstr "दस्तावेज़ आँकड़े"msgid "Document structure"msgstr "दस्तावेज़ संरचना"+msgid "Document suggestions"+msgstr "दस्तावेज़ सुझाव"+msgid "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."msgstr "इस रिपॉज़िटरी की संरचना का दस्तावेज़ीकरण करें: एक सिंहावलोकन पेज बनाएँ जो हर प्रमुख मॉड्यूल के पेज से जुड़ता हो और उसकी ज़िम्मेदारियाँ तथा प्रवेश बिंदु बताता हो।"@@ -6290,6 +6293,9 @@ msgstr "मिरर स्रोत <0>{label}</0>"msgid "Mirror source <0>api-spec</0>"msgstr "मिरर स्रोत <0>api-spec</0>"+msgid "Mirror source names"+msgstr "मिरर स्रोतों के नाम"+msgid "Missing"msgstr "अनुपस्थित"@@ -6917,6 +6923,12 @@ msgstr "कोई मेल खाती रिपॉज़िटरी नहmsgid "No matching worktrees or branches."msgstr "कोई मेल खाता वर्कट्री या ब्रांच नहीं।"+msgid "No Mirror Source block in {docName} matches the text in this field. Clear it to see them all."+msgstr "{docName} में इस फ़ील्ड के टेक्स्ट से मेल खाने वाला कोई मिरर स्रोत ब्लॉक नहीं है। सभी देखने के लिए इसे खाली करें।"++msgid "No Mirror Source blocks in {docName}"+msgstr "{docName} में कोई मिरर स्रोत ब्लॉक नहीं है"+msgid "No Outgoing"msgstr "कोई जाने वाला नहीं"diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.poindex 0ea8b33fe..6adc295d1 100644--- a/packages/app/src/locales/id/messages.po+++ b/packages/app/src/locales/id/messages.po@@ -94,8 +94,8 @@ msgstr "(terlepas)"msgid "(inline)"msgstr "(sebaris)"-msgid "(no id)"-msgstr "(tanpa id)"+msgid "(no name)"+msgstr "(tanpa nama)"msgid "(opens in new tab)"msgstr "(terbuka di tab baru)"@@ -888,11 +888,11 @@ msgstr "<0>{cliCommand}</0> tidak akan berjalan di terminal eksternal sampai Andmsgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."msgstr "<0>{filePath}</0> tidak bisa digabungkan di sini. Pilih versi yang ingin disimpan."-msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."-msgstr "<0>Cermin — pilih sebuah sumber.</0> Atur <1>src</1> + <2>anchor</2> lewat panel properti agar mengarah ke <3><MirrorSource></3> di tempat lain."+msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>name</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."+msgstr "<0>Cermin — pilih sebuah sumber.</0> Atur <1>src</1> + <2>name</2> lewat panel properti agar mengarah ke <3><MirrorSource></3> di tempat lain."-msgid "<0>Mirror anchor not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."-msgstr "<0>Jangkar cermin tidak ditemukan.</0> Tidak ada <1>{mirrorSourceTag}</1> di <2>{src}</2>."+msgid "<0>Mirror name not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."+msgstr "<0>Nama cermin tidak ditemukan.</0> Tidak ada <1>{mirrorSourceTag}</1> di <2>{src}</2>."msgid "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."msgstr "<0>Sumber cermin dihapus.</0> Dokumen <1>{src}</1> sudah tidak tersedia."@@ -3788,6 +3788,9 @@ msgstr "Statistik dokumen"msgid "Document structure"msgstr "Struktur dokumen"+msgid "Document suggestions"+msgstr "Saran dokumen"+msgid "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."msgstr "Dokumentasikan arsitektur repo ini: buat halaman ikhtisar yang menaut ke satu halaman per modul utama yang menjelaskan tanggung jawab dan titik masuknya."@@ -6290,6 +6293,9 @@ msgstr "Sumber cermin <0>{label}</0>"msgid "Mirror source <0>api-spec</0>"msgstr "Sumber cermin <0>api-spec</0>"+msgid "Mirror source names"+msgstr "Nama sumber cermin"+msgid "Missing"msgstr "Hilang"@@ -6917,6 +6923,12 @@ msgstr "Tidak ada repositori yang cocok."msgid "No matching worktrees or branches."msgstr "Tidak ada worktree atau cabang yang cocok."+msgid "No Mirror Source block in {docName} matches the text in this field. Clear it to see them all."+msgstr "Tidak ada blok sumber cermin di {docName} yang cocok dengan teks di kolom ini. Kosongkan untuk melihat semuanya."++msgid "No Mirror Source blocks in {docName}"+msgstr "Tidak ada blok sumber cermin di {docName}"+msgid "No Outgoing"msgstr "Tidak Ada Keluar"diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.poindex 8732069dd..b65b8f75a 100644--- a/packages/app/src/locales/ko/messages.po+++ b/packages/app/src/locales/ko/messages.po@@ -94,8 +94,8 @@ msgstr "(분리됨)"msgid "(inline)"msgstr "(인라인)"-msgid "(no id)"-msgstr "(ID 없음)"+msgid "(no name)"+msgstr "(이름 없음)"msgid "(opens in new tab)"msgstr "(새 탭에서 열기)"@@ -892,11 +892,11 @@ msgstr "<0>{cliCommand}</0>는 나중에 파일 메뉴에서 추가할 때까지msgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."msgstr "<0>{filePath}</0>은 여기에서 병합할 수 없습니다. 유지할 버전을 고르세요."-msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."-msgstr "<0>미러, 소스를 선택하세요.</0> 속성 패널에서 <1>src</1>와 <2>anchor</2>를 설정해 다른 곳의 <3><MirrorSource></3>를 가리키세요."+msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>name</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."+msgstr "<0>미러, 소스를 선택하세요.</0> 속성 패널에서 <1>src</1>와 <2>name</2>을 설정해 다른 곳의 <3><MirrorSource></3>를 가리키세요."-msgid "<0>Mirror anchor not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."-msgstr "<0>미러 앵커를 찾을 수 없습니다.</0> <1>{mirrorSourceTag}</1>가 <2>{src}</2>에 없습니다."+msgid "<0>Mirror name not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."+msgstr "<0>미러 이름을 찾을 수 없습니다.</0> <1>{mirrorSourceTag}</1>가 <2>{src}</2>에 없습니다."msgid "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."msgstr "<0>미러 소스가 삭제되었습니다.</0> 문서 <1>{src}</1>는 더 이상 사용할 수 없습니다."@@ -3792,6 +3792,9 @@ msgstr "문서 통계"msgid "Document structure"msgstr "문서 구조"+msgid "Document suggestions"+msgstr "문서 제안"+msgid "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."msgstr "이 리포지토리의 아키텍처를 문서화합니다. 개요 페이지를 만들고 각 주요 모듈의 책임과 진입점을 설명하는 페이지로 연결합니다."@@ -6294,6 +6297,9 @@ msgstr "미러 소스 <0>{label}</0>"msgid "Mirror source <0>api-spec</0>"msgstr "미러 소스 <0>api-spec</0>"+msgid "Mirror source names"+msgstr "미러 소스 이름"+msgid "Missing"msgstr "누락됨"@@ -6921,6 +6927,12 @@ msgstr "일치하는 저장소가 없습니다."msgid "No matching worktrees or branches."msgstr "일치하는 워크트리 또는 브랜치 없음."+msgid "No Mirror Source block in {docName} matches the text in this field. Clear it to see them all."+msgstr "{docName}에 이 입력란의 텍스트와 일치하는 미러 소스 블록이 없습니다. 모두 보려면 입력란을 비우세요."++msgid "No Mirror Source blocks in {docName}"+msgstr "{docName}에 미러 소스 블록이 없습니다"+msgid "No Outgoing"msgstr "나가는 링크 없음"diff --git a/packages/app/src/locales/pl/messages.po b/packages/app/src/locales/pl/messages.poindex 2f384cebc..2489ff111 100644--- a/packages/app/src/locales/pl/messages.po+++ b/packages/app/src/locales/pl/messages.po@@ -94,8 +94,8 @@ msgstr "(odłączony)"msgid "(inline)"msgstr "(osadzone)"-msgid "(no id)"-msgstr "(bez id)"+msgid "(no name)"+msgstr "(bez nazwy)"msgid "(opens in new tab)"msgstr "(otwiera się w nowej karcie)"@@ -892,11 +892,11 @@ msgstr "<0>{cliCommand}</0> nie będzie działać w zewnętrznych terminalach, dmsgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."msgstr "<0>{filePath}</0> nie może zostać scalony tutaj. Wybierz wersję do zachowania."-msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."-msgstr "<0>Odbicie — wybierz źródło.</0> Ustaw <1>src</1> + <2>anchor</2> w panelu właściwości tak, aby wskazywały na <3><MirrorSource></3> w innym miejscu."+msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>name</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."+msgstr "<0>Odbicie — wybierz źródło.</0> Ustaw <1>src</1> + <2>name</2> w panelu właściwości tak, aby wskazywały na <3><MirrorSource></3> w innym miejscu."-msgid "<0>Mirror anchor not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."-msgstr "<0>Nie znaleziono kotwicy odbicia.</0> Brak <1>{mirrorSourceTag}</1> w <2>{src}</2>."+msgid "<0>Mirror name not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."+msgstr "<0>Nie znaleziono nazwy odbicia.</0> Brak <1>{mirrorSourceTag}</1> w <2>{src}</2>."msgid "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."msgstr "<0>Usunięto źródło odbicia.</0> Dokument <1>{src}</1> nie jest już dostępny."@@ -3792,6 +3792,9 @@ msgstr "Statystyki dokumentu"msgid "Document structure"msgstr "Struktura dokumentu"+msgid "Document suggestions"+msgstr "Podpowiedzi dokumentów"+msgid "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."msgstr "Opisz architekturę tego repozytorium: utwórz stronę przeglądową prowadzącą do osobnej strony każdego głównego modułu, opisującą jego obowiązki i punkty wejścia."@@ -6294,6 +6297,9 @@ msgstr "Źródło lustra <0>{label}</0>"msgid "Mirror source <0>api-spec</0>"msgstr "Źródło lustra <0>api-spec</0>"+msgid "Mirror source names"+msgstr "Nazwy źródeł lustra"+msgid "Missing"msgstr "Brakujące"@@ -6921,6 +6927,12 @@ msgstr "Brak pasujących repozytoriów."msgid "No matching worktrees or branches."msgstr "Brak pasujących worktrees ani gałęzi."+msgid "No Mirror Source block in {docName} matches the text in this field. Clear it to see them all."+msgstr "Żaden blok źródła lustra w {docName} nie pasuje do tekstu w tym polu. Wyczyść je, aby zobaczyć wszystkie."++msgid "No Mirror Source blocks in {docName}"+msgstr "Brak bloków źródła lustra w {docName}"+msgid "No Outgoing"msgstr "Brak wychodzących"diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.poindex 5d0b220d8..6d2363bd1 100644--- a/packages/app/src/locales/pt-BR/messages.po+++ b/packages/app/src/locales/pt-BR/messages.po@@ -94,8 +94,8 @@ msgstr "(desanexado)"msgid "(inline)"msgstr "(em linha)"-msgid "(no id)"-msgstr "(sem id)"+msgid "(no name)"+msgstr "(sem nome)"msgid "(opens in new tab)"msgstr "(abre em uma nova aba)"@@ -888,11 +888,11 @@ msgstr "<0>{cliCommand}</0> não funcionará em terminais externos até que vocmsgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."msgstr "<0>{filePath}</0> não pode ser mesclado aqui. Escolha a versão que quer manter."-msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."-msgstr "<0>Espelho — escolha uma fonte.</0> Defina <1>src</1> + <2>anchor</2> no painel de propriedades para apontar para um <3><MirrorSource></3> em outro lugar."+msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>name</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."+msgstr "<0>Espelho — escolha uma fonte.</0> Defina <1>src</1> + <2>name</2> no painel de propriedades para apontar para um <3><MirrorSource></3> em outro lugar."-msgid "<0>Mirror anchor not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."-msgstr "<0>Âncora do espelho não encontrada.</0> Não existe nenhum <1>{mirrorSourceTag}</1> em <2>{src}</2>."+msgid "<0>Mirror name not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."+msgstr "<0>Nome do espelho não encontrado.</0> Não existe nenhum <1>{mirrorSourceTag}</1> em <2>{src}</2>."msgid "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."msgstr "<0>Fonte do espelho removida.</0> O documento <1>{src}</1> não está mais disponível."@@ -3788,6 +3788,9 @@ msgstr "Estatísticas do documento"msgid "Document structure"msgstr "Estrutura do documento"+msgid "Document suggestions"+msgstr "Sugestões de documentos"+msgid "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."msgstr "Documente a arquitetura deste repositório: crie uma página geral que aponte para uma página por módulo principal descrevendo suas responsabilidades e seus pontos de entrada."@@ -6290,6 +6293,9 @@ msgstr "Fonte do espelho <0>{label}</0>"msgid "Mirror source <0>api-spec</0>"msgstr "Fonte do espelho <0>api-spec</0>"+msgid "Mirror source names"+msgstr "Nomes das fontes do espelho"+msgid "Missing"msgstr "Ausente"@@ -6917,6 +6923,12 @@ msgstr "Nenhum repositório corresponde."msgid "No matching worktrees or branches."msgstr "Nenhum worktree ou ramo corresponde."+msgid "No Mirror Source block in {docName} matches the text in this field. Clear it to see them all."+msgstr "Nenhum bloco de fonte do espelho em {docName} corresponde ao texto deste campo. Limpe-o para ver todos."++msgid "No Mirror Source blocks in {docName}"+msgstr "Nenhum bloco de fonte do espelho em {docName}"+msgid "No Outgoing"msgstr "Sem saída"diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.poindex 9fc854e6b..403201941 100644--- a/packages/app/src/locales/ur/messages.po+++ b/packages/app/src/locales/ur/messages.po@@ -94,8 +94,8 @@ msgstr "(منقطع)"msgid "(inline)"msgstr "(اِن لائن)"-msgid "(no id)"-msgstr "(کوئی شناخت نہیں)"+msgid "(no name)"+msgstr "(کوئی نام نہیں)"msgid "(opens in new tab)"msgstr "(نئے ٹیب میں کھلتا ہے)"@@ -892,11 +892,11 @@ msgstr "<0>{cliCommand}</0> بیرونی ٹرمینلز میں اس وقت تکmsgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."msgstr "<0>{filePath}</0> کو یہاں مرج نہیں کیا جا سکتا۔ رکھنے کے لیے ورژن چنیں۔"-msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."-msgstr "<0>مرر — ایک ماخذ منتخب کریں۔</0> خصوصیات کے پینل سے <1>src</1> + <2>anchor</2> مقرر کریں تاکہ کہیں اور موجود <3><MirrorSource></3> کی طرف اشارہ ہو۔"+msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>name</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."+msgstr "<0>مرر — ایک ماخذ منتخب کریں۔</0> خصوصیات کے پینل سے <1>src</1> + <2>name</2> مقرر کریں تاکہ کہیں اور موجود <3><MirrorSource></3> کی طرف اشارہ ہو۔"-msgid "<0>Mirror anchor not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."-msgstr "<0>مرر اینکر نہیں ملا۔</0> <2>{src}</2> میں کوئی <1>{mirrorSourceTag}</1> موجود نہیں۔"+msgid "<0>Mirror name not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."+msgstr "<0>مرر کا نام نہیں ملا۔</0> <2>{src}</2> میں کوئی <1>{mirrorSourceTag}</1> موجود نہیں۔"msgid "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."msgstr "<0>مرر کا ماخذ ہٹا دیا گیا۔</0> دستاویز <1>{src}</1> اب دستیاب نہیں۔"@@ -3792,6 +3792,9 @@ msgstr "دستاویز کے اعداد و شمار"msgid "Document structure"msgstr "دستاویز کا ڈھانچہ"+msgid "Document suggestions"+msgstr "دستاویزات کی تجاویز"+msgid "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."msgstr "اس ریپو کے ڈھانچے کی دستاویز بنائیں: ایک جائزہ صفحہ بنائیں جو ہر بڑے ماڈیول کے صفحے سے جڑا ہو اور اس کی ذمہ داریاں اور داخلی نقاط بیان کرے۔"@@ -6294,6 +6297,9 @@ msgstr "مرر کا ماخذ <0>{label}</0>"msgid "Mirror source <0>api-spec</0>"msgstr "مرر کا ماخذ <0>api-spec</0>"+msgid "Mirror source names"+msgstr "مرر کے ماخذوں کے نام"+msgid "Missing"msgstr "غائب"@@ -6921,6 +6927,12 @@ msgstr "کوئی مماثل ریپازٹری نہیں۔"msgid "No matching worktrees or branches."msgstr "کوئی مماثل ورک ٹری یا برانچ نہیں۔"+msgid "No Mirror Source block in {docName} matches the text in this field. Clear it to see them all."+msgstr "{docName} میں اس فیلڈ کے متن سے ملتا ہوا مرر کا کوئی ماخذ بلاک نہیں ہے۔ سب دیکھنے کے لیے اسے خالی کریں۔"++msgid "No Mirror Source blocks in {docName}"+msgstr "{docName} میں مرر کے ماخذ کا کوئی بلاک نہیں ہے"+msgid "No Outgoing"msgstr "کوئی جانے والا نہیں"diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.poindex 8a0fec981..6d1d9e6e5 100644--- a/packages/app/src/locales/zh-Hans/messages.po+++ b/packages/app/src/locales/zh-Hans/messages.po@@ -94,8 +94,8 @@ msgstr "(游离状态)"msgid "(inline)"msgstr "(内联)"-msgid "(no id)"-msgstr "(无 id)"+msgid "(no name)"+msgstr "(无名称)"msgid "(opens in new tab)"msgstr "(在新标签页中打开)"@@ -892,11 +892,11 @@ msgstr "<0>{cliCommand}</0> 在你稍后从“文件”菜单添加之前,无msgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."msgstr "<0>{filePath}</0> 无法在这里合并。请选择要保留的版本。"-msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."-msgstr "<0>镜像——请选择一个来源。</0>在属性面板中设置 <1>src</1> + <2>anchor</2>,指向别处的 <3><MirrorSource></3>。"+msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>name</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."+msgstr "<0>镜像——请选择一个来源。</0>在属性面板中设置 <1>src</1> + <2>name</2>,指向别处的 <3><MirrorSource></3>。"-msgid "<0>Mirror anchor not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."-msgstr "<0>找不到镜像锚点。</0><2>{src}</2> 中不存在 <1>{mirrorSourceTag}</1>。"+msgid "<0>Mirror name not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."+msgstr "<0>找不到镜像名称。</0><2>{src}</2> 中不存在 <1>{mirrorSourceTag}</1>。"msgid "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."msgstr "<0>镜像来源已被移除。</0>文档 <1>{src}</1> 已不可用。"@@ -3792,6 +3792,9 @@ msgstr "文档统计"msgid "Document structure"msgstr "文件结构"+msgid "Document suggestions"+msgstr "文档建议"+msgid "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."msgstr "记录这个仓库的架构:创建一页总览,链接到每个主要模块的页面,说明各自的职责和入口。"@@ -6294,6 +6297,9 @@ msgstr "镜像来源 <0>{label}</0>"msgid "Mirror source <0>api-spec</0>"msgstr "镜像来源 <0>api-spec</0>"+msgid "Mirror source names"+msgstr "镜像来源名称"+msgid "Missing"msgstr "缺失"@@ -6921,6 +6927,12 @@ msgstr "没有匹配的仓库。"msgid "No matching worktrees or branches."msgstr "没有匹配的 worktree 或分支。"+msgid "No Mirror Source block in {docName} matches the text in this field. Clear it to see them all."+msgstr "{docName} 中没有与此字段文本匹配的镜像来源块。清空此字段即可查看全部。"++msgid "No Mirror Source blocks in {docName}"+msgstr "{docName} 中没有镜像来源块"+msgid "No Outgoing"msgstr "无出链"diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.poindex 049c49c94..434b19260 100644--- a/packages/app/src/locales/zh-Hant/messages.po+++ b/packages/app/src/locales/zh-Hant/messages.po@@ -94,8 +94,8 @@ msgstr "(分離狀態)"msgid "(inline)"msgstr "(行內)"-msgid "(no id)"-msgstr "(無 id)"+msgid "(no name)"+msgstr "(無名稱)"msgid "(opens in new tab)"msgstr "(在新分頁中開啟)"@@ -892,11 +892,11 @@ msgstr "<0>{cliCommand}</0> 在你稍後從「檔案」選單新增之前,無msgid "<0>{filePath}</0> can't be merged here. Pick the version to keep."msgstr "<0>{filePath}</0> 無法在這裡合併。請選擇要保留的版本。"-msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>anchor</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."-msgstr "<0>鏡像——請挑一個來源。</0>在屬性面板中設定 <1>src</1> + <2>anchor</2>,指向別處的 <3><MirrorSource></3>。"+msgid "<0>Mirror — pick a source.</0> Set <1>src</1> + <2>name</2> via the property panel to point at a <3><MirrorSource></3> elsewhere."+msgstr "<0>鏡像——請挑一個來源。</0>在屬性面板中設定 <1>src</1> + <2>name</2>,指向別處的 <3><MirrorSource></3>。"-msgid "<0>Mirror anchor not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."-msgstr "<0>找不到鏡像錨點。</0><2>{src}</2> 中不存在 <1>{mirrorSourceTag}</1>。"+msgid "<0>Mirror name not found.</0> No <1>{mirrorSourceTag}</1> exists in <2>{src}</2>."+msgstr "<0>找不到鏡像名稱。</0><2>{src}</2> 中不存在 <1>{mirrorSourceTag}</1>。"msgid "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."msgstr "<0>鏡像來源已移除。</0>文件 <1>{src}</1> 已無法使用。"@@ -3792,6 +3792,9 @@ msgstr "文件統計"msgid "Document structure"msgstr "文件結構"+msgid "Document suggestions"+msgstr "文件建議"+msgid "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."msgstr "記錄這個儲存庫的架構:建立一頁總覽,連到每個主要模組的頁面,說明各自的職責和進入點。"@@ -6294,6 +6297,9 @@ msgstr "鏡像來源 <0>{label}</0>"msgid "Mirror source <0>api-spec</0>"msgstr "鏡像來源 <0>api-spec</0>"+msgid "Mirror source names"+msgstr "鏡像來源名稱"+msgid "Missing"msgstr "缺失"@@ -6921,6 +6927,12 @@ msgstr "沒有相符的儲存庫。"msgid "No matching worktrees or branches."msgstr "沒有相符的 worktree 或分支。"+msgid "No Mirror Source block in {docName} matches the text in this field. Clear it to see them all."+msgstr "{docName} 中沒有與此欄位文字相符的鏡像來源區塊。清空此欄位即可查看全部。"++msgid "No Mirror Source blocks in {docName}"+msgstr "{docName} 中沒有鏡像來源區塊"+msgid "No Outgoing"msgstr "沒有連出"diff --git a/packages/app/tests/stress/commonmark-image-src-edit.e2e.ts b/packages/app/tests/stress/commonmark-image-src-edit.e2e.tsindex b65189cd8..c81a090a7 100644--- a/packages/app/tests/stress/commonmark-image-src-edit.e2e.ts+++ b/packages/app/tests/stress/commonmark-image-src-edit.e2e.ts@@ -50,7 +50,7 @@ test('a src edit on a doc-relative image in the Properties panel saves the new Ulet panel = await openImageProperties(page);await panel.locator('#prop-src').click();await page- .getByTestId('src-autocomplete-option')+ .getByTestId('suggestion-option').filter({ hasText: `notes/${imageFile}` }).click();await expect(panel.locator('#prop-src')).toHaveValue(`/notes/${imageFile}`);diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 19a35c00e..f079086b5 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -1186,6 +1186,7 @@ export {builtInComponents,type ComponentRegistry,createRegistry,+ propDescription,wildcardMeta,} from './registry/index.ts';export { JSX_SRC_REF_TAGS, type JsxSrcRefTagSpec } from './registry/jsx-src-ref-tags.ts';diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.tsindex 57a780eda..35e1beb2c 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -55,7 +55,7 @@ import {} from '../bridge/structural-freshness.ts';import type { LinkStyle } from '../extensions/link-fidelity.ts';import { isValidSourceLiteralRaw } from '../extensions/source-literal-mark.ts';-import { createRegistry } from '../registry/index.ts';+import { createRegistry, jsxAttributeValue } from '../registry/index.ts';import type { PropDef, SerializeContext } from '../registry/types.ts';import {type AuthoredJsxSourceReader,@@ -227,34 +227,7 @@ function destructureAttrs(for (const attr of attributes) {if (attr.type === 'mdxJsxExpressionAttribute') continue;-- const name = attr.name;- const propDef = propMap.get(name);-- if (attr.value === null || attr.value === undefined) {- result[name] = true;- continue;- }-- if (typeof attr.value === 'string') {- if (propDef?.type === 'number') {- const num = Number(attr.value);- result[name] = Number.isNaN(num) ? attr.value : num;- } else if (propDef?.type === 'boolean') {- result[name] = attr.value === 'true';- } else {- result[name] = attr.value;- }- continue;- }-- const exprValue = attr.value.value;- try {- const parsed = JSON.parse(exprValue);- result[name] = parsed;- } catch {- result[name] = exprValue;- }+ result[attr.name] = jsxAttributeValue(attr.value, propMap.get(attr.name));}return result;diff --git a/packages/core/src/registry/built-ins.ts b/packages/core/src/registry/built-ins.tsindex 120316376..caf7b35d9 100644--- a/packages/core/src/registry/built-ins.ts+++ b/packages/core/src/registry/built-ins.ts@@ -656,22 +656,25 @@ const mirrorProps: PropDef[] = [required: true,description: 'Path of the source doc, extension-less (e.g. `api-spec`).',autoFocus: true,+ documentPicker: true,},{- name: 'anchor',+ name: 'name',type: 'string',required: true,- description: 'Id of the `<MirrorSource>` block within the source doc.',+ legacyNames: ['anchor'],+ mirrorSourcePicker: 'src',+ description: 'Name of the `<MirrorSource>` block in the source doc.',},];const mirrorSourceProps: PropDef[] = [{- name: 'id',+ name: 'name',type: 'string',required: true,- description:- 'Stable id agents and authors use to reference this block from `<Mirror>` elsewhere.',+ legacyNames: ['id'],+ description: 'Stable name a `<Mirror>` uses to reference this block.',autoFocus: true,},{@@ -985,10 +988,10 @@ export const builtInComponents: JsxComponentMeta[] = [category: 'content',displayName: 'Mirror Source',description:- 'Mark a block as the source of truth for content that appears in multiple docs. Wrap any block content; `<Mirror src="…" anchor="<id>">` references render this verbatim read-only at every call-site. Edit here, propagate everywhere.',+ 'Mark a block as the source of truth for content that appears in multiple docs. Wrap any block content; `<Mirror src="…" name="…">` references render this verbatim read-only at every call-site. Edit here, propagate everywhere.',searchTerms: ['mirror source', 'sync source', 'source block', 'master block', 'shared'],exampleBody:- 'Authoritative content lives inside this block — edits here propagate to every `<Mirror>` that references this id.',+ 'Authoritative content lives inside this block — edits here propagate to every `<Mirror>` that references this name.',serialize: (node, ctx) => emitMdxJsx('MirrorSource', node, ctx, mirrorSourceProps),},diff --git a/packages/core/src/registry/index.ts b/packages/core/src/registry/index.tsindex 810ab5b51..2eb843117 100644--- a/packages/core/src/registry/index.ts+++ b/packages/core/src/registry/index.ts@@ -1,4 +1,6 @@export { builtInComponents } from './built-ins.ts';+export { type JsxAttributeValueSource, jsxAttributeValue } from './jsx-attribute-value.ts';+export { propDescription, resolveLegacyProps } from './legacy-props.ts';import { emitMdxJsx } from '../markdown/serialize-helpers.ts';import { builtInComponents } from './built-ins.ts';diff --git a/packages/core/src/registry/jsx-attribute-value.test.ts b/packages/core/src/registry/jsx-attribute-value.test.tsnew file mode 100644index 000000000..25856e2d0--- /dev/null+++ b/packages/core/src/registry/jsx-attribute-value.test.ts@@ -0,0 +1,36 @@+import { describe, expect, test } from 'vitest';+import { sharedExtensions } from '../extensions/shared.ts';+import { MarkdownManager } from '../markdown/index.ts';+import { jsxAttributeValue } from './jsx-attribute-value.ts';++describe('jsxAttributeValue', () => {+ test('reads a valueless attribute as true', () => {+ expect(jsxAttributeValue(null)).toBe(true);+ });++ test('reads a quoted value as text, or as the number or boolean its prop declares', () => {+ expect(jsxAttributeValue('7')).toBe('7');+ expect(jsxAttributeValue('7', { type: 'number' })).toBe(7);+ expect(jsxAttributeValue('true', { type: 'boolean' })).toBe(true);+ });++ test('keeps text that is not a number on a number prop, and reads only "true" as true', () => {+ expect(jsxAttributeValue('100%', { type: 'number' })).toBe('100%');+ expect(jsxAttributeValue('false', { type: 'boolean' })).toBe(false);+ expect(jsxAttributeValue('yes', { type: 'boolean' })).toBe(false);+ });++ test('is what the parser stores, typed by the component prop it fills', () => {+ const doc = new MarkdownManager({ extensions: sharedExtensions }).parse(+ '<img src="photo.png" alt="Team photo" width="320" />\n',+ );+ const image = (doc.content ?? []).find((node) => node.type === 'jsxComponent');+ expect((image?.attrs?.props as Record<string, unknown> | undefined)?.width).toBe(320);+ });++ test('parses an expression value as JSON, keeping its source text when it is not JSON', () => {+ expect(jsxAttributeValue({ value: '42' })).toBe(42);+ expect(jsxAttributeValue({ value: '"plans"' })).toBe('plans');+ expect(jsxAttributeValue({ value: 'plans' })).toBe('plans');+ });+});diff --git a/packages/core/src/registry/jsx-attribute-value.ts b/packages/core/src/registry/jsx-attribute-value.tsnew file mode 100644index 000000000..227c88cc3--- /dev/null+++ b/packages/core/src/registry/jsx-attribute-value.ts@@ -0,0 +1,23 @@+import type { PropDef } from './types.ts';++export type JsxAttributeValueSource = string | null | undefined | { readonly value: string };++export function jsxAttributeValue(+ value: JsxAttributeValueSource,+ propDef?: Pick<PropDef, 'type'>,+): unknown {+ if (value === null || value === undefined) return true;+ if (typeof value === 'string') {+ if (propDef?.type === 'number') {+ const num = Number(value);+ return Number.isNaN(num) ? value : num;+ }+ if (propDef?.type === 'boolean') return value === 'true';+ return value;+ }+ try {+ return JSON.parse(value.value);+ } catch {+ return value.value;+ }+}diff --git a/packages/core/src/registry/legacy-props.test.ts b/packages/core/src/registry/legacy-props.test.tsnew file mode 100644index 000000000..bbf26ed30--- /dev/null+++ b/packages/core/src/registry/legacy-props.test.ts@@ -0,0 +1,58 @@+import { describe, expect, test } from 'vitest';+import { builtInComponents } from './built-ins.ts';+import { propDescription, resolveLegacyProps } from './legacy-props.ts';++function propsOf(componentName: string) {+ const meta = builtInComponents.find((component) => component.name === componentName);+ if (!meta) throw new Error(`no built-in component named ${componentName}`);+ return meta.props;+}++describe('resolveLegacyProps', () => {+ test('reads an older Mirror `anchor` as `name`', () => {+ expect(resolveLegacyProps(propsOf('Mirror'), { src: 'pricing', anchor: 'plans' })).toEqual({+ src: 'pricing',+ name: 'plans',+ });+ });++ test('reads an older MirrorSource `id` as `name`', () => {+ expect(resolveLegacyProps(propsOf('MirrorSource'), { id: 'plans' })).toEqual({+ name: 'plans',+ });+ });++ test('`name` wins when a doc carries both spellings', () => {+ expect(resolveLegacyProps(propsOf('MirrorSource'), { id: 'old', name: 'new' })).toEqual({+ name: 'new',+ });+ });++ test('keeps an `id` on a component that declares no older spelling', () => {+ expect(resolveLegacyProps(propsOf('Tabs'), { id: 'billing-tabs' })).toEqual({+ id: 'billing-tabs',+ });+ });++ test('leaves the values it was given unchanged', () => {+ const values = { src: 'pricing', anchor: 'plans' };+ resolveLegacyProps(propsOf('Mirror'), values);+ expect(values).toEqual({ src: 'pricing', anchor: 'plans' });+ });+});++describe('propDescription', () => {+ test('says which older spelling a renamed prop still accepts', () => {+ const name = propsOf('Mirror').find((prop) => prop.name === 'name');+ if (!name) throw new Error('no Mirror name prop');+ expect(propDescription(name)).toBe(+ 'Name of the `<MirrorSource>` block in the source doc. Also read as `anchor`; write `name` instead.',+ );+ });++ test('leaves a prop without an older spelling as described', () => {+ const src = propsOf('Mirror').find((prop) => prop.name === 'src');+ if (!src) throw new Error('no Mirror src prop');+ expect(propDescription(src)).toBe(src.description);+ });+});diff --git a/packages/core/src/registry/legacy-props.ts b/packages/core/src/registry/legacy-props.tsnew file mode 100644index 000000000..2a807cd71--- /dev/null+++ b/packages/core/src/registry/legacy-props.ts@@ -0,0 +1,27 @@+import type { PropDef } from './types.ts';++export function propDescription(+ prop: Pick<PropDef, 'name' | 'description' | 'legacyNames'>,+): string | undefined {+ const legacyNames = prop.legacyNames ?? [];+ if (legacyNames.length === 0) return prop.description;+ const spellings = legacyNames.map((legacyName) => `\`${legacyName}\``).join(' or ');+ const note = `Also read as ${spellings}; write \`${prop.name}\` instead.`;+ return prop.description === undefined ? note : `${prop.description} ${note}`;+}++export function resolveLegacyProps(+ props: readonly PropDef[],+ values: Readonly<Record<string, unknown>>,+): Record<string, unknown> {+ const resolved: Record<string, unknown> = { ...values };+ for (const prop of props) {+ for (const legacyName of prop.legacyNames ?? []) {+ if (resolved[prop.name] === undefined && resolved[legacyName] !== undefined) {+ resolved[prop.name] = resolved[legacyName];+ }+ delete resolved[legacyName];+ }+ }+ return resolved;+}diff --git a/packages/core/src/registry/projection.test.ts b/packages/core/src/registry/projection.test.tsindex 00ee9bc3d..5c28cd0c8 100644--- a/packages/core/src/registry/projection.test.ts+++ b/packages/core/src/registry/projection.test.ts@@ -121,6 +121,13 @@ describe('projectFull — example + form-aware params (FR-11)', () => {expect((typeParam?.values ?? []).length).toBeGreaterThan(0);});+ test('tells agents the older spelling a renamed prop still accepts', () => {+ const mirror = getAgentCanonicalDescriptors().find((d) => d.name === 'Mirror');+ if (!mirror) throw new Error('no Mirror descriptor');+ const name = projectFull(mirror).params.find((param) => param.name === 'name');+ expect(name?.description).toContain('Also read as `anchor`; write `name` instead.');+ });+test('example for jsx-void components contains no body text', () => {const img = getCanonicalDescriptors().find((d) => d.name === 'img');expect(img).toBeDefined();diff --git a/packages/core/src/registry/projection.ts b/packages/core/src/registry/projection.tsindex a0587b4ea..21d641df6 100644--- a/packages/core/src/registry/projection.ts+++ b/packages/core/src/registry/projection.ts@@ -6,6 +6,7 @@ import { toMarkdown } from 'mdast-util-to-markdown';import { mdx } from 'micromark-extension-mdx';import { propToMdxJsxAttribute } from '../markdown/serialize-helpers.ts';import { builtInComponents } from './built-ins.ts';+import { propDescription } from './legacy-props.ts';import type { JsxComponentMeta, PropDef } from './types.ts';const MICROMARK_MDX_EXT = mdx();@@ -158,7 +159,8 @@ function projectParams(descriptor: JsxComponentMeta): ComponentParam[] {type: prop.type,required: prop.required,};- if (prop.description !== undefined) entry.description = prop.description;+ const description = propDescription(prop);+ if (description !== undefined) entry.description = description;if (prop.advanced === true) entry.advanced = true;if (prop.omitOnDefault === true) entry.omitOnDefault = true;if (prop.type === 'enum') {diff --git a/packages/core/src/registry/registry.test.ts b/packages/core/src/registry/registry.test.tsindex 0cf46586c..4f7cbcef3 100644--- a/packages/core/src/registry/registry.test.ts+++ b/packages/core/src/registry/registry.test.ts@@ -531,38 +531,44 @@ describe('builtInComponents manifest', () => {expect(mermaid?.displayName).toBe('Mermaid');});- test('Mirror exposes split-prop self-closing shape (src + anchor)', () => {+ test('Mirror exposes split-prop self-closing shape (src + name, `anchor` read as name)', () => {const mirror = builtInComponents.find((m) => m.name === 'Mirror');expect(mirror).toBeDefined();if (!mirror) return;expect(mirror.hasChildren).toBe(false);expect(mirror.isSelfClosing).toBe(true);const propNames = mirror.props.map((p) => p.name).sort();- expect(propNames).toEqual(['anchor', 'src']);+ expect(propNames).toEqual(['name', 'src']);const src = mirror.props.find((p) => p.name === 'src');- const anchor = mirror.props.find((p) => p.name === 'anchor');+ const name = mirror.props.find((p) => p.name === 'name');expect(src?.type).toBe('string');expect(src?.required).toBe(true);if (src?.type === 'string') {expect(src.autoFocus).toBe(true);+ expect(src.documentPicker).toBe(true);+ }+ expect(name?.type).toBe('string');+ expect(name?.required).toBe(true);+ expect(name?.legacyNames).toEqual(['anchor']);+ if (name?.type === 'string') {+ expect(name.mirrorSourcePicker).toBe('src');}- expect(anchor?.type).toBe('string');- expect(anchor?.required).toBe(true);});- test('MirrorSource exposes container shape (id + children slot)', () => {+ test('MirrorSource exposes container shape (name + children slot, `id` read as name)', () => {const mirrorSource = builtInComponents.find((m) => m.name === 'MirrorSource');expect(mirrorSource).toBeDefined();if (!mirrorSource) return;expect(mirrorSource.hasChildren).toBe(true);expect(mirrorSource.isSelfClosing).toBeUndefined();const propNames = mirrorSource.props.map((p) => p.name).sort();- expect(propNames).toEqual(['children', 'id']);- const id = mirrorSource.props.find((p) => p.name === 'id');- expect(id?.type).toBe('string');- expect(id?.required).toBe(true);- if (id?.type === 'string') {- expect(id.autoFocus).toBe(true);+ expect(propNames).toEqual(['children', 'name']);+ const name = mirrorSource.props.find((p) => p.name === 'name');+ expect(name?.type).toBe('string');+ expect(name?.required).toBe(true);+ expect(name?.legacyNames).toEqual(['id']);+ if (name?.type === 'string') {+ expect(name.autoFocus).toBe(true);}});diff --git a/packages/core/src/registry/types.ts b/packages/core/src/registry/types.tsindex 19aa9e590..3af293236 100644--- a/packages/core/src/registry/types.ts+++ b/packages/core/src/registry/types.ts@@ -15,6 +15,7 @@ export interface PropDefBase {* byte-identically (precedent #9 untouched).*/omitOnDefault?: boolean;+ legacyNames?: readonly string[];}export interface PropDefString extends PropDefBase {@@ -26,6 +27,8 @@ export interface PropDefString extends PropDefBase {iconPicker?: boolean;colorPicker?: boolean;cssLengthInput?: boolean;+ documentPicker?: boolean;+ mirrorSourcePicker?: string;}export interface PropDefBoolean extends PropDefBase {