@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
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Laying out the text of a text object: which letters go on which line, and how big the box is.
3
+ *
4
+ * The layout is a pure function of the text, the style, the width and a function that measures a piece of text. The
5
+ * browser measures with a canvas context and the tests with a fixed advance, but both give the same answer for the
6
+ * same measuring function. The board draws the lines this returns (each on a line of its own, never wrapped by the
7
+ * browser), and the sketch the AI is shown is drawn from the same lines, so what is on the screen is what is sent.
8
+ */
9
+ import { TEXT_DEFAULTS } from '../core/defaults.js';
10
+ /** Room so the last letter and the caret stay on the line; more than this reads as padding. */
11
+ export const TEXT_FIT_SLACK = 4;
12
+ /** Extra width for italic slant and serif overhang beyond what `measureText` returns. */
13
+ export function textFitHorizontalSlack(style) {
14
+ const overhang = Math.ceil(style.fontSize * 0.08);
15
+ const italic = style.fontStyle === 'italic' ? Math.ceil(style.fontSize * 0.2) : 0;
16
+ return TEXT_FIT_SLACK + overhang + italic;
17
+ }
18
+ /** The CSS `font` shorthand of a text object. */
19
+ export function fontShorthand(style) {
20
+ const parts = [];
21
+ if (style.fontStyle === 'italic')
22
+ parts.push('italic');
23
+ if (style.fontWeight === 'bold')
24
+ parts.push('bold');
25
+ parts.push(`${style.fontSize}px`);
26
+ parts.push(style.fontFamily);
27
+ return parts.join(' ');
28
+ }
29
+ /** The height of one line, in world units. */
30
+ export function lineBoxHeight(style) {
31
+ return style.fontSize * style.lineHeight;
32
+ }
33
+ /** The vertical room one line needs on the board: full ascent and descent, not only the CSS line-height box. */
34
+ export function textLineExtent(style) {
35
+ return Math.max(lineBoxHeight(style), style.fontSize * 1.45);
36
+ }
37
+ /** A letter of a script that is written from right to left. Digits, signs and marks have no direction of their own. */
38
+ const RIGHT_TO_LEFT_LETTER = /(?=\p{L})[\p{Script=Hebrew}\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Nko}\p{Script=Samaritan}\p{Script=Mandaic}\p{Script=Adlam}]/u;
39
+ /** A letter of any script. */
40
+ const ANY_LETTER = /\p{L}/u;
41
+ /**
42
+ * The direction a text is written in: the one of its first letter. This is what the browser's `dir="auto"` does, so the
43
+ * board (a drawing that is `ltr` on every screen), the field a text is typed in and the sketch that is drawn for the AI
44
+ * all place the same text the same way. A text with no letter (digits, signs, nothing) reads left to right.
45
+ */
46
+ export function textDirection(text) {
47
+ for (const character of text) {
48
+ if (RIGHT_TO_LEFT_LETTER.test(character))
49
+ return 'rtl';
50
+ if (ANY_LETTER.test(character))
51
+ return 'ltr';
52
+ }
53
+ return 'ltr';
54
+ }
55
+ let segmenter;
56
+ /** The letters of a word as a person counts them (an emoji with a modifier is one), when the platform can tell. */
57
+ function graphemes(word) {
58
+ if (segmenter === undefined) {
59
+ const Segmenter = Intl.Segmenter;
60
+ segmenter = Segmenter ? new Segmenter(undefined, { granularity: 'grapheme' }) : null;
61
+ }
62
+ if (!segmenter)
63
+ return Array.from(word);
64
+ return Array.from(segmenter.segment(word), (part) => part.segment);
65
+ }
66
+ /** Cuts a word that is wider than a line into pieces that each fit (at least one letter each). */
67
+ function breakLongWord(word, maxWidth, font, measure) {
68
+ const pieces = [];
69
+ let current = '';
70
+ for (const letter of graphemes(word)) {
71
+ const candidate = current + letter;
72
+ if (current !== '' && measure(candidate, font) > maxWidth) {
73
+ pieces.push(current);
74
+ current = letter;
75
+ }
76
+ else {
77
+ current = candidate;
78
+ }
79
+ }
80
+ if (current !== '')
81
+ pieces.push(current);
82
+ return pieces;
83
+ }
84
+ /** Wraps one paragraph (no line breaks in it) into lines no wider than `maxWidth`, breaking at spaces. */
85
+ function wrapParagraph(paragraph, maxWidth, font, measure) {
86
+ if (paragraph === '')
87
+ return [''];
88
+ if (measure(paragraph, font) <= maxWidth)
89
+ return [paragraph];
90
+ const lines = [];
91
+ let line = '';
92
+ // Words keep the spaces that follow them, so a line that ends in a space still measures like the browser's.
93
+ const words = paragraph.match(/\S+\s*|\s+/g) ?? [paragraph];
94
+ for (const word of words) {
95
+ const candidate = line + word;
96
+ if (measure(candidate.trimEnd(), font) <= maxWidth) {
97
+ line = candidate;
98
+ continue;
99
+ }
100
+ if (line !== '') {
101
+ lines.push(line.trimEnd());
102
+ line = '';
103
+ }
104
+ if (measure(word.trimEnd(), font) <= maxWidth) {
105
+ line = word;
106
+ }
107
+ else {
108
+ const bareWord = word.trimEnd();
109
+ const pieces = breakLongWord(bareWord, maxWidth, font, measure);
110
+ lines.push(...pieces.slice(0, -1));
111
+ // The last piece keeps the spaces that followed the word, so the next word is not glued to it
112
+ line = (pieces[pieces.length - 1] ?? '') + word.slice(bareWord.length);
113
+ }
114
+ }
115
+ if (line !== '')
116
+ lines.push(line.trimEnd());
117
+ return lines.length > 0 ? lines : [''];
118
+ }
119
+ /**
120
+ * Lays text out.
121
+ * `fixedWidth` is the width of the box when the text wraps; null lets the box be as wide as the longest line.
122
+ */
123
+ export function layoutText(text, style, fixedWidth, measure) {
124
+ const font = fontShorthand(style);
125
+ const padding = style.padding;
126
+ const paragraphs = text.split('\n');
127
+ let lines;
128
+ if (fixedWidth === null) {
129
+ lines = paragraphs;
130
+ }
131
+ else {
132
+ const maxWidth = Math.max(1, fixedWidth - padding * 2);
133
+ lines = paragraphs.flatMap((paragraph) => wrapParagraph(paragraph, maxWidth, font, measure));
134
+ }
135
+ let contentWidth = 0;
136
+ for (const line of lines)
137
+ contentWidth = Math.max(contentWidth, measure(line, font));
138
+ const height = Math.ceil(lines.length * textLineExtent(style) + padding * 2);
139
+ let width = fixedWidth === null
140
+ ? Math.max(TEXT_DEFAULTS.minimumWidth, Math.ceil(contentWidth + padding * 2 + textFitHorizontalSlack(style)))
141
+ : fixedWidth;
142
+ if (fixedWidth === null && text === '') {
143
+ const standIn = TEXT_DEFAULTS.emptyTextMeasureStandIn;
144
+ const standInWidth = measure(standIn, font);
145
+ width = Math.max(width, Math.ceil(standInWidth + padding * 2 + textFitHorizontalSlack(style)));
146
+ }
147
+ return { lines, contentWidth, width, height };
148
+ }
149
+ /** The layout of a text object as it stands. */
150
+ export function layoutTextObject(shape, measure) {
151
+ return layoutText(shape.text, shape, shape.autoWidth ? null : shape.width, measure);
152
+ }
153
+ /**
154
+ * The text object with the size its text needs: the width when it follows the text, the height always.
155
+ * The same object comes back when nothing changes, so an unchanged text is not redrawn.
156
+ */
157
+ export function fitTextObject(shape, measure) {
158
+ const layout = layoutTextObject(shape, measure);
159
+ const width = shape.autoWidth ? layout.width : shape.width;
160
+ if (width === shape.width && layout.height === shape.height)
161
+ return shape;
162
+ return { ...shape, width, height: layout.height };
163
+ }
164
+ /** A measuring function that needs no browser: every letter is `advance` times the font size wide. For tests and Node. */
165
+ export function createFixedAdvanceMeasure(advance = 0.5) {
166
+ return (text, font) => {
167
+ const size = /(\d+(?:\.\d+)?)px/.exec(font)?.[1];
168
+ return Array.from(text).length * advance * (size ? Number(size) : 16);
169
+ };
170
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * What the widget creator does with the widget cards of a board.
3
+ *
4
+ * A card is a rectangle on the board that stands for a widget: the host draws the live widget over it and the
5
+ * canvas keeps the screenshot, the name and the selection. These functions are the host's vocabulary (add a
6
+ * card for a widget, turn a sketch into one, find the card of a widget, say which cards are orphans), written
7
+ * against the engine alone so each rule is tested in Node. The component forwards them one to one.
8
+ */
9
+ import type { ObjectId, Rect, WidgetObject } from './core/types.js';
10
+ import type { EngineCore } from './EngineCore.js';
11
+ import type { EngineState } from './state.js';
12
+ /** The size of the card a new widget gets. */
13
+ export declare const WIDGET_CARD_SIZE: Readonly<{
14
+ width: 400;
15
+ height: 300;
16
+ }>;
17
+ /** The space between cards placed side by side. */
18
+ export declare const WIDGET_CARD_GAP = 48;
19
+ /** How many cards stand in a row before the next row starts. */
20
+ export declare const WIDGET_CARD_MAX_COLUMNS = 4;
21
+ /** A sketch turned into a card is never smaller than this, however little was drawn. */
22
+ export declare const ABSORBED_CARD_MIN_SIZE: Readonly<{
23
+ width: 120;
24
+ height: 80;
25
+ }>;
26
+ /** Where the card goes when nothing on the board has a size to take. */
27
+ export declare const ABSORBED_CARD_FALLBACK_ORIGIN: Readonly<{
28
+ x: 80;
29
+ y: 80;
30
+ }>;
31
+ /** The first card that stands for the widget, or undefined. */
32
+ export declare function findWidgetCard(engine: EngineCore, widgetId: string): WidgetObject | undefined;
33
+ /**
34
+ * Puts a card for a widget in the middle of what is on screen. `gridIndex` and `totalCount` spread several new
35
+ * cards in rows of up to four around that middle, so a batch of widgets does not land on top of each other.
36
+ * The card becomes the selection. Returns its id.
37
+ */
38
+ export declare function addWidgetCard(engine: EngineCore, widgetId: string, options?: {
39
+ name?: string | null;
40
+ gridIndex?: number;
41
+ totalCount?: number;
42
+ previewImage?: string | null;
43
+ }): ObjectId;
44
+ /**
45
+ * Turns the whole board into one card for a widget: everything drawn is taken off and the card stands where it
46
+ * was, as big as the drawing (never smaller than a default minimum), showing the screenshot. A board that is
47
+ * already only this widget is left as it is. An empty board gets the card the live widget needs a frame for.
48
+ * One undo step. Returns the id of the card.
49
+ */
50
+ export declare function absorbSketchIntoWidget(engine: EngineCore, widgetId: string, screenshot: string): ObjectId | null;
51
+ /** What a conversion remembers about a selection of several objects, which has no id of its own. */
52
+ export interface ConversionSnapshot {
53
+ unitIds: readonly ObjectId[];
54
+ bounds: Rect;
55
+ }
56
+ /**
57
+ * Remembers what was selected when the person pressed "convert to widget", by the id the host was given. A
58
+ * selection can be gone by the time the host answers (clicking elsewhere clears it), and the answer still has to
59
+ * replace exactly those objects, so the choice is kept here, not looked up again.
60
+ */
61
+ export declare class ConversionRegistry {
62
+ #private;
63
+ remember(id: ObjectId, snapshot: ConversionSnapshot): void;
64
+ /** The snapshot for an id, left in place (the host asks where a draft is on the screen while it makes the widget). */
65
+ peek(id: ObjectId): ConversionSnapshot | undefined;
66
+ /** The snapshot for an id, forgotten at the same time (a conversion is answered once). */
67
+ take(id: ObjectId): ConversionSnapshot | undefined;
68
+ clear(): void;
69
+ }
70
+ /**
71
+ * Replaces an object (or what a conversion remembered under that id) with a card for the widget, at the same
72
+ * place and size, showing the screenshot. What was drawn there is removed with it, groups included. One undo
73
+ * step. Returns the id of the card, or null when there was nothing to replace.
74
+ */
75
+ export declare function replaceObjectWithWidgetCard(engine: EngineCore, conversions: ConversionRegistry, objectId: ObjectId, widgetId: string, screenshot: string): ObjectId | null;
76
+ /** Gives a card a new screenshot (a refresh of its preview). It is not an undo step, but the board is marked as changed. */
77
+ export declare function updateWidgetThumbnail(engine: EngineCore, widgetId: string, dataUrl: string): boolean;
78
+ /** Picks the card of a widget. False when the board has none. */
79
+ export declare function selectWidgetCard(engine: EngineCore, widgetId: string): boolean;
80
+ /** The widget of the card that is the whole selection, or null. */
81
+ export declare function selectedWidgetId(engine: EngineCore): string | null;
82
+ /**
83
+ * Whether the whole selection is one widget card. Read from a state rather than from the engine, so a view that follows
84
+ * the state (the frame drawn above the page's live widgets) changes with the selection and not a moment after.
85
+ */
86
+ export declare function onlyCardIsSelected(state: Pick<EngineState, 'selectedIds' | 'scene'>): boolean;
87
+ /** The ids of the widgets that have a card on the board. */
88
+ export declare function linkedWidgetIds(engine: EngineCore): Set<string>;
89
+ /** Takes the cards of every other widget off the board (the simple canvas keeps one). Returns how many were removed. */
90
+ export declare function keepOnlyWidgetCard(engine: EngineCore, widgetId: string): number;
91
+ /**
92
+ * Takes everything off the board except the card of one widget: strokes, shapes, other cards. A group that
93
+ * holds the card keeps the card (and only it). Returns how many objects were removed.
94
+ */
95
+ export declare function removeSketchObjectsKeeping(engine: EngineCore, widgetId: string): number;
96
+ /** What the host knows about a widget, to fill in what an old board never stored. */
97
+ export interface WidgetMetadata {
98
+ name?: string | null;
99
+ thumbnailUrl?: string | null;
100
+ thumbnail_url?: string | null;
101
+ }
102
+ /**
103
+ * Fills in the name and the picture of cards that were saved without them. A card that already has a picture
104
+ * keeps it. Not an undo step and not a change of the board. Returns how many cards changed.
105
+ */
106
+ export declare function hydrateWidgetMetadata(engine: EngineCore, widgetsById: ReadonlyMap<string, WidgetMetadata>): number;
107
+ /**
108
+ * Marks the cards whose widget the host no longer lists. They stay on the board until the person removes them.
109
+ * Returns how many cards changed their mark.
110
+ */
111
+ export declare function markOrphanedWidgetCards(engine: EngineCore, validWidgetIds: ReadonlySet<string>): number;
112
+ /** Makes one widget the primary one of the board (the others are not). Not an undo step. */
113
+ export declare function setPrimaryWidgetCard(engine: EngineCore, widgetId: string): boolean;
114
+ /** The widget the board is about, or null. */
115
+ export declare function primaryWidgetId(engine: EngineCore): string | null;
116
+ /**
117
+ * Moves the card of a widget by a distance in screen pixels (the host's own bar drags it). Nothing is recorded
118
+ * until `commitWidgetCardMove`.
119
+ */
120
+ export declare function moveWidgetCardByScreen(engine: EngineCore, widgetId: string, deltaScreenX: number, deltaScreenY: number): boolean;
121
+ /** The host's bar let go of a card: the move is one undo step. */
122
+ export declare function commitWidgetCardMove(engine: EngineCore): void;
123
+ /** The bounds of what a conversion of the selection covers, or null when nothing is selected. */
124
+ export declare function selectionConversionBounds(engine: EngineCore): Rect | null;
@@ -0,0 +1,345 @@
1
+ /**
2
+ * What the widget creator does with the widget cards of a board.
3
+ *
4
+ * A card is a rectangle on the board that stands for a widget: the host draws the live widget over it and the
5
+ * canvas keeps the screenshot, the name and the selection. These functions are the host's vocabulary (add a
6
+ * card for a widget, turn a sketch into one, find the card of a widget, say which cards are orphans), written
7
+ * against the engine alone so each rule is tested in Node. The component forwards them one to one.
8
+ */
9
+ import { createWidgetObject } from './core/defaults.js';
10
+ import { unionRects } from './core/geometry.js';
11
+ import { boundsOfObjects, leafShapesOf, normalizeScene, removeObjects as removeFromScene, shapeVisualBounds, topLevelAncestorId, withDescendantIds } from './core/scene.js';
12
+ /** The size of the card a new widget gets. */
13
+ export const WIDGET_CARD_SIZE = Object.freeze({ width: 400, height: 300 });
14
+ /** The space between cards placed side by side. */
15
+ export const WIDGET_CARD_GAP = 48;
16
+ /** How many cards stand in a row before the next row starts. */
17
+ export const WIDGET_CARD_MAX_COLUMNS = 4;
18
+ /** A sketch turned into a card is never smaller than this, however little was drawn. */
19
+ export const ABSORBED_CARD_MIN_SIZE = Object.freeze({ width: 120, height: 80 });
20
+ /** Where the card goes when nothing on the board has a size to take. */
21
+ export const ABSORBED_CARD_FALLBACK_ORIGIN = Object.freeze({ x: 80, y: 80 });
22
+ /** The prefix of the id of a card made here. */
23
+ const CARD_ID_PREFIX = 'widget_img';
24
+ function cardsOf(scene) {
25
+ return scene.filter((object) => object.type === 'widget');
26
+ }
27
+ /** The first card that stands for the widget, or undefined. */
28
+ export function findWidgetCard(engine, widgetId) {
29
+ if (!widgetId)
30
+ return undefined;
31
+ return cardsOf(engine.state.scene).find((card) => card.widgetId === widgetId);
32
+ }
33
+ /** The rectangle around the shapes of some units, strokes included: what a screenshot of them would show. */
34
+ function visualBoundsOfUnits(scene, ids) {
35
+ return unionRects(leafShapesOf(scene, ids).map(shapeVisualBounds));
36
+ }
37
+ /**
38
+ * Puts a card for a widget in the middle of what is on screen. `gridIndex` and `totalCount` spread several new
39
+ * cards in rows of up to four around that middle, so a batch of widgets does not land on top of each other.
40
+ * The card becomes the selection. Returns its id.
41
+ */
42
+ export function addWidgetCard(engine, widgetId, options = {}) {
43
+ const totalCount = Math.max(1, Math.floor(Number.isFinite(options.totalCount) ? options.totalCount : 1));
44
+ const gridIndex = Math.max(0, Math.floor(Number.isFinite(options.gridIndex) ? options.gridIndex : 0));
45
+ const center = engine.visibleCenter();
46
+ const columns = Math.min(totalCount, WIDGET_CARD_MAX_COLUMNS);
47
+ const rows = Math.max(1, Math.ceil(totalCount / columns));
48
+ const column = gridIndex % columns;
49
+ const row = Math.floor(gridIndex / columns);
50
+ // The whole grid is centred on the middle of the view: each card is shifted by half of the extent of the grid.
51
+ const offsetX = (column - (columns - 1) / 2) * (WIDGET_CARD_SIZE.width + WIDGET_CARD_GAP);
52
+ const offsetY = (row - (rows - 1) / 2) * (WIDGET_CARD_SIZE.height + WIDGET_CARD_GAP);
53
+ const card = createWidgetObject({
54
+ id: engine.services.createId(CARD_ID_PREFIX),
55
+ widgetId,
56
+ widgetName: options.name ?? null,
57
+ x: center.x - WIDGET_CARD_SIZE.width / 2 + offsetX,
58
+ y: center.y - WIDGET_CARD_SIZE.height / 2 + offsetY,
59
+ width: WIDGET_CARD_SIZE.width,
60
+ height: WIDGET_CARD_SIZE.height,
61
+ thumbnail: options.previewImage || null
62
+ });
63
+ engine.addObjects([card], { select: true });
64
+ return card.id;
65
+ }
66
+ /**
67
+ * Turns the whole board into one card for a widget: everything drawn is taken off and the card stands where it
68
+ * was, as big as the drawing (never smaller than a default minimum), showing the screenshot. A board that is
69
+ * already only this widget is left as it is. An empty board gets the card the live widget needs a frame for.
70
+ * One undo step. Returns the id of the card.
71
+ */
72
+ export function absorbSketchIntoWidget(engine, widgetId, screenshot) {
73
+ if (!widgetId)
74
+ return null;
75
+ engine.endTextEdit();
76
+ engine.clearSelection();
77
+ const scene = engine.state.scene;
78
+ const shapes = scene.filter((object) => object.type !== 'group');
79
+ if (shapes.length === 0) {
80
+ return addWidgetCard(engine, widgetId, { previewImage: screenshot || null });
81
+ }
82
+ if (shapes.every((shape) => shape.type === 'widget' && shape.widgetId === widgetId)) {
83
+ return shapes[0].id;
84
+ }
85
+ const bounds = visualBoundsOfUnits(scene, scene.map((object) => object.id));
86
+ const box = {
87
+ x: bounds ? bounds.x : ABSORBED_CARD_FALLBACK_ORIGIN.x,
88
+ y: bounds ? bounds.y : ABSORBED_CARD_FALLBACK_ORIGIN.y,
89
+ width: Math.max(ABSORBED_CARD_MIN_SIZE.width, bounds ? bounds.width : 0),
90
+ height: Math.max(ABSORBED_CARD_MIN_SIZE.height, bounds ? bounds.height : 0)
91
+ };
92
+ const card = createWidgetObject({
93
+ id: engine.services.createId(CARD_ID_PREFIX),
94
+ widgetId,
95
+ ...box,
96
+ thumbnail: screenshot || null
97
+ });
98
+ engine.applyScene([card], 'push');
99
+ engine.select([card.id]);
100
+ return card.id;
101
+ }
102
+ /**
103
+ * Remembers what was selected when the person pressed "convert to widget", by the id the host was given. A
104
+ * selection can be gone by the time the host answers (clicking elsewhere clears it), and the answer still has to
105
+ * replace exactly those objects, so the choice is kept here, not looked up again.
106
+ */
107
+ export class ConversionRegistry {
108
+ #snapshots = new Map();
109
+ remember(id, snapshot) {
110
+ this.#snapshots.set(id, snapshot);
111
+ }
112
+ /** The snapshot for an id, left in place (the host asks where a draft is on the screen while it makes the widget). */
113
+ peek(id) {
114
+ return this.#snapshots.get(id);
115
+ }
116
+ /** The snapshot for an id, forgotten at the same time (a conversion is answered once). */
117
+ take(id) {
118
+ const snapshot = this.#snapshots.get(id);
119
+ this.#snapshots.delete(id);
120
+ return snapshot;
121
+ }
122
+ clear() {
123
+ this.#snapshots.clear();
124
+ }
125
+ }
126
+ /**
127
+ * Replaces an object (or what a conversion remembered under that id) with a card for the widget, at the same
128
+ * place and size, showing the screenshot. What was drawn there is removed with it, groups included. One undo
129
+ * step. Returns the id of the card, or null when there was nothing to replace.
130
+ */
131
+ export function replaceObjectWithWidgetCard(engine, conversions, objectId, widgetId, screenshot) {
132
+ if (!objectId || !widgetId)
133
+ return null;
134
+ const scene = engine.state.scene;
135
+ const index = engine.sceneIndex(scene);
136
+ const remembered = conversions.take(objectId);
137
+ let unitIds;
138
+ let bounds;
139
+ let opacity = 1;
140
+ if (remembered) {
141
+ unitIds = remembered.unitIds.filter((id) => index.has(id));
142
+ bounds = remembered.bounds;
143
+ }
144
+ else if (index.has(objectId)) {
145
+ // A member of a group is replaced together with its group: the group is the thing that was converted.
146
+ const unitId = topLevelAncestorId(index, objectId);
147
+ unitIds = [unitId];
148
+ bounds = visualBoundsOfUnits(scene, unitIds);
149
+ const first = leafShapesOf(scene, unitIds)[0];
150
+ if (first)
151
+ opacity = first.opacity;
152
+ }
153
+ else {
154
+ return null;
155
+ }
156
+ if (unitIds.length === 0 || !bounds)
157
+ return null;
158
+ engine.endTextEdit();
159
+ const doomed = withDescendantIds(scene, unitIds);
160
+ const card = createWidgetObject({
161
+ id: engine.services.createId(CARD_ID_PREFIX),
162
+ widgetId,
163
+ x: bounds.x,
164
+ y: bounds.y,
165
+ width: Math.max(1, bounds.width),
166
+ height: Math.max(1, bounds.height),
167
+ opacity,
168
+ thumbnail: screenshot || null
169
+ });
170
+ const next = normalizeScene([...scene.filter((object) => !doomed.has(object.id)), card]);
171
+ engine.applyScene(next, 'push');
172
+ engine.select([card.id]);
173
+ return card.id;
174
+ }
175
+ /** Gives a card a new screenshot (a refresh of its preview). It is not an undo step, but the board is marked as changed. */
176
+ export function updateWidgetThumbnail(engine, widgetId, dataUrl) {
177
+ const card = findWidgetCard(engine, widgetId);
178
+ if (!card)
179
+ return false;
180
+ const next = engine.state.scene.map((object) => object.id === card.id ? { ...card, thumbnail: dataUrl || null, thumbnailRef: null } : object);
181
+ engine.applyScene(next, 'replace');
182
+ return true;
183
+ }
184
+ /** Picks the card of a widget. False when the board has none. */
185
+ export function selectWidgetCard(engine, widgetId) {
186
+ const card = findWidgetCard(engine, widgetId);
187
+ if (!card)
188
+ return false;
189
+ engine.select([card.id]);
190
+ return true;
191
+ }
192
+ /** The widget of the card that is the whole selection, or null. */
193
+ export function selectedWidgetId(engine) {
194
+ const { selectedIds } = engine.state;
195
+ if (selectedIds.length !== 1)
196
+ return null;
197
+ const object = engine.getObject(selectedIds[0]);
198
+ return object && object.type === 'widget' ? object.widgetId : null;
199
+ }
200
+ /**
201
+ * Whether the whole selection is one widget card. Read from a state rather than from the engine, so a view that follows
202
+ * the state (the frame drawn above the page's live widgets) changes with the selection and not a moment after.
203
+ */
204
+ export function onlyCardIsSelected(state) {
205
+ if (state.selectedIds.length !== 1)
206
+ return false;
207
+ const selectedId = state.selectedIds[0];
208
+ return state.scene.some((object) => object.id === selectedId && object.type === 'widget');
209
+ }
210
+ /** The ids of the widgets that have a card on the board. */
211
+ export function linkedWidgetIds(engine) {
212
+ const ids = new Set();
213
+ for (const card of cardsOf(engine.state.scene)) {
214
+ if (card.widgetId)
215
+ ids.add(card.widgetId);
216
+ }
217
+ return ids;
218
+ }
219
+ /** Takes the cards of every other widget off the board (the simple canvas keeps one). Returns how many were removed. */
220
+ export function keepOnlyWidgetCard(engine, widgetId) {
221
+ if (!widgetId)
222
+ return 0;
223
+ const extras = cardsOf(engine.state.scene).filter((card) => card.widgetId && card.widgetId !== widgetId);
224
+ if (extras.length === 0)
225
+ return 0;
226
+ engine.removeObjects(extras.map((card) => card.id));
227
+ engine.clearSelection();
228
+ return extras.length;
229
+ }
230
+ /**
231
+ * Takes everything off the board except the card of one widget: strokes, shapes, other cards. A group that
232
+ * holds the card keeps the card (and only it). Returns how many objects were removed.
233
+ */
234
+ export function removeSketchObjectsKeeping(engine, widgetId) {
235
+ if (!widgetId)
236
+ return 0;
237
+ const scene = engine.state.scene;
238
+ const index = engine.sceneIndex(scene);
239
+ const keep = new Set();
240
+ for (const card of cardsOf(scene)) {
241
+ if (card.widgetId !== widgetId)
242
+ continue;
243
+ let current = card;
244
+ while (current && !keep.has(current.id)) {
245
+ keep.add(current.id);
246
+ current = current.parentId ? index.get(current.parentId) : undefined;
247
+ }
248
+ }
249
+ const doomed = scene.filter((object) => !keep.has(object.id) && object.type !== 'group').map((object) => object.id);
250
+ if (doomed.length === 0)
251
+ return 0;
252
+ engine.endTextEdit();
253
+ const next = removeFromScene(scene, doomed);
254
+ engine.applyScene(next, 'push');
255
+ engine.clearSelection();
256
+ return doomed.length;
257
+ }
258
+ /**
259
+ * Fills in the name and the picture of cards that were saved without them. A card that already has a picture
260
+ * keeps it. Not an undo step and not a change of the board. Returns how many cards changed.
261
+ */
262
+ export function hydrateWidgetMetadata(engine, widgetsById) {
263
+ let updated = 0;
264
+ const next = engine.state.scene.map((object) => {
265
+ if (object.type !== 'widget' || !object.widgetId)
266
+ return object;
267
+ const metadata = widgetsById.get(object.widgetId);
268
+ if (!metadata)
269
+ return object;
270
+ const preview = metadata.thumbnailUrl ?? metadata.thumbnail_url ?? null;
271
+ let card = object;
272
+ if (metadata.name && card.widgetName !== metadata.name)
273
+ card = { ...card, widgetName: metadata.name };
274
+ if (preview && !card.thumbnail && !card.thumbnailRef)
275
+ card = { ...card, thumbnail: preview };
276
+ if (card === object)
277
+ return object;
278
+ updated += 1;
279
+ return card;
280
+ });
281
+ if (updated > 0)
282
+ engine.applySilently(next);
283
+ return updated;
284
+ }
285
+ /**
286
+ * Marks the cards whose widget the host no longer lists. They stay on the board until the person removes them.
287
+ * Returns how many cards changed their mark.
288
+ */
289
+ export function markOrphanedWidgetCards(engine, validWidgetIds) {
290
+ let changed = 0;
291
+ for (const card of cardsOf(engine.state.scene)) {
292
+ if (!card.widgetId)
293
+ continue;
294
+ const orphaned = !validWidgetIds.has(card.widgetId);
295
+ if (engine.setWidgetRuntime(card.widgetId, { orphaned }))
296
+ changed += 1;
297
+ }
298
+ return changed;
299
+ }
300
+ /** Makes one widget the primary one of the board (the others are not). Not an undo step. */
301
+ export function setPrimaryWidgetCard(engine, widgetId) {
302
+ if (!widgetId)
303
+ return false;
304
+ let changed = false;
305
+ const next = engine.state.scene.map((object) => {
306
+ if (object.type !== 'widget')
307
+ return object;
308
+ const primary = object.widgetId === widgetId;
309
+ if (object.isPrimary === primary)
310
+ return object;
311
+ changed = true;
312
+ return { ...object, isPrimary: primary };
313
+ });
314
+ if (changed)
315
+ engine.applyScene(next, 'replace');
316
+ return true;
317
+ }
318
+ /** The widget the board is about, or null. */
319
+ export function primaryWidgetId(engine) {
320
+ return cardsOf(engine.state.scene).find((card) => card.isPrimary)?.widgetId ?? null;
321
+ }
322
+ /**
323
+ * Moves the card of a widget by a distance in screen pixels (the host's own bar drags it). Nothing is recorded
324
+ * until `commitWidgetCardMove`.
325
+ */
326
+ export function moveWidgetCardByScreen(engine, widgetId, deltaScreenX, deltaScreenY) {
327
+ const card = findWidgetCard(engine, widgetId);
328
+ if (!card)
329
+ return false;
330
+ const zoom = engine.state.viewport.zoom || 1;
331
+ const deltaX = deltaScreenX / zoom;
332
+ const deltaY = deltaScreenY / zoom;
333
+ if (!Number.isFinite(deltaX) || !Number.isFinite(deltaY))
334
+ return false;
335
+ engine.applyScene(engine.state.scene.map((object) => (object.id === card.id ? { ...card, x: card.x + deltaX, y: card.y + deltaY } : object)), 'transient');
336
+ return true;
337
+ }
338
+ /** The host's bar let go of a card: the move is one undo step. */
339
+ export function commitWidgetCardMove(engine) {
340
+ engine.commit();
341
+ }
342
+ /** The bounds of what a conversion of the selection covers, or null when nothing is selected. */
343
+ export function selectionConversionBounds(engine) {
344
+ return visualBoundsOfUnits(engine.state.scene, engine.state.selectedIds) ?? boundsOfObjects(engine.state.scene, engine.state.selectedIds);
345
+ }
@@ -1,23 +1,12 @@
1
1
  import type { Translate } from '@widgetic/design-system/i18n';
