@liminis/editor 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Pure helpers for a C4 node's manual layout.
3
+ *
4
+ * Imported only by the lazy `C4Component`, never by `C4Node.tsx`, so that
5
+ * `C4Node` stays free of static `@liminis/diagrams` imports (ADR-075/079).
6
+ */
7
+ import type { ManualLayout } from '@liminis/diagrams/core';
8
+ /**
9
+ * Reconcile a manual layout with hand-edited source.
10
+ *
11
+ * Keeps positions whose id still exists in the parsed source (and reserved
12
+ * `__` keys); drops the rest. Never drops anything on the strength of a failed
13
+ * or partial parse. Returns the same object when nothing was dropped, and
14
+ * `undefined` when no positions remain.
15
+ */
16
+ export declare function mergeManualLayout(code: string, layout: ManualLayout | undefined): ManualLayout | undefined;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Pure helpers for a C4 node's manual layout.
3
+ *
4
+ * Imported only by the lazy `C4Component`, never by `C4Node.tsx`, so that
5
+ * `C4Node` stays free of static `@liminis/diagrams` imports (ADR-075/079).
6
+ */
7
+ import { parseC4 } from '@liminis/diagrams/core';
8
+ /** Position keys starting with this prefix are synthetic (e.g. `__legend__`), not element ids. */
9
+ const RESERVED_PREFIX = '__';
10
+ /**
11
+ * Reconcile a manual layout with hand-edited source.
12
+ *
13
+ * Keeps positions whose id still exists in the parsed source (and reserved
14
+ * `__` keys); drops the rest. Never drops anything on the strength of a failed
15
+ * or partial parse. Returns the same object when nothing was dropped, and
16
+ * `undefined` when no positions remain.
17
+ */
18
+ export function mergeManualLayout(code, layout) {
19
+ if (!layout)
20
+ return layout;
21
+ const parsed = parseC4(code);
22
+ if (!parsed.diagram || parsed.errors.length > 0)
23
+ return layout;
24
+ const ids = new Set(parsed.diagram.elements.map((e) => e.id));
25
+ const kept = {};
26
+ let dropped = false;
27
+ for (const [id, position] of Object.entries(layout.positions)) {
28
+ if (id.startsWith(RESERVED_PREFIX) || ids.has(id)) {
29
+ kept[id] = position;
30
+ }
31
+ else {
32
+ dropped = true;
33
+ }
34
+ }
35
+ if (!dropped)
36
+ return layout;
37
+ return Object.keys(kept).length > 0 ? { ...layout, positions: kept } : undefined;
38
+ }
@@ -43,7 +43,23 @@ export type TransclusionRenderState = {
43
43
  * second site.
44
44
  */
45
45
  export declare function resolveAndRenderTransclusion(file: string, blockId: string, resolver: TransclusionResolver | undefined, visitedPath?: readonly string[]): Promise<TransclusionRenderState>;
46
+ /** The source a transclusion points at, used to render its navigation badge. */
47
+ export interface TransclusionSourceRef {
48
+ file: string;
49
+ blockId?: string;
50
+ }
51
+ /**
52
+ * The trailing "↗" source badge (#192). Link-shaped exactly like a
53
+ * `[[file#^id]]` link — `data-href` + `data-block-id` — so `LinkClickPlugin`
54
+ * emits `openLink(url, blockId)` with no changes. It carries `editor-link` (so
55
+ * the `modifier-held` / `links-clickable` cursor rules apply) but deliberately
56
+ * NOT `data-wiki-link`, which `WikiLinkExistencePlugin` would pick up and style
57
+ * as a possibly-broken link. `contenteditable=false` keeps the caret out of it.
58
+ */
59
+ export declare function renderTransclusionSourceBadge(ref: TransclusionSourceRef): ReactNode;
46
60
  /** Render a {@link TransclusionRenderState} to a React node, for both the
47
61
  * top-level `TransclusionComponent` and a nested `wikiEmbed` inside
48
- * resolved content — the two share the same visual vocabulary. */
49
- export declare function renderTransclusionState(state: TransclusionRenderState): ReactNode;
62
+ * resolved content — the two share the same visual vocabulary. When `ref` is
63
+ * given, a source badge navigating to it follows the state (#192); the badge
64
+ * is a sibling of the content, never an ancestor of nested links. */
65
+ export declare function renderTransclusionState(state: TransclusionRenderState, ref?: TransclusionSourceRef): ReactNode;
@@ -12,6 +12,7 @@
12
12
  */
13
13
  import { createElement, Fragment } from 'react';
14
14
  import { parseMarkdown } from '../../../markdown/parse.js';
15
+ import { wikiTargetToUrl, wikiLinkTargetToUrl } from '../../../utils/file-types.js';
15
16
  /**
16
17
  * Nested transclusion depth bound (FR-011). A Plan-stage numeric choice, not
17
18
  * derived from anything structural — deep enough that legitimate nesting
@@ -75,10 +76,38 @@ export async function resolveAndRenderTransclusion(file, blockId, resolver, visi
75
76
  return { kind: 'unresolved' };
76
77
  }
77
78
  }
79
+ const SOURCE_BADGE_LABEL = 'Open source block';
80
+ /**
81
+ * The trailing "↗" source badge (#192). Link-shaped exactly like a
82
+ * `[[file#^id]]` link — `data-href` + `data-block-id` — so `LinkClickPlugin`
83
+ * emits `openLink(url, blockId)` with no changes. It carries `editor-link` (so
84
+ * the `modifier-held` / `links-clickable` cursor rules apply) but deliberately
85
+ * NOT `data-wiki-link`, which `WikiLinkExistencePlugin` would pick up and style
86
+ * as a possibly-broken link. `contenteditable=false` keeps the caret out of it.
87
+ */
88
+ export function renderTransclusionSourceBadge(ref) {
89
+ return createElement('a', {
90
+ className: 'editor-link editor-transclusion-source',
91
+ 'data-href': wikiTargetToUrl(ref.file),
92
+ ...(ref.blockId ? { 'data-block-id': ref.blockId } : {}),
93
+ contentEditable: false,
94
+ suppressContentEditableWarning: true,
95
+ title: SOURCE_BADGE_LABEL,
96
+ 'aria-label': SOURCE_BADGE_LABEL,
97
+ }, '↗');
98
+ }
78
99
  /** Render a {@link TransclusionRenderState} to a React node, for both the
79
100
  * top-level `TransclusionComponent` and a nested `wikiEmbed` inside
80
- * resolved content — the two share the same visual vocabulary. */
81
- export function renderTransclusionState(state) {
101
+ * resolved content — the two share the same visual vocabulary. When `ref` is
102
+ * given, a source badge navigating to it follows the state (#192); the badge
103
+ * is a sibling of the content, never an ancestor of nested links. */
104
+ export function renderTransclusionState(state, ref) {
105
+ const body = renderTransclusionBody(state);
106
+ if (!ref)
107
+ return body;
108
+ return createElement('span', { className: 'editor-transclusion-wrap' }, body, renderTransclusionSourceBadge(ref));
109
+ }
110
+ function renderTransclusionBody(state) {
82
111
  switch (state.kind) {
83
112
  case 'resolved':
84
113
  return createElement('span', { className: 'editor-transclusion-content' }, state.content);
@@ -159,14 +188,24 @@ async function renderNode(node, resolver, visitedPath, key) {
159
188
  return extractPlainText(n);
160
189
  }
161
190
  const nested = await resolveAndRenderTransclusion(target, blockId, resolver, visitedPath);
162
- return createElement('span', { key }, renderTransclusionState(nested));
191
+ return createElement('span', { key }, renderTransclusionState(nested, { file: target, blockId }));
163
192
  }
164
193
  case 'wikiLink': {
165
- // A link-only reference inside transcluded content: render its label
166
- // as inert text. Live navigation from inside a transclusion is out of
167
- // scope (this is a read-only render, not a second editable surface).
194
+ // A link-only reference inside transcluded content (#192: now live —
195
+ // ADR-192 amends ADR-119 §8). Same link shape as the badge, so the click
196
+ // plugin's `closest('a')` finds this innermost anchor. No `data-wiki-link`:
197
+ // the existence plugin only walks the editor's own DOM.
168
198
  const data = n.data;
169
- return data?.alias || n.value || '';
199
+ const target = n.value ?? '';
200
+ const label = data?.alias || target;
201
+ if (!target)
202
+ return label;
203
+ return createElement('a', {
204
+ key,
205
+ className: 'editor-link',
206
+ 'data-href': wikiLinkTargetToUrl(target),
207
+ ...(data?.blockId ? { 'data-block-id': data.blockId } : {}),
208
+ }, label);
170
209
  }
171
210
  default:
172
211
  return extractPlainText(n);
@@ -5,7 +5,7 @@ import { $isLinkNode } from '@lexical/link';
5
5
  import { $createHorizontalRuleNode, $createImageNode, $isImageNode, $createCalloutNode, $createToggleContainerNode, $createToggleTitleNode, $createToggleContentNode, $createEquationNode, $isEquationNode, $createFootnoteNode, $isFootnoteNode, $createBlockAnchorNode, $isBlockAnchorNode, $createHtmlNode, $isHtmlNode, $createMermaidNode, $createC4Node, $createFrontmatterNode, $createCustomLinkNode, $createCustomListNode, $createDefinitionListNode, $createDefinitionTermNode, $createDefinitionDescriptionNode, $createCustomListItemNode, $createListItemParagraphBreakNode, $createTransclusionNode, } from '../editor/nodes/index.js';
6
6
  import { parseFormattedAlias } from '../editor/MarkdownShortcutsPlugin.js';
7
7
  import { $createTableNode, $createTableRowNode, $createTableCellNode, TableCellHeaderStates } from '@lexical/table';
8
- import { getFileType } from '../../utils/file-types.js';
8
+ import { wikiTargetToUrl, wikiLinkTargetToUrl } from '../../utils/file-types.js';
9
9
  // Set only while a *WithOffsets import is running, so convertText/convertInlineCode
10
10
  // can record spans without threading a collector parameter through every one of
11
11
  // this file's many recursive conversion functions. Lexical updates run their
@@ -271,7 +271,7 @@ function convertBlockNode(node) {
271
271
  const wikiLink = node;
272
272
  const target = wikiLink.value || '';
273
273
  const rawDisplayText = wikiLink.data?.alias || target;
274
- const url = getFileType(target) !== 'unknown' ? target : `${target}.md`;
274
+ const url = wikiTargetToUrl(target);
275
275
  const paragraph = $createParagraphNode();
276
276
  const link = $createCustomLinkNode(url);
277
277
  link.setWikiLinkOrigin(true);
@@ -861,35 +861,9 @@ function convertInlineNode(node) {
861
861
  return [$createTextNode('[[]]')];
862
862
  }
863
863
  const displayText = wikiLink.data?.alias || target;
864
- // Convert to URL, preserving semantic intent
865
- // Directory links (trailing slash) are preserved - navigation layer resolves them
866
- // Example: [[entities/people/]] → stays as entities/people/ (resolved to index.md at navigation time)
867
- let url;
868
- if (target.startsWith('#')) {
869
- // Anchor-only: #anchor → #anchor
870
- url = target;
871
- }
872
- else if (target.endsWith('/')) {
873
- // Directory link: preserve trailing slash for semantic clarity
874
- // Navigation layer will resolve to index.md or README.md
875
- url = target;
876
- }
877
- else if (target.includes('#')) {
878
- // Path with anchor: page#anchor → page.md#anchor (or dir/#anchor preserved)
879
- const [path, anchor] = target.split('#', 2);
880
- if (path.endsWith('/')) {
881
- // Directory with anchor - preserve for navigation layer
882
- url = target;
883
- }
884
- else {
885
- const pathWithExt = getFileType(path) !== 'unknown' ? path : `${path}.md`;
886
- url = `${pathWithExt}#${anchor}`;
887
- }
888
- }
889
- else {
890
- // Simple path: page → page.md (unless it already has a recognized extension)
891
- url = getFileType(target) !== 'unknown' ? target : `${target}.md`;
892
- }
864
+ // Convert to URL, preserving semantic intent (anchor, directory and
865
+ // extension handling live in wikiLinkTargetToUrl)
866
+ const url = wikiLinkTargetToUrl(target);
893
867
  const link = $createCustomLinkNode(url);
894
868
  // Marks this link as genuine author-written wiki-link syntax, so export
895
869
  // (convertLinkNode) always emits it back as a wiki-link even when a host
@@ -16,7 +16,8 @@ const wikiLinkOptions = { aliasDivider: '|' };
16
16
  const EMPTY_ALIAS_SENTINEL = '__EMPTY_ALIAS__';
17
17
  // Private-Use-Area sentinel marking a `!` that immediately precedes `[[`
18
18
  // (candidate transclusion/embed marker, #119). The next free codepoint after
19
- // `annotate-sentinels.ts`'s E000-E003 range and `stringify.ts`'s E004.
19
+ // `annotate-sentinels.ts`'s E000-E003 range and E004, which `stringify.ts`
20
+ // used as its force-escape placeholder until that moved to U+2BFF.
20
21
  //
21
22
  // Why substitute at all, rather than just checking "does the wikiLink node
22
23
  // have a `!` text sibling" after parsing: the micromark wiki-link tokenizer
@@ -145,7 +145,18 @@ function addCheckboxTextToOrderedLists(root) {
145
145
  // backslash-free, it is provably invisible to the existing intraword-
146
146
  // underscore and bracket-preservation post-processes below, so neither one
147
147
  // needs to change to account for it.
148
- const FORCE_ESCAPE_PLACEHOLDER = '\u{E004}';
148
+ //
149
+ // It must classify as punctuation, because it stands in for a backslash.
150
+ // mdast-util-to-markdown >= 2.1.3 leaves an underscore unescaped when both
151
+ // neighbours are neither whitespace nor punctuation (`a_b`), and it sees the
152
+ // placeholder, not the backslash. The previous placeholder, U+E004, is
153
+ // private-use and so classified as a word character: an underscore typed
154
+ // beside a preserved escape went out bare and re-parsed as emphasis. No
155
+ // private-use codepoint can be punctuation, so this is an assigned symbol:
156
+ // U+2BFF HELLSCHREIBER PAUSE SYMBOL (`So`), chosen because nothing writes
157
+ // it. It must stay in the BMP: upstream reads neighbours with `charCodeAt`,
158
+ // which would see half of a surrogate pair and call that a word character.
159
+ const FORCE_ESCAPE_PLACEHOLDER = '\u{2BFF}';
149
160
  // The character class the placeholder-restoration post-process (below) is
150
161
  // allowed to wrap in a backslash. Kept narrow — rather than matching any
151
162
  // character between two placeholder codepoints — so that if the placeholder
package/dist/styles.css CHANGED
@@ -717,6 +717,30 @@ body {
717
717
  font-weight: 600;
718
718
  }
719
719
 
720
+ /* Source badge (#192): trailing "↗" that navigates to the transcluded block.
721
+ It reuses `.editor-link` so the `modifier-held` / `links-clickable` cursor
722
+ rules apply unchanged; the rules below only size it down and cancel the
723
+ shared link hover underline/opacity, which look wrong on a lone glyph. */
724
+ .editor-transclusion-wrap {
725
+ display: inline;
726
+ }
727
+
728
+ .editor-transclusion-source {
729
+ margin-inline-start: 0.25em;
730
+ font-size: 0.75em;
731
+ line-height: 1;
732
+ vertical-align: super;
733
+ user-select: none;
734
+ }
735
+
736
+ .editor-link.editor-transclusion-source,
737
+ .editor-link.editor-transclusion-source:hover,
738
+ .modifier-held .editor-link.editor-transclusion-source:hover,
739
+ .links-clickable .editor-link.editor-transclusion-source:hover {
740
+ text-decoration: none;
741
+ opacity: 1;
742
+ }
743
+
720
744
  /* Tables */
721
745
  .editor-table {
722
746
  width: 100%;
@@ -2653,6 +2677,11 @@ body {
2653
2677
  text-decoration: underline !important;
2654
2678
  }
2655
2679
 
2680
+ /* The source badge is a lone glyph; an underline reads as noise in print */
2681
+ .editor-link.editor-transclusion-source {
2682
+ text-decoration: none !important;
2683
+ }
2684
+
2656
2685
  /* Tables */
2657
2686
  .editor-table {
2658
2687
  page-break-inside: auto !important;
@@ -8,3 +8,19 @@ export type FileType = 'markdown' | 'image' | 'pdf' | 'mermaid' | 'code' | 'rema
8
8
  * @returns The detected file type
9
9
  */
10
10
  export declare function getFileType(path: string | null): FileType;
11
+ /**
12
+ * Normalise a wiki-link / transclusion target to the URL form carried on a
13
+ * link node: a target with a recognised extension is kept as-is, anything else
14
+ * gets `.md` appended (`[[page]]` -> `page.md`). Shared by the mapper and the
15
+ * transclusion renderer so `[[file#^id]]` and `![[file#^id]]` hand the host the
16
+ * same `url` shape.
17
+ */
18
+ export declare function wikiTargetToUrl(target: string): string;
19
+ /**
20
+ * Full wiki-link target -> URL derivation, covering the anchor and directory
21
+ * forms the bare {@link wikiTargetToUrl} does not: `#anchor` and `dir/` are
22
+ * kept, `page#anchor` becomes `page.md#anchor`. Shared by the mapper's inline
23
+ * wiki-link conversion and the transclusion renderer's nested links, so a link
24
+ * inside transcluded content navigates to the same URL as a top-level one.
25
+ */
26
+ export declare function wikiLinkTargetToUrl(target: string): string;
@@ -44,3 +44,34 @@ export function getFileType(path) {
44
44
  return 'code';
45
45
  return 'unknown';
46
46
  }
47
+ /**
48
+ * Normalise a wiki-link / transclusion target to the URL form carried on a
49
+ * link node: a target with a recognised extension is kept as-is, anything else
50
+ * gets `.md` appended (`[[page]]` -> `page.md`). Shared by the mapper and the
51
+ * transclusion renderer so `[[file#^id]]` and `![[file#^id]]` hand the host the
52
+ * same `url` shape.
53
+ */
54
+ export function wikiTargetToUrl(target) {
55
+ return getFileType(target) !== 'unknown' ? target : `${target}.md`;
56
+ }
57
+ /**
58
+ * Full wiki-link target -> URL derivation, covering the anchor and directory
59
+ * forms the bare {@link wikiTargetToUrl} does not: `#anchor` and `dir/` are
60
+ * kept, `page#anchor` becomes `page.md#anchor`. Shared by the mapper's inline
61
+ * wiki-link conversion and the transclusion renderer's nested links, so a link
62
+ * inside transcluded content navigates to the same URL as a top-level one.
63
+ */
64
+ export function wikiLinkTargetToUrl(target) {
65
+ // Anchor-only (#anchor) and directory links (trailing slash) are preserved;
66
+ // the navigation layer resolves directories to index.md / README.md.
67
+ if (target.startsWith('#') || target.endsWith('/'))
68
+ return target;
69
+ if (target.includes('#')) {
70
+ const [path, anchor] = target.split('#', 2);
71
+ // Directory with anchor: preserve for the navigation layer
72
+ if (path.endsWith('/'))
73
+ return target;
74
+ return `${wikiTargetToUrl(path)}#${anchor}`;
75
+ }
76
+ return wikiTargetToUrl(target);
77
+ }
@@ -157,6 +157,13 @@ block content" (FR-015 — any `^id`-carrying block is a valid target, not
157
157
  just checkboxes) without committing to full visual parity for every mdast
158
158
  construct.
159
159
 
160
+ > **Amended 2026-11-13 — the "inert link text" part of this clause no longer
161
+ > holds.** A `wikiLink` inside transcluded content now renders as a live
162
+ > anchor, and every transclusion carries a trailing "↗" source badge that
163
+ > navigates to its own source block. See ADR-192
164
+ > (`adr-192-transclusion-source-affordance.md`). The renderer is still partial
165
+ > and still render-only; only link navigation changed.
166
+
160
167
  ### 9. `openLink` gets an additive optional `blockId` parameter
161
168
 
162
169
  A host that has not implemented block-aware navigation still receives
@@ -0,0 +1,103 @@
1
+ # ADR-192: Transclusions Navigate to Their Source Through a Trailing Badge
2
+
3
+ **Date:** 2026-11-13
4
+ **Status:** Accepted
5
+ **Supersedes:** none
6
+ **Amends:** ADR-119 (§8, nested link navigation)
7
+ **Issue:** #192 (verveguy/liminis-editor)
8
+
9
+ ## Context
10
+
11
+ `![[file#^id]]` transclusion (ADR-119, #119) renders the referenced block
12
+ inline, but the rendered output was a dead end: only `<span>`s, no `<a>`, so
13
+ `LinkClickPlugin` — which reacts to `a[data-href]` — never saw anything to
14
+ follow. A `[[file#^id]]` link was navigable; the same block embedded was not.
15
+
16
+ The block-scoped `OPEN_LINK { url, blockId }` path already exists (ADR-119 §9),
17
+ so the only missing piece was a link-shaped element on the transclusion.
18
+
19
+ ## Decision
20
+
21
+ ### 1. A trailing "↗" badge, not a whole-container link
22
+
23
+ Every transclusion renders `<a class="editor-link editor-transclusion-source"
24
+ data-href data-block-id>↗</a>` after its state span, in all four states
25
+ (resolved, unresolved, circular, depth-exceeded). It is a *sibling* of the
26
+ content, never an ancestor of it, so:
27
+
28
+ - `target.closest('a')` in `LinkClickPlugin` always finds the innermost anchor:
29
+ a wiki link inside the transcluded content wins over the badge, with no
30
+ `stopPropagation` ordering to maintain;
31
+ - no `<a>`-in-`<a>`;
32
+ - caret placement and selection inside the transcluded text are untouched.
33
+
34
+ `LinkClickPlugin`, `TransclusionNode`, `exportDOM` and the mdast round-trip are
35
+ unchanged. The badge is presentation only.
36
+
37
+ ### 2. The badge carries `editor-link` but not `data-wiki-link`
38
+
39
+ `editor-link` makes the existing `modifier-held` / `links-clickable` cursor
40
+ rules apply with no new cursor CSS. `data-wiki-link` is deliberately absent:
41
+ `WikiLinkExistencePlugin` queries `a[data-wiki-link="true"]` and would resolve
42
+ the badge and could style it as a broken link.
43
+
44
+ ### 3. `data-href` is normalised exactly as a wiki link is
45
+
46
+ `wikiTargetToUrl(target)` (in `src/utils/file-types.ts`) appends `.md` to a
47
+ target without a recognised extension. The mapper's duplicated expressions now
48
+ call it too. A host that handles block-scoped links therefore receives the same
49
+ `url` shape from `![[x#^id]]` as from `[[x#^id]]`.
50
+
51
+ ### 4. Nested wiki links in transcluded content are now live
52
+
53
+ ADR-119 §8 left `wikiLink` inside transcluded content as inert text. That had to
54
+ change: with a badge present but nested links inert, the requirement that a
55
+ nested link navigate to *its own* target would pass vacuously. They render as
56
+ `<a class="editor-link" data-href data-block-id?>`, again without
57
+ `data-wiki-link` (the existence plugin only walks the editor's own DOM, and
58
+ resolver calls per nested link are not wanted).
59
+
60
+ ### 5. The badge renders from props, not from resolved state
61
+
62
+ `TransclusionComponent` passes `{ file, blockId }` from its props, so the badge
63
+ is present and stable across debounced re-resolves. It is absent only in the
64
+ loading state, which is not one of the four states in scope. A nested
65
+ `wikiEmbed` passes its own `{ file, blockId }`, so each level navigates to its
66
+ own source.
67
+
68
+ ### 6. `contenteditable="false"` and accessible name
69
+
70
+ The badge is `contenteditable="false"` so the caret does not land inside it. It
71
+ has `title` and `aria-label` "Open source block". It has no `href` or
72
+ `tabindex`, matching every other editor link, so keyboard activation is
73
+ whatever existing links support (nothing new).
74
+
75
+ ## Consequences — what this costs
76
+
77
+ - **An always-present "↗" glyph** in transclusions, including editable mode.
78
+ Existing transclusions grow by one small element; a host that screenshots or
79
+ styles transclusions will see it. It can be restyled or hidden via
80
+ `.editor-transclusion-source` without changing the emitted event.
81
+ - **A larger click target in read-only mode.** A plain click on the badge
82
+ navigates there, where previously nothing did. Nested wiki links in
83
+ transcluded content also now navigate on click, which they never did.
84
+ - **A small `contenteditable="false"` island** inside editable content, next to
85
+ an inline decorator. It was verified in jsdom (a plain click is not
86
+ default-prevented and does not navigate) but not in a real browser, where
87
+ caret behaviour around inline decorators is Lexical's and the browser's call.
88
+ - **Not keyboard-focusable.** Consistent with existing links, but it means the
89
+ affordance is pointer-only until links gain `tabindex`/`href` generally.
90
+ - **The whole transclusion is not a link target.** Clicking the transcluded text
91
+ still does nothing; only the badge navigates. That was a design choice, and a
92
+ whole-container target can be added later without changing the event.
93
+ - **Unresolved/circular/depth-exceeded states pass the block id along.** The
94
+ host may ignore it if the block no longer exists; the file still opens, which
95
+ is what a user repairing a broken reference needs.
96
+ - **Not done: making the transcluded checkbox writable** (#181) and host-side
97
+ scroll-to-block (shadoworg/liminis-notes#1318).
98
+
99
+ ## References
100
+
101
+ - ADR-119 — transclusion node and renderer (§8 amended, §9 reused)
102
+ - ADR-122 — block-anchor badge (visual vocabulary)
103
+ - Issue #192 (this ADR), #119 (transclusion), #181 (one logical item)
@@ -0,0 +1,101 @@
1
+ # ADR-194: C4 Manual Positions Are Merged at the Hand-Edit Commit, Not Cleared
2
+
3
+ **Date:** 2026-11-15
4
+ **Status:** Accepted
5
+ **Supersedes:** none
6
+ **Amends:** none
7
+ **Issue:** #194 (verveguy/liminis-editor)
8
+
9
+ ## Context
10
+
11
+ `@liminis/diagrams` 0.2.0 lets a user add elements and relationships on the
12
+ rendered C4 diagram. The renderer reports `onEdit(edit, { positions })`; the
13
+ host turns the edit into source with `applyC4Edit` and stores the reported
14
+ `positions`, which is the complete, already-merged map.
15
+
16
+ The C4 node could not adopt this. `C4Component` had an effect ("TASK 7") that
17
+ cleared the whole manual layout whenever the set of element ids differed from
18
+ the layout's keys. Adding one box from the diagram changes that set, so every
19
+ position the user had arranged would have been discarded the moment they added
20
+ something.
21
+
22
+ ## Decision
23
+
24
+ ### 1. A diagram edit replaces code and layout in one `editor.update`
25
+
26
+ `handleEdit` reads the source from the **node** (never from component state,
27
+ which lags by a render), calls `applyC4Edit`, and on success calls
28
+ `setCode(result.source)` and `setManualLayout({ positions: context.positions })`
29
+ in the same update. One update is one history entry, so a single undo restores
30
+ both. `context.positions` is stored as received: not filtered, not merged with
31
+ the old layout. On `{ ok: false }` nothing is mutated, so there is no history
32
+ entry; `code` and `message` are logged with `console.warn`.
33
+
34
+ ### 2. A hand edit merges at the commit, in the same update as `setCode`
35
+
36
+ The only point where a hand edit reaches the Lexical node is `onHide`
37
+ (`node.setCode(codeValue)`). The merge runs there: `mergeManualLayout` keeps the
38
+ positions of ids still present in the parsed source and any reserved `__` key
39
+ (such as `__legend__`), and drops the rest. It is a no-op (same object) when
40
+ nothing is dropped, and yields `undefined` when nothing is left. A source that
41
+ fails to parse, or parses with errors, never drops anything. An unchanged close
42
+ no longer dirties the node.
43
+
44
+ ### 3. The display renders from a `{ code, manualLayout }` snapshot
45
+
46
+ `C4DiagramDisplay` reads both from the node together, in its initial state and in
47
+ `registerUpdateListener`, instead of taking `code` from a prop that is synced in
48
+ an effect. A diagram edit or undo/redo therefore never renders new positions
49
+ against old code (the "visible jump" the diagrams recipe warns about).
50
+
51
+ ### Alternatives rejected
52
+
53
+ - **An effect that merges when ids change.** It can run with the new layout
54
+ (containing the just-placed id) before the new code reaches the display, see an
55
+ id absent from the parsed diagram, and drop the position it was meant to keep.
56
+ Undo and redo have the same ordering problem. Telling diagram-originated
57
+ changes from hand edits with a ref flag is order-dependent and fragile.
58
+
59
+ ## Consequences — what this costs
60
+
61
+ - **The layout is no longer cleared on an id-set change.** A hand-added element
62
+ is auto-placed beside existing pinned ones, and the result may not look as
63
+ tidy as a full re-layout did. "Reset to auto layout" remains the way to start
64
+ over.
65
+ - **A renamed id loses its position.** The old id is dropped and the new id has
66
+ none; the merge cannot tell a rename from a remove plus an add.
67
+ - **Clearing the source drops every position.** An empty source parses cleanly
68
+ with zero elements, so all positions go. Only a parse that fails, or reports
69
+ errors, is protected.
70
+ - **`setCode` callers other than the editor commit are not covered.** The merge
71
+ lives in `onHide`, not in `C4Node.setCode`. Anything else that later changes a
72
+ C4 node's code (a host, an import, collaboration) must merge the layout itself
73
+ or leave stale positions for removed ids. Stale keys are harmless to rendering
74
+ (the layout ignores unknown ids) but are written to the `@layout` fence meta
75
+ until the next hand edit prunes them. `C4Node` was deliberately not given this
76
+ logic: it must not import `@liminis/diagrams` statically (ADR-075, ADR-079).
77
+ - **Structural editing is only available in layout-edit mode.** The
78
+ interactive renderer is only mounted while the user is editing layout, and the
79
+ renderer shows its add affordances only in edit mode.
80
+ - **Hand-edit merging is validated against `parseC4` element ids**, which include
81
+ boundaries and nested elements (covered by tests). Whether the renderer keys
82
+ boundary positions identically was checked against the 0.2.0 type
83
+ declarations, not against a rendered diagram.
84
+
85
+ > **Amended 2026-11-16 — structural editing now shows one context menu.** The
86
+ > clause "Structural editing is only available in layout-edit mode" still holds,
87
+ > but trying the first version by hand showed that layout mode opened two
88
+ > overlapping menus: the renderer's own add-element menu and the editor's
89
+ > `DiagramContextMenu` (the renderer called `preventDefault()` but not
90
+ > `stopPropagation()`, so the event also reached the container's
91
+ > `onContextMenu`). `@liminis/diagrams` 0.2.1 added an `onContextMenu` hook that
92
+ > hands the host the diagram's items instead of drawing a menu. The C4 node now
93
+ > passes it and renders **one** `DiagramContextMenu`, with the diagram's items
94
+ > (elements, then boundaries) as their own groups above the editor's items; over
95
+ > a node the diagram offers none, so only the editor's items show. A long-press
96
+ > opens the same menu. Choosing an item calls the item's `select()`, so
97
+ > placement, the label prompt, `onEdit` and the single undo step are the
98
+ > diagram's own. The cost: the menu's look is now the editor's, not the
99
+ > renderer's, and the editor depends on `@liminis/diagrams` >= 0.2.1 (the hook
100
+ > is opt-in; without it the renderer's behaviour is unchanged). Guarded by
101
+ > `C4Component.contextmenu.test.tsx`, which uses the real renderer.