@bendyline/squisq-editor-react 1.5.3 → 1.6.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.
Files changed (165) hide show
  1. package/dist/index.d.ts +757 -20
  2. package/dist/index.js +16875 -6883
  3. package/dist/index.js.map +1 -1
  4. package/package.json +4 -4
  5. package/src/BlockCardView.tsx +121 -0
  6. package/src/BlockPreviewPanel.tsx +69 -0
  7. package/src/BlockPropertiesPopover.tsx +191 -0
  8. package/src/EditorContext.tsx +143 -0
  9. package/src/EditorShell.tsx +200 -120
  10. package/src/FolderView.tsx +131 -0
  11. package/src/Icon.tsx +26 -0
  12. package/src/ImageEditor.tsx +69 -22
  13. package/src/OutlinePanel.tsx +38 -3
  14. package/src/PlainHtmlPreview.tsx +30 -3
  15. package/src/PreviewControls.tsx +180 -8
  16. package/src/RawEditor.tsx +169 -13
  17. package/src/RecorderEntry.tsx +9 -16
  18. package/src/TemplateAnnotation.ts +44 -0
  19. package/src/TemplatePicker.tsx +329 -54
  20. package/src/ThemeCustomizerPanel.tsx +30 -336
  21. package/src/ThemePicker.tsx +112 -3
  22. package/src/TimelineBlockPreview.tsx +37 -0
  23. package/src/TimelineTrack.tsx +671 -0
  24. package/src/Toolbar.tsx +528 -174
  25. package/src/Tooltip.tsx +22 -4
  26. package/src/TransitionPicker.tsx +351 -0
  27. package/src/VersionHistoryPanel.tsx +2 -14
  28. package/src/ViewMenuPanel.tsx +17 -14
  29. package/src/WysiwygEditor.tsx +161 -65
  30. package/src/__tests__/blockProperties.test.ts +92 -0
  31. package/src/__tests__/blockRange.test.ts +105 -0
  32. package/src/__tests__/buildPreviewDocTransition.test.ts +73 -0
  33. package/src/__tests__/createShapeLayer.test.ts +46 -0
  34. package/src/__tests__/drawingShapeRoundTrip.test.ts +49 -0
  35. package/src/__tests__/embeddedMedia.test.ts +48 -0
  36. package/src/__tests__/headingTransition.test.ts +138 -0
  37. package/src/__tests__/layoutChildRoundTrip.test.ts +71 -0
  38. package/src/__tests__/plainHtmlPreview.test.tsx +10 -8
  39. package/src/__tests__/recorderMediaInsert.test.ts +86 -0
  40. package/src/__tests__/templateAnnotationRoundTrip.test.ts +18 -0
  41. package/src/__tests__/templatePickerMetadata.test.ts +32 -0
  42. package/src/__tests__/timelineSource.test.ts +134 -0
  43. package/src/__tests__/tiptapBridge.test.ts +92 -0
  44. package/src/__tests__/tiptapBridgeConformance.test.ts +47 -0
  45. package/src/__tests__/tooltip.test.tsx +72 -0
  46. package/src/__tests__/transitionCatalog.test.ts +64 -0
  47. package/src/__tests__/useBlockNavigator.test.tsx +67 -0
  48. package/src/__tests__/useMediaRecorder.test.ts +24 -0
  49. package/src/__tests__/useTimelineClock.test.ts +21 -0
  50. package/src/blockProperties.ts +88 -0
  51. package/src/blockRange.ts +132 -0
  52. package/src/buildPreviewDoc.ts +98 -9
  53. package/src/customTemplates/AddBin.tsx +126 -0
  54. package/src/customTemplates/CustomLayoutManager.tsx +233 -0
  55. package/src/customTemplates/CustomTemplateContext.tsx +182 -0
  56. package/src/customTemplates/LayerToolbar.tsx +580 -0
  57. package/src/customTemplates/ShapeGlyph.tsx +47 -0
  58. package/src/customTemplates/TemplateDesigner.tsx +430 -0
  59. package/src/customTemplates/__tests__/library.test.ts +88 -0
  60. package/src/customTemplates/__tests__/normalizePositions.test.ts +109 -0
  61. package/src/customTemplates/__tests__/shapeDefs.test.ts +49 -0
  62. package/src/customTemplates/__tests__/useMemoryLayerAdapter.test.ts +95 -0
  63. package/src/customTemplates/designer.css +673 -0
  64. package/src/customTemplates/index.ts +31 -0
  65. package/src/customTemplates/library.ts +97 -0
  66. package/src/customTemplates/normalizePositions.ts +75 -0
  67. package/src/customTemplates/shapeDefs.ts +131 -0
  68. package/src/customTemplates/thumbnail.tsx +63 -0
  69. package/src/customTemplates/tokenDefs.ts +60 -0
  70. package/src/customTemplates/useDocCustomTemplates.ts +52 -0
  71. package/src/customTemplates/useMemoryLayerAdapter.ts +123 -0
  72. package/src/customThemes/CustomThemeContext.tsx +179 -0
  73. package/src/customThemes/CustomThemeDialog.tsx +286 -0
  74. package/src/customThemes/__tests__/CustomThemeContext.test.tsx +64 -0
  75. package/src/customThemes/__tests__/CustomThemeDialog.test.tsx +47 -0
  76. package/src/customThemes/__tests__/customThemeLibrary.test.ts +51 -0
  77. package/src/customThemes/customThemeLibrary.ts +97 -0
  78. package/src/customThemes/index.ts +31 -0
  79. package/src/customThemes/themeControls.tsx +229 -0
  80. package/src/customThemes/themeDraft.ts +272 -0
  81. package/src/customThemes/useDocCustomThemes.ts +49 -0
  82. package/src/diagram/DiagramCanvas.tsx +240 -0
  83. package/src/diagram/DiagramExtension.ts +209 -0
  84. package/src/diagram/DiagramMaximizedOverlay.tsx +46 -0
  85. package/src/diagram/DiagramWidget.tsx +270 -0
  86. package/src/diagram/diagramCommands.ts +604 -0
  87. package/src/diagram/diagramConstants.ts +17 -0
  88. package/src/diagram/useDiagramData.ts +126 -0
  89. package/src/embeddedMedia.ts +78 -0
  90. package/src/frontmatter.ts +29 -0
  91. package/src/headingTransition.ts +231 -0
  92. package/src/imageEditor/CanvasSurface.tsx +383 -88
  93. package/src/imageEditor/PropertiesPanel.tsx +47 -1
  94. package/src/imageEditor/Toolbar.tsx +229 -16
  95. package/src/imageEditor/createShapeLayer.ts +280 -0
  96. package/src/imageEditor/icons.tsx +34 -114
  97. package/src/imageEditor/image-editor.css +54 -5
  98. package/src/imageEditor/state.ts +23 -3
  99. package/src/index.ts +77 -0
  100. package/src/recorder/RecorderModal.tsx +120 -53
  101. package/src/recorder/RecorderPanel.tsx +2 -26
  102. package/src/recorder/hooks/useMediaRecorder.ts +8 -1
  103. package/src/recorder/insertMediaBlock.ts +30 -0
  104. package/src/resolveBlockVisual.ts +33 -0
  105. package/src/scene/Scene.tsx +540 -0
  106. package/src/scene/SceneBlockExtension.ts +198 -0
  107. package/src/scene/SceneBlockToolbar.tsx +201 -0
  108. package/src/scene/SceneBlockWidget.tsx +434 -0
  109. package/src/scene/ScenePropsBar.tsx +85 -0
  110. package/src/scene/SceneSelection.tsx +107 -0
  111. package/src/scene/SceneViewport.tsx +102 -0
  112. package/src/scene/ShapePalette.tsx +181 -0
  113. package/src/scene/__tests__/DiagramAdapter.test.ts +56 -0
  114. package/src/scene/__tests__/bezierEdit.test.ts +85 -0
  115. package/src/scene/__tests__/blockLayers.test.ts +57 -0
  116. package/src/scene/__tests__/shapeLayers.test.ts +106 -0
  117. package/src/scene/__tests__/useSceneHitTest.test.ts +90 -0
  118. package/src/scene/__tests__/useScenePanZoom.test.ts +103 -0
  119. package/src/scene/adapters/DiagramAdapter.ts +168 -0
  120. package/src/scene/adapters/DrawingAdapter.ts +415 -0
  121. package/src/scene/adapters/LayoutAdapter.ts +310 -0
  122. package/src/scene/adapters/blockLayers.ts +159 -0
  123. package/src/scene/commands/SceneCommand.ts +70 -0
  124. package/src/scene/commands/drawingCommands.ts +318 -0
  125. package/src/scene/commands/layoutCommands.ts +301 -0
  126. package/src/scene/hooks/useSceneHitTest.ts +105 -0
  127. package/src/scene/hooks/useScenePanZoom.ts +147 -0
  128. package/src/scene/hooks/useSceneSelection.ts +62 -0
  129. package/src/scene/index.ts +95 -0
  130. package/src/scene/layers/DiagramEdges.tsx +127 -0
  131. package/src/scene/layers/edgeGeometry.ts +77 -0
  132. package/src/scene/layers/nodeCard.tsx +145 -0
  133. package/src/scene/layers/renderLayer.tsx +70 -0
  134. package/src/scene/layers/shapeLayers.ts +201 -0
  135. package/src/scene/paths/bezierEdit.ts +208 -0
  136. package/src/scene/scene.css +649 -0
  137. package/src/scene/text/SceneTextOverlay.tsx +161 -0
  138. package/src/scene/text/sceneTextChannel.ts +40 -0
  139. package/src/scene/text/sceneTextConfig.ts +27 -0
  140. package/src/scene/text/sceneTiptap.ts +36 -0
  141. package/src/scene/text/useSceneTextEditing.ts +39 -0
  142. package/src/scene/tools/ConnectTool.ts +111 -0
  143. package/src/scene/tools/DrawingConnectTool.ts +161 -0
  144. package/src/scene/tools/PathTool.ts +158 -0
  145. package/src/scene/tools/PlaceTool.ts +47 -0
  146. package/src/scene/tools/SceneTool.ts +75 -0
  147. package/src/scene/tools/SelectTool.ts +284 -0
  148. package/src/scene/tools/ShapeTool.ts +144 -0
  149. package/src/scene/tools/TextTool.ts +72 -0
  150. package/src/scene/tools/TokenTool.ts +95 -0
  151. package/src/scene/tools/createDrawShapeTool.ts +82 -0
  152. package/src/styles/diagram.css +183 -0
  153. package/src/styles/editor.css +1615 -203
  154. package/src/styles/folder-view.css +210 -0
  155. package/src/styles/image-edit-affordance.css +2 -2
  156. package/src/styles/index.css +4 -0
  157. package/src/timelineSource.ts +244 -0
  158. package/src/tiptapBridge.ts +115 -34
  159. package/src/tooltipPlacement.ts +13 -0
  160. package/src/transitionCatalog.ts +159 -0
  161. package/src/types/monaco-shims.d.ts +10 -0
  162. package/src/useBlockNavigator.ts +153 -0
  163. package/src/useMonacoLoader.ts +23 -1
  164. package/src/useTimelineClock.ts +76 -0
  165. package/src/utils/dropUtils.ts +1 -1
