@widgetic/canvas 0.5.34 → 0.5.36

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 (212) hide show
  1. package/README.md +105 -36
  2. package/dist/canvas/DomCanvas.svelte +454 -0
  3. package/dist/canvas/DomCanvas.svelte.d.ts +222 -0
  4. package/dist/canvas/autosaveScheduler.d.ts +58 -0
  5. package/dist/canvas/autosaveScheduler.js +157 -0
  6. package/dist/canvas/boardFrame.d.ts +13 -0
  7. package/dist/canvas/boardFrame.js +13 -0
  8. package/dist/canvas/boardSurface.d.ts +9 -0
  9. package/dist/canvas/boardSurface.js +9 -0
  10. package/dist/canvas/chromeLayout.d.ts +76 -0
  11. package/dist/canvas/chromeLayout.js +121 -0
  12. package/dist/canvas/emptyBoardHint.d.ts +17 -0
  13. package/dist/canvas/emptyBoardHint.js +12 -0
  14. package/dist/canvas/eventScope.d.ts +1 -1
  15. package/dist/canvas/eventScope.js +1 -1
  16. package/dist/canvas/host/CanvasHost.d.ts +351 -0
  17. package/dist/canvas/host/CanvasHost.js +1740 -0
  18. package/dist/canvas/host/CanvasHostApi.d.ts +30 -0
  19. package/dist/canvas/host/CanvasHostApi.js +95 -0
  20. package/dist/canvas/host/browserServices.d.ts +46 -0
  21. package/dist/canvas/host/browserServices.js +167 -0
  22. package/dist/canvas/host/conversion.d.ts +51 -0
  23. package/dist/canvas/host/conversion.js +123 -0
  24. package/dist/canvas/host/hostObject.d.ts +40 -0
  25. package/dist/canvas/host/hostObject.js +93 -0
  26. package/dist/canvas/host/pageEvents.d.ts +24 -0
  27. package/dist/canvas/host/pageEvents.js +35 -0
  28. package/dist/canvas/host/screenRects.d.ts +66 -0
  29. package/dist/canvas/host/screenRects.js +102 -0
  30. package/dist/canvas/host/strokeSnap.d.ts +67 -0
  31. package/dist/canvas/host/strokeSnap.js +165 -0
  32. package/dist/canvas/index.d.ts +9 -7
  33. package/dist/canvas/index.js +9 -7
  34. package/dist/canvas/openMarks.d.ts +17 -0
  35. package/dist/canvas/openMarks.js +26 -0
  36. package/dist/canvas/panZoomPosition.d.ts +15 -0
  37. package/dist/canvas/panZoomPosition.js +16 -0
  38. package/dist/canvas/preferredTextFont.d.ts +12 -0
  39. package/dist/canvas/preferredTextFont.js +38 -0
  40. package/dist/canvas/shapes/ShapeLibrary.d.ts +1 -1
  41. package/dist/canvas/shapes/ShapeLibrary.js +13 -1
  42. package/dist/canvas/shapes/strokeShapeSnap.d.ts +14 -12
  43. package/dist/canvas/shapes/strokeShapeSnap.js +10 -8
  44. package/dist/canvas/toolbarPosition.d.ts +24 -0
  45. package/dist/canvas/toolbarPosition.js +24 -0
  46. package/dist/canvas/types.d.ts +14 -0
  47. package/dist/canvas/ui/CanvasContextMenu.svelte +173 -0
  48. package/dist/canvas/ui/CanvasContextMenu.svelte.d.ts +12 -0
  49. package/dist/canvas/ui/CanvasHint.svelte +20 -0
  50. package/dist/canvas/ui/CanvasHint.svelte.d.ts +18 -0
  51. package/dist/canvas/ui/CanvasToolbar.svelte +95 -0
  52. package/dist/canvas/ui/CanvasToolbar.svelte.d.ts +14 -0
  53. package/dist/canvas/ui/ColorField.svelte +155 -0
  54. package/dist/canvas/ui/ColorField.svelte.d.ts +14 -0
  55. package/dist/canvas/ui/LoadNotice.svelte +39 -0
  56. package/dist/canvas/ui/LoadNotice.svelte.d.ts +8 -0
  57. package/dist/canvas/ui/SelectionPanel.svelte +300 -0
  58. package/dist/canvas/ui/SelectionPanel.svelte.d.ts +20 -0
  59. package/dist/canvas/ui/SelectorBar.svelte +82 -0
  60. package/dist/canvas/ui/SelectorBar.svelte.d.ts +12 -0
  61. package/dist/canvas/ui/ShapesMenu.svelte +185 -0
  62. package/dist/canvas/ui/ShapesMenu.svelte.d.ts +15 -0
  63. package/dist/canvas/ui/ShortcutsPanel.svelte +124 -0
  64. package/dist/canvas/ui/ShortcutsPanel.svelte.d.ts +7 -0
  65. package/dist/canvas/ui/ToolButton.svelte +78 -0
  66. package/dist/canvas/ui/ToolButton.svelte.d.ts +20 -0
  67. package/dist/canvas/ui/WidgetActions.svelte +152 -0
  68. package/dist/canvas/ui/WidgetActions.svelte.d.ts +19 -0
  69. package/dist/canvas/ui/ZoomControl.svelte +89 -0
  70. package/dist/canvas/ui/ZoomControl.svelte.d.ts +18 -0
  71. package/dist/canvas/ui/colorModel.d.ts +18 -0
  72. package/dist/canvas/ui/colorModel.js +85 -0
  73. package/dist/canvas/ui/colorPickerMessages.d.ts +5 -0
  74. package/dist/canvas/ui/colorPickerMessages.js +15 -0
  75. package/dist/canvas/ui/floatingCard.d.ts +107 -0
  76. package/dist/canvas/ui/floatingCard.js +107 -0
  77. package/dist/canvas/ui/floatingLayer.d.ts +21 -0
  78. package/dist/canvas/ui/floatingLayer.js +52 -0
  79. package/dist/canvas/ui/icons.d.ts +12 -0
  80. package/dist/canvas/ui/icons.js +7 -0
  81. package/dist/canvas/ui/keyHints.d.ts +27 -0
  82. package/dist/canvas/ui/keyHints.js +43 -0
  83. package/dist/canvas/ui/popoverSide.d.ts +5 -0
  84. package/dist/canvas/ui/popoverSide.js +20 -0
  85. package/dist/canvas/ui/selectionTraits.d.ts +61 -0
  86. package/dist/canvas/ui/selectionTraits.js +99 -0
  87. package/dist/canvas/view/CanvasStage.svelte +132 -0
  88. package/dist/canvas/view/CanvasStage.svelte.d.ts +21 -0
  89. package/dist/canvas/view/EraserTrail.svelte +50 -0
  90. package/dist/canvas/view/EraserTrail.svelte.d.ts +9 -0
  91. package/dist/canvas/view/ObjectView.svelte +245 -0
  92. package/dist/canvas/view/ObjectView.svelte.d.ts +21 -0
  93. package/dist/canvas/view/SelectionOverlay.svelte +487 -0
  94. package/dist/canvas/view/SelectionOverlay.svelte.d.ts +17 -0
  95. package/dist/canvas/view/TextEditor.svelte +76 -0
  96. package/dist/canvas/view/TextEditor.svelte.d.ts +9 -0
  97. package/dist/canvas/view/WidgetChromeLayer.svelte +83 -0
  98. package/dist/canvas/view/WidgetChromeLayer.svelte.d.ts +13 -0
  99. package/dist/canvas/view/erasingMarks.d.ts +13 -0
  100. package/dist/canvas/view/erasingMarks.js +34 -0
  101. package/dist/canvas/view/geometry.d.ts +169 -0
  102. package/dist/canvas/view/geometry.js +272 -0
  103. package/dist/components/CanvasBoardPlaceholder.svelte +5 -3
  104. package/dist/components/CanvasBoardPlaceholder.svelte.d.ts +3 -3
  105. package/dist/components/index.js +1 -1
  106. package/dist/components/input-controls/ColorIC.svelte +2 -2
  107. package/dist/engine/EngineCore.d.ts +273 -0
  108. package/dist/engine/EngineCore.js +1051 -0
  109. package/dist/engine/codec/canvasDocument.d.ts +57 -0
  110. package/dist/engine/codec/canvasDocument.js +471 -0
  111. package/dist/engine/codec/hostReadableKeys.d.ts +25 -0
  112. package/dist/engine/codec/hostReadableKeys.js +25 -0
  113. package/dist/engine/core/arrange.d.ts +20 -0
  114. package/dist/engine/core/arrange.js +81 -0
  115. package/dist/engine/core/arrow.d.ts +91 -0
  116. package/dist/engine/core/arrow.js +182 -0
  117. package/dist/engine/core/brush.d.ts +68 -0
  118. package/dist/engine/core/brush.js +173 -0
  119. package/dist/engine/core/defaults.d.ts +70 -0
  120. package/dist/engine/core/defaults.js +158 -0
  121. package/dist/engine/core/freehand.d.ts +130 -0
  122. package/dist/engine/core/freehand.js +430 -0
  123. package/dist/engine/core/geometry.d.ts +44 -0
  124. package/dist/engine/core/geometry.js +216 -0
  125. package/dist/engine/core/history.d.ts +39 -0
  126. package/dist/engine/core/history.js +69 -0
  127. package/dist/engine/core/hitTest.d.ts +54 -0
  128. package/dist/engine/core/hitTest.js +298 -0
  129. package/dist/engine/core/matrix.d.ts +47 -0
  130. package/dist/engine/core/matrix.js +101 -0
  131. package/dist/engine/core/pathData.d.ts +50 -0
  132. package/dist/engine/core/pathData.js +550 -0
  133. package/dist/engine/core/rotationReset.d.ts +10 -0
  134. package/dist/engine/core/rotationReset.js +17 -0
  135. package/dist/engine/core/scene.d.ts +99 -0
  136. package/dist/engine/core/scene.js +450 -0
  137. package/dist/engine/core/scribble.d.ts +64 -0
  138. package/dist/engine/core/scribble.js +121 -0
  139. package/dist/engine/core/shapePaths.d.ts +34 -0
  140. package/dist/engine/core/shapePaths.js +69 -0
  141. package/dist/engine/core/shapeTools.d.ts +80 -0
  142. package/dist/engine/core/shapeTools.js +161 -0
  143. package/dist/engine/core/snapping.d.ts +64 -0
  144. package/dist/engine/core/snapping.js +164 -0
  145. package/dist/engine/core/style.d.ts +40 -0
  146. package/dist/engine/core/style.js +151 -0
  147. package/dist/engine/core/transform.d.ts +79 -0
  148. package/dist/engine/core/transform.js +258 -0
  149. package/dist/engine/core/types.d.ts +238 -0
  150. package/dist/engine/core/types.js +31 -0
  151. package/dist/engine/core/viewport.d.ts +32 -0
  152. package/dist/engine/core/viewport.js +84 -0
  153. package/dist/engine/input/PointerController.d.ts +38 -0
  154. package/dist/engine/input/PointerController.js +545 -0
  155. package/dist/engine/input/arrowHandles.d.ts +38 -0
  156. package/dist/engine/input/arrowHandles.js +60 -0
  157. package/dist/engine/input/gestures.d.ts +79 -0
  158. package/dist/engine/input/gestures.js +769 -0
  159. package/dist/engine/input/hoverCursor.d.ts +29 -0
  160. package/dist/engine/input/hoverCursor.js +23 -0
  161. package/dist/engine/input/keyboard.d.ts +75 -0
  162. package/dist/engine/input/keyboard.js +264 -0
  163. package/dist/engine/input/selectionHandles.d.ts +89 -0
  164. package/dist/engine/input/selectionHandles.js +169 -0
  165. package/dist/engine/input/types.d.ts +82 -0
  166. package/dist/engine/input/types.js +5 -0
  167. package/dist/engine/render/rasterize.d.ts +74 -0
  168. package/dist/engine/render/rasterize.js +273 -0
  169. package/dist/engine/state.d.ts +124 -0
  170. package/dist/engine/state.js +47 -0
  171. package/dist/engine/text/layoutText.d.ts +53 -0
  172. package/dist/engine/text/layoutText.js +170 -0
  173. package/dist/engine/widgets.d.ts +124 -0
  174. package/dist/engine/widgets.js +345 -0
  175. package/dist/i18n/labels.d.ts +4 -15
  176. package/dist/i18n/labels.js +33 -53
  177. package/dist/i18n/language.d.ts +3 -3
  178. package/dist/i18n/messages.d.ts +51 -122
  179. package/dist/i18n/messages.js +58 -131
  180. package/dist/i18n/shortcuts.d.ts +0 -1
  181. package/dist/i18n/shortcuts.js +2 -11
  182. package/dist/index.d.ts +6 -2
  183. package/dist/index.js +6 -2
  184. package/package.json +30 -5
  185. package/dist/canvas/Canvas.svelte +0 -13299
  186. package/dist/canvas/Canvas.svelte.d.ts +0 -281
  187. package/dist/canvas/CanvasToolbar.svelte +0 -1498
  188. package/dist/canvas/CanvasToolbar.svelte.d.ts +0 -69
  189. package/dist/canvas/ContextMenu.svelte +0 -305
  190. package/dist/canvas/ContextMenu.svelte.d.ts +0 -42
  191. package/dist/canvas/PanZoomPanel.svelte +0 -478
  192. package/dist/canvas/PanZoomPanel.svelte.d.ts +0 -38
  193. package/dist/canvas/WidgetSelectionLayer.svelte +0 -156
  194. package/dist/canvas/WidgetSelectionLayer.svelte.d.ts +0 -11
  195. package/dist/canvas/props-panel/PropsPanel.svelte +0 -2075
  196. package/dist/canvas/props-panel/PropsPanel.svelte.d.ts +0 -84
  197. package/dist/canvas/props-panel/TextPropsICSection.svelte +0 -242
  198. package/dist/canvas/props-panel/TextPropsICSection.svelte.d.ts +0 -40
  199. package/dist/canvas/shadowRootText.d.ts +0 -5
  200. package/dist/canvas/shadowRootText.js +0 -43
  201. package/dist/canvas/shapes/FrameShape.d.ts +0 -97
  202. package/dist/canvas/shapes/FrameShape.js +0 -953
  203. package/dist/canvas/shapes/ImageShape.d.ts +0 -47
  204. package/dist/canvas/shapes/ImageShape.js +0 -339
  205. package/dist/canvas/shapes/WidgetShape.d.ts +0 -30
  206. package/dist/canvas/shapes/WidgetShape.js +0 -200
  207. package/dist/canvas/widgetPreviewGeometry.d.ts +0 -19
  208. package/dist/canvas/widgetPreviewGeometry.js +0 -66
  209. package/dist/i18n/shapeWords.d.ts +0 -30
  210. package/dist/i18n/shapeWords.js +0 -36
  211. package/dist/i18n/slots.d.ts +0 -20
  212. package/dist/i18n/slots.js +0 -40
