@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,97 @@
1
+ /**
2
+ * Browser-local library of user-defined custom themes.
3
+ *
4
+ * The theme analog of `customTemplates/library.ts`. Library themes live in
5
+ * `localStorage` under `THEME_LIBRARY_STORAGE_KEY`. They're a cross-doc
6
+ * convenience — a personal collection the user reuses across documents — but
7
+ * they're NOT used by the SSR / export pipeline. When a user applies a library
8
+ * theme to a doc, `applyTheme` (in CustomThemeContext) copies the definition
9
+ * into the doc's `customThemes` so the doc remains self-sufficient (the
10
+ * markdown file ships with everything it needs), exactly as applying a library
11
+ * template copies it into `Doc.customTemplates`.
12
+ *
13
+ * Safe to import in SSR / Node — gracefully no-ops when `localStorage` is
14
+ * unavailable.
15
+ */
16
+
17
+ import type { Theme } from '@bendyline/squisq/schemas';
18
+
19
+ export const THEME_LIBRARY_STORAGE_KEY = 'squisq:custom-theme-library';
20
+
21
+ interface LibraryPayload {
22
+ /** Schema version for forward-compatibility. */
23
+ version: 1;
24
+ themes: Theme[];
25
+ }
26
+
27
+ function safeStorage(): Storage | null {
28
+ try {
29
+ return typeof globalThis !== 'undefined' && globalThis.localStorage
30
+ ? globalThis.localStorage
31
+ : null;
32
+ } catch {
33
+ // Some browsers throw on localStorage access in private mode.
34
+ return null;
35
+ }
36
+ }
37
+
38
+ function readPayload(): LibraryPayload {
39
+ const storage = safeStorage();
40
+ if (!storage) return { version: 1, themes: [] };
41
+ const raw = storage.getItem(THEME_LIBRARY_STORAGE_KEY);
42
+ if (!raw) return { version: 1, themes: [] };
43
+ try {
44
+ const parsed = JSON.parse(raw) as Partial<LibraryPayload>;
45
+ if (parsed && Array.isArray(parsed.themes)) {
46
+ return { version: 1, themes: parsed.themes };
47
+ }
48
+ } catch {
49
+ // Corrupt payload — drop it.
50
+ }
51
+ return { version: 1, themes: [] };
52
+ }
53
+
54
+ function writePayload(payload: LibraryPayload): void {
55
+ const storage = safeStorage();
56
+ if (!storage) return;
57
+ try {
58
+ storage.setItem(THEME_LIBRARY_STORAGE_KEY, JSON.stringify(payload));
59
+ } catch {
60
+ // Quota exceeded or storage disabled — best-effort write.
61
+ }
62
+ }
63
+
64
+ /** Return every theme currently in the user's library, sorted by name. */
65
+ export function listLibraryThemes(): Theme[] {
66
+ const { themes } = readPayload();
67
+ return themes.slice().sort((a, b) => a.name.localeCompare(b.name));
68
+ }
69
+
70
+ /**
71
+ * Insert or replace a library theme (matched by `id`). Returns the persisted
72
+ * list so callers can update their state without re-reading.
73
+ */
74
+ export function saveLibraryTheme(theme: Theme): Theme[] {
75
+ const payload = readPayload();
76
+ const idx = payload.themes.findIndex((t) => t.id === theme.id);
77
+ if (idx >= 0) {
78
+ payload.themes[idx] = theme;
79
+ } else {
80
+ payload.themes.push(theme);
81
+ }
82
+ writePayload(payload);
83
+ return payload.themes.slice().sort((a, b) => a.name.localeCompare(b.name));
84
+ }
85
+
86
+ /** Remove a library theme by id. Returns the updated list. */
87
+ export function deleteLibraryTheme(id: string): Theme[] {
88
+ const payload = readPayload();
89
+ payload.themes = payload.themes.filter((t) => t.id !== id);
90
+ writePayload(payload);
91
+ return payload.themes.slice().sort((a, b) => a.name.localeCompare(b.name));
92
+ }
93
+
94
+ /** Wipe the entire theme library — useful for tests and "reset" affordances. */
95
+ export function clearThemeLibrary(): void {
96
+ writePayload({ version: 1, themes: [] });
97
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Public exports for the custom-theme designer + runtime — the theme analog
3
+ * of `customTemplates/index.ts`.
4
+ *
5
+ * - `<CustomThemeProvider>` wraps the editor so the picker and dialog can
6
+ * read/write doc + library theme lists.
7
+ * - `<CustomThemeDialog>` is the modal designer opened from the ThemePicker's
8
+ * "+ Create custom theme" affordance.
9
+ * - the `*LibraryTheme` helpers back the browser-local theme library.
10
+ */
11
+
12
+ export {
13
+ CustomThemeProvider,
14
+ useCustomThemes,
15
+ type CustomThemeContextValue,
16
+ type CustomThemeProviderProps,
17
+ } from './CustomThemeContext';
18
+ export {
19
+ listLibraryThemes,
20
+ saveLibraryTheme,
21
+ deleteLibraryTheme,
22
+ clearThemeLibrary,
23
+ THEME_LIBRARY_STORAGE_KEY,
24
+ } from './customThemeLibrary';
25
+ export { useDocCustomThemes, type DocCustomThemes } from './useDocCustomThemes';
26
+ export {
27
+ CustomThemeDialog,
28
+ type CustomThemeDialogProps,
29
+ type ThemeSaveTarget,
30
+ } from './CustomThemeDialog';
31
+ export { compileDraft, themeToDraft, type Draft } from './themeDraft';
@@ -0,0 +1,229 @@
1
+ /**
2
+ * themeControls — presentational form rows shared by the ThemeCustomizerPanel
3
+ * popover and the CustomThemeDialog. Pure/controlled; they carry the existing
4
+ * `squisq-theme-customizer-*` classes so both surfaces style identically.
5
+ */
6
+
7
+ import { AVAILABLE_FONT_STACKS, isHex } from '@bendyline/squisq/schemas';
8
+ import {
9
+ type CustomFontInput,
10
+ type FallbackOption,
11
+ type AccentInput,
12
+ FALLBACK_OPTIONS,
13
+ nextAccent,
14
+ } from './themeDraft';
15
+
16
+ export function Section({
17
+ title,
18
+ hint,
19
+ children,
20
+ }: {
21
+ title: string;
22
+ hint?: string;
23
+ children: React.ReactNode;
24
+ }) {
25
+ return (
26
+ <div className="squisq-theme-customizer-section">
27
+ <div className="squisq-theme-customizer-section-title">{title}</div>
28
+ {hint && <div className="squisq-theme-customizer-section-hint">{hint}</div>}
29
+ <div className="squisq-theme-customizer-section-body">{children}</div>
30
+ </div>
31
+ );
32
+ }
33
+
34
+ export function SeedColorRow({
35
+ label,
36
+ value,
37
+ onChange,
38
+ }: {
39
+ label: string;
40
+ value: string;
41
+ onChange: (hex: string) => void;
42
+ }) {
43
+ const safeValue = isHex(value) ? value : '#000000';
44
+ return (
45
+ <label className="squisq-theme-customizer-row">
46
+ <span className="squisq-theme-customizer-row-label">{label}</span>
47
+ <input
48
+ type="color"
49
+ className="squisq-theme-customizer-color"
50
+ value={safeValue}
51
+ onChange={(e) => onChange(e.target.value)}
52
+ />
53
+ <input
54
+ type="text"
55
+ className="squisq-theme-customizer-input squisq-theme-customizer-input--hex"
56
+ value={value}
57
+ onChange={(e) => onChange(e.target.value)}
58
+ spellCheck={false}
59
+ aria-label={`${label} hex value`}
60
+ />
61
+ </label>
62
+ );
63
+ }
64
+
65
+ export function FontPicker({
66
+ label,
67
+ value,
68
+ onChange,
69
+ }: {
70
+ label: string;
71
+ value: CustomFontInput;
72
+ onChange: (next: CustomFontInput) => void;
73
+ }) {
74
+ // Render the closed <select> (and each option) in the font it names, so the
75
+ // dropdown doubles as a live font preview. Faces are provided by the host
76
+ // (the site links `/fonts/fonts.css`; the same fonts the player renders
77
+ // with) — no external font fetch here. Unloaded faces fall back gracefully.
78
+ const selectedFamily =
79
+ value.kind === 'curated'
80
+ ? AVAILABLE_FONT_STACKS.find((s) => s.id === value.stackId)?.family
81
+ : undefined;
82
+
83
+ return (
84
+ <div className="squisq-theme-customizer-row squisq-theme-customizer-row--font">
85
+ <span className="squisq-theme-customizer-row-label">{label}</span>
86
+ <select
87
+ className="squisq-theme-customizer-input"
88
+ style={selectedFamily ? { fontFamily: selectedFamily } : undefined}
89
+ value={value.kind === 'custom' ? '__custom__' : (value.stackId ?? '')}
90
+ onChange={(e) => {
91
+ const v = e.target.value;
92
+ if (v === '__custom__') {
93
+ onChange({
94
+ kind: 'custom',
95
+ customName: value.customName ?? '',
96
+ customFallback: value.customFallback ?? 'sans-serif',
97
+ });
98
+ } else {
99
+ onChange({ kind: 'curated', stackId: v });
100
+ }
101
+ }}
102
+ aria-label={`${label} font`}
103
+ >
104
+ {AVAILABLE_FONT_STACKS.map((stack) => (
105
+ <option key={stack.id} value={stack.id} style={{ fontFamily: stack.family }}>
106
+ {stack.label}
107
+ </option>
108
+ ))}
109
+ <option value="__custom__">Custom…</option>
110
+ </select>
111
+ {value.kind === 'custom' && (
112
+ <>
113
+ <input
114
+ type="text"
115
+ className="squisq-theme-customizer-input"
116
+ placeholder="Font name"
117
+ value={value.customName ?? ''}
118
+ onChange={(e) => onChange({ ...value, customName: e.target.value })}
119
+ aria-label={`${label} custom font name`}
120
+ />
121
+ <select
122
+ className="squisq-theme-customizer-input"
123
+ value={value.customFallback ?? 'sans-serif'}
124
+ onChange={(e) =>
125
+ onChange({ ...value, customFallback: e.target.value as FallbackOption })
126
+ }
127
+ aria-label={`${label} custom font fallback`}
128
+ >
129
+ {FALLBACK_OPTIONS.map((opt) => (
130
+ <option key={opt} value={opt}>
131
+ {opt}
132
+ </option>
133
+ ))}
134
+ </select>
135
+ </>
136
+ )}
137
+ </div>
138
+ );
139
+ }
140
+
141
+ export function PresetRow<T extends string>({
142
+ label,
143
+ value,
144
+ options,
145
+ onChange,
146
+ }: {
147
+ label: string;
148
+ value: T;
149
+ options: readonly T[];
150
+ onChange: (v: T) => void;
151
+ }) {
152
+ return (
153
+ <label className="squisq-theme-customizer-row">
154
+ <span className="squisq-theme-customizer-row-label">{label}</span>
155
+ <select
156
+ className="squisq-theme-customizer-input"
157
+ value={value}
158
+ onChange={(e) => onChange(e.target.value as T)}
159
+ aria-label={label}
160
+ >
161
+ {options.map((o) => (
162
+ <option key={o} value={o}>
163
+ {o}
164
+ </option>
165
+ ))}
166
+ </select>
167
+ </label>
168
+ );
169
+ }
170
+
171
+ /**
172
+ * AccentEditor — the "N accent colors" list. Add / edit / remove accent
173
+ * colors; each maps to a per-block color scheme in the compiled theme.
174
+ */
175
+ export function AccentEditor({
176
+ accents,
177
+ onChange,
178
+ }: {
179
+ accents: AccentInput[];
180
+ onChange: (next: AccentInput[]) => void;
181
+ }) {
182
+ const setColor = (idx: number, color: string) =>
183
+ onChange(accents.map((a, i) => (i === idx ? { ...a, color } : a)));
184
+ const remove = (idx: number) => onChange(accents.filter((_, i) => i !== idx));
185
+ const add = () => onChange([...accents, nextAccent(accents)]);
186
+
187
+ return (
188
+ <div className="squisq-theme-customizer-accents">
189
+ {accents.map((a, idx) => (
190
+ <div
191
+ key={a.key}
192
+ className="squisq-theme-customizer-row squisq-theme-customizer-row--accent"
193
+ >
194
+ <input
195
+ type="color"
196
+ className="squisq-theme-customizer-color"
197
+ value={isHex(a.color) ? a.color : '#000000'}
198
+ onChange={(e) => setColor(idx, e.target.value)}
199
+ aria-label={`Accent ${idx + 1}`}
200
+ />
201
+ <input
202
+ type="text"
203
+ className="squisq-theme-customizer-input squisq-theme-customizer-input--hex"
204
+ value={a.color}
205
+ onChange={(e) => setColor(idx, e.target.value)}
206
+ spellCheck={false}
207
+ aria-label={`Accent ${idx + 1} hex value`}
208
+ />
209
+ <button
210
+ type="button"
211
+ className="squisq-theme-customizer-accent-remove"
212
+ onClick={() => remove(idx)}
213
+ aria-label={`Remove accent ${idx + 1}`}
214
+ title="Remove accent"
215
+ >
216
+ ×
217
+ </button>
218
+ </div>
219
+ ))}
220
+ <button
221
+ type="button"
222
+ className="squisq-theme-customizer-button squisq-theme-customizer-accent-add"
223
+ onClick={add}
224
+ >
225
+ + Add accent
226
+ </button>
227
+ </div>
228
+ );
229
+ }
@@ -0,0 +1,272 @@
1
+ /**
2
+ * themeDraft — the editable subset of the Theme schema, shared by the
3
+ * ThemeCustomizerPanel popover and the CustomThemeDialog.
4
+ *
5
+ * A `Draft` mirrors the handful of fields a user actually edits (name, seed
6
+ * colors, N accents, fonts, style presets, and a base theme to inherit from).
7
+ * `compileDraft` turns it into a full validated `Theme` via `compileTheme`;
8
+ * everything the draft doesn't mention inherits from the chosen base (or the
9
+ * compiler's neutral STARTER_THEME when no base is picked).
10
+ */
11
+
12
+ import type {
13
+ Theme,
14
+ FontFamily,
15
+ ThemeSeedColors,
16
+ ThemeColorScheme,
17
+ } from '@bendyline/squisq/schemas';
18
+ import { compileTheme, deriveScale, isHex } from '@bendyline/squisq/schemas';
19
+
20
+ // ── Preset → schema-value tables ────────────────────────────────────
21
+
22
+ export const BORDER_RADIUS_PRESETS = {
23
+ sharp: 0,
24
+ soft: 6,
25
+ rounded: 16,
26
+ } as const;
27
+ export type BorderRadiusPreset = keyof typeof BORDER_RADIUS_PRESETS;
28
+
29
+ export const ANIMATION_SPEED_PRESETS = {
30
+ static: 0,
31
+ subtle: 1.4,
32
+ normal: 1.0,
33
+ expressive: 0.7,
34
+ } as const;
35
+ export type AnimationSpeedPreset = keyof typeof ANIMATION_SPEED_PRESETS;
36
+
37
+ export const TEXT_SHADOW_PRESETS = {
38
+ off: false,
39
+ on: true,
40
+ } as const;
41
+ export type TextShadowPreset = keyof typeof TEXT_SHADOW_PRESETS;
42
+
43
+ export const CONTRAST_PRESETS = ['subtle', 'balanced', 'high'] as const;
44
+ export type ContrastPreset = (typeof CONTRAST_PRESETS)[number];
45
+
46
+ export const IMAGE_TREATMENT_PRESETS = ['none', 'mono', 'duotone', 'warm', 'cool'] as const;
47
+ export type ImageTreatmentPreset = (typeof IMAGE_TREATMENT_PRESETS)[number];
48
+
49
+ export const FALLBACK_OPTIONS = ['sans-serif', 'serif', 'monospace', 'system-ui'] as const;
50
+ export type FallbackOption = (typeof FALLBACK_OPTIONS)[number];
51
+
52
+ // ── Draft state — reflects the editable subset of the schema ────────
53
+
54
+ export interface CustomFontInput {
55
+ kind: 'curated' | 'custom';
56
+ stackId?: string;
57
+ customName?: string;
58
+ customFallback?: FallbackOption;
59
+ }
60
+
61
+ /** One editable accent: a color plus the colorScheme key it maps to. */
62
+ export interface AccentInput {
63
+ key: string;
64
+ color: string;
65
+ }
66
+
67
+ export interface Draft {
68
+ name: string;
69
+ /** Id of the base theme this draft inherits render style / layout from. */
70
+ baseId?: string;
71
+ seeds: ThemeSeedColors;
72
+ /** The "N accents" — each becomes a `colorSchemes` entry. */
73
+ accents: AccentInput[];
74
+ /** True once the user has touched the accent list; gates wholesale replace. */
75
+ accentsEdited: boolean;
76
+ titleFont: CustomFontInput;
77
+ bodyFont: CustomFontInput;
78
+ borderRadius: BorderRadiusPreset;
79
+ animationSpeed: AnimationSpeedPreset;
80
+ textShadow: TextShadowPreset;
81
+ contrast: ContrastPreset;
82
+ imageTreatment: ImageTreatmentPreset;
83
+ }
84
+
85
+ export const DEFAULT_DRAFT: Draft = {
86
+ name: 'My Theme',
87
+ seeds: {
88
+ primary: '#3182ce',
89
+ secondary: '#4a5568',
90
+ accent: '#63b3ed',
91
+ background: '#1a202c',
92
+ text: '#f7fafc',
93
+ },
94
+ accents: [],
95
+ accentsEdited: false,
96
+ titleFont: { kind: 'curated', stackId: 'system-serif' },
97
+ bodyFont: { kind: 'curated', stackId: 'system-sans' },
98
+ borderRadius: 'soft',
99
+ animationSpeed: 'normal',
100
+ textShadow: 'on',
101
+ contrast: 'balanced',
102
+ imageTreatment: 'none',
103
+ };
104
+
105
+ function findRadiusPreset(value: number | undefined): BorderRadiusPreset {
106
+ if (value === undefined) return 'soft';
107
+ let best: BorderRadiusPreset = 'soft';
108
+ let bestDist = Infinity;
109
+ (Object.entries(BORDER_RADIUS_PRESETS) as [BorderRadiusPreset, number][]).forEach(([k, v]) => {
110
+ const d = Math.abs(v - value);
111
+ if (d < bestDist) {
112
+ best = k;
113
+ bestDist = d;
114
+ }
115
+ });
116
+ return best;
117
+ }
118
+
119
+ function findAnimationPreset(value: number | undefined): AnimationSpeedPreset {
120
+ if (value === undefined || value === 0) return value === 0 ? 'static' : 'normal';
121
+ let best: AnimationSpeedPreset = 'normal';
122
+ let bestDist = Infinity;
123
+ (Object.entries(ANIMATION_SPEED_PRESETS) as [AnimationSpeedPreset, number][]).forEach(
124
+ ([k, v]) => {
125
+ if (v === 0) return; // 'static' handled above
126
+ const d = Math.abs(v - value);
127
+ if (d < bestDist) {
128
+ best = k;
129
+ bestDist = d;
130
+ }
131
+ },
132
+ );
133
+ return best;
134
+ }
135
+
136
+ function fontFamilyToInput(f: FontFamily | undefined, fallbackStackId: string): CustomFontInput {
137
+ if (!f) return { kind: 'curated', stackId: fallbackStackId };
138
+ if ('stackId' in f) return { kind: 'curated', stackId: f.stackId };
139
+ if ('custom' in f)
140
+ return {
141
+ kind: 'custom',
142
+ customName: f.custom.name,
143
+ customFallback: f.custom.fallback,
144
+ };
145
+ return { kind: 'curated', stackId: fallbackStackId };
146
+ }
147
+
148
+ function inputToFontFamily(input: CustomFontInput): FontFamily {
149
+ if (input.kind === 'curated') {
150
+ return { stackId: input.stackId ?? 'system-sans' };
151
+ }
152
+ return {
153
+ custom: {
154
+ name: input.customName ?? 'Sans',
155
+ fallback: input.customFallback ?? 'sans-serif',
156
+ },
157
+ };
158
+ }
159
+
160
+ /** Read a theme's per-block color schemes back into the editable accent list. */
161
+ export function accentsFromTheme(theme: Theme | null): AccentInput[] {
162
+ if (!theme) return [];
163
+ return Object.entries(theme.colorSchemes).map(([key, scheme]) => ({ key, color: scheme.accent }));
164
+ }
165
+
166
+ /**
167
+ * Expand one accent color into a full `{bg, text, accent}` color scheme via
168
+ * the OKLCh scale — dark saturated bg, light readable text, the picked accent.
169
+ * Falls back to a neutral scheme when the input isn't a valid hex.
170
+ */
171
+ export function schemeFromAccent(accent: string): ThemeColorScheme {
172
+ if (!isHex(accent)) return { bg: '#1a202c', text: '#e2e8f0', accent: '#63b3ed' };
173
+ const scale = deriveScale(accent, 0.3);
174
+ return { bg: scale.darker2, text: scale.lighter2, accent: scale.base };
175
+ }
176
+
177
+ export function themeToDraft(theme: Theme | null): Draft {
178
+ if (!theme) return { ...DEFAULT_DRAFT };
179
+ const seeds: ThemeSeedColors = theme.seedColors ?? {
180
+ primary: theme.colors.primary,
181
+ secondary: theme.colors.secondary,
182
+ accent: theme.colors.highlight,
183
+ background: theme.colors.background,
184
+ text: theme.colors.text,
185
+ };
186
+ return {
187
+ name: theme.name,
188
+ baseId: theme.basedOn,
189
+ seeds: {
190
+ primary: seeds.primary,
191
+ secondary: seeds.secondary,
192
+ accent: seeds.accent,
193
+ background: seeds.background,
194
+ text: seeds.text,
195
+ },
196
+ accents: accentsFromTheme(theme),
197
+ // Populated for display, but NOT treated as authored by default: with
198
+ // `accentsEdited` false the compiled theme inherits the base's color
199
+ // schemes verbatim. The dialog flips this true when the user actually
200
+ // edits an accent (or when re-opening an existing custom theme, so its
201
+ // own accents survive a re-save). The popover panel never edits accents,
202
+ // so it always inherits — preserving its prior behavior.
203
+ accentsEdited: false,
204
+ titleFont: fontFamilyToInput(theme.typography.titleFont, 'system-serif'),
205
+ bodyFont: fontFamilyToInput(theme.typography.bodyFont, 'system-sans'),
206
+ borderRadius: findRadiusPreset(theme.style.borderRadius),
207
+ animationSpeed: findAnimationPreset(theme.style.animationSpeed),
208
+ textShadow: theme.style.textShadow === false ? 'off' : 'on',
209
+ contrast: 'balanced',
210
+ imageTreatment: theme.style.imageTreatment?.type ?? 'none',
211
+ };
212
+ }
213
+
214
+ export function slugify(s: string): string {
215
+ return (
216
+ s
217
+ .toLowerCase()
218
+ .replace(/[^a-z0-9]+/g, '-')
219
+ .replace(/^-+|-+$/g, '') || 'custom'
220
+ );
221
+ }
222
+
223
+ export interface CompileDraftOptions {
224
+ /** Existing id to preserve across edits (keeps `squisq-theme` selection stable). */
225
+ existingId?: string;
226
+ /** Base theme to inherit render style / color schemes / typography from. */
227
+ base?: Theme;
228
+ }
229
+
230
+ /**
231
+ * Compile a `Draft` into a full validated `Theme`. Colors derive from the seed
232
+ * colors; the accent list (when edited) replaces `colorSchemes` wholesale; and
233
+ * everything else inherits from `opts.base` (or the neutral STARTER_THEME).
234
+ */
235
+ export function compileDraft(draft: Draft, opts: CompileDraftOptions = {}): Theme {
236
+ const existingId = opts.existingId;
237
+ const id =
238
+ existingId && existingId.startsWith('custom-') ? existingId : `custom-${slugify(draft.name)}`;
239
+
240
+ const colorSchemes =
241
+ draft.accentsEdited && draft.accents.length > 0
242
+ ? Object.fromEntries(draft.accents.map((a) => [a.key, schemeFromAccent(a.color)]))
243
+ : undefined;
244
+
245
+ return compileTheme(
246
+ {
247
+ id,
248
+ name: draft.name,
249
+ seedColors: draft.seeds,
250
+ typography: {
251
+ titleFont: inputToFontFamily(draft.titleFont),
252
+ bodyFont: inputToFontFamily(draft.bodyFont),
253
+ },
254
+ style: {
255
+ borderRadius: BORDER_RADIUS_PRESETS[draft.borderRadius],
256
+ animationSpeed: ANIMATION_SPEED_PRESETS[draft.animationSpeed],
257
+ textShadow: TEXT_SHADOW_PRESETS[draft.textShadow],
258
+ ...(draft.imageTreatment !== 'none'
259
+ ? { imageTreatment: { type: draft.imageTreatment, strength: 0.5 } }
260
+ : {}),
261
+ },
262
+ ...(colorSchemes ? { colorSchemes } : {}),
263
+ },
264
+ { contrast: draft.contrast, base: opts.base },
265
+ );
266
+ }
267
+
268
+ /** Add a fresh accent slot with a sensible starting color. */
269
+ export function nextAccent(accents: AccentInput[]): AccentInput {
270
+ const n = accents.length + 1;
271
+ return { key: `accent${n}`, color: '#63b3ed' };
272
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * useDocCustomThemes — read + persist the active doc's custom themes (the
3
+ * list inlined into the doc's frontmatter under `squisq-custom-themes`).
4
+ *
5
+ * The theme analog of `useDocCustomTemplates`. Both the CustomThemeProvider
6
+ * and any manager surface need the same two things: the current
7
+ * `Doc.customThemes` array and a way to write a new list back into the
8
+ * markdown source. Centralizing the frontmatter encoding here keeps call
9
+ * sites from drifting.
10
+ */
11
+
12
+ import { useCallback, useMemo } from 'react';
13
+ import type { Theme } from '@bendyline/squisq/schemas';
14
+ import {
15
+ FRONTMATTER_CUSTOM_THEMES_KEY,
16
+ writeCustomThemesToFrontmatter,
17
+ } from '@bendyline/squisq/doc';
18
+ import { setFrontmatterValues } from '@bendyline/squisq/markdown';
19
+ import { useEditorContext } from '../EditorContext';
20
+
21
+ export interface DocCustomThemes {
22
+ /** Custom themes inlined in the active doc's frontmatter. */
23
+ docThemes: Theme[];
24
+ /**
25
+ * Persist a new custom-themes list back into the markdown source's
26
+ * frontmatter so the doc round-trips through save/load. The whole list is
27
+ * encoded as a single compact JSON string per the flat YAML frontmatter
28
+ * parser's constraint.
29
+ */
30
+ onDocThemesChange: (next: Theme[]) => void;
31
+ }
32
+
33
+ export function useDocCustomThemes(): DocCustomThemes {
34
+ const { doc, markdownSource, setMarkdownSource } = useEditorContext();
35
+ // Memoized so identity is stable across renders that don't touch
36
+ // frontmatter — keeps the CustomThemeProvider value stable.
37
+ const docThemes = useMemo<Theme[]>(() => doc?.customThemes ?? [], [doc?.customThemes]);
38
+ const onDocThemesChange = useCallback(
39
+ (next: Theme[]) => {
40
+ const payload = writeCustomThemesToFrontmatter(next);
41
+ const updated = setFrontmatterValues(markdownSource, {
42
+ [FRONTMATTER_CUSTOM_THEMES_KEY]: payload ?? null,
43
+ });
44
+ if (updated !== markdownSource) setMarkdownSource(updated);
45
+ },
46
+ [markdownSource, setMarkdownSource],
47
+ );
48
+ return { docThemes, onDocThemesChange };
49
+ }