@bendyline/squisq-editor-react 1.5.2 → 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 +16910 -6844
  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 +216 -29
  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 +61 -31
  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 +17 -2
  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 +105 -0
  164. package/src/useTimelineClock.ts +76 -0
  165. package/src/utils/dropUtils.ts +1 -1
@@ -0,0 +1,430 @@
1
+ /**
2
+ * TemplateDesigner — modal Scene-backed editor for authoring a
3
+ * `CustomTemplateDefinition`. Mounts the Scene with the in-memory
4
+ * adapter, exposes a placeholder palette, and lets the user save the
5
+ * result to either the current doc or the browser-local library.
6
+ *
7
+ * Responsiveness preview: a small viewport-aspect toggle (16:9 /
8
+ * 9:16 / 1:1) re-mounts the Scene at the alternate viewport so the
9
+ * author can see how their `%`-based layout will adapt. The
10
+ * underlying layer array is the same; only the Scene's `viewport`
11
+ * prop changes.
12
+ *
13
+ * Save flow: numeric position fields are normalized to `%`-strings
14
+ * relative to the design canvas (always 1920×1080 in v1), then the
15
+ * resulting Layer[] is bundled into a `CustomTemplateDefinition`
16
+ * and handed to the host via `onSave`. The host decides whether to
17
+ * persist to the doc, the library, or both.
18
+ */
19
+
20
+ import { useCallback, useMemo, useState } from 'react';
21
+ import { createPortal } from 'react-dom';
22
+ import { MediaContext } from '@bendyline/squisq-react';
23
+ import type {
24
+ CustomTemplateDefinition,
25
+ ImageLayer,
26
+ Layer,
27
+ MediaProvider,
28
+ ViewportConfig,
29
+ } from '@bendyline/squisq/schemas';
30
+ import {
31
+ Scene,
32
+ SelectTool,
33
+ createTokenTool,
34
+ createPlaceTool,
35
+ buildTokenLayer,
36
+ type SceneTool,
37
+ } from '../scene';
38
+ import { useMemoryLayerAdapter } from './useMemoryLayerAdapter';
39
+ import { normalizePositions } from './normalizePositions';
40
+ import { AddBin } from './AddBin';
41
+ import { TOKEN_DEFS, TOKEN_DRAG_MIME } from './tokenDefs';
42
+ import { SHAPE_DEFS, SHAPE_DRAG_MIME, buildShapeLayer } from './shapeDefs';
43
+ import { partitionFiles, processMediaFiles } from '../utils/dropUtils';
44
+ import { LayerToolbar } from './LayerToolbar';
45
+
46
+ export type DesignerSaveTarget = 'doc' | 'library';
47
+
48
+ interface TemplateDesignerProps {
49
+ /** Optional initial template to edit (vs starting from scratch). */
50
+ initial?: CustomTemplateDefinition;
51
+ /**
52
+ * Called when the user clicks Save. The host decides where to
53
+ * persist (usually via `CustomTemplateContext.upsertDocTemplate`
54
+ * and/or `upsertLibraryTemplate`).
55
+ */
56
+ onSave: (def: CustomTemplateDefinition, target: DesignerSaveTarget) => void;
57
+ /** Called when the user dismisses the modal without saving. */
58
+ onClose: () => void;
59
+ /**
60
+ * Embedded mode: render the designer inline (no full-screen portal /
61
+ * backdrop, no close button, no Cancel) so a host frame — e.g. the
62
+ * Custom Layout Manager — can place it inside its own panel. The
63
+ * designer fills its container and does NOT call `onClose` after a
64
+ * save, so the host stays in control of selection.
65
+ */
66
+ embedded?: boolean;
67
+ /**
68
+ * Label for the primary (save-to-doc) button. Defaults to
69
+ * "Save to this doc"; the Custom Layout Manager passes a plain "Save"
70
+ * when the open layout already lives in the doc.
71
+ */
72
+ primarySaveLabel?: string;
73
+ /**
74
+ * Media storage. When provided, images dropped on the canvas (or
75
+ * picked via the Add bin's Media section) are uploaded and pinned as a
76
+ * full-bleed background layer, and the canvas resolves their URLs for
77
+ * preview. Omit to disable media in the bin.
78
+ */
79
+ mediaProvider?: MediaProvider | null;
80
+ }
81
+
82
+ const DESIGN_CANVAS = { width: 1920, height: 1080 };
83
+
84
+ /**
85
+ * Derive a technical name slug from a human label: lowercase, collapse
86
+ * runs of non-alphanumerics to single hyphens, trim leading/trailing
87
+ * hyphens, and drop any leading non-letter chars so the result matches
88
+ * the `^[a-z][a-z0-9-]*$` rule enforced by `validate()`.
89
+ */
90
+ function slugifyLabel(label: string): string {
91
+ return label
92
+ .toLowerCase()
93
+ .replace(/[^a-z0-9]+/g, '-')
94
+ .replace(/^[^a-z]+/, '')
95
+ .replace(/^-+|-+$/g, '');
96
+ }
97
+
98
+ const VIEWPORT_OPTIONS: {
99
+ id: 'landscape' | 'portrait' | 'square';
100
+ label: string;
101
+ viewport: ViewportConfig;
102
+ }[] = [
103
+ { id: 'landscape', label: '16:9', viewport: { width: 1920, height: 1080, name: 'Landscape' } },
104
+ { id: 'portrait', label: '9:16', viewport: { width: 1080, height: 1920, name: 'Portrait' } },
105
+ { id: 'square', label: '1:1', viewport: { width: 1080, height: 1080, name: 'Square' } },
106
+ ];
107
+
108
+ export function TemplateDesigner({
109
+ initial,
110
+ onSave,
111
+ onClose,
112
+ embedded = false,
113
+ primarySaveLabel = 'Save to this doc',
114
+ mediaProvider = null,
115
+ }: TemplateDesignerProps) {
116
+ const [name, setName] = useState(initial?.name ?? '');
117
+ const [label, setLabel] = useState(initial?.label ?? '');
118
+ const [description, setDescription] = useState(initial?.description ?? '');
119
+ // While true, the name auto-tracks the label (the 90% case). Editing
120
+ // the name field manually pins it; clearing the name resumes tracking.
121
+ const [nameAutoDerived, setNameAutoDerived] = useState(!initial?.name);
122
+
123
+ const handleLabelChange = useCallback(
124
+ (value: string) => {
125
+ setLabel(value);
126
+ if (nameAutoDerived) setName(slugifyLabel(value));
127
+ },
128
+ [nameAutoDerived],
129
+ );
130
+
131
+ const handleNameChange = useCallback(
132
+ (value: string) => {
133
+ // An empty name re-enables auto-derivation and re-syncs to the
134
+ // current label; any text pins the name to what the user typed.
135
+ if (value.trim() === '') {
136
+ setNameAutoDerived(true);
137
+ setName(slugifyLabel(label));
138
+ } else {
139
+ setNameAutoDerived(false);
140
+ setName(value);
141
+ }
142
+ },
143
+ [label],
144
+ );
145
+ const [previewViewportId, setPreviewViewportId] = useState<'landscape' | 'portrait' | 'square'>(
146
+ 'landscape',
147
+ );
148
+
149
+ // Build the toolset once. Each bin entry — placeholder token or shape —
150
+ // gets a click-to-place tool; SelectTool is the singleton from
151
+ // scene/tools/SelectTool.ts. Tools are factories so each has its own
152
+ // state-free closure.
153
+ const tools: SceneTool[] = useMemo(
154
+ () => [
155
+ SelectTool,
156
+ ...TOKEN_DEFS.map((d) => createTokenTool(d)),
157
+ ...SHAPE_DEFS.map((s) =>
158
+ createPlaceTool({ id: s.id, label: s.label, build: (p) => buildShapeLayer(s, p) }),
159
+ ),
160
+ ],
161
+ [],
162
+ );
163
+
164
+ const adapter = useMemoryLayerAdapter({
165
+ initial: initial?.layers ?? [],
166
+ tools,
167
+ });
168
+
169
+ // Upload image files and pin each as a full-bleed background layer,
170
+ // prepended so it sits behind everything (layers composite back-to-front).
171
+ const addMediaBackgrounds = useCallback(
172
+ async (files: File[]) => {
173
+ if (!mediaProvider) return;
174
+ const { media } = partitionFiles(files);
175
+ if (media.length === 0) return;
176
+ const paths = await processMediaFiles(media, mediaProvider);
177
+ const backgrounds: ImageLayer[] = paths
178
+ .filter((p): p is string => !!p)
179
+ .map((src, i) => ({
180
+ id: `bg-${Date.now().toString(36)}-${i}`,
181
+ type: 'image',
182
+ position: { x: 0, y: 0, width: DESIGN_CANVAS.width, height: DESIGN_CANVAS.height },
183
+ content: { src, alt: '', fit: 'cover' },
184
+ }));
185
+ if (backgrounds.length === 0) return;
186
+ adapter.setLayers([...backgrounds, ...adapter.layers]);
187
+ },
188
+ [adapter, mediaProvider],
189
+ );
190
+
191
+ // Drag-and-drop onto the canvas. A dragged placeholder or shape adds the
192
+ // same layer its click-to-place tool would, at the drop point (`point`
193
+ // is already in viewport coordinates). Dropped image files become
194
+ // full-bleed background layers.
195
+ const handleCanvasDrop = useCallback(
196
+ (e: React.DragEvent, point: { x: number; y: number }) => {
197
+ const tokenDef = TOKEN_DEFS.find((d) => d.id === e.dataTransfer.getData(TOKEN_DRAG_MIME));
198
+ if (tokenDef) {
199
+ adapter.dispatch({ kind: 'addLayer', layer: buildTokenLayer(tokenDef, point) });
200
+ return;
201
+ }
202
+ const shapeDef = SHAPE_DEFS.find((s) => s.id === e.dataTransfer.getData(SHAPE_DRAG_MIME));
203
+ if (shapeDef) {
204
+ adapter.dispatch({ kind: 'addLayer', layer: buildShapeLayer(shapeDef, point) });
205
+ return;
206
+ }
207
+ const files = Array.from(e.dataTransfer.files ?? []);
208
+ if (files.length > 0) void addMediaBackgrounds(files);
209
+ },
210
+ [adapter, addMediaBackgrounds],
211
+ );
212
+
213
+ // Track the selected layer so the contextual styling toolbar can edit
214
+ // it. The Scene reports a set of ids; the designer is single-select for
215
+ // styling purposes, so we take the first.
216
+ const [selectedLayerId, setSelectedLayerId] = useState<string | null>(null);
217
+ const selectedLayer = adapter.layers.find((l) => l.id === selectedLayerId) ?? null;
218
+
219
+ const handleLayerAttr = useCallback(
220
+ (path: string, value: unknown) => {
221
+ if (!selectedLayerId) return;
222
+ adapter.dispatch({ kind: 'setLayerAttr', id: selectedLayerId, path, value });
223
+ },
224
+ [adapter, selectedLayerId],
225
+ );
226
+
227
+ const [activeToolId, setActiveToolId] = useState<string>('select');
228
+
229
+ const currentViewport =
230
+ VIEWPORT_OPTIONS.find((v) => v.id === previewViewportId)?.viewport ?? DESIGN_CANVAS;
231
+
232
+ const validate = (): string | null => {
233
+ const slug = name.trim();
234
+ if (!slug) return 'Name is required.';
235
+ if (!/^[a-z][a-z0-9-]*$/.test(slug)) {
236
+ return 'Name must be lowercase letters, digits, and hyphens (no spaces).';
237
+ }
238
+ if (!label.trim()) return 'Label is required.';
239
+ if (adapter.layers.length === 0) return 'Add at least one layer or placeholder.';
240
+ return null;
241
+ };
242
+
243
+ const handleSave = (target: DesignerSaveTarget) => {
244
+ const error = validate();
245
+ if (error) {
246
+ alert(error);
247
+ return;
248
+ }
249
+ // Normalize against the design canvas so the saved template is
250
+ // resolution-independent — see normalizePositions.ts.
251
+ const layers: Layer[] = normalizePositions(adapter.layers, DESIGN_CANVAS);
252
+ const def: CustomTemplateDefinition = {
253
+ name: name.trim(),
254
+ label: label.trim(),
255
+ viewport: DESIGN_CANVAS,
256
+ layers,
257
+ ...(description.trim() ? { description: description.trim() } : {}),
258
+ };
259
+ onSave(def, target);
260
+ // Embedded hosts (the Custom Layout Manager) own selection state, so
261
+ // staying mounted after a save lets the user keep editing.
262
+ if (!embedded) onClose();
263
+ };
264
+
265
+ const panel = (
266
+ <div
267
+ className={`squisq-template-designer-panel${
268
+ embedded ? ' squisq-template-designer-panel--embedded' : ''
269
+ }`}
270
+ >
271
+ {/* Standalone modal owns its title + close button. Embedded in the
272
+ Custom Layout Manager, the host frame provides both, so the
273
+ designer drops its header entirely. */}
274
+ {!embedded && (
275
+ <header className="squisq-template-designer-header">
276
+ <h2 className="squisq-template-designer-title">
277
+ {initial ? 'Edit layout' : 'New layout'}
278
+ </h2>
279
+ <button
280
+ type="button"
281
+ className="squisq-template-designer-close"
282
+ onClick={onClose}
283
+ aria-label="Close designer"
284
+ title="Close (Esc)"
285
+ >
286
+ ×
287
+ </button>
288
+ </header>
289
+ )}
290
+
291
+ <div className="squisq-template-designer-meta">
292
+ <label className="squisq-template-designer-field">
293
+ <span>Label</span>
294
+ <input
295
+ type="text"
296
+ value={label}
297
+ placeholder="Hero Section"
298
+ onChange={(e) => handleLabelChange(e.target.value)}
299
+ />
300
+ </label>
301
+ <label className="squisq-template-designer-field">
302
+ <span>Name</span>
303
+ <input
304
+ type="text"
305
+ value={name}
306
+ placeholder="auto from label"
307
+ onChange={(e) => handleNameChange(e.target.value)}
308
+ spellCheck={false}
309
+ />
310
+ <span className="squisq-template-designer-field-hint">
311
+ Auto-derived from the label — edit to override.
312
+ </span>
313
+ </label>
314
+ <label className="squisq-template-designer-field">
315
+ <span>Description</span>
316
+ <input
317
+ type="text"
318
+ value={description}
319
+ placeholder="One-sentence description (optional)"
320
+ onChange={(e) => setDescription(e.target.value)}
321
+ />
322
+ </label>
323
+ </div>
324
+
325
+ <div className="squisq-template-designer-body">
326
+ <AddBin
327
+ activeToolId={activeToolId}
328
+ onActivate={setActiveToolId}
329
+ canAddMedia={!!mediaProvider}
330
+ onAddMediaFiles={(files) => void addMediaBackgrounds(files)}
331
+ />
332
+ <div className="squisq-template-designer-stage">
333
+ {/* One controls row: the compact aspect-ratio dropdown plus the
334
+ contextual layer styling controls (when a layer is selected),
335
+ so the two share a row instead of stacking. */}
336
+ <div className="squisq-template-designer-stage-bar">
337
+ <span className="squisq-template-designer-viewport-label">Preview</span>
338
+ <select
339
+ className="squisq-layer-toolbar-select"
340
+ aria-label="Preview aspect ratio"
341
+ title="Preview aspect ratio"
342
+ value={previewViewportId}
343
+ onChange={(e) =>
344
+ setPreviewViewportId(e.target.value as 'landscape' | 'portrait' | 'square')
345
+ }
346
+ >
347
+ {VIEWPORT_OPTIONS.map((v) => (
348
+ <option key={v.id} value={v.id}>
349
+ {v.label}
350
+ </option>
351
+ ))}
352
+ </select>
353
+ {/* Contextual styling controls — appear when a layer is selected. */}
354
+ {selectedLayer && (
355
+ <>
356
+ <div className="squisq-layer-toolbar-sep" aria-hidden="true" />
357
+ <LayerToolbar layer={selectedLayer} onAttr={handleLayerAttr} />
358
+ </>
359
+ )}
360
+ </div>
361
+ <div className="squisq-template-designer-scene">
362
+ {/* MediaContext lets image layers resolve uploaded media to
363
+ displayable (blob) URLs in the canvas, matching preview. */}
364
+ <MediaContext.Provider value={mediaProvider}>
365
+ <Scene
366
+ viewport={currentViewport}
367
+ layers={adapter.layers}
368
+ tools={tools}
369
+ activeToolId={activeToolId}
370
+ onActiveToolIdChange={setActiveToolId}
371
+ onCommand={adapter.dispatch}
372
+ onSelectionChange={(ids) => setSelectedLayerId(ids.values().next().value ?? null)}
373
+ onDrop={handleCanvasDrop}
374
+ showToolbar={false}
375
+ />
376
+ </MediaContext.Provider>
377
+ </div>
378
+ </div>
379
+ </div>
380
+
381
+ <footer className="squisq-template-designer-footer">
382
+ <span className="squisq-template-designer-footer-hint">
383
+ Layers are saved as % of a 1920×1080 canvas so the layout adapts to any viewport.
384
+ </span>
385
+ <div className="squisq-template-designer-footer-actions">
386
+ {!embedded && (
387
+ <button type="button" className="squisq-template-designer-btn" onClick={onClose}>
388
+ Cancel
389
+ </button>
390
+ )}
391
+ <button
392
+ type="button"
393
+ className="squisq-template-designer-btn"
394
+ onClick={() => handleSave('library')}
395
+ title="Save to your browser-local library so other docs can use it"
396
+ >
397
+ Save to library
398
+ </button>
399
+ <button
400
+ type="button"
401
+ className="squisq-template-designer-btn squisq-template-designer-btn--primary"
402
+ onClick={() => handleSave('doc')}
403
+ >
404
+ {primarySaveLabel}
405
+ </button>
406
+ </div>
407
+ </footer>
408
+ </div>
409
+ );
410
+
411
+ // Embedded: hand the bare panel back so a host frame can place it.
412
+ if (embedded) return panel;
413
+
414
+ // Standalone: full-screen modal over a click-to-dismiss backdrop.
415
+ return createPortal(
416
+ <div
417
+ className="squisq-template-designer-overlay"
418
+ role="dialog"
419
+ aria-modal="true"
420
+ aria-label="Custom layout designer"
421
+ onClick={(e) => {
422
+ // Click on the backdrop (not the panel) closes the modal.
423
+ if (e.target === e.currentTarget) onClose();
424
+ }}
425
+ >
426
+ {panel}
427
+ </div>,
428
+ document.body,
429
+ );
430
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * library — localStorage-backed library of user-defined templates.
3
+ *
4
+ * Verifies the CRUD shape (list / save / delete / clear), and that
5
+ * each operation persists across reads. Uses jsdom's localStorage.
6
+ */
7
+
8
+ import { describe, it, expect, beforeEach } from 'vitest';
9
+ import {
10
+ listLibraryTemplates,
11
+ saveLibraryTemplate,
12
+ deleteLibraryTemplate,
13
+ clearLibrary,
14
+ LIBRARY_STORAGE_KEY,
15
+ } from '../library';
16
+ import type { CustomTemplateDefinition } from '@bendyline/squisq/schemas';
17
+
18
+ function defn(name: string, label = name): CustomTemplateDefinition {
19
+ return {
20
+ name,
21
+ label,
22
+ viewport: { width: 1920, height: 1080 },
23
+ layers: [
24
+ {
25
+ id: 'a',
26
+ type: 'text',
27
+ position: { x: '0%', y: '0%', width: '100%' },
28
+ content: { text: name, style: { fontSize: 24, color: '#000' } },
29
+ },
30
+ ],
31
+ };
32
+ }
33
+
34
+ describe('library', () => {
35
+ beforeEach(() => {
36
+ clearLibrary();
37
+ });
38
+
39
+ it('returns an empty list when no templates are saved', () => {
40
+ expect(listLibraryTemplates()).toEqual([]);
41
+ });
42
+
43
+ it('saveLibraryTemplate persists across reads', () => {
44
+ saveLibraryTemplate(defn('a', 'Alpha'));
45
+ expect(listLibraryTemplates().map((t) => t.name)).toEqual(['a']);
46
+ expect(window.localStorage.getItem(LIBRARY_STORAGE_KEY)).toBeTruthy();
47
+ });
48
+
49
+ it('saving a template with an existing name replaces it', () => {
50
+ saveLibraryTemplate(defn('a', 'Alpha'));
51
+ saveLibraryTemplate({ ...defn('a', 'Alpha v2'), description: 'updated' });
52
+ const list = listLibraryTemplates();
53
+ expect(list).toHaveLength(1);
54
+ expect(list[0].label).toBe('Alpha v2');
55
+ expect(list[0].description).toBe('updated');
56
+ });
57
+
58
+ it('list sorts by label', () => {
59
+ saveLibraryTemplate(defn('z', 'Zebra'));
60
+ saveLibraryTemplate(defn('a', 'Aardvark'));
61
+ saveLibraryTemplate(defn('m', 'Mango'));
62
+ expect(listLibraryTemplates().map((t) => t.label)).toEqual(['Aardvark', 'Mango', 'Zebra']);
63
+ });
64
+
65
+ it('deleteLibraryTemplate removes by name and is a no-op for missing names', () => {
66
+ saveLibraryTemplate(defn('a'));
67
+ saveLibraryTemplate(defn('b'));
68
+ let after = deleteLibraryTemplate('a');
69
+ expect(after.map((t) => t.name)).toEqual(['b']);
70
+ after = deleteLibraryTemplate('not-there');
71
+ expect(after.map((t) => t.name)).toEqual(['b']);
72
+ });
73
+
74
+ it('clearLibrary wipes everything', () => {
75
+ saveLibraryTemplate(defn('a'));
76
+ saveLibraryTemplate(defn('b'));
77
+ clearLibrary();
78
+ expect(listLibraryTemplates()).toEqual([]);
79
+ });
80
+
81
+ it('gracefully recovers from a corrupt payload', () => {
82
+ window.localStorage.setItem(LIBRARY_STORAGE_KEY, '{not-valid-json');
83
+ expect(listLibraryTemplates()).toEqual([]);
84
+ // Subsequent save replaces the corrupt blob with a clean one.
85
+ saveLibraryTemplate(defn('a'));
86
+ expect(listLibraryTemplates().map((t) => t.name)).toEqual(['a']);
87
+ });
88
+ });
@@ -0,0 +1,109 @@
1
+ /**
2
+ * normalizePositions — pixel → %-string conversion against the
3
+ * designer canvas.
4
+ */
5
+
6
+ import { describe, it, expect } from 'vitest';
7
+ import { normalizePositions } from '../normalizePositions';
8
+ import type { Layer, ShapeLayer, TextLayer } from '@bendyline/squisq/schemas';
9
+
10
+ const CANVAS = { width: 1920, height: 1080 };
11
+
12
+ function shape(id: string, x: number, y: number, w: number, h: number): ShapeLayer {
13
+ return {
14
+ id,
15
+ type: 'shape',
16
+ position: { x, y, width: w, height: h },
17
+ content: { shape: 'rect' },
18
+ };
19
+ }
20
+
21
+ describe('normalizePositions', () => {
22
+ it('converts pixel positions to %-strings against the canvas', () => {
23
+ const layers: Layer[] = [shape('a', 192, 108, 960, 540)];
24
+ const out = normalizePositions(layers, CANVAS);
25
+ expect(out[0].position.x).toBe('10%');
26
+ expect(out[0].position.y).toBe('10%');
27
+ expect(out[0].position.width).toBe('50%');
28
+ expect(out[0].position.height).toBe('50%');
29
+ });
30
+
31
+ it('width converts against width, height against height (not both against width)', () => {
32
+ // 1080 height; a 1080px tall layer should be 100% of height, not 56.25%.
33
+ const layers: Layer[] = [shape('a', 0, 0, 1920, 1080)];
34
+ const out = normalizePositions(layers, CANVAS);
35
+ expect(out[0].position.width).toBe('100%');
36
+ expect(out[0].position.height).toBe('100%');
37
+ });
38
+
39
+ it('passes %-string values through unchanged', () => {
40
+ const layers: Layer[] = [
41
+ {
42
+ id: 'a',
43
+ type: 'shape',
44
+ position: { x: '10%', y: '20%', width: '30%', height: '40%' },
45
+ content: { shape: 'rect' },
46
+ },
47
+ ];
48
+ const out = normalizePositions(layers, CANVAS);
49
+ expect(out[0].position).toEqual({ x: '10%', y: '20%', width: '30%', height: '40%' });
50
+ });
51
+
52
+ it('preserves anchor field', () => {
53
+ const layers: Layer[] = [
54
+ {
55
+ id: 'a',
56
+ type: 'shape',
57
+ position: { x: 100, y: 100, width: 200, height: 100, anchor: 'center' },
58
+ content: { shape: 'rect' },
59
+ },
60
+ ];
61
+ const out = normalizePositions(layers, CANVAS);
62
+ expect(out[0].position.anchor).toBe('center');
63
+ });
64
+
65
+ it('handles mixed pixel + percent in the same layer', () => {
66
+ const layers: Layer[] = [
67
+ {
68
+ id: 'a',
69
+ type: 'shape',
70
+ // x pixel, y percent
71
+ position: { x: 192, y: '20%', width: 960, height: 540 },
72
+ content: { shape: 'rect' },
73
+ },
74
+ ];
75
+ const out = normalizePositions(layers, CANVAS);
76
+ expect(out[0].position.x).toBe('10%');
77
+ expect(out[0].position.y).toBe('20%');
78
+ expect(out[0].position.width).toBe('50%');
79
+ expect(out[0].position.height).toBe('50%');
80
+ });
81
+
82
+ it('formats fractional percentages with up to 2 decimal places', () => {
83
+ // 100 / 1920 ≈ 5.208333…% → rounded to 5.21%.
84
+ const layers: Layer[] = [shape('a', 100, 100, 100, 100)];
85
+ const out = normalizePositions(layers, CANVAS);
86
+ expect(out[0].position.x).toBe('5.21%');
87
+ });
88
+
89
+ it('does not mutate the input layers', () => {
90
+ const layers: Layer[] = [shape('a', 100, 200, 300, 400)];
91
+ const before = JSON.stringify(layers);
92
+ normalizePositions(layers, CANVAS);
93
+ expect(JSON.stringify(layers)).toBe(before);
94
+ });
95
+
96
+ it('preserves non-position layer content (TextLayer)', () => {
97
+ const layers: Layer[] = [
98
+ {
99
+ id: 't',
100
+ type: 'text',
101
+ position: { x: 192, y: 108, width: 480 },
102
+ content: { text: '{title}', style: { fontSize: 36, color: '#000' } },
103
+ } as TextLayer,
104
+ ];
105
+ const out = normalizePositions(layers, CANVAS);
106
+ expect((out[0] as TextLayer).content.text).toBe('{title}');
107
+ expect((out[0] as TextLayer).content.style.fontSize).toBe(36);
108
+ });
109
+ });
@@ -0,0 +1,49 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { SHAPE_DEFS, buildShapeLayer } from '../shapeDefs';
3
+
4
+ describe('buildShapeLayer', () => {
5
+ const point = { x: 100, y: 200 };
6
+
7
+ it('builds a native ShapeLayer for rect / circle / line', () => {
8
+ for (const kind of ['rect', 'circle', 'line'] as const) {
9
+ const def = SHAPE_DEFS.find((s) => s.kind === kind && !s.rounded)!;
10
+ const layer = buildShapeLayer(def, point);
11
+ expect(layer.type).toBe('shape');
12
+ if (layer.type === 'shape') {
13
+ expect(layer.content.shape).toBe(kind);
14
+ }
15
+ expect(layer.position.x).toBe(100);
16
+ expect(layer.position.y).toBe(200);
17
+ }
18
+ });
19
+
20
+ it('rounds the rounded-rectangle variant', () => {
21
+ const def = SHAPE_DEFS.find((s) => s.id === 'shape-rect-rounded')!;
22
+ const layer = buildShapeLayer(def, point);
23
+ expect(layer.type).toBe('shape');
24
+ if (layer.type === 'shape') {
25
+ expect(layer.content.borderRadius).toBeGreaterThan(0);
26
+ }
27
+ });
28
+
29
+ it('builds a computed PathLayer with non-empty geometry for non-native shapes', () => {
30
+ const def = SHAPE_DEFS.find((s) => s.kind === 'diamond')!;
31
+ const layer = buildShapeLayer(def, point);
32
+ expect(layer.type).toBe('path');
33
+ if (layer.type === 'path') {
34
+ expect(layer.content.d.length).toBeGreaterThan(0);
35
+ // Diamond path should reference the drop origin region.
36
+ expect(layer.content.d).toMatch(/^M /);
37
+ // The kind is recorded so the renderer can re-derive geometry on
38
+ // move/resize and adapt to the viewport.
39
+ expect(layer.content.shapeKind).toBe('diamond');
40
+ }
41
+ });
42
+
43
+ it('assigns unique ids across calls', () => {
44
+ const def = SHAPE_DEFS[0];
45
+ const a = buildShapeLayer(def, point);
46
+ const b = buildShapeLayer(def, point);
47
+ expect(a.id).not.toBe(b.id);
48
+ });
49
+ });