@liminis/editor 0.7.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.
package/README.md CHANGED
@@ -46,10 +46,10 @@ produce a broken editor context — peering is what prevents both.
46
46
 
47
47
  ```bash
48
48
  pnpm add react@^19 react-dom@^19 \
49
- lexical@^0.52 @lexical/react@^0.52 @lexical/code@^0.52 \
50
- @lexical/code-prism@^0.52 @lexical/link@^0.52 @lexical/list@^0.52 \
51
- @lexical/mark@^0.52 @lexical/markdown@^0.52 @lexical/rich-text@^0.52 \
52
- @lexical/selection@^0.52 @lexical/table@^0.52 @lexical/utils@^0.52
49
+ lexical@^0.53 @lexical/react@^0.53 @lexical/code@^0.53 \
50
+ @lexical/code-prism@^0.53 @lexical/link@^0.53 @lexical/list@^0.53 \
51
+ @lexical/mark@^0.53 @lexical/markdown@^0.53 @lexical/rich-text@^0.53 \
52
+ @lexical/selection@^0.53 @lexical/table@^0.53 @lexical/utils@^0.53
53
53
  ```
54
54
 
55
55
  > **The Lexical peer ranges are single-caret, not a wide band.** Lexical is
@@ -14,7 +14,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
14
14
  */
15
15
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
16
16
  import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
17
- import { $getRoot, $isTextNode } from 'lexical';
17
+ import { $getRoot, $isElementNode, $isTextNode } from 'lexical';
18
18
  import { useCorrectionStore } from '../../stores/correctionStore.js';
19
19
  import { useEditorHost } from '../../host/context.js';
20
20
  import { parseCorrectionsYaml, serializeCorrectionsYaml, mergeCorrection, isExistingCanonical, } from './correction-yaml.js';
@@ -206,10 +206,9 @@ export function CorrectionPanelPlugin() {
206
206
  node.setTextContent(replaced);
207
207
  return;
208
208
  }
209
- if ('getChildren' in node && typeof node.getChildren === 'function') {
210
- for (const child of node.getChildren()) {
209
+ if ($isElementNode(node)) {
210
+ for (const child of node.getChildren())
211
211
  walk(child);
212
- }
213
212
  }
214
213
  };
215
214
  walk($getRoot());
@@ -11,36 +11,67 @@ import { mergeRegister } from '@lexical/utils';
11
11
  import { $getNodeByKey, $getSelection, $isNodeSelection, COMMAND_PRIORITY_HIGH, KEY_ESCAPE_COMMAND, SELECTION_CHANGE_COMMAND, } from 'lexical';
12
12
  import { Move, RotateCcw } from 'lucide-react';
13
13
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
14
- import { parseC4, validateC4, layoutC4Diagram } from '@liminis/diagrams/core';
14
+ import { parseC4, validateC4, layoutC4Diagram, applyC4Edit } from '@liminis/diagrams/core';
15
15
  import { C4Renderer, C4ErrorDisplay, C4InteractiveRenderer } from '@liminis/diagrams/react';
16
16
  import { $isC4Node } from './C4Node.js';
17
17
  import { DiagramContextMenu, useDiagramContextMenu } from './DiagramContextMenu.js';