@@ -0,0 +1,145 @@
1
+ /**
2
+ * nodeCard — synthesize the (rect + label) layer pair for a diagram node.
3
+ *
4
+ * Mirrors the shape `diagramBlock.ts` emits for SSR so the editor and
5
+ * preview render identical pixels. The actual Layer instances are
6
+ * regular ShapeLayer + TextLayer objects — the Scene's RenderLayer
7
+ * draws them with the normal SSR components.
8
+ *
9
+ * Edges are NOT generated here; the DiagramAdapter renders edges as a
10
+ * separate PathLayer pass since they need to be drawn behind the cards.
11
+ */
12
+
13
+ import type { ShapeLayer, TextLayer, Layer } from '@bendyline/squisq/schemas';
14
+
15
+ export const NODE_WIDTH = 180;
16
+ export const NODE_HEIGHT = 64;
17
+
18
+ export interface DiagramNodeDescriptor {
19
+ /** Stable id (matches the heading slug / Pandoc `#id`). */
20
+ id: string;
21
+ /** Display label. */
22
+ label: string;
23
+ /** Top-left position in viewport units. */
24
+ x: number;
25
+ /** Top-left position in viewport units. */
26
+ y: number;
27
+ /** Width in viewport units. Defaults to `NODE_WIDTH`. */
28
+ width?: number;
29
+ /** Height in viewport units. Defaults to `NODE_HEIGHT`. */
30
+ height?: number;
31
+ /** Optional override fill color (resolved from a color scheme). */
32
+ fill?: string;
33
+ /** Optional override stroke color. */
34
+ stroke?: string;
35
+ /** Optional shape: 'rect' (default) or 'pill' (fully rounded). */
36
+ shape?: 'rect' | 'pill';
37
+ }
38
+
39
+ /**
40
+ * Build a (card, label) pair of Layer objects for a diagram node. Both
41
+ * layers share an id prefix (`node-card-<id>` / `node-label-<id>`) so
42
+ * the SceneSelection overlay can highlight the card while hit-testing
43
+ * works on the card's bounding rect.
44
+ */
45
+ export function nodeCardLayers(node: DiagramNodeDescriptor): [ShapeLayer, TextLayer] {
46
+ const width = node.width ?? NODE_WIDTH;
47
+ const height = node.height ?? NODE_HEIGHT;
48
+ const card: ShapeLayer = {
49
+ id: `node-card-${node.id}`,
50
+ type: 'shape',
51
+ position: { x: node.x, y: node.y, width, height },
52
+ content: {
53
+ shape: 'rect',
54
+ fill: node.fill ?? '#ffffff',
55
+ stroke: node.stroke ?? '#1e293b',
56
+ strokeWidth: 2,
57
+ borderRadius: node.shape === 'pill' ? height / 2 : 10,
58
+ },
59
+ };
60
+
61
+ // Scale the label font with the node height so resized cards stay
62
+ // legible without the text overflowing.
63
+ const fontSize = Math.max(12, Math.min(48, Math.round(height * 0.34)));
64
+
65
+ // Label has no explicit height — that keeps its bounding box
66
+ // unresolvable in `layerBounds`, which in turn keeps it out of the
67
+ // Scene's hit-test. The label rides along visually via `layerFollows`
68
+ // but never wins a pointer-down (the card underneath does), so a
69
+ // drag-on-text moves the card as expected.
70
+ const label: TextLayer = {
71
+ id: `node-label-${node.id}`,
72
+ type: 'text',
73
+ position: {
74
+ x: node.x + width / 2,
75
+ y: node.y + height / 2,
76
+ width,
77
+ anchor: 'center',
78
+ },
79
+ content: {
80
+ text: node.label,
81
+ style: {
82
+ fontSize,
83
+ fontWeight: 'bold',
84
+ color: node.stroke ?? '#1e293b',
85
+ textAlign: 'center',
86
+ },
87
+ },
88
+ };
89
+
90
+ return [card, label];
91
+ }
92
+
93
+ /**
94
+ * Convenience: derive a node-label id from a node-card id. Used by
95
+ * `layerFollows` to keep labels visually attached to their cards during
96
+ * drag and resize previews.
97
+ */
98
+ export function labelLayerIdForCard(cardId: string): string {
99
+ if (!cardId.startsWith('node-card-')) return cardId;
100
+ return `node-label-${cardId.slice('node-card-'.length)}`;
101
+ }
102
+
103
+ /**
104
+ * Convenience: derive a node-card id from a node-label id.
105
+ */
106
+ export function cardLayerIdForLabel(labelId: string): string {
107
+ if (!labelId.startsWith('node-label-')) return labelId;
108
+ return `node-card-${labelId.slice('node-label-'.length)}`;
109
+ }
110
+
111
+ /**
112
+ * Implementation of the Scene's `layerFollows` prop for diagram mode —
113
+ * a label layer follows its card layer, so dragging or resizing the
114
+ * card visually moves both.
115
+ */
116
+ export function diagramLayerFollows(layerId: string): string | null {
117
+ if (layerId.startsWith('node-label-')) return cardLayerIdForLabel(layerId);
118
+ return null;
119
+ }
120
+
121
+ /**
122
+ * Convert a list of diagram nodes to a flat Layer[] suitable for
123
+ * `<Scene layers={...} />`. Returns cards followed by labels so labels
124
+ * paint over their cards.
125
+ */
126
+ export function nodesToCardLayers(nodes: readonly DiagramNodeDescriptor[]): Layer[] {
127
+ const cards: ShapeLayer[] = [];
128
+ const labels: TextLayer[] = [];
129
+ for (const n of nodes) {
130
+ const [c, l] = nodeCardLayers(n);
131
+ cards.push(c);
132
+ labels.push(l);
133
+ }
134
+ return [...cards, ...labels];
135
+ }
136
+
137
+ /**
138
+ * Pull the node id back out of a card layer's synthetic id. Returns null
139
+ * if the layer wasn't produced by `nodeCardLayers`.
140
+ */
141
+ export function nodeIdFromCardLayerId(layerId: string): string | null {
142
+ if (layerId.startsWith('node-card-')) return layerId.slice('node-card-'.length);
143
+ if (layerId.startsWith('node-label-')) return layerId.slice('node-label-'.length);
144
+ return null;
145
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * renderLayer — render a single Layer for the editor surface.
3
+ *
4
+ * Reuses the SSR layer components from `@bendyline/squisq-react` so what
5
+ * the editor shows matches what the final block render produces. The
6
+ * Scene already runs inside an SVG group with the viewport transform
7
+ * applied, so the SSR components — which assume they're rendered inside
8
+ * a `<svg>` with the viewport in user units — drop in unmodified.
9
+ *
10
+ * Editor decorations (the selection outline, drag handles) are NOT
11
+ * rendered here. The Scene renders the SceneSelection overlay separately
12
+ * so a layer's bounding rect can be highlighted without modifying the
13
+ * layer's own DOM.
14
+ */
15
+
16
+ import {
17
+ ImageLayer,
18
+ TextLayer,
19
+ ShapeLayer,
20
+ PathLayer,
21
+ VideoLayer,
22
+ MapLayer,
23
+ TableLayer,
24
+ } from '@bendyline/squisq-react';
25
+ import type { Layer } from '@bendyline/squisq/schemas';
26
+
27
+ interface RenderLayerProps {
28
+ layer: Layer;
29
+ viewport: { width: number; height: number };
30
+ /**
31
+ * Layer renderers accept a `blockTime` to drive Ken Burns / animations.
32
+ * In editor mode we always pin to t=0 so static positions are shown
33
+ * (no Ken Burns drift) and selection outlines stay aligned.
34
+ */
35
+ blockTime?: number;
36
+ /**
37
+ * Base path for resolving media URLs (image / video / map tile cache).
38
+ * Defaults to empty — the host should pass the same value used by the
39
+ * preview renderer so editor and preview show identical content.
40
+ */
41
+ basePath?: string;
42
+ }
43
+
44
+ export function RenderLayer({ layer, viewport, blockTime = 0, basePath = '' }: RenderLayerProps) {
45
+ switch (layer.type) {
46
+ case 'image':
47
+ return (
48
+ <ImageLayer layer={layer} viewport={viewport} blockTime={blockTime} basePath={basePath} />
49
+ );
50
+ case 'text':
51
+ return <TextLayer layer={layer} viewport={viewport} blockTime={blockTime} />;
52
+ case 'shape':
53
+ return <ShapeLayer layer={layer} viewport={viewport} blockTime={blockTime} />;
54
+ case 'path':
55
+ return <PathLayer layer={layer} viewport={viewport} blockTime={blockTime} />;
56
+ case 'video':
57
+ return (
58
+ <VideoLayer layer={layer} viewport={viewport} blockTime={blockTime} basePath={basePath} />
59
+ );
60
+ case 'map':
61
+ return (
62
+ <MapLayer layer={layer} viewport={viewport} blockTime={blockTime} basePath={basePath} />
63
+ );
64
+ case 'table':
65
+ return <TableLayer layer={layer} viewport={viewport} blockTime={blockTime} />;
66
+ default:
67
+ // Exhaustiveness check — TypeScript will flag any unhandled types.
68
+ return null;
69
+ }
70
+ }
@@ -0,0 +1,201 @@
1
+ /**
2
+ * shapeLayers — synthesize Scene Layer(s) for a drawing shape.
3
+ *
4
+ * The drawing editor's counterpart to `nodeCard.tsx`: a core `DrawingShape`
5
+ * (from `computeDrawingLayout`) becomes a primary Layer (`dshape-<id>`) plus,
6
+ * for non-text shapes with a label, a follower TextLayer (`dlabel-<id>`).
7
+ * The Scene's `RenderLayer` draws them with the normal SSR components, so the
8
+ * canvas and the `drawingBlock` preview render the same primitives.
9
+ *
10
+ * Coordinates are author units used 1:1 as the Scene's viewport units (the
11
+ * same convention diagrams use) — the SSR template fit-scales independently.
12
+ */
13
+
14
+ import type { Layer, ShapeLayer, TextLayer, PathLayer } from '@bendyline/squisq/schemas';
15
+ import { shapePath, type DrawingShape } from '@bendyline/squisq/doc';
16
+
17
+ /** Prefix for a shape's primary (geometry) layer id. */
18
+ const SHAPE_PREFIX = 'dshape-';
19
+ /** Prefix for a shape's follower label layer id. */
20
+ const LABEL_PREFIX = 'dlabel-';
21
+
22
+ const DEFAULT_STROKE = '#1e293b';
23
+ const DEFAULT_FILL = 'none';
24
+
25
+ /** A `{id,x,y,width,height}` box per shape — feeds the connector renderer. */
26
+ export interface ShapeBox {
27
+ id: string;
28
+ x: number;
29
+ y: number;
30
+ width: number;
31
+ height: number;
32
+ }
33
+
34
+ /**
35
+ * Build the Scene layer(s) for one shape. rect/circle → ShapeLayer;
36
+ * line/arrow → ShapeLayer `line` (a bounding-box line, editable via the
37
+ * Select tool's resize handles); path → PathLayer; text → TextLayer. A
38
+ * non-text shape with a label also gets a centered, hit-test-transparent
39
+ * label layer that follows the primary (see {@link drawingLayerFollows}).
40
+ */
41
+ export function shapeToLayers(shape: DrawingShape): Layer[] {
42
+ const { id, x, y, width, height } = shape;
43
+ const stroke = shape.stroke ?? DEFAULT_STROKE;
44
+ const fill = shape.fill ?? DEFAULT_FILL;
45
+ const strokeWidth = shape.strokeWidth ?? 2;
46
+
47
+ if (shape.kind === 'text') {
48
+ const text: TextLayer = {
49
+ id: `${SHAPE_PREFIX}${id}`,
50
+ type: 'text',
51
+ position: { x, y, width, height },
52
+ content: {
53
+ text: shape.text ?? shape.label ?? '',
54
+ style: {
55
+ fontSize: labelFontSize(height),
56
+ color: stroke,
57
+ textAlign: 'center',
58
+ },
59
+ },
60
+ };
61
+ return [text];
62
+ }
63
+
64
+ let primary: Layer;
65
+ if (shape.kind === 'rect' || shape.kind === 'circle') {
66
+ const layer: ShapeLayer = {
67
+ id: `${SHAPE_PREFIX}${id}`,
68
+ type: 'shape',
69
+ position: { x, y, width, height },
70
+ content: {
71
+ shape: shape.kind,
72
+ fill,
73
+ stroke,
74
+ strokeWidth,
75
+ ...(shape.kind === 'rect' && shape.borderRadius != null
76
+ ? { borderRadius: shape.borderRadius }
77
+ : {}),
78
+ },
79
+ };
80
+ primary = layer;
81
+ } else if (shape.kind === 'path') {
82
+ const layer: PathLayer = {
83
+ id: `${SHAPE_PREFIX}${id}`,
84
+ type: 'path',
85
+ position: { x, y, width, height },
86
+ content: {
87
+ d: shape.d ?? `M ${x} ${y} L ${x + width} ${y + height}`,
88
+ stroke,
89
+ strokeWidth,
90
+ fill,
91
+ ...(shape.dasharray ? { dasharray: shape.dasharray } : {}),
92
+ },
93
+ };
94
+ primary = layer;
95
+ } else if (shape.kind === 'line') {
96
+ // Plain line → a bounding-box line (editable via resize handles).
97
+ const layer: ShapeLayer = {
98
+ id: `${SHAPE_PREFIX}${id}`,
99
+ type: 'shape',
100
+ position: { x, y, width, height },
101
+ content: { shape: 'line', stroke, strokeWidth },
102
+ };
103
+ primary = layer;
104
+ } else if (shape.kind === 'arrow') {
105
+ const layer: PathLayer = {
106
+ id: `${SHAPE_PREFIX}${id}`,
107
+ type: 'path',
108
+ position: { x, y, width, height },
109
+ content: {
110
+ d: `M ${x} ${y} L ${x + width} ${y + height}`,
111
+ stroke,
112
+ strokeWidth,
113
+ fill: 'none',
114
+ endMarker: 'arrow',
115
+ },
116
+ };
117
+ primary = layer;
118
+ } else {
119
+ // Named polygon / curved shape → computed filled path.
120
+ const layer: PathLayer = {
121
+ id: `${SHAPE_PREFIX}${id}`,
122
+ type: 'path',
123
+ position: { x, y, width, height },
124
+ content: {
125
+ d: shapePath(shape.kind, x, y, width, height) ?? `M ${x} ${y} L ${x + width} ${y + height}`,
126
+ stroke,
127
+ strokeWidth,
128
+ fill,
129
+ ...(shape.dasharray ? { dasharray: shape.dasharray } : {}),
130
+ },
131
+ };
132
+ primary = layer;
133
+ }
134
+
135
+ const out: Layer[] = [primary];
136
+ if (shape.label) {
137
+ // No explicit height keeps the label out of the hit-test (the primary
138
+ // wins pointer-down), exactly like nodeCard's label.
139
+ out.push({
140
+ id: `${LABEL_PREFIX}${id}`,
141
+ type: 'text',
142
+ position: { x: x + width / 2, y: y + height / 2, width, anchor: 'center' },
143
+ content: {
144
+ text: shape.label,
145
+ style: {
146
+ fontSize: labelFontSize(height),
147
+ fontWeight: 'bold',
148
+ color: stroke,
149
+ textAlign: 'center',
150
+ },
151
+ },
152
+ } satisfies TextLayer);
153
+ }
154
+ return out;
155
+ }
156
+
157
+ /** Convert shapes to a flat Layer[] — primaries first, then labels (paint order). */
158
+ export function shapesToSceneLayers(shapes: readonly DrawingShape[]): Layer[] {
159
+ const primaries: Layer[] = [];
160
+ const labels: Layer[] = [];
161
+ for (const shape of shapes) {
162
+ const [primary, label] = shapeToLayers(shape);
163
+ primaries.push(primary);
164
+ if (label) labels.push(label);
165
+ }
166
+ return [...primaries, ...labels];
167
+ }
168
+
169
+ /** `{id,x,y,width,height}` boxes for the connector renderer. */
170
+ export function shapeBoxes(shapes: readonly DrawingShape[]): ShapeBox[] {
171
+ return shapes.map((s) => ({ id: s.id, x: s.x, y: s.y, width: s.width, height: s.height }));
172
+ }
173
+
174
+ /** A label layer follows its primary shape during drag/resize previews. */
175
+ export function drawingLayerFollows(layerId: string): string | null {
176
+ if (layerId.startsWith(LABEL_PREFIX)) {
177
+ return `${SHAPE_PREFIX}${layerId.slice(LABEL_PREFIX.length)}`;
178
+ }
179
+ return null;
180
+ }
181
+
182
+ /** Recover the shape (heading) id from a primary or label layer id. */
183
+ export function shapeIdFromLayerId(layerId: string): string | null {
184
+ if (layerId.startsWith(SHAPE_PREFIX)) return layerId.slice(SHAPE_PREFIX.length);
185
+ if (layerId.startsWith(LABEL_PREFIX)) return layerId.slice(LABEL_PREFIX.length);
186
+ return null;
187
+ }
188
+
189
+ /** True for a primary shape layer id (not a label). */
190
+ export function isPrimaryShapeLayer(layerId: string): boolean {
191
+ return layerId.startsWith(SHAPE_PREFIX);
192
+ }
193
+
194
+ /** The primary layer id for a shape (heading) id. */
195
+ export function primaryLayerId(shapeId: string): string {
196
+ return `${SHAPE_PREFIX}${shapeId}`;
197
+ }
198
+
199
+ function labelFontSize(height: number): number {
200
+ return Math.max(12, Math.min(48, Math.round(height * 0.34)));
201
+ }
@@ -0,0 +1,208 @@
1
+ /**
2
+ * bezierEdit — parse / serialize SVG path `d` strings to and from an
3
+ * editable control-point representation.
4
+ *
5
+ * v1 supports the common subset authors actually draw:
6
+ * - `M x y` (moveto, absolute)
7
+ * - `L x y` (lineto, absolute)
8
+ * - `C x1 y1 x2 y2 x y` (cubic bezier)
9
+ * - `Z` / `z` (closepath)
10
+ *
11
+ * Other commands (Q, T, A, S, H, V, relative variants) round-trip as
12
+ * opaque tokens — they survive serialize/parse but can't be edited via
13
+ * control points in the UI. This keeps the editor honest about what it
14
+ * can edit while still preserving paths authored by hand.
15
+ */
16
+
17
+ export interface PathPoint {
18
+ /** Anchor coordinate (where a segment ends / a moveto starts). */
19
+ x: number;
20
+ y: number;
21
+ /**
22
+ * Incoming control handle (controls the curve approaching this point).
23
+ * Null for moveto and lineto segments.
24
+ */
25
+ cpIn?: { x: number; y: number };
26
+ /**
27
+ * Outgoing control handle (controls the curve leaving this point).
28
+ * Null for the final point in an open path.
29
+ */
30
+ cpOut?: { x: number; y: number };
31
+ /**
32
+ * The SVG command that produced this point. Drives serialization back
33
+ * to the right command letter.
34
+ */
35
+ kind: 'move' | 'line' | 'curve' | 'close';
36
+ }
37
+
38
+ export interface ParsedPath {
39
+ points: PathPoint[];
40
+ /** True if the path ends with `Z`/`z`. */
41
+ closed: boolean;
42
+ }
43
+
44
+ /**
45
+ * Parse an SVG `d` string. Unknown commands are silently skipped — they
46
+ * don't appear in the result, which means re-serializing a parsed-then-
47
+ * serialized path is lossless only for the supported subset. Callers
48
+ * that need fidelity should keep the original string around for
49
+ * untouched paths.
50
+ */
51
+ export function parsePath(d: string): ParsedPath {
52
+ const tokens = tokenize(d);
53
+ const points: PathPoint[] = [];
54
+ let closed = false;
55
+ let i = 0;
56
+ while (i < tokens.length) {
57
+ const cmd = tokens[i++];
58
+ if (typeof cmd !== 'string') continue;
59
+ switch (cmd) {
60
+ case 'M':
61
+ case 'm': {
62
+ const x = takeNum(tokens, i++);
63
+ const y = takeNum(tokens, i++);
64
+ if (x == null || y == null) return { points, closed };
65
+ points.push({ kind: 'move', x, y });
66
+ // Subsequent coordinate pairs after an M are implicit L's.
67
+ while (i + 1 < tokens.length && typeof tokens[i] === 'number') {
68
+ const lx = takeNum(tokens, i++);
69
+ const ly = takeNum(tokens, i++);
70
+ if (lx == null || ly == null) break;
71
+ points.push({ kind: 'line', x: lx, y: ly });
72
+ }
73
+ break;
74
+ }
75
+ case 'L':
76
+ case 'l': {
77
+ while (i + 1 < tokens.length && typeof tokens[i] === 'number') {
78
+ const x = takeNum(tokens, i++);
79
+ const y = takeNum(tokens, i++);
80
+ if (x == null || y == null) break;
81
+ points.push({ kind: 'line', x, y });
82
+ }
83
+ break;
84
+ }
85
+ case 'C':
86
+ case 'c': {
87
+ while (i + 5 < tokens.length && typeof tokens[i] === 'number') {
88
+ const x1 = takeNum(tokens, i++);
89
+ const y1 = takeNum(tokens, i++);
90
+ const x2 = takeNum(tokens, i++);
91
+ const y2 = takeNum(tokens, i++);
92
+ const x = takeNum(tokens, i++);
93
+ const y = takeNum(tokens, i++);
94
+ if (x1 == null || y1 == null || x2 == null || y2 == null || x == null || y == null) break;
95
+ // The previous point gets an outgoing control handle.
96
+ const prev = points[points.length - 1];
97
+ if (prev) prev.cpOut = { x: x1, y: y1 };
98
+ points.push({ kind: 'curve', x, y, cpIn: { x: x2, y: y2 } });
99
+ }
100
+ break;
101
+ }
102
+ case 'Z':
103
+ case 'z':
104
+ closed = true;
105
+ break;
106
+ default:
107
+ // Unsupported command — skip any numeric args that follow.
108
+ while (i < tokens.length && typeof tokens[i] === 'number') i++;
109
+ break;
110
+ }
111
+ }
112
+ return { points, closed };
113
+ }
114
+
115
+ /**
116
+ * Serialize a ParsedPath back into an SVG `d` string. Uses absolute
117
+ * commands and a single space between tokens. Round-trip behavior:
118
+ * `serialize(parse(d))` is equivalent (not byte-identical) for paths
119
+ * built from M/L/C/Z; whitespace and number formatting are normalized.
120
+ */
121
+ export function serializePath(path: ParsedPath): string {
122
+ const parts: string[] = [];
123
+ for (let i = 0; i < path.points.length; i++) {
124
+ const p = path.points[i];
125
+ switch (p.kind) {
126
+ case 'move':
127
+ parts.push(`M ${fmt(p.x)} ${fmt(p.y)}`);
128
+ break;
129
+ case 'line':
130
+ parts.push(`L ${fmt(p.x)} ${fmt(p.y)}`);
131
+ break;
132
+ case 'curve': {
133
+ const prev = path.points[i - 1];
134
+ const out = prev?.cpOut ?? { x: prev?.x ?? p.x, y: prev?.y ?? p.y };
135
+ const inc = p.cpIn ?? { x: p.x, y: p.y };
136
+ parts.push(
137
+ `C ${fmt(out.x)} ${fmt(out.y)} ${fmt(inc.x)} ${fmt(inc.y)} ${fmt(p.x)} ${fmt(p.y)}`,
138
+ );
139
+ break;
140
+ }
141
+ case 'close':
142
+ // Encoded via the trailing Z below.
143
+ break;
144
+ }
145
+ }
146
+ if (path.closed) parts.push('Z');
147
+ return parts.join(' ');
148
+ }
149
+
150
+ /**
151
+ * Update the anchor coordinate of point `index`, shifting its incoming
152
+ * and outgoing control handles by the same delta so the curve shape is
153
+ * preserved. Returns a new ParsedPath; doesn't mutate the input.
154
+ */
155
+ export function moveAnchor(path: ParsedPath, index: number, dx: number, dy: number): ParsedPath {
156
+ if (index < 0 || index >= path.points.length) return path;
157
+ const next: PathPoint[] = path.points.map((p, i) => {
158
+ if (i !== index) return p;
159
+ const out: PathPoint = { ...p, x: p.x + dx, y: p.y + dy };
160
+ if (p.cpIn) out.cpIn = { x: p.cpIn.x + dx, y: p.cpIn.y + dy };
161
+ if (p.cpOut) out.cpOut = { x: p.cpOut.x + dx, y: p.cpOut.y + dy };
162
+ return out;
163
+ });
164
+ return { points: next, closed: path.closed };
165
+ }
166
+
167
+ /** Update a single control handle on point `index`. */
168
+ export function moveHandle(
169
+ path: ParsedPath,
170
+ index: number,
171
+ side: 'cpIn' | 'cpOut',
172
+ x: number,
173
+ y: number,
174
+ ): ParsedPath {
175
+ if (index < 0 || index >= path.points.length) return path;
176
+ const next: PathPoint[] = path.points.map((p, i) => {
177
+ if (i !== index) return p;
178
+ return { ...p, [side]: { x, y } } as PathPoint;
179
+ });
180
+ return { points: next, closed: path.closed };
181
+ }
182
+
183
+ // ── Internals ──────────────────────────────────────────────
184
+
185
+ type Token = string | number;
186
+
187
+ function tokenize(d: string): Token[] {
188
+ const out: Token[] = [];
189
+ // Split on whitespace and commas, plus pull out single-letter commands.
190
+ const re = /([a-zA-Z])|(-?\d*\.?\d+(?:[eE][+-]?\d+)?)/g;
191
+ let m: RegExpExecArray | null;
192
+ while ((m = re.exec(d)) !== null) {
193
+ if (m[1]) out.push(m[1]);
194
+ else if (m[2]) out.push(parseFloat(m[2]));
195
+ }
196
+ return out;
197
+ }
198
+
199
+ function takeNum(tokens: Token[], i: number): number | null {
200
+ const t = tokens[i];
201
+ return typeof t === 'number' ? t : null;
202
+ }
203
+
204
+ function fmt(n: number): string {
205
+ // Keep integer-valued numbers tidy; otherwise trim to 3 decimal places.
206
+ if (Number.isInteger(n)) return String(n);
207
+ return n.toFixed(3).replace(/\.?0+$/, '');
208
+ }