@bendyline/squisq-editor-react 1.5.3 → 1.6.1

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 (186) hide show
  1. package/README.md +57 -10
  2. package/dist/index.d.ts +1114 -52
  3. package/dist/index.js +18446 -8050
  4. package/dist/index.js.map +1 -1
  5. package/dist/styles/fa-brands-400-AHOAZHCU.woff2 +0 -0
  6. package/dist/styles/fa-regular-400-VRZYIBIZ.woff2 +0 -0
  7. package/dist/styles/fa-solid-900-MDEYK55F.woff2 +0 -0
  8. package/dist/styles/fa-v4compatibility-ETEVP6IB.woff2 +0 -0
  9. package/dist/styles/index.css +13867 -0
  10. package/package.json +15 -7
  11. package/src/BlockCardView.tsx +121 -0
  12. package/src/BlockPreviewPanel.tsx +69 -0
  13. package/src/BlockPropertiesPopover.tsx +191 -0
  14. package/src/EditorContext.tsx +165 -16
  15. package/src/EditorShell.tsx +265 -144
  16. package/src/FolderView.tsx +131 -0
  17. package/src/Icon.tsx +26 -0
  18. package/src/ImageEditor.tsx +69 -22
  19. package/src/OutlinePanel.tsx +64 -7
  20. package/src/PlainHtmlPreview.tsx +30 -3
  21. package/src/PreviewControls.tsx +491 -122
  22. package/src/PreviewPanel.tsx +15 -9
  23. package/src/RawEditor.tsx +179 -17
  24. package/src/RecorderEntry.tsx +9 -16
  25. package/src/TemplateAnnotation.ts +44 -0
  26. package/src/TemplatePicker.tsx +329 -54
  27. package/src/ThemeCustomizerPanel.tsx +30 -336
  28. package/src/ThemePicker.tsx +112 -3
  29. package/src/TimelineBlockPreview.tsx +37 -0
  30. package/src/TimelineTrack.tsx +671 -0
  31. package/src/Toolbar.tsx +544 -180
  32. package/src/Tooltip.tsx +22 -4
  33. package/src/TransitionPicker.tsx +351 -0
  34. package/src/VersionHistoryPanel.tsx +4 -16
  35. package/src/ViewMenuPanel.tsx +17 -14
  36. package/src/WysiwygEditor.tsx +161 -65
  37. package/src/__tests__/blockProperties.test.ts +92 -0
  38. package/src/__tests__/blockRange.test.ts +105 -0
  39. package/src/__tests__/buildPreviewDocTransition.test.ts +73 -0
  40. package/src/__tests__/codeContextSectionView.test.tsx +95 -0
  41. package/src/__tests__/codeContextZoneManager.test.ts +127 -0
  42. package/src/__tests__/createShapeLayer.test.ts +46 -0
  43. package/src/__tests__/diffContextSections.test.ts +39 -0
  44. package/src/__tests__/drawingShapeRoundTrip.test.ts +49 -0
  45. package/src/__tests__/editorShellCodeContext.test.tsx +86 -0
  46. package/src/__tests__/editorShellProps.test.tsx +96 -0
  47. package/src/__tests__/embeddedMedia.test.ts +48 -0
  48. package/src/__tests__/headingTransition.test.ts +138 -0
  49. package/src/__tests__/layoutChildRoundTrip.test.ts +71 -0
  50. package/src/__tests__/plainHtmlPreview.test.tsx +10 -8
  51. package/src/__tests__/previewControls.test.tsx +70 -0
  52. package/src/__tests__/recorderMediaInsert.test.ts +86 -0
  53. package/src/__tests__/templateAnnotationRoundTrip.test.ts +18 -0
  54. package/src/__tests__/templatePickerMetadata.test.ts +32 -0
  55. package/src/__tests__/timelineSource.test.ts +134 -0
  56. package/src/__tests__/tiptapBridge.test.ts +92 -0
  57. package/src/__tests__/tiptapBridgeConformance.test.ts +47 -0
  58. package/src/__tests__/tooltip.test.tsx +72 -0
  59. package/src/__tests__/transitionCatalog.test.ts +64 -0
  60. package/src/__tests__/useBlockNavigator.test.tsx +67 -0
  61. package/src/__tests__/useJsonEditorTokens.test.ts +59 -0
  62. package/src/__tests__/useMediaRecorder.test.ts +41 -0
  63. package/src/__tests__/useTimelineClock.test.ts +21 -0
  64. package/src/blockProperties.ts +88 -0
  65. package/src/blockRange.ts +132 -0
  66. package/src/buildPreviewDoc.ts +98 -9
  67. package/src/codeContext/CodeContextSectionView.tsx +124 -0
  68. package/src/codeContext/CodeContextZoneManager.ts +149 -0
  69. package/src/codeContext/CodeContextZones.tsx +121 -0
  70. package/src/codeContext/diffContextSections.ts +38 -0
  71. package/src/codeContext/types.ts +75 -0
  72. package/src/customTemplates/AddBin.tsx +126 -0
  73. package/src/customTemplates/CustomLayoutManager.tsx +233 -0
  74. package/src/customTemplates/CustomTemplateContext.tsx +182 -0
  75. package/src/customTemplates/LayerToolbar.tsx +580 -0
  76. package/src/customTemplates/ShapeGlyph.tsx +47 -0
  77. package/src/customTemplates/TemplateDesigner.tsx +430 -0
  78. package/src/customTemplates/__tests__/library.test.ts +88 -0
  79. package/src/customTemplates/__tests__/normalizePositions.test.ts +109 -0
  80. package/src/customTemplates/__tests__/shapeDefs.test.ts +49 -0
  81. package/src/customTemplates/__tests__/useMemoryLayerAdapter.test.ts +95 -0
  82. package/src/customTemplates/designer.css +673 -0
  83. package/src/customTemplates/index.ts +31 -0
  84. package/src/customTemplates/library.ts +97 -0
  85. package/src/customTemplates/normalizePositions.ts +75 -0
  86. package/src/customTemplates/shapeDefs.ts +131 -0
  87. package/src/customTemplates/thumbnail.tsx +63 -0
  88. package/src/customTemplates/tokenDefs.ts +60 -0
  89. package/src/customTemplates/useDocCustomTemplates.ts +52 -0
  90. package/src/customTemplates/useMemoryLayerAdapter.ts +123 -0
  91. package/src/customThemes/CustomThemeContext.tsx +179 -0
  92. package/src/customThemes/CustomThemeDialog.tsx +286 -0
  93. package/src/customThemes/__tests__/CustomThemeContext.test.tsx +64 -0
  94. package/src/customThemes/__tests__/CustomThemeDialog.test.tsx +47 -0
  95. package/src/customThemes/__tests__/customThemeLibrary.test.ts +51 -0
  96. package/src/customThemes/customThemeLibrary.ts +97 -0
  97. package/src/customThemes/index.ts +31 -0
  98. package/src/customThemes/themeControls.tsx +229 -0
  99. package/src/customThemes/themeDraft.ts +272 -0
  100. package/src/customThemes/useDocCustomThemes.ts +49 -0
  101. package/src/diagram/DiagramCanvas.tsx +240 -0
  102. package/src/diagram/DiagramExtension.ts +209 -0
  103. package/src/diagram/DiagramMaximizedOverlay.tsx +46 -0
  104. package/src/diagram/DiagramWidget.tsx +270 -0
  105. package/src/diagram/diagramCommands.ts +604 -0
  106. package/src/diagram/diagramConstants.ts +17 -0
  107. package/src/diagram/useDiagramData.ts +126 -0
  108. package/src/embeddedMedia.ts +78 -0
  109. package/src/frontmatter.ts +29 -0
  110. package/src/headingTransition.ts +231 -0
  111. package/src/imageEditor/CanvasSurface.tsx +383 -88
  112. package/src/imageEditor/PropertiesPanel.tsx +47 -1
  113. package/src/imageEditor/Toolbar.tsx +229 -16
  114. package/src/imageEditor/createShapeLayer.ts +280 -0
  115. package/src/imageEditor/icons.tsx +34 -114
  116. package/src/imageEditor/image-editor.css +54 -5
  117. package/src/imageEditor/state.ts +23 -3
  118. package/src/index.ts +109 -1
  119. package/src/jsonEditor/useJsonEditorTokens.ts +13 -43
  120. package/src/recorder/RecorderModal.tsx +120 -53
  121. package/src/recorder/RecorderPanel.tsx +2 -26
  122. package/src/recorder/hooks/useMediaRecorder.ts +17 -11
  123. package/src/recorder/insertMediaBlock.ts +30 -0
  124. package/src/resolveBlockVisual.ts +33 -0
  125. package/src/scene/Scene.tsx +540 -0
  126. package/src/scene/SceneBlockExtension.ts +198 -0
  127. package/src/scene/SceneBlockToolbar.tsx +201 -0
  128. package/src/scene/SceneBlockWidget.tsx +434 -0
  129. package/src/scene/ScenePropsBar.tsx +85 -0
  130. package/src/scene/SceneSelection.tsx +107 -0
  131. package/src/scene/SceneViewport.tsx +102 -0
  132. package/src/scene/ShapePalette.tsx +181 -0
  133. package/src/scene/__tests__/DiagramAdapter.test.ts +56 -0
  134. package/src/scene/__tests__/bezierEdit.test.ts +85 -0
  135. package/src/scene/__tests__/blockLayers.test.ts +57 -0
  136. package/src/scene/__tests__/shapeLayers.test.ts +106 -0
  137. package/src/scene/__tests__/useSceneHitTest.test.ts +90 -0
  138. package/src/scene/__tests__/useScenePanZoom.test.ts +103 -0
  139. package/src/scene/adapters/DiagramAdapter.ts +168 -0
  140. package/src/scene/adapters/DrawingAdapter.ts +415 -0
  141. package/src/scene/adapters/LayoutAdapter.ts +310 -0
  142. package/src/scene/adapters/blockLayers.ts +159 -0
  143. package/src/scene/commands/SceneCommand.ts +70 -0
  144. package/src/scene/commands/drawingCommands.ts +318 -0
  145. package/src/scene/commands/layoutCommands.ts +301 -0
  146. package/src/scene/hooks/useSceneHitTest.ts +105 -0
  147. package/src/scene/hooks/useScenePanZoom.ts +147 -0
  148. package/src/scene/hooks/useSceneSelection.ts +62 -0
  149. package/src/scene/index.ts +95 -0
  150. package/src/scene/layers/DiagramEdges.tsx +127 -0
  151. package/src/scene/layers/edgeGeometry.ts +77 -0
  152. package/src/scene/layers/nodeCard.tsx +145 -0
  153. package/src/scene/layers/renderLayer.tsx +70 -0
  154. package/src/scene/layers/shapeLayers.ts +201 -0
  155. package/src/scene/paths/bezierEdit.ts +208 -0
  156. package/src/scene/scene.css +649 -0
  157. package/src/scene/text/SceneTextOverlay.tsx +161 -0
  158. package/src/scene/text/sceneTextChannel.ts +40 -0
  159. package/src/scene/text/sceneTextConfig.ts +27 -0
  160. package/src/scene/text/sceneTiptap.ts +36 -0
  161. package/src/scene/text/useSceneTextEditing.ts +39 -0
  162. package/src/scene/tools/ConnectTool.ts +111 -0
  163. package/src/scene/tools/DrawingConnectTool.ts +161 -0
  164. package/src/scene/tools/PathTool.ts +158 -0
  165. package/src/scene/tools/PlaceTool.ts +47 -0
  166. package/src/scene/tools/SceneTool.ts +75 -0
  167. package/src/scene/tools/SelectTool.ts +284 -0
  168. package/src/scene/tools/ShapeTool.ts +144 -0
  169. package/src/scene/tools/TextTool.ts +72 -0
  170. package/src/scene/tools/TokenTool.ts +95 -0
  171. package/src/scene/tools/createDrawShapeTool.ts +82 -0
  172. package/src/styles/code-context.css +155 -0
  173. package/src/styles/diagram.css +183 -0
  174. package/src/styles/editor.css +1708 -150
  175. package/src/styles/folder-view.css +210 -0
  176. package/src/styles/image-edit-affordance.css +2 -2
  177. package/src/styles/index.css +5 -0
  178. package/src/timelineSource.ts +244 -0
  179. package/src/tiptapBridge.ts +115 -34
  180. package/src/tooltipPlacement.ts +13 -0
  181. package/src/transitionCatalog.ts +159 -0
  182. package/src/types/monaco-shims.d.ts +10 -0
  183. package/src/useBlockNavigator.ts +153 -0
  184. package/src/useMonacoLoader.ts +23 -1
  185. package/src/useTimelineClock.ts +76 -0
  186. package/src/utils/dropUtils.ts +1 -1
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Browser-local library of user-defined custom templates.
3
+ *
4
+ * Library templates live in `localStorage` under
5
+ * `LIBRARY_STORAGE_KEY`. They're a cross-doc convenience — a personal
6
+ * collection of designs the user reuses across documents — but they're
7
+ * NOT used by the SSR pipeline. When a user applies a library template
8
+ * to a block, `applyTemplate` (in CustomTemplateContext) copies the
9
+ * definition into the doc's `customTemplates` so the doc remains
10
+ * self-sufficient (the markdown file ships with everything it needs).
11
+ *
12
+ * Safe to import in SSR / Node — gracefully no-ops when
13
+ * `localStorage` is unavailable.
14
+ */
15
+
16
+ import type { CustomTemplateDefinition } from '@bendyline/squisq/schemas';
17
+
18
+ export const LIBRARY_STORAGE_KEY = 'squisq:custom-template-library';
19
+
20
+ interface LibraryPayload {
21
+ /** Schema version for forward-compatibility. */
22
+ version: 1;
23
+ templates: CustomTemplateDefinition[];
24
+ }
25
+
26
+ function safeStorage(): Storage | null {
27
+ try {
28
+ return typeof globalThis !== 'undefined' && globalThis.localStorage
29
+ ? globalThis.localStorage
30
+ : null;
31
+ } catch {
32
+ // Some browsers throw on localStorage access in private mode.
33
+ return null;
34
+ }
35
+ }
36
+
37
+ function readPayload(): LibraryPayload {
38
+ const storage = safeStorage();
39
+ if (!storage) return { version: 1, templates: [] };
40
+ const raw = storage.getItem(LIBRARY_STORAGE_KEY);
41
+ if (!raw) return { version: 1, templates: [] };
42
+ try {
43
+ const parsed = JSON.parse(raw) as Partial<LibraryPayload>;
44
+ if (parsed && Array.isArray(parsed.templates)) {
45
+ return { version: 1, templates: parsed.templates };
46
+ }
47
+ } catch {
48
+ // Corrupt payload — drop it.
49
+ }
50
+ return { version: 1, templates: [] };
51
+ }
52
+
53
+ function writePayload(payload: LibraryPayload): void {
54
+ const storage = safeStorage();
55
+ if (!storage) return;
56
+ try {
57
+ storage.setItem(LIBRARY_STORAGE_KEY, JSON.stringify(payload));
58
+ } catch {
59
+ // Quota exceeded or storage disabled — best-effort write.
60
+ }
61
+ }
62
+
63
+ /** Return every template currently in the user's library, sorted by label. */
64
+ export function listLibraryTemplates(): CustomTemplateDefinition[] {
65
+ const { templates } = readPayload();
66
+ return templates.slice().sort((a, b) => a.label.localeCompare(b.label));
67
+ }
68
+
69
+ /**
70
+ * Insert or replace a library template (matched by `name`). Returns
71
+ * the persisted list so callers can update their state without
72
+ * re-reading.
73
+ */
74
+ export function saveLibraryTemplate(def: CustomTemplateDefinition): CustomTemplateDefinition[] {
75
+ const payload = readPayload();
76
+ const idx = payload.templates.findIndex((t) => t.name === def.name);
77
+ if (idx >= 0) {
78
+ payload.templates[idx] = def;
79
+ } else {
80
+ payload.templates.push(def);
81
+ }
82
+ writePayload(payload);
83
+ return payload.templates.slice().sort((a, b) => a.label.localeCompare(b.label));
84
+ }
85
+
86
+ /** Remove a library template by name. Returns the updated list. */
87
+ export function deleteLibraryTemplate(name: string): CustomTemplateDefinition[] {
88
+ const payload = readPayload();
89
+ payload.templates = payload.templates.filter((t) => t.name !== name);
90
+ writePayload(payload);
91
+ return payload.templates.slice().sort((a, b) => a.label.localeCompare(b.label));
92
+ }
93
+
94
+ /** Wipe the entire library — useful for tests and "reset" affordances. */
95
+ export function clearLibrary(): void {
96
+ writePayload({ version: 1, templates: [] });
97
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Normalize numeric position fields on a Layer[] to `%`-strings
3
+ * relative to the designer canvas.
4
+ *
5
+ * Why: the designer drags layers around in pixel coordinates (that's
6
+ * how pointer events work), but saved templates need to be
7
+ * resolution-independent so the same definition renders correctly
8
+ * across the landscape / portrait / square viewport presets. On Save
9
+ * we run this normalizer to convert pixel positions to percentages.
10
+ *
11
+ * Width / height are converted against their own dimension (width
12
+ * against canvas width, height against canvas height) — not "always
13
+ * against width" like SVG `viewBox`-style coordinates.
14
+ *
15
+ * Already-`%`-valued fields are preserved verbatim. Anchor fields and
16
+ * non-position content fields are untouched. Layers without an
17
+ * explicit `position` are passed through unchanged.
18
+ */
19
+
20
+ import type { Layer, Position } from '@bendyline/squisq/schemas';
21
+
22
+ export interface Canvas {
23
+ width: number;
24
+ height: number;
25
+ }
26
+
27
+ /**
28
+ * Return a new Layer[] where each numeric position field has been
29
+ * converted to a `%`-string relative to `canvas`. Pure function;
30
+ * doesn't mutate the input.
31
+ */
32
+ export function normalizePositions(layers: readonly Layer[], canvas: Canvas): Layer[] {
33
+ return layers.map((layer) => normalizeLayer(layer, canvas));
34
+ }
35
+
36
+ function normalizeLayer<L extends Layer>(layer: L, canvas: Canvas): L {
37
+ if (!layer.position) return layer;
38
+ const pos: Position = { ...layer.position };
39
+ if (pos.x !== undefined) pos.x = toPercent(pos.x, canvas.width);
40
+ if (pos.y !== undefined) pos.y = toPercent(pos.y, canvas.height);
41
+ if (pos.width !== undefined) pos.width = toPercent(pos.width, canvas.width);
42
+ if (pos.height !== undefined) pos.height = toPercent(pos.height, canvas.height);
43
+ // `anchor` (top-left / center / etc.) is preserved verbatim.
44
+ return { ...layer, position: pos } as L;
45
+ }
46
+
47
+ /**
48
+ * Convert a single position value to a `%`-string. Already-string
49
+ * `%` values pass through; non-numeric strings (e.g. hand-written
50
+ * pixel expressions) are returned unchanged so we don't corrupt
51
+ * intentional author markup.
52
+ */
53
+ function toPercent(value: number | string, base: number): string {
54
+ if (typeof value === 'string') {
55
+ if (value.endsWith('%')) return value;
56
+ // Try to parse as a number ("180" → 180px → percent).
57
+ const n = parseFloat(value);
58
+ if (Number.isFinite(n) && String(n) === value) {
59
+ return formatPercent((n / base) * 100);
60
+ }
61
+ return value;
62
+ }
63
+ if (!Number.isFinite(value) || base <= 0) return String(value);
64
+ return formatPercent((value / base) * 100);
65
+ }
66
+
67
+ /** Format a percentage with up to two decimal places, trailing zeros trimmed. */
68
+ function formatPercent(pct: number): string {
69
+ // Round to 0.01% precision — enough for visually faithful round-trip
70
+ // without bloating the saved layout JSON.
71
+ const rounded = Math.round(pct * 100) / 100;
72
+ // Drop trailing zeros: 50.00 → "50%", 50.10 → "50.1%".
73
+ const str = rounded.toString();
74
+ return `${str}%`;
75
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Standard shape definitions for the template designer's "Add" bin.
3
+ *
4
+ * Each entry maps to one of Squisq's shape kinds. The three primitives
5
+ * the renderer draws natively (`rect`, `circle`, `line`) become a
6
+ * `ShapeLayer`; every other kind is compiled to an SVG path via
7
+ * {@link shapePath} and stored as a `PathLayer` — the same split the
8
+ * `drawing` template uses (see `shapeGeometry.ts`). Both render through
9
+ * the shared layer components, so the bin preview, the editor canvas,
10
+ * and the final block render stay identical.
11
+ *
12
+ * Like {@link TOKEN_DEFS}, a shape can be placed two ways: drag it onto
13
+ * the canvas (the drag carries the id on {@link SHAPE_DRAG_MIME}) or
14
+ * click it to arm the matching place tool, then click the canvas.
15
+ */
16
+
17
+ import type { Layer, PathLayer, ShapeLayer } from '@bendyline/squisq/schemas';
18
+ import { shapePath } from '@bendyline/squisq/doc';
19
+
20
+ /** MIME type carried on the drag's `dataTransfer` for a shape. */
21
+ export const SHAPE_DRAG_MIME = 'application/x-squisq-shape';
22
+
23
+ export interface ShapeDef {
24
+ /** Stable id, used both as the place-tool id and the drag payload. */
25
+ id: string;
26
+ /** Short button label. */
27
+ label: string;
28
+ /**
29
+ * Shape kind. `rect`/`circle`/`line` render as a native `ShapeLayer`;
30
+ * any other kind is compiled to a `PathLayer` path via `shapePath`.
31
+ */
32
+ kind: string;
33
+ /** For `rect`: render with rounded corners. */
34
+ rounded?: boolean;
35
+ }
36
+
37
+ export const SHAPE_DEFS: ShapeDef[] = [
38
+ { id: 'shape-rect', label: 'Rectangle', kind: 'rect' },
39
+ { id: 'shape-rect-rounded', label: 'Rounded', kind: 'rect', rounded: true },
40
+ { id: 'shape-circle', label: 'Ellipse', kind: 'circle' },
41
+ { id: 'shape-line', label: 'Line', kind: 'line' },
42
+ { id: 'shape-triangle', label: 'Triangle', kind: 'triangle' },
43
+ { id: 'shape-right-triangle', label: 'Right triangle', kind: 'right-triangle' },
44
+ { id: 'shape-diamond', label: 'Diamond', kind: 'diamond' },
45
+ { id: 'shape-pentagon', label: 'Pentagon', kind: 'pentagon' },
46
+ { id: 'shape-hexagon', label: 'Hexagon', kind: 'hexagon' },
47
+ { id: 'shape-octagon', label: 'Octagon', kind: 'octagon' },
48
+ { id: 'shape-star', label: 'Star', kind: 'star' },
49
+ { id: 'shape-star4', label: '4-point star', kind: 'star4' },
50
+ { id: 'shape-star6', label: '6-point star', kind: 'star6' },
51
+ { id: 'shape-parallelogram', label: 'Parallelogram', kind: 'parallelogram' },
52
+ { id: 'shape-trapezoid', label: 'Trapezoid', kind: 'trapezoid' },
53
+ { id: 'shape-plus', label: 'Plus', kind: 'plus' },
54
+ { id: 'shape-chevron', label: 'Chevron', kind: 'chevron' },
55
+ { id: 'shape-arrow-right', label: 'Arrow right', kind: 'arrow-right' },
56
+ { id: 'shape-arrow-left', label: 'Arrow left', kind: 'arrow-left' },
57
+ { id: 'shape-arrow-up', label: 'Arrow up', kind: 'arrow-up' },
58
+ { id: 'shape-arrow-down', label: 'Arrow down', kind: 'arrow-down' },
59
+ { id: 'shape-double-arrow', label: 'Double arrow', kind: 'double-arrow' },
60
+ { id: 'shape-callout', label: 'Callout', kind: 'callout' },
61
+ { id: 'shape-cylinder', label: 'Cylinder', kind: 'cylinder' },
62
+ { id: 'shape-cloud', label: 'Cloud', kind: 'cloud' },
63
+ { id: 'shape-heart', label: 'Heart', kind: 'heart' },
64
+ { id: 'shape-lightning', label: 'Lightning', kind: 'lightning' },
65
+ ];
66
+
67
+ /** Kinds the renderer draws natively as a `ShapeLayer`. */
68
+ const NATIVE_KINDS = new Set(['rect', 'circle', 'line']);
69
+
70
+ /** Default visual styling for a freshly placed shape. */
71
+ const FILL = '#e2e8f0'; // slate-200
72
+ const STROKE = '#475569'; // slate-600
73
+ const STROKE_WIDTH = 2;
74
+ const ROUNDED_RADIUS = 20;
75
+
76
+ /** Default placement box (top-left anchored at the drop/click point). */
77
+ function defaultSize(kind: string): { width: number; height: number } {
78
+ if (kind === 'line') return { width: 280, height: 120 };
79
+ return { width: 220, height: 180 };
80
+ }
81
+
82
+ let counter = 0;
83
+ function nextShapeId(): string {
84
+ counter += 1;
85
+ return `shape-${Date.now().toString(36)}-${counter}`;
86
+ }
87
+
88
+ /**
89
+ * Build the layer a shape def adds, top-left at the given viewport point.
90
+ * Native kinds produce a `ShapeLayer`; everything else a computed
91
+ * `PathLayer`. Shared by the click-to-place tool and the drag-drop
92
+ * handler so both paths produce identical layers.
93
+ */
94
+ export function buildShapeLayer(def: ShapeDef, point: { x: number; y: number }): Layer {
95
+ const { width, height } = defaultSize(def.kind);
96
+ const position = { x: point.x, y: point.y, width, height };
97
+ const id = nextShapeId();
98
+
99
+ if (NATIVE_KINDS.has(def.kind)) {
100
+ const layer: ShapeLayer = {
101
+ id,
102
+ type: 'shape',
103
+ position,
104
+ content: {
105
+ shape: def.kind as 'rect' | 'circle' | 'line',
106
+ fill: def.kind === 'line' ? 'none' : FILL,
107
+ stroke: STROKE,
108
+ strokeWidth: STROKE_WIDTH,
109
+ ...(def.kind === 'rect' ? { borderRadius: def.rounded ? ROUNDED_RADIUS : 0 } : {}),
110
+ },
111
+ };
112
+ return layer;
113
+ }
114
+
115
+ const layer: PathLayer = {
116
+ id,
117
+ type: 'path',
118
+ position,
119
+ content: {
120
+ // `d` is the initial geometry; `shapeKind` lets the renderer
121
+ // re-derive it from `position` so the shape moves, resizes, and
122
+ // adapts to the viewport (see PathLayer).
123
+ d: shapePath(def.kind, point.x, point.y, width, height) ?? '',
124
+ shapeKind: def.kind,
125
+ fill: FILL,
126
+ stroke: STROKE,
127
+ strokeWidth: STROKE_WIDTH,
128
+ },
129
+ };
130
+ return layer;
131
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Custom-template thumbnails for the picker gallery.
3
+ *
4
+ * Renders a CustomTemplateDefinition's layers in a small SVG that
5
+ * matches the picker card's icon slot (56×40). Layers are rendered via
6
+ * the same `RenderLayer` the editor canvas uses, so the thumbnail is
7
+ * an accurate (just smaller) preview.
8
+ *
9
+ * Tokens are NOT resolved — the thumbnail shows placeholder strings
10
+ * (`{title}`, `{content}`) so the user can see what fields the
11
+ * template will fill in. That's the point of a template preview.
12
+ */
13
+
14
+ import type { CustomTemplateDefinition } from '@bendyline/squisq/schemas';
15
+ import { RenderLayer } from '../scene/layers/renderLayer';
16
+
17
+ const W = 56;
18
+ const H = 40;
19
+
20
+ interface TemplateThumbnailProps {
21
+ def: CustomTemplateDefinition;
22
+ /** Override width / height (defaults match the picker icon slot). */
23
+ width?: number;
24
+ height?: number;
25
+ }
26
+
27
+ export function TemplateThumbnail({ def, width = W, height = H }: TemplateThumbnailProps) {
28
+ // The SVG renders the template's authoring viewport as its viewBox,
29
+ // so a 1920×1080 design becomes a 56×40 preview at the same aspect.
30
+ // `preserveAspectRatio="xMidYMid meet"` letterboxes when the
31
+ // requested width/height don't match — important for very narrow or
32
+ // very wide custom canvases.
33
+ return (
34
+ <svg
35
+ width={width}
36
+ height={height}
37
+ viewBox={`0 0 ${def.viewport.width} ${def.viewport.height}`}
38
+ preserveAspectRatio="xMidYMid meet"
39
+ className="squisq-template-thumbnail"
40
+ aria-hidden="true"
41
+ >
42
+ {/* Background so an all-text template doesn't paint over the card. */}
43
+ <rect width={def.viewport.width} height={def.viewport.height} fill="#f8fafc" />
44
+ {def.layers.map((layer) => (
45
+ <g key={layer.id}>
46
+ <RenderLayer layer={layer} viewport={def.viewport} />
47
+ </g>
48
+ ))}
49
+ {/* Subtle 1px border in viewport-space so the preview stays
50
+ distinguishable from the picker card around it. */}
51
+ <rect
52
+ x={0}
53
+ y={0}
54
+ width={def.viewport.width}
55
+ height={def.viewport.height}
56
+ fill="none"
57
+ stroke="#cbd5e1"
58
+ strokeWidth={2}
59
+ vectorEffect="non-scaling-stroke"
60
+ />
61
+ </svg>
62
+ );
63
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Placeholder token definitions for the template designer — the single
3
+ * source of truth shared by:
4
+ *
5
+ * - `AddBin` (renders the draggable/clickable buttons),
6
+ * - `TemplateDesigner` (builds one `createTokenTool` per entry, and
7
+ * looks an entry up by id on drop).
8
+ *
9
+ * Each token's `token` string is the literal substituted at render time
10
+ * (e.g. `{title}`) and doubles as the preview shown on the button.
11
+ */
12
+
13
+ import type { TokenKind } from '../scene';
14
+
15
+ export interface TokenDef {
16
+ /** Stable id, used both as the tool id and the drag payload. */
17
+ id: string;
18
+ /** Short button label. */
19
+ label: string;
20
+ /** Tooltip describing what the placeholder substitutes. */
21
+ desc: string;
22
+ /** Placeholder string dropped into the layer and shown as the preview. */
23
+ token: string;
24
+ /** Which layer kind the token creates. */
25
+ kind: TokenKind;
26
+ }
27
+
28
+ /** MIME type carried on the drag's `dataTransfer` for a placeholder token. */
29
+ export const TOKEN_DRAG_MIME = 'application/x-squisq-token';
30
+
31
+ export const TOKEN_DEFS: TokenDef[] = [
32
+ {
33
+ id: 'token-title',
34
+ label: 'Title',
35
+ desc: "Substitutes the block's heading text.",
36
+ token: '{title}',
37
+ kind: 'text',
38
+ },
39
+ {
40
+ id: 'token-content',
41
+ label: 'Content',
42
+ desc: "Substitutes the block's body text.",
43
+ token: '{content}',
44
+ kind: 'text',
45
+ },
46
+ {
47
+ id: 'token-children',
48
+ label: 'Children',
49
+ desc: 'Comma-joined list of child heading titles.',
50
+ token: '{children}',
51
+ kind: 'text',
52
+ },
53
+ {
54
+ id: 'token-image',
55
+ label: 'Image',
56
+ desc: "The first image found in the block's body.",
57
+ token: '{image:0}',
58
+ kind: 'image',
59
+ },
60
+ ];
@@ -0,0 +1,52 @@
1
+ /**
2
+ * useDocCustomTemplates — read + persist the active doc's custom
3
+ * templates (the list inlined into the doc's frontmatter under
4
+ * `squisq-custom-templates`).
5
+ *
6
+ * Both the WYSIWYG editor and the standalone Custom Layout Manager need
7
+ * the same two things: the current `Doc.customTemplates` array and a way
8
+ * to write a new list back into the markdown source. Centralizing the
9
+ * frontmatter encoding here keeps the two call sites from drifting.
10
+ */
11
+
12
+ import { useCallback, useMemo } from 'react';
13
+ import type { CustomTemplateDefinition } from '@bendyline/squisq/schemas';
14
+ import {
15
+ FRONTMATTER_CUSTOM_TEMPLATES_KEY,
16
+ writeCustomTemplatesToFrontmatter,
17
+ } from '@bendyline/squisq/doc';
18
+ import { setFrontmatterValues } from '@bendyline/squisq/markdown';
19
+ import { useEditorContext } from '../EditorContext';
20
+
21
+ export interface DocCustomTemplates {
22
+ /** Custom templates inlined in the active doc's frontmatter. */
23
+ docTemplates: CustomTemplateDefinition[];
24
+ /**
25
+ * Persist a new custom-templates list back into the markdown source's
26
+ * frontmatter so the doc round-trips through save/load. The whole list
27
+ * is encoded as a single base64-JSON string per the flat YAML
28
+ * frontmatter parser's constraint.
29
+ */
30
+ onDocTemplatesChange: (next: CustomTemplateDefinition[]) => void;
31
+ }
32
+
33
+ export function useDocCustomTemplates(): DocCustomTemplates {
34
+ const { doc, markdownSource, setMarkdownSource } = useEditorContext();
35
+ // Memoized so identity is stable across renders that don't touch
36
+ // frontmatter — keeps the CustomTemplateProvider value stable.
37
+ const docTemplates = useMemo<CustomTemplateDefinition[]>(
38
+ () => doc?.customTemplates ?? [],
39
+ [doc?.customTemplates],
40
+ );
41
+ const onDocTemplatesChange = useCallback(
42
+ (next: CustomTemplateDefinition[]) => {
43
+ const payload = writeCustomTemplatesToFrontmatter(next);
44
+ const updated = setFrontmatterValues(markdownSource, {
45
+ [FRONTMATTER_CUSTOM_TEMPLATES_KEY]: payload ?? null,
46
+ });
47
+ if (updated !== markdownSource) setMarkdownSource(updated);
48
+ },
49
+ [markdownSource, setMarkdownSource],
50
+ );
51
+ return { docTemplates, onDocTemplatesChange };
52
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * In-memory variant of LayoutAdapter.
3
+ *
4
+ * `useLayoutAdapter` persists Layer mutations to a heading's
5
+ * `data-block-attrs` Pandoc param. For the template designer, the
6
+ * Layer[] doesn't belong to a heading — it's being authored in a
7
+ * modal and saved to the doc / library as a `CustomTemplateDefinition`
8
+ * only when the user clicks Save. This adapter swaps Tiptap-backed
9
+ * storage for a plain React state holder so the designer can reuse
10
+ * the Scene component verbatim.
11
+ *
12
+ * Returns the same `{ layers, tools, dispatch }` shape as
13
+ * `useLayoutAdapter` so the Scene API surface stays consistent.
14
+ */
15
+
16
+ import { useCallback, useState } from 'react';
17
+ import type { Layer } from '@bendyline/squisq/schemas';
18
+ import type { SceneCommand, SceneTool } from '../scene';
19
+
20
+ export interface MemoryLayerAdapterResult {
21
+ layers: Layer[];
22
+ tools: SceneTool[];
23
+ dispatch: (cmd: SceneCommand) => void;
24
+ /** Replace the entire layer array (e.g. for Load / Reset / template-fork flows). */
25
+ setLayers: (next: Layer[]) => void;
26
+ }
27
+
28
+ export interface MemoryLayerAdapterOptions {
29
+ /** Initial layer array. */
30
+ initial?: Layer[];
31
+ /** Tool set the host should expose. Required — typically Select + token tools. */
32
+ tools: SceneTool[];
33
+ }
34
+
35
+ /**
36
+ * Manage a Layer[] in React state and expose it through the same
37
+ * adapter contract the Scene expects. SceneCommands are interpreted
38
+ * against the in-memory array and applied via `setLayers`.
39
+ */
40
+ export function useMemoryLayerAdapter(
41
+ options: MemoryLayerAdapterOptions,
42
+ ): MemoryLayerAdapterResult {
43
+ const [layers, setLayers] = useState<Layer[]>(() => options.initial ?? []);
44
+
45
+ const dispatch = useCallback((cmd: SceneCommand) => {
46
+ setLayers((current) => applyCommand(current, cmd));
47
+ }, []);
48
+
49
+ return {
50
+ layers,
51
+ tools: options.tools,
52
+ dispatch,
53
+ setLayers,
54
+ };
55
+ }
56
+
57
+ /**
58
+ * Pure application of a SceneCommand against a Layer[]. Exported so
59
+ * tests can exercise the reducer in isolation.
60
+ */
61
+ export function applyCommand(layers: readonly Layer[], cmd: SceneCommand): Layer[] {
62
+ switch (cmd.kind) {
63
+ case 'moveLayer':
64
+ return layers.map((l) =>
65
+ l.id === cmd.id ? ({ ...l, position: { ...l.position, x: cmd.x, y: cmd.y } } as Layer) : l,
66
+ );
67
+ case 'resizeLayer':
68
+ return layers.map((l) =>
69
+ l.id === cmd.id
70
+ ? ({
71
+ ...l,
72
+ position: { ...l.position, width: cmd.width, height: cmd.height },
73
+ } as Layer)
74
+ : l,
75
+ );
76
+ case 'addLayer':
77
+ return [...layers, cmd.layer];
78
+ case 'removeLayer':
79
+ return layers.filter((l) => l.id !== cmd.id);
80
+ case 'setLayerAttr':
81
+ return layers.map((l) => (l.id === cmd.id ? setAttrAtPath(l, cmd.path, cmd.value) : l));
82
+ case 'renameLayer':
83
+ return layers.map((l) => {
84
+ if (l.id !== cmd.id) return l;
85
+ if (l.type !== 'text') return l;
86
+ return { ...l, content: { ...l.content, text: cmd.label } };
87
+ });
88
+ case 'setLayerText':
89
+ return layers.map((l) => {
90
+ if (l.id !== cmd.id || l.type !== 'text') return l;
91
+ const content = { ...l.content, text: cmd.text };
92
+ if (cmd.html && cmd.html.trim()) content.html = cmd.html;
93
+ else delete content.html;
94
+ return { ...l, content };
95
+ });
96
+ case 'addEdge':
97
+ case 'removeEdge':
98
+ // No edge model in memory adapter; ignored.
99
+ return layers.slice();
100
+ }
101
+ const _exhaustive: never = cmd;
102
+ void _exhaustive;
103
+ return layers.slice();
104
+ }
105
+
106
+ /**
107
+ * Set a deeply-nested field on a Layer via a dotted path. Returns a
108
+ * new Layer; the input is not mutated. JSON-clone is safe for Layer
109
+ * since the schema is pure plain data.
110
+ */
111
+ function setAttrAtPath(layer: Layer, path: string, value: unknown): Layer {
112
+ const segments = path.split('.');
113
+ const next = JSON.parse(JSON.stringify(layer)) as Layer;
114
+ let target: Record<string, unknown> = next as unknown as Record<string, unknown>;
115
+ for (let i = 0; i < segments.length - 1; i++) {
116
+ const key = segments[i];
117
+ const child = target[key];
118
+ if (typeof child !== 'object' || child === null) return layer;
119
+ target = child as Record<string, unknown>;
120
+ }
121
+ target[segments[segments.length - 1]] = value;
122
+ return next;
123
+ }