18
- function C4DiagramDisplay({ code, nodeKey, onDoubleClick, isEditable, }) {
18
+ import { mergeManualLayout } from './c4-layout.js';
19
+ import { scrollContainerFor } from '../scrollContainer.js';
20
+ // =============================================================================
21
+ // LIVE ORIGIN-SHIFT COMPENSATION (ADR-203, amended for #206)
22
+ // =============================================================================
23
+ /**
24
+ * Scroll `target` by up to (`dx`, `dy`) and return how far it actually moved. The
25
+ * browser clamps to the scroll range, and snaps to whole device pixels, so the
26
+ * result can fall short of what was asked. `instant` so a host's `scroll-behavior:
27
+ * smooth` cannot defer the scroll past the layout phase.
28
+ */
29
+ function scrollBy(target, dx, dy) {
30
+ const left = target.scrollLeft;
31
+ const top = target.scrollTop;
32
+ if (typeof target.scrollTo === 'function') {
33
+ target.scrollTo({
34
+ left: dx !== 0 ? left + dx : undefined,
35
+ top: dy !== 0 ? top + dy : undefined,
36
+ behavior: 'instant',
37
+ });
38
+ }
39
+ else {
40
+ if (dx !== 0)
41
+ target.scrollLeft = left + dx;
42
+ if (dy !== 0)
43
+ target.scrollTop = top + dy;
44
+ }
45
+ return { dx: target.scrollLeft - left, dy: target.scrollTop - top };
46
+ }
47
+ function C4DiagramDisplay({ nodeKey, onDoubleClick, isEditable, }) {
19
48
  const [editor] = useLexicalComposerContext();
20
49
  const containerRef = useRef(null);
21
50
  const [isDarkMode, setIsDarkMode] = useState(false);
22
51
  const [showToolbar, setShowToolbar] = useState(false);
23
52
  const [isEditingLayout, setIsEditingLayout] = useState(false);
24
53
  const contextMenu = useDiagramContextMenu();
25
- const previousCodeRef = useRef(code);
26
- // Read manual layout from the node
27
- const [manualLayout, setManualLayout] = useState(() => {
54
+ const unabsorbedShiftRef = useRef({ x: 0, y: 0 });
55
+ // Read code and manual layout from the node as one snapshot. Rendering from
56
+ // the node (not from a prop synced in an effect) means a diagram edit or an
57
+ // undo/redo never renders new positions against old code, or vice versa.
58
+ const [snapshot, setSnapshot] = useState(() => {
28
59
  return editor.getEditorState().read(() => {
29
60
  const node = $getNodeByKey(nodeKey);
30
- if ($isC4Node(node)) {
31
- return node.getManualLayout();
32
- }
33
- return undefined;
61
+ return $isC4Node(node)
62
+ ? { code: node.getCode(), manualLayout: node.getManualLayout() }
63
+ : { code: '', manualLayout: undefined };
34
64
  });
35
65
  });
36
- // Sync manual layout from node when it changes externally (e.g., undo/redo)
66
+ const { code, manualLayout } = snapshot;
67
+ // Keep the snapshot in step with the node (diagram edits, drags, undo/redo).
37
68
  useEffect(() => {
38
69
  return editor.registerUpdateListener(({ editorState }) => {
39
70
  editorState.read(() => {
40
71
  const node = $getNodeByKey(nodeKey);
41
72
  if ($isC4Node(node)) {
42
- const nodeLayout = node.getManualLayout();
43
- setManualLayout(nodeLayout);
73
+ const next = { code: node.getCode(), manualLayout: node.getManualLayout() };
74
+ setSnapshot((prev) => prev.code === next.code && prev.manualLayout === next.manualLayout ? prev : next);
44
75
  }
45
76
  });
46
77
  });
@@ -74,32 +105,12 @@ function C4DiagramDisplay({ code, nodeKey, onDoubleClick, isEditable, }) {
74
105
  const positions = manualLayout?.positions;
75
106
  return layoutC4Diagram(parseResult.diagram, undefined, positions);
76
107
  }, [parseResult, manualLayout]);
77
- // TASK 7: Clear manual layout when DSL code changes (elements added/removed)
78
- useEffect(() => {
79
- if (manualLayout && code !== previousCodeRef.current && parseResult.diagram) {
80
- const newElementIds = new Set(parseResult.diagram.elements.map(e => e.id));
81
- const oldElementIds = new Set(Object.keys(manualLayout.positions).filter(id => !id.startsWith('__')));
82
- // Check if elements were added or removed
83
- const hasChanges = newElementIds.size !== oldElementIds.size ||
84
- [...newElementIds].some(id => !oldElementIds.has(id)) ||
85
- [...oldElementIds].some(id => !newElementIds.has(id));
86
- if (hasChanges) {
87
- // Clear manual layout
88
- editor.update(() => {
89
- const node = $getNodeByKey(nodeKey);
90
- if ($isC4Node(node)) {
91
- node.setManualLayout(undefined);
92
- }
93
- });
94
- setIsEditingLayout(false);
95
- }
96
- }
97
- previousCodeRef.current = code;
98
- }, [code, manualLayout, parseResult.diagram, editor, nodeKey]);
99
- // TASK 6: Handle position changes with Lexical undo integration
108
+ // Handle position changes with Lexical undo integration
100
109
  // The update listener above will sync manualLayout state from the node,
101
110
  // so we only need to write to the Lexical node here.
102
111
  const handlePositionChange = useCallback((newPositions) => {
112
+ // The drag is over: whatever could not be absorbed stays as an accepted shift.
113
+ unabsorbedShiftRef.current = { x: 0, y: 0 };
103
114
  editor.update(() => {
104
115
  const node = $getNodeByKey(nodeKey);
105
116
  if ($isC4Node(node)) {
@@ -107,6 +118,36 @@ function C4DiagramDisplay({ code, nodeKey, onDoubleClick, isEditable, }) {
107
118
  }
108
119
  });
109
120
  }, [editor, nodeKey]);
121
+ // Apply a structural edit from the diagram. Code and layout are written in
122
+ // one update so there is one history entry and no frame renders one without
123
+ // the other. The source comes from the node, never from component state,
124
+ // which can lag. A rejected edit mutates nothing, so no history entry.
125
+ const handleEdit = useCallback((edit, context) => {
126
+ editor.update(() => {
127
+ const node = $getNodeByKey(nodeKey);
128
+ if (!$isC4Node(node))
129
+ return;
130
+ const result = applyC4Edit(node.getCode(), edit);
131
+ if (!result.ok) {
132
+ console.warn(`C4 edit rejected (${result.code}): ${result.message}`);
133
+ return;
134
+ }
135
+ node.setCode(result.source);
136
+ node.setManualLayout({ positions: context.positions });
137
+ });
138
+ }, [editor, nodeKey]);
139
+ // The interactive renderer hands us the diagram's menu items instead of
140
+ // drawing its own menu, so the editor shows exactly one menu: its own items
141
+ // plus the diagram's, as separate groups. `items` is [] over a node.
142
+ const { showAt: showMenuAt } = contextMenu;
143
+ const handleDiagramContextMenu = useCallback((request) => {
144
+ showMenuAt(request.clientX, request.clientY, containerRef, request.items.map((item) => ({
145
+ id: item.id,
146
+ label: item.label,
147
+ group: item.group,
148
+ onSelect: () => item.select(),
149
+ })));
150
+ }, [showMenuAt]);
110
151
  // Handle reset to auto layout
111
152
  const handleResetLayout = useCallback(() => {
112
153
  editor.update(() => {
@@ -115,7 +156,6 @@ function C4DiagramDisplay({ code, nodeKey, onDoubleClick, isEditable, }) {
115
156
  node.setManualLayout(undefined);
116
157
  }
117
158
  });
118
- setManualLayout(undefined);
119
159
  setIsEditingLayout(false);
120
160
  }, [editor, nodeKey]);
121
161
  // Exit edit mode when clicking outside or pressing Escape
@@ -142,6 +182,42 @@ function C4DiagramDisplay({ code, nodeKey, onDoubleClick, isEditable, }) {
142
182
  document.removeEventListener('mousedown', handleMouseDown);
143
183
  };
144
184
  }, [isEditingLayout]);
185
+ // Leaving layout mode unmounts the interactive renderer, possibly mid-drag, with
186
+ // neither `onPositionChange` nor a balancing reverse shift. Drop whatever remainder
187
+ // that drag left, so the next one starts from zero instead of inheriting it.
188
+ useEffect(() => {
189
+ if (!isEditingLayout)
190
+ unabsorbedShiftRef.current = { x: 0, y: 0 };
191
+ }, [isEditingLayout]);
192
+ // Absorb the origin shift the renderer reports while a node is dragged past the
193
+ // top or left edge (liminis-diagrams `holdOrigin={false}`, ADR-203 amended for
194
+ // #206). Called from the renderer's layout effect, before paint, with the
195
+ // displacement since the previous commit; scrolling by the same amount keeps the
196
+ // rest of the diagram still on screen. Vertically that is the nearest scroller
197
+ // (or the document): the grown strip is part of the container's box, so nothing
198
+ // is clipped, and with no scroll range the shift is accepted. Horizontally the
199
+ // container scrolls if it overflows; the svg shrinks to fit (`max-width: 100%`),
200
+ // so normally it does not, and the diagram just re-centres, as it does past the
201
+ // right edge. A cancelled drag reports the reverse shift, which undoes this.
202
+ // `unabsorbedShiftRef` is what the scrolling could not take (a clamped range, or a
203
+ // scroll position snapped to whole pixels). It is carried into the next frame so
204
+ // rounding cannot accumulate into a visible drift, and so that a reverse shift
205
+ // unwinds exactly what was scrolled, no more.
206
+ const handleOriginShift = useCallback(({ dx, dy }) => {
207
+ const container = containerRef.current;
208
+ if (!container)
209
+ return;
210
+ const owed = unabsorbedShiftRef.current;
211
+ if (dy !== 0) {
212
+ const scroller = scrollContainerFor(container) ?? document.scrollingElement;
213
+ const want = dy + owed.y;
214
+ owed.y = scroller ? want - scrollBy(scroller, 0, want).dy : want;
215
+ }
216
+ if (dx !== 0) {
217
+ const want = dx + owed.x;
218
+ owed.x = want - scrollBy(container, want, 0).dx;
219
+ }
220
+ }, []);
145
221
  if (!layout || !parseResult.diagram) {
146
222
  return _jsx(C4ErrorDisplay, { errors: parseResult.errors, isDarkMode: isDarkMode });
147
223
  }
@@ -153,11 +229,16 @@ function C4DiagramDisplay({ code, nodeKey, onDoubleClick, isEditable, }) {
153
229
  }
154
230
  }, onMouseEnter: () => setShowToolbar(true), onMouseLeave: () => setShowToolbar(false), className: "c4-renderer c4-diagram-container", style: {
155
231
  display: 'flex',
156
- justifyContent: 'center',
232
+ // `safe`: when the svg overflows, plain centring makes the left overflow
233
+ // unreachable by scrolling, so left growth could never be scrolled back.
234
+ justifyContent: 'safe center',
157
235
  padding: '1rem',
158
236
  cursor: isEditingLayout ? 'default' : 'pointer',
159
237
  minHeight: '100px',
160
238
  overflowX: 'auto',
239
+ // Scroll anchoring would be a second, uncoordinated adjustment on top of
240
+ // the origin-shift scroll compensation.
241
+ overflowAnchor: 'none',
161
242
  position: 'relative',
162
243
  }, children: [isEditable && (showToolbar || isEditingLayout) && (_jsxs("div", { style: {
163
244
  position: 'absolute',
@@ -198,7 +279,7 @@ function C4DiagramDisplay({ code, nodeKey, onDoubleClick, isEditable, }) {
198
279
  cursor: 'pointer',
199
280
  backgroundColor: 'var(--liminis-editor-muted-100)',
200
281
  color: 'var(--liminis-editor-muted-foreground)',
201
- }, children: _jsx(RotateCcw, { size: 16 }) }))] })), isEditingLayout && parseResult.diagram ? (_jsx(C4InteractiveRenderer, { diagram: parseResult.diagram, isDarkMode: isDarkMode, isEditMode: isEditingLayout, manualPositions: manualPositions, onPositionChange: handlePositionChange })) : (_jsx(C4Renderer, { layout: layout, isDarkMode: isDarkMode })), _jsx(DiagramContextMenu, { ...contextMenu.props, onEditText: isEditable ? onDoubleClick : undefined, onEditLayout: isEditable ? () => setIsEditingLayout(prev => !prev) : undefined, onResetLayout: isEditable ? handleResetLayout : undefined, isEditingLayout: isEditingLayout, hasManualLayout: !!manualLayout })] }));
282
+ }, children: _jsx(RotateCcw, { size: 16 }) }))] })), isEditingLayout && parseResult.diagram ? (_jsx(C4InteractiveRenderer, { diagram: parseResult.diagram, isDarkMode: isDarkMode, isEditMode: isEditingLayout, manualPositions: manualPositions, onPositionChange: handlePositionChange, holdOrigin: false, onOriginShift: handleOriginShift, onEdit: handleEdit, onContextMenu: handleDiagramContextMenu })) : (_jsx(C4Renderer, { layout: layout, isDarkMode: isDarkMode })), _jsx(DiagramContextMenu, { ...contextMenu.props, onEditText: isEditable ? onDoubleClick : undefined, onEditLayout: isEditable ? () => setIsEditingLayout(prev => !prev) : undefined, onResetLayout: isEditable ? handleResetLayout : undefined, isEditingLayout: isEditingLayout, hasManualLayout: !!manualLayout })] }));
202
283
  }
