@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.
package/README.md CHANGED
@@ -9,7 +9,7 @@ into this repository so it can stand on its own. MIT-licensed.
9
9
 
10
10
  Its history, and how to read the `ADR-0NNN`, `FR-NNN` and `#NNN` references that
11
11
  travelled with the code, are recorded in [`docs/provenance.md`](./docs/provenance.md)
12
- ([on the docs site](https://v3rv.com/liminis-editor/guide/provenance/)).
12
+ ([on the docs site](https://docs.liminis.app/liminis-editor/guide/provenance/)).
13
13
 
14
14
  ## What you get
15
15
 
@@ -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.49 @lexical/react@^0.49 @lexical/code@^0.49 \
50
- @lexical/code-prism@^0.49 @lexical/link@^0.49 @lexical/list@^0.49 \
51
- @lexical/mark@^0.49 @lexical/markdown@^0.49 @lexical/rich-text@^0.49 \
52
- @lexical/selection@^0.49 @lexical/table@^0.49 @lexical/utils@^0.49
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
@@ -557,7 +557,7 @@ every fixture-representable node class renders somewhere in it. See
557
557
  [`examples/demo/README.md`](./examples/demo/README.md).
558
558
 
559
559
  `examples/demo` is also the demo on the public GitHub Pages site, at
560
- **[v3rv.com/liminis-editor/demo/](https://v3rv.com/liminis-editor/demo/)** — a
560
+ **[docs.liminis.app/liminis-editor/demo/](https://docs.liminis.app/liminis-editor/demo/)** — a
561
561
  `release`-triggered (not merge-triggered) build of this same shell, showing a
562
562
  visible version badge for the published release it represents. Between releases
563
563
  the deployed site stays on the last published version even as `main` keeps
@@ -566,7 +566,7 @@ moving — that staleness is intentional, not a bug (see
566
566
 
567
567
  ## Documentation site
568
568
 
569
- **[v3rv.com/liminis-editor](https://v3rv.com/liminis-editor/)** publishes the
569
+ **[docs.liminis.app/liminis-editor](https://docs.liminis.app/liminis-editor/)** publishes the
570
570
  pages in [`docs/`](./docs/) with search, cross-links, and the C4 diagrams
571
571
  rendered live rather than as pictures.
572
572
 
@@ -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());
@@ -17,6 +17,7 @@ import { registerCodeHighlighting } from '@lexical/code-prism';
17
17
  import { $createParagraphNode, $createRangeSelection, $getRoot, $getSelection, $isElementNode, $isLineBreakNode, $isRangeSelection, $isTextNode, $setSelection, COMMAND_PRIORITY_LOW, KEY_ENTER_COMMAND, } from 'lexical';
18
18
  import { mergeRegister } from '@lexical/utils';
19
19
  import { Toolbar } from './Toolbar.js';
20
+ import { MarkNodePastePlugin } from './MarkNodePastePlugin.js';
20
21
  import { SlashMenuPlugin } from './SlashMenuPlugin.js';
21
22
  import { DragHandlePlugin } from './DragHandlePlugin.js';
22
23
  import { MarkdownShortcutsPlugin } from './MarkdownShortcutsPlugin.js';
@@ -543,7 +544,7 @@ export function Editor({ initialContent, autoFocus = false, contentVersion = 0,
543
544
  onError: editorOnError,
544
545
  editable,
545
546
  };
546
- return (_jsx(AssetContext.Provider, { value: assetContextValue, children: _jsx(LexicalComposer, { initialConfig: initialConfig, children: _jsx("div", { className: "editor-container", children: _jsxs("div", { className: "editor-inner", children: [_jsx(RichTextPlugin, { contentEditable: _jsx(ContentEditable, { className: "editor-input", "aria-label": "Markdown editor" }), placeholder: _jsx("div", { className: "editor-placeholder", children: "Type '/' for commands..." }), ErrorBoundary: LexicalErrorBoundary }), _jsx(HistoryPlugin, {}), _jsx(ListPlugin, {}), _jsx(CheckListPlugin, {}), _jsx(OrderedTaskListPlugin, {}), _jsx(TabIndentationPlugin, {}), _jsx(LinkPlugin, {}), _jsx(TablePlugin, {}), _jsx(CodeHighlightPlugin, {}), _jsx(OnChangePlugin, { onChange: handleChange, ignoreSelectionChange: true }), _jsx(InitializePlugin, { content: initialContent, onOffsets: handleOffsets }), _jsx(EditablePlugin, { editable: editable }), autoFocus && _jsx(AutoFocusPlugin, {}), _jsx(CursorTrackingPlugin, { onCursorChange: onCursorChange }), _jsx(CursorRestorePlugin, { contentVersion: contentVersion, cursorToRestoreRef: effectiveCursorRef }), _jsx(ExternalUpdatePlugin, { content: initialContent, lastExternalLoadRef: lastExternalLoadRef, currentContentRef: currentContentRef, lastEditorChangeRef: lastEditorChangeRef, onOffsets: handleOffsets }), _jsx(SlashMenuPlugin, {}), _jsx(DragHandlePlugin, {}), _jsx(MarkdownShortcutsPlugin, {}), _jsx(TableActionsPlugin, {}), _jsx(CodeBlockPlugin, {}), _jsx(TogglePlugin, {}), _jsx(ImagePlugin, {}), _jsx(BlockClickPlugin, {}), _jsx(LinkClickPlugin, { editable: editable }), _jsx(Toolbar, { annotationAffordances: toolbarAnnotationAffordances }), _jsx(SearchPlugin, {}), _jsx(FrontmatterPlugin, { filePath: filePath }), _jsx(WikiLinkExistencePlugin, {}), _jsx(WikiLinkFormatPlugin, {}), _jsx(AnchorScrollPlugin, {}), documentOutlineHandle && _jsx(OutlinePlugin, { handle: documentOutlineHandle }), _jsx(SelectionContextMenuPlugin, { onSelectionContextMenu: onSelectionContextMenu,
547
+ return (_jsx(AssetContext.Provider, { value: assetContextValue, children: _jsx(LexicalComposer, { initialConfig: initialConfig, children: _jsx("div", { className: "editor-container", children: _jsxs("div", { className: "editor-inner", children: [_jsx(RichTextPlugin, { contentEditable: _jsx(ContentEditable, { className: "editor-input", "aria-label": "Markdown editor" }), placeholder: _jsx("div", { className: "editor-placeholder", children: "Type '/' for commands..." }), ErrorBoundary: LexicalErrorBoundary }), _jsx(HistoryPlugin, {}), _jsx(MarkNodePastePlugin, {}), _jsx(ListPlugin, {}), _jsx(CheckListPlugin, {}), _jsx(OrderedTaskListPlugin, {}), _jsx(TabIndentationPlugin, {}), _jsx(LinkPlugin, {}), _jsx(TablePlugin, {}), _jsx(CodeHighlightPlugin, {}), _jsx(OnChangePlugin, { onChange: handleChange, ignoreSelectionChange: true }), _jsx(InitializePlugin, { content: initialContent, onOffsets: handleOffsets }), _jsx(EditablePlugin, { editable: editable }), autoFocus && _jsx(AutoFocusPlugin, {}), _jsx(CursorTrackingPlugin, { onCursorChange: onCursorChange }), _jsx(CursorRestorePlugin, { contentVersion: contentVersion, cursorToRestoreRef: effectiveCursorRef }), _jsx(ExternalUpdatePlugin, { content: initialContent, lastExternalLoadRef: lastExternalLoadRef, currentContentRef: currentContentRef, lastEditorChangeRef: lastEditorChangeRef, onOffsets: handleOffsets }), _jsx(SlashMenuPlugin, {}), _jsx(DragHandlePlugin, {}), _jsx(MarkdownShortcutsPlugin, {}), _jsx(TableActionsPlugin, {}), _jsx(CodeBlockPlugin, {}), _jsx(TogglePlugin, {}), _jsx(ImagePlugin, {}), _jsx(BlockClickPlugin, {}), _jsx(LinkClickPlugin, { editable: editable }), _jsx(Toolbar, { annotationAffordances: toolbarAnnotationAffordances }), _jsx(SearchPlugin, {}), _jsx(FrontmatterPlugin, { filePath: filePath }), _jsx(WikiLinkExistencePlugin, {}), _jsx(WikiLinkFormatPlugin, {}), _jsx(AnchorScrollPlugin, {}), documentOutlineHandle && _jsx(OutlinePlugin, { handle: documentOutlineHandle }), _jsx(SelectionContextMenuPlugin, { onSelectionContextMenu: onSelectionContextMenu,
547
548
  // Only kinds that actually ask for a context-menu affordance:
548
549
  // with none configured, or one on another surface, AnnotationPlugin
549
550
  // would decline the command anyway, and dispatching from here would
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Pasted content never carries annotation marks.
3
+ *
4
+ * A live `MarkNode` is placed by the annotation surface for an annotation the
5
+ * host owns; it is not document content. Lexical 0.50 changed the in-editor
6
+ * clipboard payload to ask `excludeFromCopy('clone')`, which `MarkNode`
7
+ * answers by staying in the copy, so pasting annotated text produced a second
8
+ * mark with the same annotation ids — a highlight nothing placed, and a second
9
+ * rect reported for one annotation. Before 0.50 the mark was dropped on copy;
10
+ * this restores that by unwrapping marks on the way in, whatever the source.
11
+ *
12
+ * Mounted unconditionally: `MarkNode` is always registered, whether or not
13
+ * annotation kinds are configured.
14
+ */
15
+ export declare function MarkNodePastePlugin(): null;
@@ -0,0 +1,60 @@
1
+ import { useEffect } from 'react';
2
+ import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
3
+ import { $isMarkNode } from '@lexical/mark';
4
+ import { $isElementNode, COMMAND_PRIORITY_CRITICAL, SELECTION_INSERT_CLIPBOARD_NODES_COMMAND, } from 'lexical';
5
+ /**
6
+ * Pasted content never carries annotation marks.
7
+ *
8
+ * A live `MarkNode` is placed by the annotation surface for an annotation the
9
+ * host owns; it is not document content. Lexical 0.50 changed the in-editor
10
+ * clipboard payload to ask `excludeFromCopy('clone')`, which `MarkNode`
11
+ * answers by staying in the copy, so pasting annotated text produced a second
12
+ * mark with the same annotation ids — a highlight nothing placed, and a second
13
+ * rect reported for one annotation. Before 0.50 the mark was dropped on copy;
14
+ * this restores that by unwrapping marks on the way in, whatever the source.
15
+ *
16
+ * Mounted unconditionally: `MarkNode` is always registered, whether or not
17
+ * annotation kinds are configured.
18
+ */
19
+ export function MarkNodePastePlugin() {
20
+ const [editor] = useLexicalComposerContext();
21
+ useEffect(() => editor.registerCommand(SELECTION_INSERT_CLIPBOARD_NODES_COMMAND, ({ nodes }) => {
22
+ // In place: every later handler, and the default insertion, read
23
+ // this same array.
24
+ nodes.splice(0, nodes.length, ...$unwrapMarks(nodes));
25
+ return false;
26
+ }, COMMAND_PRIORITY_CRITICAL), [editor]);
27
+ return null;
28
+ }
29
+ /** Replaces every `MarkNode` in `nodes`, at any depth, with its children. */
30
+ function $unwrapMarks(nodes) {
31
+ const out = [];
32
+ for (const node of nodes) {
33
+ if ($isMarkNode(node)) {
34
+ const children = node.getChildren();
35
+ for (const child of children)
36
+ child.remove(true);
37
+ out.push(...$unwrapMarks(children));
38
+ }
39
+ else {
40
+ if ($isElementNode(node))
41
+ $unwrapNestedMarks(node);
42
+ out.push(node);
43
+ }
44
+ }
45
+ return out;
46
+ }
47
+ function $unwrapNestedMarks(element) {
48
+ for (const child of element.getChildren()) {
49
+ if ($isMarkNode(child)) {
50
+ for (const grandchild of child.getChildren())
51
+ child.insertBefore(grandchild);
52
+ child.remove();
53
+ // The moved children may themselves be (or contain) marks.
54
+ $unwrapNestedMarks(element);
55
+ return;
56
+ }
57
+ if ($isElementNode(child))
58
+ $unwrapNestedMarks(child);
59
+ }
60
+ }
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useCallback, useEffect, useState, useRef } from 'react';
3
3
  import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
4
- import { $getSelection, $isRangeSelection, FORMAT_TEXT_COMMAND, SELECTION_CHANGE_COMMAND, COMMAND_PRIORITY_CRITICAL, COMMAND_PRIORITY_LOW, } from 'lexical';
4
+ import { $getSelection, $isRangeSelection, $onUpdate, FORMAT_TEXT_COMMAND, SELECTION_CHANGE_COMMAND, COMMAND_PRIORITY_CRITICAL, COMMAND_PRIORITY_LOW, } from 'lexical';
5
5
  import { $isLinkNode, TOGGLE_LINK_COMMAND } from '@lexical/link';
6
6
  import { getSelectedNode } from './utils.js';
7
7
  import { OPEN_ANNOTATION_COMPOSER_COMMAND } from './annotationCommands.js';
@@ -122,12 +122,18 @@ export function Toolbar({ annotationAffordances = [] }) {
122
122
  }, [editor, updateFormatFlags]);
123
123
  useEffect(() => {
124
124
  const unregisterSelection = editor.registerCommand(SELECTION_CHANGE_COMMAND, () => {
125
- updateVisibility();
126
- if (editor.isEditable()) {
127
- editor.getEditorState().read(() => {
128
- updateFormatFlags();
125
+ // Since Lexical 0.52 this command runs inside the pending update,
126
+ // before DOM reconciliation: `getEditorState()` would still hold the
127
+ // previous selection, and the native selection may not have moved
128
+ // yet. Defer both reads until the update has committed.
129
+ $onUpdate(() => {
130
+ editor.read('latest', () => {
131
+ updateVisibility();
132
+ if (editor.isEditable()) {
133
+ updateFormatFlags();
134
+ }
129
135
  });
130
- }
136
+ });
131
137
  return false;
132
138
  }, COMMAND_PRIORITY_CRITICAL);
133
139
  // Also listen for format changes to update button states
@@ -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
  }
@@ -10,7 +10,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
10
10
  */
11
11
  import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
12
12
  import { mergeRegister } from '@lexical/utils';
13
- import { $getNodeByKey, $getSelection, $isNodeSelection, COMMAND_PRIORITY_HIGH, KEY_ESCAPE_COMMAND, SELECTION_CHANGE_COMMAND, } from 'lexical';
13
+ import { $getNodeByKey, $getSelection, $isNodeSelection, $onUpdate, COMMAND_PRIORITY_HIGH, KEY_ESCAPE_COMMAND, SELECTION_CHANGE_COMMAND, } from 'lexical';
14
14
  import { useCallback, useEffect, useRef, useState, forwardRef } from 'react';
15
15
  import { createBrowserAdaptorDocument } from '../../../mathjax-config.js';
16
16
  import { $isEquationNode } from './EquationNode.js';
@@ -89,11 +89,13 @@ export default function EquationComponent({ equation, inline, nodeKey, }) {
89
89
  }
90
90
  if (showEquationEditor) {
91
91
  return mergeRegister(editor.registerCommand(SELECTION_CHANGE_COMMAND, () => {
92
- const activeElement = document.activeElement;
93
- const inputElem = inputRef.current;
94
- if (inputElem !== activeElement) {
95
- onHide();
96
- }
92
+ // Since Lexical 0.52 this runs before DOM reconciliation; check
93
+ // focus once the update has committed, as it did before.
94
+ $onUpdate(() => {
95
+ if (inputRef.current !== document.activeElement) {
96
+ onHide();
97
+ }
98
+ });
97
99
  return false;
98
100
  }, COMMAND_PRIORITY_HIGH), editor.registerCommand(KEY_ESCAPE_COMMAND, () => {
99
101
  const activeElement = document.activeElement;
@@ -12,11 +12,18 @@ import { useHostMessages } from '../../../host/messages.js';
12
12
  import { $isMermaidNode } from './MermaidNode.js';
13
13
  import { DiagramContextMenu, useDiagramContextMenu } from './DiagramContextMenu.js';
14
14
  // Initialize mermaid with default config
15
+ //
16
+ // `layout` and `look` pin mermaid 11's appearance. Mermaid 12 made ELK the
17
+ // default layout and `neo` the default look, which re-lays out and restyles
18
+ // every existing diagram in a user's documents. A dependency upgrade should
19
+ // not do that silently; adopting the new defaults is a decision of its own.
15
20
  mermaid.initialize({
16
21
  startOnLoad: false,
17
22
  theme: 'dark',
18
23
  securityLevel: 'strict',
19
24
  fontFamily: 'inherit',
25
+ layout: 'dagre',
26
+ look: 'classic',
20
27
  });
21
28
  // Mermaid Renderer component using Shadow DOM
22
29
  function MermaidRenderer({ code, onDoubleClick, }) {
@@ -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
  }