@@ -1,953 +0,0 @@
1
- /**
2
- * FrameShape - A container shape extending Fabric.js Group
3
- *
4
- * Features:
5
- * - Extends fabric.Group to act as a container for child objects
6
- * - interactive: true — children can be selected/edited directly (tldraw-like)
7
- * - Click on a child → selects that child for individual editing
8
- * - Click on frame background → selects the frame itself
9
- * - ClipPath for bounding/clipping content inside frame boundaries
10
- * - Customizable label drawn above the frame (with text wrapping, rotation support)
11
- * - Custom controls: corner resize only, no rotation handle
12
- * - Minimum size enforcement
13
- * - Serialization support with custom properties
14
- * - addObjectToFrame / removeObjectFromFrame with automatic coordinate conversion
15
- * (Fabric's native _enterGroup/_exitGroup handles absolute ↔ group-relative transforms)
16
- *
17
- * Containment detection (drag in/out) is handled by Canvas.svelte's
18
- * object:modified handler since it requires canvas-level access.
19
- */
20
- import { Group, Rect, Control, controlsUtils, util, LayoutManager, FixedLayout, classRegistry } from 'fabric';
21
- import { canvasLog, canvasWarn } from '../canvasLogger';
22
- import { shapeWordsOf } from '../../i18n/shapeWords.js';
23
- // ─────────────────────────────────────────────
24
- // Constants
25
- // ─────────────────────────────────────────────
26
- export const MIN_FRAME_WIDTH = 50;
27
- export const MIN_FRAME_HEIGHT = 30;
28
- const DEFAULT_LABEL_FONT_SIZE = 16;
29
- const DEFAULT_LABEL_FONT_FAMILY = 'Inter, system-ui, sans-serif';
30
- const DEFAULT_LABEL_COLOR = '#1f2937';
31
- const DEFAULT_LABEL_BG_COLOR = '#ffffff';
32
- const DEFAULT_FILL = '#ffffff';
33
- export const DEFAULT_STROKE = '#2563eb';
34
- // Slightly darker blue shown on border/label hover (replaces separate overlay border)
35
- export const FRAME_HOVER_STROKE = '#1d4ed8';
36
- const DEFAULT_STROKE_WIDTH = 3;
37
- // ─────────────────────────────────────────────
38
- // Helper: Wrap text into lines that fit a max width
39
- // Handles both word-level and character-level wrapping for long words
40
- // ─────────────────────────────────────────────
41
- function wrapText(ctx, text, maxWidth) {
42
- const words = text.split(' ');
43
- const lines = [];
44
- let currentLine = '';
45
- // Break a single long word into character chunks
46
- function breakWord(word) {
47
- if (ctx.measureText(word).width <= maxWidth)
48
- return [word];
49
- const chunks = [];
50
- let chunk = '';
51
- for (const char of word) {
52
- const test = chunk + char;
53
- if (ctx.measureText(test).width > maxWidth && chunk) {
54
- chunks.push(chunk);
55
- chunk = char;
56
- }
57
- else {
58
- chunk = test;
59
- }
60
- }
61
- if (chunk)
62
- chunks.push(chunk);
63
- return chunks;
64
- }
65
- for (const word of words) {
66
- if (ctx.measureText(word).width > maxWidth) {
67
- // Word itself is too long - break by characters
68
- if (currentLine) {
69
- lines.push(currentLine);
70
- currentLine = '';
71
- }
72
- const broken = breakWord(word);
73
- for (let i = 0; i < broken.length - 1; i++) {
74
- lines.push(broken[i]);
75
- }
76
- currentLine = broken[broken.length - 1] || '';
77
- }
78
- else {
79
- const testLine = currentLine ? `${currentLine} ${word}` : word;
80
- if (ctx.measureText(testLine).width > maxWidth && currentLine) {
81
- lines.push(currentLine);
82
- currentLine = word;
83
- }
84
- else {
85
- currentLine = testLine;
86
- }
87
- }
88
- }
89
- if (currentLine)
90
- lines.push(currentLine);
91
- return lines.length > 0 ? lines : [text];
92
- }
93
- // ─────────────────────────────────────────────
94
- // Helper: Draw the label above the frame
95
- // ─────────────────────────────────────────────
96
- function renderFrameLabel(ctx, frame) {
97
- // A frame with no name says "Frame", in the language of the canvas it is on
98
- const text = frame._labelText || shapeWordsOf(frame.canvas).frameLabel;
99
- const fontSize = frame._labelFontSize || DEFAULT_LABEL_FONT_SIZE;
100
- const fontFamily = frame._labelFontFamily || DEFAULT_LABEL_FONT_FAMILY;
101
- const textColor = frame._labelColor || DEFAULT_LABEL_COLOR;
102
- const bgColor = frame._labelBackgroundColor || DEFAULT_LABEL_BG_COLOR;
103
- const textAlign = frame._labelTextAlign || 'left';
104
- const fontWeight = frame._labelFontWeight || 'normal';
105
- const fontStyle = frame._labelFontStyle || 'normal';
106
- const underline = frame._labelUnderline || false;
107
- // Use FULL visual dimensions (including parent group scales).
108
- // The calling code positions the context at the frame's center via this.transform()
109
- // then counter-scales to 1:1 via getObjectScaling(). In this 1:1 context, the
110
- // frame's visual extent from center is (width/2 * totalScale), not (width/2 * localScale).
111
- const scaling = frame.getObjectScaling ? frame.getObjectScaling() : { x: frame.scaleX || 1, y: frame.scaleY || 1 };
112
- const frameW = (frame.width || 100) * scaling.x;
113
- const frameH = (frame.height || 100) * scaling.y;
114
- ctx.save();
115
- // Set font to measure text
116
- ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`;
117
- const padding = 6;
118
- const gap = 4;
119
- const lineHeight = fontSize * 1.2;
120
- // Label width matches the frame's visual width (clipPath boundary).
121
- // The background rect's stroke is centered on the edge; the outward half is clipped,
122
- // so the visible frame width is exactly frameW.
123
- const minLabelWidth = 50;
124
- const labelBgWidth = Math.max(frameW, minLabelWidth);
125
- const maxTextWidth = labelBgWidth - padding * 2;
126
- // Wrap text
127
- const lines = wrapText(ctx, text, maxTextWidth);
128
- const labelBgHeight = lines.length * lineHeight + padding * 2;
129
- // Position: label sits above the frame
130
- // In Group's local coordinate system, center is (0, 0)
131
- // So top-left of frame content area is at (-frameW/2, -frameH/2)
132
- const labelBgX = -frameW / 2;
133
- const labelBgY = -frameH / 2 - labelBgHeight - gap;
134
- // Draw label background
135
- ctx.fillStyle = bgColor;
136
- ctx.fillRect(labelBgX, labelBgY, labelBgWidth, labelBgHeight);
137
- // Clip to label bounds (overflow hidden)
138
- ctx.beginPath();
139
- ctx.rect(labelBgX, labelBgY, labelBgWidth, labelBgHeight);
140
- ctx.clip();
141
- // Draw text lines
142
- ctx.fillStyle = textColor;
143
- ctx.textBaseline = 'top';
144
- lines.forEach((line, index) => {
145
- const lineWidth = ctx.measureText(line).width;
146
- let textX;
147
- switch (textAlign) {
148
- case 'center':
149
- textX = labelBgX + (labelBgWidth - lineWidth) / 2;
150
- break;
151
- case 'right':
152
- textX = labelBgX + labelBgWidth - lineWidth - padding;
153
- break;
154
- default:
155
- textX = labelBgX + padding;
156
- break;
157
- }
158
- const textY = labelBgY + padding + index * lineHeight;
159
- ctx.fillText(line, textX, textY);
160
- // Draw underline if enabled
161
- if (underline) {
162
- ctx.beginPath();
163
- ctx.strokeStyle = textColor;
164
- ctx.lineWidth = 1;
165
- ctx.moveTo(textX, textY + fontSize);
166
- ctx.lineTo(textX + lineWidth, textY + fontSize);
167
- ctx.stroke();
168
- }
169
- });
170
- ctx.restore();
171
- }
172
- // ─────────────────────────────────────────────
173
- // FrameShape — registered Fabric class
174
- // Extends Group with a unique type so Fabric's classRegistry
175
- // dispatches loadFromJSON to FrameShape.fromObject, which calls
176
- // reapplyFrameRender automatically. New saves use type: 'FrameShape'.
177
- // Old saves (type: 'Group' with _isFrame: true) are handled by the
178
- // object:added fallback in Canvas.svelte for backward compatibility.
179
- // ─────────────────────────────────────────────
180
- export class FrameShape extends Group {
181
- static type = 'FrameShape';
182
- /**
183
- * Serialise the frame with type = 'FrameShape' plus all custom label/style
184
- * props so they survive a canvas.toJSON() → loadFromJSON() round-trip.
185
- * FRAME_CUSTOM_PROPS and _objectId are always included regardless of what
186
- * the canvas passes as propertiesToInclude.
187
- */
188
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
189
- toObject(propertiesToInclude) {
190
- return {
191
- // Merge FRAME_CUSTOM_PROPS + _objectId with whatever the canvas requests
192
- ...super.toObject([
193
- ...FRAME_CUSTOM_PROPS,
194
- '_objectId',
195
- ...(propertiesToInclude || []),
196
- ]),
197
- type: FrameShape.type,
198
- };
199
- }
200
- /**
201
- * Deserialise a saved FrameShape.
202
- * Delegates to Group.fromObject (handles enlivenObjects, FixedLayout setup,
203
- * and subscribeTargets) then upgrades the plain Group to a proper FrameShape
204
- * instance via Object.setPrototypeOf before re-applying the custom render.
205
- *
206
- * WHY setPrototypeOf:
207
- * Group.fromObject always returns `new Group(...)` whose prototype is Group.prototype.
208
- * After setPrototypeOf → FrameShape.prototype, the instance:
209
- * • reports type === 'FrameShape' (via FrameShape.prototype.type)
210
- * • calls FrameShape.prototype.toObject() on save → emits type:'FrameShape' + custom props
211
- * • classRegistry dispatches FrameShape.fromObject on next reload
212
- */
213
- static fromObject(object, options) {
214
- // Treat as a plain Group first so Group.fromObject handles all the
215
- // heavy lifting (enlivenObjects, LayoutManager, coords, etc.)
216
- const groupJson = { ...object, type: 'Group' };
217
- canvasLog('FrameShape.fromObject: deserialising frame label=' + object._labelText
218
- + ' children=' + (object.objects || []).length);
219
- return Group.fromObject(groupJson, options).then((group) => {
220
- // Upgrade Group instance → FrameShape instance.
221
- // This must happen BEFORE reapplyFrameRender so that
222
- // reapplyFrameRender's prototype check (below) is a no-op.
223
- Object.setPrototypeOf(group, FrameShape.prototype);
224
- reapplyFrameRender(group);
225
- canvasLog('FrameShape.fromObject: restored frame label=' + group._labelText
226
- + ' children=' + group.getObjects().length
227
- + ' type=' + group.type);
228
- return group;
229
- });
230
- }
231
- }
232
- // Register with Fabric so classRegistry.getClass('FrameShape') resolves in loadFromJSON.
233
- // NOTE: Fabric's type getter reads this.constructor.type.toLowerCase().
234
- // Object.setPrototypeOf(group, FrameShape.prototype) changes group.constructor to FrameShape,
235
- // so group.type becomes 'frameshape' automatically — no prototype.type setter needed.
236
- classRegistry.setClass(FrameShape);
237
- // ─────────────────────────────────────────────
238
- // Create a new FrameShape instance
239
- // ─────────────────────────────────────────────
240
- export function createFrameShape(options = {}) {
241
- const { left = 0, top = 0, width = 200, height = 150, fill = DEFAULT_FILL, stroke = DEFAULT_STROKE, strokeWidth = DEFAULT_STROKE_WIDTH, labelText = shapeWordsOf(undefined).frameLabel, labelFontSize = DEFAULT_LABEL_FONT_SIZE, labelFontFamily = DEFAULT_LABEL_FONT_FAMILY, labelColor = DEFAULT_LABEL_COLOR, labelBackgroundColor = DEFAULT_LABEL_BG_COLOR, labelTextAlign = 'left', labelFontWeight = 'normal', labelFontStyle = 'normal', labelUnderline = false, } = options;
242
- // Enforce minimum dimensions
243
- const finalWidth = Math.max(width, MIN_FRAME_WIDTH);
244
- const finalHeight = Math.max(height, MIN_FRAME_HEIGHT);
245
- // Create the background rectangle (visual frame body)
246
- // In Group's local coords, origin is center, so rect goes from -w/2 to w/2
247
- const backgroundRect = new Rect({
248
- left: 0,
249
- top: 0,
250
- width: finalWidth,
251
- height: finalHeight,
252
- fill: fill,
253
- stroke: stroke,
254
- strokeWidth: strokeWidth,
255
- strokeUniform: true,
256
- originX: 'center',
257
- originY: 'center',
258
- // Background rect is NOT interactive - clicks on it pass through to the frame group
259
- // This allows clicking on the frame's empty area to select the frame itself
260
- selectable: false,
261
- evented: false,
262
- });
263
- // Tag the background rect so we can identify it
264
- backgroundRect._isFrameBackground = true;
265
- // Use FrameShape (registered Fabric class) so canvas.toJSON() emits
266
- // type: 'FrameShape', allowing loadFromJSON to call FrameShape.fromObject
267
- // which restores the custom render automatically on reload.
268
- const frame = new FrameShape([backgroundRect], {
269
- left: left,
270
- top: top,
271
- originX: 'left',
272
- originY: 'top',
273
- // Sub-target check allows detecting clicks on children inside the group
274
- subTargetCheck: true,
275
- // Interactive: children can be selected/edited directly without entering edit mode
276
- // Click on a child → selects that child for individual editing
277
- // Click on frame background → selects the frame itself
278
- interactive: true,
279
- selectable: true,
280
- // No rotation for frames
281
- lockRotation: true,
282
- // Minimum scale limit
283
- minScaleLimit: 0.1,
284
- // Disable object caching so children render directly on canvas.
285
- // This ensures property changes on children are immediately visible.
286
- objectCaching: false,
287
- // Show move cursor when hovering over frame body
288
- hoverCursor: 'move',
289
- moveCursor: 'move',
290
- // FixedLayout: frame keeps its explicit size, children don't expand selection border
291
- layoutManager: new LayoutManager(new FixedLayout()),
292
- });
293
- // ─── Custom properties ───
294
- const frameAny = frame;
295
- frameAny._customType = 'frame';
296
- frameAny._isFrame = true;
297
- // Label properties (editable via PropsPanel)
298
- frameAny._labelText = labelText;
299
- frameAny._labelFontSize = labelFontSize;
300
- frameAny._labelFontFamily = labelFontFamily;
301
- frameAny._labelColor = labelColor;
302
- frameAny._labelBackgroundColor = labelBackgroundColor;
303
- frameAny._labelTextAlign = labelTextAlign;
304
- frameAny._labelFontWeight = labelFontWeight;
305
- frameAny._labelFontStyle = labelFontStyle;
306
- frameAny._labelUnderline = labelUnderline;
307
- // Frame visual properties (stored separately from Fabric's defaults)
308
- frameAny._frameFill = fill;
309
- frameAny._frameStroke = stroke;
310
- frameAny._frameStrokeWidth = strokeWidth;
311
- // ─── ClipPath: clips children to frame boundaries ───
312
- setupClipPath(frame);
313
- // ─── Custom controls: corner resize only, no rotation ───
314
- setupFrameControls(frame);
315
- // ─── Custom render: draw label above the frame ───
316
- const originalRender = frame.render.bind(frame);
317
- frame.render = function (ctx) {
318
- // Render the group normally (background rect + any children)
319
- originalRender(ctx);
320
- // Draw the label on top.
321
- // After originalRender (Group.render → FabricObject.render → save/transform/restore),
322
- // the ctx is back to the parent's coordinate space. We use Fabric's own transform()
323
- // method to apply the frame's transform correctly (handles _transformDone flag and
324
- // group chain automatically). This works for both top-level and nested frames.
325
- ctx.save();
326
- this.transform(ctx);
327
- // Counter-scale so label text stays crisp at 1:1 size.
328
- // getObjectScaling() returns the total visual scale including parent groups.
329
- const scaling = this.getObjectScaling();
330
- ctx.scale(1 / scaling.x, 1 / scaling.y);
331
- // Now context is at frame center, at 1:1 scale.
332
- // renderFrameLabel uses local dimensions (frame.width * frame.scaleX).
333
- renderFrameLabel(ctx, this);
334
- ctx.restore();
335
- };
336
- // ─── Border-only hit test: frame is selectable only at its border/stroke ───
337
- // or label — clicking the empty interior is a click-through so the user
338
- // can start a rubber-band selection of frame children from there.
339
- applyFrameHitTest(frame);
340
- // Mark the frame as dirty so it renders immediately
341
- frame.dirty = true;
342
- canvasLog('FrameShape created', {
343
- width: finalWidth,
344
- height: finalHeight,
345
- left,
346
- top,
347
- labelText
348
- });
349
- return frame;
350
- }
351
- // ─────────────────────────────────────────────
352
- // Setup ClipPath on a frame Group
353
- // Clips children to frame boundaries so content doesn't overflow
354
- // ─────────────────────────────────────────────
355
- export function setupClipPath(frame) {
356
- const clipRect = new Rect({
357
- left: 0,
358
- top: 0,
359
- width: frame.width,
360
- height: frame.height,
361
- originX: 'center',
362
- originY: 'center',
363
- absolutePositioned: false, // Relative to the group
364
- });
365
- frame.clipPath = clipRect;
366
- }
367
- // ─────────────────────────────────────────────
368
- // Update ClipPath when frame is resized
369
- // Call this after frame dimensions change
370
- // ─────────────────────────────────────────────
371
- export function updateClipPath(frame) {
372
- // Preserve corner radius from the frame's custom property
373
- const cornerRadius = frame._frameCornerRadius || 0;
374
- if (frame.clipPath) {
375
- frame.clipPath.set({
376
- width: frame.width,
377
- height: frame.height,
378
- rx: cornerRadius,
379
- ry: cornerRadius,
380
- });
381
- }
382
- else {
383
- setupClipPath(frame);
384
- }
385
- }
386
- // ─────────────────────────────────────────────
387
- // Update corner radius on frame's background rect + clip path
388
- // Called from Canvas.svelte when the user changes the roundness slider
389
- // ─────────────────────────────────────────────
390
- export function updateFrameCornerRadius(frame, radiusPixels) {
391
- const bg = getFrameBackground(frame);
392
- if (bg) {
393
- bg.set({ rx: radiusPixels, ry: radiusPixels });
394
- bg.dirty = true;
395
- }
396
- // Also update the clip path so children are clipped to rounded bounds
397
- if (frame.clipPath) {
398
- frame.clipPath.set({ rx: radiusPixels, ry: radiusPixels });
399
- }
400
- // Store the pixel value on the frame for serialization/restoration
401
- frame._frameCornerRadius = radiusPixels;
402
- frame.dirty = true;
403
- }
404
- // ─────────────────────────────────────────────
405
- // Setup custom controls for the frame
406
- // Corner resize only (no rotation handle)
407
- // ─────────────────────────────────────────────
408
- function setupFrameControls(frame) {
409
- // Remove the default rotation control (mtr)
410
- // Keep corner controls for resize and middle controls for width/height
411
- if (frame.controls && frame.controls.mtr) {
412
- delete frame.controls.mtr;
413
- }
414
- }
415
- // ─────────────────────────────────────────────
416
- // Add an object into the frame
417
- //
418
- // Uses frame.add() for correct coordinate conversion and internal state.
419
- // The key challenge: Fabric's _enterGroup (line ~11795 in index.node.mjs)
420
- // calls object.setCoords() BEFORE setting object.group and object.canvas,
421
- // producing wrong aCoords (no group context) and no oCoords (no canvas).
422
- //
423
- // Solution: Temporarily replace object.setCoords with a no-op during
424
- // frame.add(), then restore it and call setCoords() ourselves AFTER
425
- // _enterGroup has set object.group and object.canvas.
426
- //
427
- // IMPORTANT: We do NOT touch frame._shouldSetNestedCoords — that would
428
- // break the prototype chain and prevent Group.setCoords() from propagating
429
- // to children when the frame is moved.
430
- // ─────────────────────────────────────────────
431
- export function addObjectToFrame(frame, object, canvas) {
432
- try {
433
- // Skip if object is already in this frame (by group ref)
434
- if (object.group === frame) {
435
- canvasLog('addObjectToFrame: Object already in this frame (group ref)');
436
- return;
437
- }
438
- // Skip if object is already in frame._objects (safety for edge cases
439
- // where group ref wasn't set due to a previous partial add)
440
- if (frame._objects && frame._objects.includes(object)) {
441
- canvasWarn('addObjectToFrame: Object already in frame._objects array, fixing state');
442
- // Fix: manually set group and canvas if they weren't set
443
- if (object.group !== frame) {
444
- object._set('group', frame);
445
- }
446
- if (!object.canvas && frame.canvas) {
447
- object._set('canvas', frame.canvas);
448
- }
449
- object.setCoords();
450
- return;
451
- }
452
- // Skip if object is the frame's background rect
453
- if (object._isFrameBackground) {
454
- canvasLog('addObjectToFrame: Cannot add frame background to itself');
455
- return;
456
- }
457
- // Prevent self-nesting and circular nesting
458
- if (object === frame) {
459
- canvasLog('addObjectToFrame: Cannot add frame to itself');
460
- return;
461
- }
462
- if (object._isFrame && isFrameShape(object)) {
463
- let parent = frame.group;
464
- while (parent) {
465
- if (parent === object) {
466
- canvasLog('addObjectToFrame: Circular nesting prevented');
467
- return;
468
- }
469
- parent = parent.group;
470
- }
471
- }
472
- // ── 1. Clear ALL stale matrix caches ──
473
- object.matrixCache = undefined;
474
- object.ownMatrixCache = undefined;
475
- frame.matrixCache = undefined;
476
- frame.ownMatrixCache = undefined;
477
- // ── 2. Save frame dimensions (frame.add can trigger layout side-effects) ──
478
- const savedFrameWidth = frame.width;
479
- const savedFrameHeight = frame.height;
480
- const savedFrameLeft = frame.left;
481
- const savedFrameTop = frame.top;
482
- // ── 3. Remove from current location ──
483
- if (object.group) {
484
- object.group.remove(object);
485
- }
486
- else if (canvas) {
487
- canvas.remove(object);
488
- }
489
- // Clear caches after removal
490
- object.matrixCache = undefined;
491
- object.ownMatrixCache = undefined;
492
- // ── 4. Block premature setCoords inside _enterGroup ──
493
- // Fabric's _enterGroup calls: this._shouldSetNestedCoords() && object.setCoords()
494
- // At that point, object.group and object.canvas are NOT yet set, producing
495
- // wrong coords. We patch object.setCoords to a no-op during frame.add().
496
- // This is safer than patching frame._shouldSetNestedCoords which breaks
497
- // the frame's prototype chain (Group.setCoords won't propagate to children).
498
- object.setCoords = function () { }; // no-op during frame.add
499
- // ── 5. Use frame.add() — handles coordinate conversion, events, layout ──
500
- frame.add(object);
501
- // ── 6. Restore object.setCoords from prototype ──
502
- // Remove own property so it falls back to InteractiveObject.prototype.setCoords
503
- delete object.setCoords;
504
- // ── 7. Safety: ensure object.canvas is set ──
505
- // _enterGroup should have set it, but verify as a safety net
506
- if (!object.canvas && frame.canvas) {
507
- canvasWarn('addObjectToFrame: canvas not set by _enterGroup, fixing manually');
508
- object._set('canvas', frame.canvas);
509
- }
510
- // ── 8. Safety: ensure object.group is set ──
511
- if (object.group !== frame) {
512
- canvasWarn('addObjectToFrame: group not set by _enterGroup, fixing manually');
513
- object._set('group', frame);
514
- }
515
- // ── 9. Restore frame dimensions if layout changed them ──
516
- if (frame.width !== savedFrameWidth || frame.height !== savedFrameHeight ||
517
- frame.left !== savedFrameLeft || frame.top !== savedFrameTop) {
518
- frame.set({
519
- width: savedFrameWidth,
520
- height: savedFrameHeight,
521
- left: savedFrameLeft,
522
- top: savedFrameTop,
523
- });
524
- }
525
- // ── 10. Clear stale matrix caches after group membership change ──
526
- object.matrixCache = undefined;
527
- object.ownMatrixCache = undefined;
528
- frame.matrixCache = undefined;
529
- frame.ownMatrixCache = undefined;
530
- // ── 11. Clear stale _activeObjects ──
531
- if (frame._activeObjects && frame._activeObjects.length > 0) {
532
- frame._activeObjects = [];
533
- }
534
- // ── 12. NOW call setCoords — with object.group and object.canvas properly set ──
535
- // This produces correct aCoords (corners in absolute space via
536
- // calcTransformMatrix = frameMatrix * ownMatrix) and correct oCoords
537
- // (control positions in viewport space, requires this.canvas).
538
- object.setCoords();
539
- // frame.setCoords() propagates to ALL children via _shouldSetNestedCoords()
540
- // which returns this.subTargetCheck (true for our frame).
541
- frame.setCoords();
542
- frame.dirty = true;
543
- // ── 13. Update clip path ──
544
- updateClipPath(frame);
545
- // ── 14. Track parent frame ID on child for orphan-repair on reload ──
546
- // If the child is somehow not inside the frame group after a save/load cycle,
547
- // loadCanvas will use _parentFrameId to re-attach it to the correct frame.
548
- object._parentFrameId = frame._objectId || null;
549
- // Debug: verify all state is correct
550
- const hasGroup = object.group === frame;
551
- const hasCanvas = !!object.canvas;
552
- const hasOCoords = !!object.oCoords;
553
- const nestedCoordsWorks = frame._shouldSetNestedCoords();
554
- const isInObjects = frame._objects.includes(object);
555
- canvasLog('addObjectToFrame: Object added to frame', {
556
- objectType: object.type || object._customType,
557
- frameLabel: frame._labelText,
558
- hasGroup,
559
- hasCanvas,
560
- hasOCoords,
561
- nestedCoordsWorks,
562
- isInObjects,
563
- });
564
- }
565
- catch (error) {
566
- console.error('addObjectToFrame: Failed to add object', error);
567
- }
568
- }
569
- // ─────────────────────────────────────────────
570
- // Remove an object from the frame
571
- // Manual coordinate conversion that converts group-relative → canvas-absolute
572
- // ─────────────────────────────────────────────
573
- export function removeObjectFromFrame(frame, object, canvas) {
574
- try {
575
- // Skip if object is not in this frame
576
- if (object.group !== frame) {
577
- canvasLog('removeObjectFromFrame: Object not in this frame');
578
- return;
579
- }
580
- // Skip the background rect
581
- if (object._isFrameBackground) {
582
- canvasLog('removeObjectFromFrame: Cannot remove frame background');
583
- return;
584
- }
585
- const { applyTransformToObject } = util;
586
- // Calculate absolute transform BEFORE any removal
587
- // (calcTransformMatrix chains through the parent group)
588
- const absMatrix = object.calcTransformMatrix();
589
- // Use Fabric's own Group.remove() for thorough internal cleanup.
590
- // This handles _objects removal, _watchObject, canvas refs, events, etc.
591
- frame.remove(object);
592
- // Apply absolute coordinates (Group.remove may reset them)
593
- applyTransformToObject(object, absMatrix);
594
- // Explicitly clear any lingering group/parent references
595
- object._set('group', undefined);
596
- object._set('parent', undefined);
597
- // Clear parent frame tracking — object is no longer in any frame
598
- object._parentFrameId = undefined;
599
- // Clear stale matrix caches
600
- object.matrixCache = undefined;
601
- object.ownMatrixCache = undefined;
602
- frame.setCoords();
603
- frame.dirty = true;
604
- // Add back to canvas as a free-standing object with absolute coordinates
605
- if (canvas) {
606
- canvas.add(object);
607
- object.setCoords();
608
- }
609
- canvasLog('removeObjectFromFrame: Object removed from frame', {
610
- objectType: object.type || object._customType,
611
- frameLabel: frame._labelText,
612
- });
613
- }
614
- catch (error) {
615
- console.error('removeObjectFromFrame: Failed to remove object', error);
616
- }
617
- }
618
- // ─────────────────────────────────────────────
619
- // Check if a canvas-space point is inside a frame's label area
620
- // Used for extending the clickable/draggable area to include the label
621
- // ─────────────────────────────────────────────
622
- export function isPointInFrameLabel(frame, point) {
623
- try {
624
- // Use full transform to get visual dimensions (including parent groups)
625
- const m = frame.calcTransformMatrix();
626
- const totalScaleX = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
627
- const totalScaleY = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
628
- const frameW = (frame.width || 100) * totalScaleX;
629
- const frameH = (frame.height || 100) * totalScaleY;
630
- const center = frame.getCenterPoint();
631
- // Label sits above the top of the frame
632
- const fontSize = frame._labelFontSize || DEFAULT_LABEL_FONT_SIZE;
633
- const lineHeight = fontSize * 1.2;
634
- const padding = 6;
635
- const gap = 4;
636
- const labelHeight = lineHeight + padding * 2;
637
- const frameLeft = center.x - frameW / 2;
638
- const frameTop = center.y - frameH / 2;
639
- const labelBgX = frameLeft;
640
- const labelBgY = frameTop - labelHeight - gap;
641
- return (point.x >= labelBgX && point.x <= labelBgX + frameW &&
642
- point.y >= labelBgY && point.y <= frameTop);
643
- }
644
- catch {
645
- return false;
646
- }
647
- }
648
- // ─────────────────────────────────────────────
649
- // Check if a canvas-absolute point is inside a frame's boundaries
650
- // Used for containment detection during drag
651
- // ─────────────────────────────────────────────
652
- export function isPointInsideFrame(frame, point) {
653
- try {
654
- const frameCenter = frame.getCenterPoint();
655
- // Use visual (scaled) dimensions for the hit-test
656
- const halfW = ((frame.width || 0) * (frame.scaleX || 1)) / 2;
657
- const halfH = ((frame.height || 0) * (frame.scaleY || 1)) / 2;
658
- // Simple AABB check (ignoring rotation for now - frames have lockRotation)
659
- return (point.x >= frameCenter.x - halfW &&
660
- point.x <= frameCenter.x + halfW &&
661
- point.y >= frameCenter.y - halfH &&
662
- point.y <= frameCenter.y + halfH);
663
- }
664
- catch {
665
- return false;
666
- }
667
- }
668
- // ─────────────────────────────────────────────
669
- // Check if a canvas-space point is on a frame's border/stroke area.
670
- // Returns true only for points near the frame edge (within hit thickness),
671
- // not for points in the interior.
672
- // ─────────────────────────────────────────────
673
- export function isPointOnFrameBorder(frame, point) {
674
- try {
675
- const m = frame.calcTransformMatrix();
676
- const totalScaleX = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
677
- const totalScaleY = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
678
- const frameW = (frame.width || 100) * totalScaleX;
679
- const frameH = (frame.height || 100) * totalScaleY;
680
- const center = frame.getCenterPoint();
681
- const left = center.x - frameW / 2;
682
- const right = center.x + frameW / 2;
683
- const top = center.y - frameH / 2;
684
- const bottom = center.y + frameH / 2;
685
- // Hit zone: half the stroke width + a generous pointer buffer for easy grabbing
686
- const strokeW = frame._frameStrokeWidth || DEFAULT_STROKE_WIDTH;
687
- const hitZone = Math.max(strokeW / 2 + 4, 6);
688
- // Must be within outer bounds (with tolerance)
689
- if (point.x < left - hitZone || point.x > right + hitZone ||
690
- point.y < top - hitZone || point.y > bottom + hitZone) {
691
- return false;
692
- }
693
- // If well inside the inner bounds, it's the interior — not the border
694
- if (point.x > left + hitZone && point.x < right - hitZone &&
695
- point.y > top + hitZone && point.y < bottom - hitZone) {
696
- return false;
697
- }
698
- return true;
699
- }
700
- catch {
701
- return false;
702
- }
703
- }
704
- // ─────────────────────────────────────────────
705
- // Apply border-only hit test to a frame instance.
706
- // Frame is selectable only by clicking its border/stroke or label area —
707
- // clicking the interior is a click-through so rubber-band selection can start there.
708
- // Must be called from both createFrameShape and reapplyFrameRender.
709
- // ─────────────────────────────────────────────
710
- export function applyFrameHitTest(frame) {
711
- frame.containsPoint = function (point) {
712
- const canvasRef = this.canvas;
713
- if (!canvasRef)
714
- return false;
715
- // Convert viewport-space point to canvas (scene) space
716
- const vpt = canvasRef.viewportTransform || [1, 0, 0, 1, 0, 0];
717
- const inv = util.invertTransform(vpt);
718
- const canvasX = inv[0] * point.x + inv[2] * point.y + inv[4];
719
- const canvasY = inv[1] * point.x + inv[3] * point.y + inv[5];
720
- const canvasPoint = { x: canvasX, y: canvasY };
721
- // 1. Label area (above the frame) → selectable
722
- if (isPointInFrameLabel(this, canvasPoint))
723
- return true;
724
- // 2. Border/stroke area → selectable
725
- if (isPointOnFrameBorder(this, canvasPoint))
726
- return true;
727
- // 3. Interior → click-through (Fabric will start rubber-band selection)
728
- return false;
729
- };
730
- }
731
- // ─────────────────────────────────────────────
732
- // Get all non-background children of a frame
733
- // (Excludes the background rect)
734
- // ─────────────────────────────────────────────
735
- export function getFrameChildren(frame) {
736
- return frame.getObjects().filter((obj) => !obj._isFrameBackground);
737
- }
738
- // ─────────────────────────────────────────────
739
- // Get the background rect of a frame
740
- // ─────────────────────────────────────────────
741
- export function getFrameBackground(frame) {
742
- const bg = frame.getObjects().find((obj) => obj._isFrameBackground);
743
- if (bg)
744
- return bg;
745
- // Fallback: when _isFrameBackground flag is missing (e.g. after JSON round-trip with
746
- // incomplete custom props), the first Rect in the group is the background rect.
747
- const fallbackRect = frame.getObjects().find((obj) => (obj.type === 'rect' || obj.type === 'Rect') && !obj._isFrame);
748
- if (fallbackRect) {
749
- fallbackRect._isFrameBackground = true; // Re-mark so future calls skip this path
750
- canvasLog('FrameShape: getFrameBackground — fallback, re-marked rect as background for frame', frame._labelText);
751
- return fallbackRect;
752
- }
753
- return null;
754
- }
755
- // ─────────────────────────────────────────────
756
- // Update the frame's background rect visual properties
757
- // (fill, stroke, strokeWidth)
758
- // ─────────────────────────────────────────────
759
- export function updateFrameBackground(frame, props) {
760
- const bg = getFrameBackground(frame);
761
- if (bg) {
762
- bg.set(props);
763
- bg.dirty = true;
764
- }
765
- // Also store on frame custom props
766
- const frameAny = frame;
767
- if (props.fill !== undefined)
768
- frameAny._frameFill = props.fill;
769
- if (props.stroke !== undefined)
770
- frameAny._frameStroke = props.stroke;
771
- if (props.strokeWidth !== undefined)
772
- frameAny._frameStrokeWidth = props.strokeWidth;
773
- frame.dirty = true;
774
- }
775
- // ─────────────────────────────────────────────
776
- // Normalize frame after scaling
777
- // Converts scaleX/scaleY back to width/height so the label stays consistent.
778
- // preserveChildren = false (default): children scale with frame
779
- // preserveChildren = true (Option key): only frame resizes, children stay at position/size
780
- // ─────────────────────────────────────────────
781
- export function normalizeFrameAfterScaling(frame, preserveChildren = false) {
782
- const scaleX = frame.scaleX || 1;
783
- const scaleY = frame.scaleY || 1;
784
- if (scaleX === 1 && scaleY === 1)
785
- return;
786
- let newWidth = (frame.width || 0) * scaleX;
787
- let newHeight = (frame.height || 0) * scaleY;
788
- // Enforce minimums
789
- newWidth = Math.max(newWidth, MIN_FRAME_WIDTH);
790
- newHeight = Math.max(newHeight, MIN_FRAME_HEIGHT);
791
- // Also scale the background rect dimensions and reset its scale
792
- const bg = getFrameBackground(frame);
793
- if (bg) {
794
- bg.set({
795
- width: newWidth,
796
- height: newHeight,
797
- scaleX: 1,
798
- scaleY: 1,
799
- });
800
- }
801
- // Adjust children based on mode
802
- const children = getFrameChildren(frame);
803
- if (!preserveChildren) {
804
- // DEFAULT: Scale children's positions and sizes so they appear at the same
805
- // visual position/size as during the scaling drag
806
- for (const child of children) {
807
- child.set({
808
- left: (child.left || 0) * scaleX,
809
- top: (child.top || 0) * scaleY,
810
- scaleX: (child.scaleX || 1) * scaleX,
811
- scaleY: (child.scaleY || 1) * scaleY,
812
- });
813
- child.setCoords();
814
- }
815
- }
816
- // When preserveChildren = true: don't adjust children at all.
817
- // After normalization (frame scaleX/Y → 1), children remain at their
818
- // original group-relative positions and sizes. The frame's viewport expands
819
- // but children stay put.
820
- // Reset frame scale and set new dimensions
821
- frame.set({
822
- width: newWidth,
823
- height: newHeight,
824
- scaleX: 1,
825
- scaleY: 1,
826
- });
827
- // Update clip path for new dimensions
828
- updateClipPath(frame);
829
- // Recalculate corner radius from percentage after resize
830
- // (percentage stays constant, pixel value adapts to new dimensions)
831
- const cornerRoundness = frame._cornerRoundness || 0;
832
- if (cornerRoundness > 0) {
833
- const minDim = Math.min(newWidth, newHeight);
834
- const newRadius = (cornerRoundness / 100) * (minDim / 2);
835
- updateFrameCornerRadius(frame, newRadius);
836
- }
837
- frame.setCoords();
838
- frame.dirty = true;
839
- }
840
- // ─────────────────────────────────────────────
841
- // Enforce minimum size during scaling (call from object:scaling event)
842
- // ─────────────────────────────────────────────
843
- export function enforceFrameMinSize(frame) {
844
- const currentWidth = (frame.width || 0) * (frame.scaleX || 1);
845
- const currentHeight = (frame.height || 0) * (frame.scaleY || 1);
846
- if (currentWidth < MIN_FRAME_WIDTH) {
847
- frame.scaleX = MIN_FRAME_WIDTH / (frame.width || 1);
848
- }
849
- if (currentHeight < MIN_FRAME_HEIGHT) {
850
- frame.scaleY = MIN_FRAME_HEIGHT / (frame.height || 1);
851
- }
852
- }
853
- // ─────────────────────────────────────────────
854
- // List of custom properties for copy/paste serialization
855
- // ─────────────────────────────────────────────
856
- export const FRAME_CUSTOM_PROPS = [
857
- '_customType', '_isFrame', '_isFrameBackground',
858
- '_labelText', '_labelFontSize', '_labelFontFamily', '_labelColor',
859
- '_labelBackgroundColor', '_labelTextAlign', '_labelFontWeight',
860
- '_labelFontStyle', '_labelUnderline',
861
- '_frameFill', '_frameStroke', '_frameStrokeWidth', '_frameStrokeDashArray',
862
- '_cornerRoundness', '_frameCornerRadius',
863
- // Tracks which frame a child belongs to; used to repair orphaned children on reload
864
- '_parentFrameId',
865
- ];
866
- // ─────────────────────────────────────────────
867
- // Helper: Check if a Fabric object is a FrameShape
868
- // ─────────────────────────────────────────────
869
- export function isFrameShape(obj) {
870
- return obj && (obj._isFrame === true || obj._customType === 'frame');
871
- }
872
- // ─────────────────────────────────────────────
873
- // Reapply custom render to a cloned/deserialized frame
874
- // Call this after copy/paste or JSON load to restore the label rendering
875
- // ─────────────────────────────────────────────
876
- export function reapplyFrameRender(frame) {
877
- // ── Upgrade to FrameShape prototype if needed ──────────────────────────────
878
- // Called on: (a) newly deserialized objects via FrameShape.fromObject (already upgraded),
879
- // (b) old-format saves (type:'Group' + _isFrame:true) via loadCanvas reviver,
880
- // (c) any backward-compat path that still passes plain Groups here.
881
- // Fabric's type getter reads this.constructor.type.toLowerCase(), so after setPrototypeOf:
882
- // frame.constructor === FrameShape → frame.type === 'frameshape'
883
- // frame.toObject() calls FrameShape.prototype.toObject() → serializes type:'FrameShape'
884
- if (Object.getPrototypeOf(frame) !== FrameShape.prototype) {
885
- Object.setPrototypeOf(frame, FrameShape.prototype);
886
- canvasLog('FrameShape: reapplyFrameRender — upgraded Group to FrameShape prototype for', frame._labelText || '(unlabelled)');
887
- }
888
- // Ensure backward-compat flags are always present
889
- if (!frame._isFrame)
890
- frame._isFrame = true;
891
- if (!frame._customType)
892
- frame._customType = 'frame';
893
- const originalRender = Group.prototype.render.bind(frame);
894
- frame.render = function (ctx) {
895
- originalRender(ctx);
896
- // Draw label using Fabric's this.transform() which automatically handles
897
- // the parent chain (_transformDone flag), then counter-scale to 1:1.
898
- // This approach works identically for top-level and nested frames.
899
- ctx.save();
900
- this.transform(ctx);
901
- const scaling = this.getObjectScaling();
902
- ctx.scale(1 / scaling.x, 1 / scaling.y);
903
- renderFrameLabel(ctx, this);
904
- ctx.restore();
905
- };
906
- // Remove rotation control if it exists
907
- if (frame.controls && frame.controls.mtr) {
908
- delete frame.controls.mtr;
909
- }
910
- // Restore interactive Group properties lost during clone/fromObject
911
- // (Group.fromObject creates a plain Group without these)
912
- frame.interactive = true;
913
- frame.subTargetCheck = true;
914
- frame.objectCaching = false;
915
- frame.lockRotation = true;
916
- frame.hoverCursor = 'move';
917
- frame.moveCursor = 'move';
918
- // Unsubscribe old LayoutManager from children before replacing it.
919
- // Group.fromObject subscribes a FitContentLayout (or the saved one) to all
920
- // children — if we just overwrite layoutManager without cleaning up, those
921
- // event handlers keep pointing to the old manager and can cause stale layouts.
922
- if (frame.layoutManager) {
923
- try {
924
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
925
- frame.layoutManager.unsubscribeTargets({ target: frame, targets: frame.getObjects() });
926
- }
927
- catch {
928
- // Ignore errors if old manager has no subscriptions
929
- }
930
- }
931
- frame.layoutManager = new LayoutManager(new FixedLayout());
932
- // Restore background rect's non-interactive flags (not serialized by Fabric)
933
- // Without this, the cloned background becomes selectable and "breaks" the Frame:
934
- // clicking the frame selects the rect child instead of the Group.
935
- const bg = getFrameBackground(frame);
936
- if (bg) {
937
- bg.selectable = false;
938
- bg.evented = false;
939
- }
940
- // Ensure clip path is set
941
- if (!frame.clipPath) {
942
- setupClipPath(frame);
943
- }
944
- // Restore corner radius on background rect and clip path
945
- // (after clipPath is ensured, so we can set rx/ry on it)
946
- const cornerRadius = frame._frameCornerRadius || 0;
947
- if (cornerRadius > 0) {
948
- updateFrameCornerRadius(frame, cornerRadius);
949
- }
950
- // Restore border-only hit test (lost during clone/fromObject)
951
- applyFrameHitTest(frame);
952
- frame.dirty = true;
953
- }