203
284
  // =============================================================================
204
285
  // C4 EDITOR
@@ -231,8 +312,15 @@ export default function C4Component({ code, nodeKey, }) {
231
312
  setShowEditor(false);
232
313
  editor.update(() => {
233
314
  const node = $getNodeByKey(nodeKey);
234
- if ($isC4Node(node)) {
235
- node.setCode(codeValue);
315
+ if (!$isC4Node(node) || node.getCode() === codeValue)
316
+ return;
317
+ // Hand edit: keep positions of ids that still exist, drop the rest, in
318
+ // the same update as the code so undo restores both in one step.
319
+ const layout = node.getManualLayout();
320
+ const merged = mergeManualLayout(codeValue, layout);
321
+ node.setCode(codeValue);
322
+ if (merged !== layout) {
323
+ node.setManualLayout(merged);
236
324
  }
237
325
  });
238
326
  }, [editor, codeValue, nodeKey]);
@@ -274,7 +362,7 @@ export default function C4Component({ code, nodeKey, }) {
274
362
  if (showEditor && isEditable) {
275
363
  return (_jsx(C4Editor, { code: codeValue, setCode: setCodeValue, onClose: onHide }));
276
364
  }
277
- return (_jsx(C4DiagramDisplay, { code: codeValue, nodeKey: nodeKey, isEditable: isEditable, onDoubleClick: () => {
365
+ return (_jsx(C4DiagramDisplay, { nodeKey: nodeKey, isEditable: isEditable, onDoubleClick: () => {
278
366
  if (isEditable) {
279
367
  setShowEditor(true);
280
368
  }
@@ -2,11 +2,23 @@
2
2
  * Shared context menu overlay for diagram nodes (C4, Mermaid).
3
3
  * Provides "Copy image to clipboard" and optional diagram-specific actions.
4
4
  */
5
+ /**
6
+ * An extra action a diagram contributes to the menu (e.g. C4 "add element").
7
+ * Items sharing a `group` are shown together; groups are separated from each
8
+ * other and from the editor's own items.
9
+ */
10
+ export interface DiagramMenuItem {
11
+ id: string;
12
+ label: string;
13
+ group: string;
14
+ onSelect: () => void;
15
+ }
5
16
  export interface DiagramContextMenuState {
6
17
  visible: boolean;
7
18
  x: number;
8
19
  y: number;
9
20
  containerRef: React.RefObject<HTMLElement | null> | null;
21
+ items: DiagramMenuItem[];
10
22
  }
11
23
  export interface DiagramContextMenuProps {
12
24
  visible: boolean;
@@ -24,16 +36,24 @@ export interface DiagramContextMenuProps {
24
36
  isEditingLayout?: boolean;
25
37
  /** Whether manual layout exists (show reset option) */
26
38
  hasManualLayout?: boolean;
39
+ /**
40
+ * Diagram-contributed items, shown above the editor's own items as one
41
+ * group per `group` value. Absent or empty for diagrams that have none
42
+ * (Mermaid), which leaves the menu unchanged.
43
+ */
44
+ items?: DiagramMenuItem[];
27
45
  }
28
46
  /**
29
47
  * Hook to manage diagram context menu state.
30
48
  */
31
49
  export declare function useDiagramContextMenu(): {
32
50
  show: (e: React.MouseEvent, containerRef: React.RefObject<HTMLElement | null>) => void;
51
+ showAt: (x: number, y: number, containerRef: React.RefObject<HTMLElement | null>, items: DiagramMenuItem[]) => void;
33
52
  props: {
34
53
  visible: boolean;
35
54
  x: number;
36
55
  y: number;
56
+ items: DiagramMenuItem[];
37
57
  onCopyImage: () => Promise<void>;
38
58
  onClose: () => void;
39
59
  };
@@ -42,4 +62,4 @@ export declare function useDiagramContextMenu(): {
42
62
  * Context menu overlay component. Uses CSS variables for theming
43
63
  * with light/dark hex fallbacks for environments without VS Code vars.
44
64
  */
45
- export declare function DiagramContextMenu({ visible, x, y, onCopyImage, onClose, onEditText, onEditLayout, onResetLayout, isEditingLayout, hasManualLayout, }: DiagramContextMenuProps): JSX.Element | null;
65
+ export declare function DiagramContextMenu({ visible, x, y, onCopyImage, onClose, onEditText, onEditLayout, onResetLayout, isEditingLayout, hasManualLayout, items, }: DiagramContextMenuProps): JSX.Element | null;
@@ -15,6 +15,7 @@ export function useDiagramContextMenu() {
15
15
  x: 0,
16
16
  y: 0,
17
17
  containerRef: null,
18
+ items: [],
18
19
  });
19
20
  const show = useCallback((e, containerRef) => {
20
21
  e.preventDefault();
@@ -24,8 +25,17 @@ export function useDiagramContextMenu() {
24
25
  x: e.clientX,
25
26
  y: e.clientY,
26
27
  containerRef,
28
+ items: [],
27
29
  });
28
30
  }, []);
31
+ /**
32
+ * Open the menu at a viewport point with diagram-contributed items. Used
33
+ * when the diagram owns the contextmenu event and hands the host its items,
34
+ * so there is still exactly one menu.
35
+ */
36
+ const showAt = useCallback((x, y, containerRef, items) => {
37
+ setState({ visible: true, x, y, containerRef, items });
38
+ }, []);
29
39
  const close = useCallback(() => {
30
40
  setState((prev) => ({ ...prev, visible: false }));
31
41
  }, []);
@@ -37,10 +47,12 @@ export function useDiagramContextMenu() {
37
47
  }, [state.containerRef, close]);
38
48
  return {
39
49
  show,
50
+ showAt,
40
51
  props: {
41
52
  visible: state.visible,
42
53
  x: state.x,
43
54
  y: state.y,
55
+ items: state.items,
44
56
  onCopyImage: handleCopyImage,
45
57
  onClose: close,
46
58
  },
@@ -72,7 +84,7 @@ const separatorStyle = {
72
84
  * Context menu overlay component. Uses CSS variables for theming
73
85
  * with light/dark hex fallbacks for environments without VS Code vars.
74
86
  */
75
- export function DiagramContextMenu({ visible, x, y, onCopyImage, onClose, onEditText, onEditLayout, onResetLayout, isEditingLayout, hasManualLayout, }) {
87
+ export function DiagramContextMenu({ visible, x, y, onCopyImage, onClose, onEditText, onEditLayout, onResetLayout, isEditingLayout, hasManualLayout, items, }) {
76
88
  const menuRef = useRef(null);
77
89
  const isDark = typeof document !== 'undefined' && document.documentElement.classList.contains('dark');
78
90
  const bgColor = `var(--liminis-editor-menu-background)`;
@@ -105,12 +117,21 @@ export function DiagramContextMenu({ visible, x, y, onCopyImage, onClose, onEdit
105
117
  const handleHover = (e, entering) => {
106
118
  e.currentTarget.style.background = entering ? hoverBg : 'transparent';
107
119
  };
108
- return (_jsxs("div", { ref: menuRef, style: {
120
+ // Diagram items grouped in first-seen order (elements, then boundaries).
121
+ const itemGroups = [];
122
+ for (const item of items ?? []) {
123
+ const group = itemGroups.find((g) => g[0].group === item.group);
124
+ if (group)
125
+ group.push(item);
126
+ else
127
+ itemGroups.push([item]);
128
+ }
129
+ return (_jsxs("div", { ref: menuRef, role: "menu", "data-diagram-context-menu": "", style: {
109
130
  ...menuStyle,
110
131
  left: x,
111
132
  top: y,
112
133
  background: bgColor,
113
134
  border: `1px solid ${borderColor}`,
114
135
  boxShadow: isDark ? '0 4px 12px rgba(0,0,0,0.3)' : '0 4px 12px rgba(0,0,0,0.12)',
115
- }, children: [onEditText && (_jsx("button", { onClick: () => { onEditText(); onClose(); }, style: { ...itemStyle, color: textColor }, onMouseEnter: (e) => handleHover(e, true), onMouseLeave: (e) => handleHover(e, false), children: "Edit text\u2026" })), onEditLayout && (_jsx("button", { onClick: () => { onEditLayout(); onClose(); }, style: { ...itemStyle, color: textColor }, onMouseEnter: (e) => handleHover(e, true), onMouseLeave: (e) => handleHover(e, false), children: isEditingLayout ? 'Exit layout mode' : 'Edit layout' })), onResetLayout && hasManualLayout && (_jsx("button", { onClick: () => { onResetLayout(); onClose(); }, style: { ...itemStyle, color: textColor }, onMouseEnter: (e) => handleHover(e, true), onMouseLeave: (e) => handleHover(e, false), children: "Reset to auto layout" })), (onEditText || onEditLayout) && (_jsx("div", { style: { ...separatorStyle, background: separatorColor } })), _jsx("button", { onClick: onCopyImage, style: { ...itemStyle, color: textColor }, onMouseEnter: (e) => handleHover(e, true), onMouseLeave: (e) => handleHover(e, false), children: "Copy image to clipboard" })] }));
136
+ }, children: [itemGroups.map((group) => (_jsxs("div", { role: "group", "aria-label": group[0].group, children: [group.map((item) => (_jsx("button", { role: "menuitem", "data-menu-item-id": item.id, onClick: () => { onClose(); item.onSelect(); }, style: { ...itemStyle, color: textColor }, onMouseEnter: (e) => handleHover(e, true), onMouseLeave: (e) => handleHover(e, false), children: item.label }, item.id))), _jsx("div", { style: { ...separatorStyle, background: separatorColor } })] }, group[0].group))), onEditText && (_jsx("button", { onClick: () => { onEditText(); onClose(); }, style: { ...itemStyle, color: textColor }, onMouseEnter: (e) => handleHover(e, true), onMouseLeave: (e) => handleHover(e, false), children: "Edit text\u2026" })), onEditLayout && (_jsx("button", { onClick: () => { onEditLayout(); onClose(); }, style: { ...itemStyle, color: textColor }, onMouseEnter: (e) => handleHover(e, true), onMouseLeave: (e) => handleHover(e, false), children: isEditingLayout ? 'Exit layout mode' : 'Edit layout' })), onResetLayout && hasManualLayout && (_jsx("button", { onClick: () => { onResetLayout(); onClose(); }, style: { ...itemStyle, color: textColor }, onMouseEnter: (e) => handleHover(e, true), onMouseLeave: (e) => handleHover(e, false), children: "Reset to auto layout" })), (onEditText || onEditLayout) && (_jsx("div", { style: { ...separatorStyle, background: separatorColor } })), _jsx("button", { onClick: onCopyImage, style: { ...itemStyle, color: textColor }, onMouseEnter: (e) => handleHover(e, true), onMouseLeave: (e) => handleHover(e, false), children: "Copy image to clipboard" })] }));
116
137
  }
@@ -61,5 +61,5 @@ export default function TransclusionComponent({ file, blockId }) {
61
61
  if (state === null) {
62
62
  return renderTransclusionLoading();
63
63
  }
64
- return renderTransclusionState(state);
64
+ return renderTransclusionState(state, { file, blockId });
65
65
  }
@@ -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);