2
+ import type { SceneObject } from '../engine/core/types.js';
2
3
  import type { CanvasMessageKey } from './messages.js';
3
4
  type Translator = Translate<CanvasMessageKey>;
4
- /**
5
- * The hint of a button that has a key: its name and the key that does the same, "Draw (D)". A button with no key is
6
- * just its name.
7
- */
8
- export declare function toolTitle(name: CanvasMessageKey, shortcut: string | null | undefined, t: Translator): string;
9
5
  /** The name of a group of the shape library, by the English name the library keeps it under. */
10
6
  export declare function categoryLabel(category: string, t: Translator): string;
11
- /** What the properties panel needs to know about the selected object to name it. */
12
- export interface NamedObject {
13
- type?: string | null;
14
- _customType?: string | null;
15
- _isWidgetImage?: boolean | null;
16
- _shapeKey?: string | null;
17
- }
18
7
  /**
19
- * What the properties panel calls the selected object, in the page's language: "Frame", "Widget", "Star (Drawing)".
20
- * A kind of object it has no name for is shown by the name the canvas library gave it.
8
+ * What the selection panel calls an object, in the page's language: "Rectangle", "Widget", "Star (Drawing)".
9
+ * A drawing with no key at all is a freehand stroke, and a path whose key the library does not know is named after it.
21
10
  */
22
- export declare function displayTypeText(object: NamedObject | null | undefined, t: Translator): string;
11
+ export declare function objectName(object: SceneObject | null | undefined, t: Translator): string;
23
12
  export {};