@widgetic/canvas 0.5.41 → 0.5.42

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 (85) hide show
  1. package/dist/canvas/autosaveScheduler.js +37 -89
  2. package/dist/canvas/boardFrame.js +1 -1
  3. package/dist/canvas/boardSurface.js +1 -1
  4. package/dist/canvas/canvasLogger.js +7 -19
  5. package/dist/canvas/chromeLayout.js +17 -18
  6. package/dist/canvas/eventScope.js +10 -14
  7. package/dist/canvas/host/CanvasHost.js +1286 -1536
  8. package/dist/canvas/host/CanvasHostApi.js +4 -19
  9. package/dist/canvas/host/browserServices.js +65 -116
  10. package/dist/canvas/host/conversion.js +82 -170
  11. package/dist/canvas/host/hostObject.js +7 -7
  12. package/dist/canvas/host/pageEvents.js +4 -4
  13. package/dist/canvas/host/screenRects.js +28 -31
  14. package/dist/canvas/host/strokeSnap.js +88 -143
  15. package/dist/canvas/openMarks.js +2 -2
  16. package/dist/canvas/outsideClickDeselect.js +6 -7
  17. package/dist/canvas/panZoomPosition.js +2 -2
  18. package/dist/canvas/preferredTextFont.js +13 -25
  19. package/dist/canvas/shapes/ShapeLibrary.js +138 -148
  20. package/dist/canvas/shapes/shapeImageStore.js +3 -3
  21. package/dist/canvas/shapes/strokeShapeSnap.js +188 -233
  22. package/dist/canvas/toolbarPosition.js +2 -2
  23. package/dist/canvas/ui/colorModel.js +21 -32
  24. package/dist/canvas/ui/colorPickerMessages.js +5 -5
  25. package/dist/canvas/ui/floatingCard.js +18 -18
  26. package/dist/canvas/ui/floatingLayer.js +5 -6
  27. package/dist/canvas/ui/keyHints.js +9 -11
  28. package/dist/canvas/ui/popoverSide.js +2 -3
  29. package/dist/canvas/ui/selectionTraits.js +34 -40
  30. package/dist/canvas/view/erasingMarks.js +7 -7
  31. package/dist/canvas/view/geometry.js +71 -90
  32. package/dist/components/preferenceStorage.js +2 -2
  33. package/dist/engine/EngineCore.js +696 -795
  34. package/dist/engine/codec/canvasDocument.js +183 -147
  35. package/dist/engine/codec/hostReadableKeys.js +1 -1
  36. package/dist/engine/core/arrange.js +26 -38
  37. package/dist/engine/core/arrow.js +76 -89
  38. package/dist/engine/core/arrowBinding.js +98 -116
  39. package/dist/engine/core/arrowBindingRecords.js +23 -38
  40. package/dist/engine/core/brush.js +67 -94
  41. package/dist/engine/core/defaults.js +90 -51
  42. package/dist/engine/core/freehand.js +147 -163
  43. package/dist/engine/core/geometry.js +47 -54
  44. package/dist/engine/core/history.js +33 -50
  45. package/dist/engine/core/hitTest.js +68 -81
  46. package/dist/engine/core/matrix.js +18 -20
  47. package/dist/engine/core/pathData.js +183 -210
  48. package/dist/engine/core/rotationReset.js +5 -6
  49. package/dist/engine/core/scene.js +129 -187
  50. package/dist/engine/core/scribble.js +59 -84
  51. package/dist/engine/core/shapePaths.js +12 -15
  52. package/dist/engine/core/shapeTools.js +72 -63
  53. package/dist/engine/core/snapping.js +65 -117
  54. package/dist/engine/core/style.js +31 -64
  55. package/dist/engine/core/transform.js +83 -94
  56. package/dist/engine/core/types.js +4 -4
  57. package/dist/engine/core/viewport.js +23 -36
  58. package/dist/engine/input/PointerController.js +467 -474
  59. package/dist/engine/input/arrowHandles.js +12 -12
  60. package/dist/engine/input/gestures.js +262 -308
  61. package/dist/engine/input/hoverCursor.js +1 -1
  62. package/dist/engine/input/keyboard.js +27 -30
  63. package/dist/engine/input/selectionHandles.js +45 -50
  64. package/dist/engine/input/types.js +1 -1
  65. package/dist/engine/render/rasterize.js +86 -158
  66. package/dist/engine/state.js +4 -15
  67. package/dist/engine/text/layoutText.js +43 -62
  68. package/dist/engine/text/textMetrics.js +8 -10
  69. package/dist/engine/widgets.js +101 -137
  70. package/dist/fonts/interFont.js +17 -68
  71. package/dist/fonts/workspaceFonts.js +32 -90
  72. package/dist/i18n/labels.js +4 -4
  73. package/dist/i18n/language.js +4 -4
  74. package/dist/i18n/messages.js +1 -1
  75. package/dist/i18n/shortcuts.js +14 -14
  76. package/dist/settings/workspaceToolSettings.js +32 -48
  77. package/dist/tools/components/catalog.js +64 -74
  78. package/dist/tools/components/grouping.js +6 -28
  79. package/dist/tools/definitions.js +5 -5
  80. package/dist/tools/executors.js +105 -141
  81. package/dist/tools/hostAdapter.js +11 -13
  82. package/dist/tools/sceneSummary.js +43 -57
  83. package/dist/tools/sketchIntent.js +13 -21
  84. package/dist/tools/types.js +1 -1
  85. package/package.json +1 -1
@@ -9,17 +9,8 @@
9
9
  * Kept free of Svelte so that Node can test it: `tests/host/hostSurface.test.mjs` holds this list, the fixture and the
10
10
  * shell to each other.
11
11
  */
12
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
13
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
14
- if (ar || !(i in from)) {
15
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
16
- ar[i] = from[i];
17
- }
18
- }
19
- return to.concat(ar || Array.prototype.slice.call(from));
20
- };
21
12
  /** Every function a page already calls, in the order the fixture lists them. */
22
- export var CANVAS_CONTRACT_FUNCTION_NAMES = [
13
+ export const CANVAS_CONTRACT_FUNCTION_NAMES = [
23
14
  'shapeFillColor',
24
15
  'captureCanvasSketch',
25
16
  'absorbCanvasSketchIntoWidget',
@@ -91,7 +82,7 @@ export var CANVAS_CONTRACT_FUNCTION_NAMES = [
91
82
  * (feat/shopify-feedback-canvas) adds the same one, so it keeps the name and the answer (how many objects went): removes
92
83
  * the sketch objects around one widget card and keeps the card.
93
84
  */
94
- export var CANVAS_ADDED_FUNCTION_NAMES = [
85
+ export const CANVAS_ADDED_FUNCTION_NAMES = [
95
86
  'removeSketchObjectsKeepingWidget',
96
87
  'getSketchSceneSummary',
97
88
  'executeSketchTool',
@@ -99,18 +90,12 @@ export var CANVAS_ADDED_FUNCTION_NAMES = [
99
90
  'endSketchToolBatch'
100
91
  ];
101
92
  /** Every function the shell exports. */
102
- export var CANVAS_EXPORTED_FUNCTION_NAMES = __spreadArray(__spreadArray([], CANVAS_CONTRACT_FUNCTION_NAMES, true), CANVAS_ADDED_FUNCTION_NAMES, true);
93
+ export const CANVAS_EXPORTED_FUNCTION_NAMES = [...CANVAS_CONTRACT_FUNCTION_NAMES, ...CANVAS_ADDED_FUNCTION_NAMES];
103
94
  /**
104
95
  * One exported function of the shell: it calls the host's method of that name, with the host as `this`, and has the
105
96
  * method's own type. A page that holds the shell's reference calls it exactly as it calls the host's method.
106
97
  */
107
98
  export function forwardToHost(host, name) {
108
- var forwarded = function () {
109
- var values = [];
110
- for (var _i = 0; _i < arguments.length; _i++) {
111
- values[_i] = arguments[_i];
112
- }
113
- return host[name].apply(host, values);
114
- };
99
+ const forwarded = (...values) => host[name].apply(host, values);
115
100
  return forwarded;
116
101
  }
@@ -6,57 +6,21 @@
6
6
  * Every function checks for the browser itself and answers with the safest fallback when it is not there (the page
7
7
  * is rendered on the server first, and nothing here may throw then).
8
8
  */
9
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
10
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
11
- return new (P || (P = Promise))(function (resolve, reject) {
12
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
13
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
14
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
15
- step((generator = generator.apply(thisArg, _arguments || [])).next());
16
- });
17
- };
18
- var __generator = (this && this.__generator) || function (thisArg, body) {
19
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
20
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
21
- function verb(n) { return function (v) { return step([n, v]); }; }
22
- function step(op) {
23
- if (f) throw new TypeError("Generator is already executing.");
24
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
25
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
26
- if (y = 0, t) op = [op[0] & 2, t.value];
27
- switch (op[0]) {
28
- case 0: case 1: t = op; break;
29
- case 4: _.label++; return { value: op[1], done: false };
30
- case 5: _.label++; y = op[1]; op = [0]; continue;
31
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
32
- default:
33
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
34
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
35
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
36
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
37
- if (t[2]) _.ops.pop();
38
- _.trys.pop(); continue;
39
- }
40
- op = body.call(thisArg, _);
41
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
42
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
43
- }
44
- };
45
9
  import { createFixedAdvanceMeasure } from '../../engine/text/layoutText.js';
46
10
  import { getTransientHostFor } from '../eventScope.js';
47
- var hasDocument = function () { return typeof document !== 'undefined' && typeof document.createElement === 'function'; };
11
+ const hasDocument = () => typeof document !== 'undefined' && typeof document.createElement === 'function';
48
12
  /** A text measurer that uses the browser's canvas, or a fixed advance where there is none (the server, a test). */
49
13
  export function createBrowserMeasureText() {
50
14
  if (!hasDocument())
51
15
  return createFixedAdvanceMeasure();
52
- var context;
53
- var fallback = createFixedAdvanceMeasure();
54
- return function (text, font) {
16
+ let context;
17
+ const fallback = createFixedAdvanceMeasure();
18
+ return (text, font) => {
55
19
  if (context === undefined) {
56
20
  try {
57
21
  context = document.createElement('canvas').getContext('2d');
58
22
  }
59
- catch (_a) {
23
+ catch {
60
24
  context = null;
61
25
  }
62
26
  }
@@ -71,63 +35,62 @@ export function createBrowserMeasureText() {
71
35
  export function loadImageElement(source) {
72
36
  if (typeof Image === 'undefined')
73
37
  return Promise.resolve(null);
74
- return new Promise(function (resolve) {
75
- var image = new Image();
38
+ return new Promise((resolve) => {
39
+ const image = new Image();
76
40
  // A picture from another site is only usable in a canvas when that site allows it; a data address needs nothing.
77
41
  if (/^https?:/i.test(source))
78
42
  image.crossOrigin = 'anonymous';
79
- image.onload = function () {
43
+ image.onload = () => {
80
44
  if (typeof image.decode === 'function') {
81
- image.decode().then(function () { return resolve(image); }, function () { return resolve(image.naturalWidth > 0 ? image : null); });
45
+ image.decode().then(() => resolve(image), () => resolve(image.naturalWidth > 0 ? image : null));
82
46
  }
83
47
  else {
84
48
  resolve(image);
85
49
  }
86
50
  };
87
- image.onerror = function () { return resolve(null); };
51
+ image.onerror = () => resolve(null);
88
52
  image.src = source;
89
53
  });
90
54
  }
91
55
  /** The services the rasterizer needs, made of the browser. */
92
56
  export function createBrowserRasterServices(measureText) {
93
57
  return {
94
- createCanvas: function (width, height) {
58
+ createCanvas(width, height) {
95
59
  if (!hasDocument())
96
60
  return null;
97
61
  try {
98
- var canvas = document.createElement('canvas');
62
+ const canvas = document.createElement('canvas');
99
63
  canvas.width = width;
100
64
  canvas.height = height;
101
65
  return canvas;
102
66
  }
103
- catch (_a) {
67
+ catch {
104
68
  return null;
105
69
  }
106
70
  },
107
71
  loadImage: loadImageElement,
108
- createPath: function (data) { return new Path2D(data); },
109
- measureText: measureText
72
+ createPath: (data) => new Path2D(data),
73
+ measureText
110
74
  };
111
75
  }
112
76
  /** Whether the person's keyboard says Cmd rather than Ctrl. */
113
77
  export function isApplePlatform() {
114
- var _a;
115
78
  if (typeof navigator === 'undefined')
116
79
  return false;
117
- var platform = ((_a = navigator.userAgentData) === null || _a === void 0 ? void 0 : _a.platform) || navigator.platform || navigator.userAgent || '';
80
+ const platform = navigator.userAgentData?.platform || navigator.platform || navigator.userAgent || '';
118
81
  return /Mac|iPhone|iPad|iPod/i.test(platform);
119
82
  }
120
83
  /** The longest side a picture keeps when it is large; a bigger one is scaled down before it is stored in the board. */
121
- export var IMAGE_MAX_SIDE = 2048;
84
+ export const IMAGE_MAX_SIDE = 2048;
122
85
  /** Pictures smaller than this are stored as they came. */
123
- export var IMAGE_RESIZE_THRESHOLD_BYTES = 2.5 * 1024 * 1024;
86
+ export const IMAGE_RESIZE_THRESHOLD_BYTES = 2.5 * 1024 * 1024;
124
87
  /** What a picture without a size of its own (an SVG with no width and height) is given. */
125
- export var IMAGE_FALLBACK_SIDE = 300;
88
+ export const IMAGE_FALLBACK_SIDE = 300;
126
89
  function readAsDataUrl(file) {
127
- return new Promise(function (resolve, reject) {
128
- var reader = new FileReader();
129
- reader.onload = function () { return (typeof reader.result === 'string' ? resolve(reader.result) : reject(new Error('The file could not be read'))); };
130
- reader.onerror = function () { var _a; return reject((_a = reader.error) !== null && _a !== void 0 ? _a : new Error('The file could not be read')); };
90
+ return new Promise((resolve, reject) => {
91
+ const reader = new FileReader();
92
+ reader.onload = () => (typeof reader.result === 'string' ? resolve(reader.result) : reject(new Error('The file could not be read')));
93
+ reader.onerror = () => reject(reader.error ?? new Error('The file could not be read'));
131
94
  reader.readAsDataURL(file);
132
95
  });
133
96
  }
@@ -136,82 +99,68 @@ function readAsDataUrl(file) {
136
99
  * `IMAGE_MAX_SIDE` so the saved board does not grow by megabytes; small files, and every SVG, are kept as they are.
137
100
  * Rejects when the file is not a picture the browser can show.
138
101
  */
139
- export function readImageFile(file_1) {
140
- return __awaiter(this, arguments, Promise, function (file, fileName) {
141
- var name, dataUrl, image, width, height, src, isSvg, tooBig, scale, scaledWidth, scaledHeight, canvas, context, keepsAlpha;
142
- if (fileName === void 0) { fileName = ''; }
143
- return __generator(this, function (_a) {
144
- switch (_a.label) {
145
- case 0:
146
- name = fileName || file.name || '';
147
- return [4 /*yield*/, readAsDataUrl(file)];
148
- case 1:
149
- dataUrl = _a.sent();
150
- return [4 /*yield*/, loadImageElement(dataUrl)];
151
- case 2:
152
- image = _a.sent();
153
- if (!image)
154
- throw new Error('The file is not a picture the browser can show');
155
- width = image.naturalWidth || image.width || IMAGE_FALLBACK_SIDE;
156
- height = image.naturalHeight || image.height || IMAGE_FALLBACK_SIDE;
157
- src = dataUrl;
158
- isSvg = file.type === 'image/svg+xml' || /\.svg$/i.test(name);
159
- tooBig = Math.max(width, height) > IMAGE_MAX_SIDE;
160
- if (!isSvg && tooBig && file.size > IMAGE_RESIZE_THRESHOLD_BYTES && hasDocument()) {
161
- try {
162
- scale = IMAGE_MAX_SIDE / Math.max(width, height);
163
- scaledWidth = Math.max(1, Math.round(width * scale));
164
- scaledHeight = Math.max(1, Math.round(height * scale));
165
- canvas = document.createElement('canvas');
166
- canvas.width = scaledWidth;
167
- canvas.height = scaledHeight;
168
- context = canvas.getContext('2d');
169
- if (context) {
170
- context.drawImage(image, 0, 0, scaledWidth, scaledHeight);
171
- keepsAlpha = /png|gif|webp/i.test(file.type);
172
- src = canvas.toDataURL(keepsAlpha ? 'image/png' : 'image/jpeg', 0.88);
173
- width = scaledWidth;
174
- height = scaledHeight;
175
- }
176
- }
177
- catch (error) {
178
- console.warn('Canvas: the picture could not be scaled down, it is stored as it came', error);
179
- }
180
- }
181
- return [2 /*return*/, { src: src, width: width, height: height, fileName: name }];
102
+ export async function readImageFile(file, fileName = '') {
103
+ const name = fileName || file.name || '';
104
+ const dataUrl = await readAsDataUrl(file);
105
+ const image = await loadImageElement(dataUrl);
106
+ if (!image)
107
+ throw new Error('The file is not a picture the browser can show');
108
+ let width = image.naturalWidth || image.width || IMAGE_FALLBACK_SIDE;
109
+ let height = image.naturalHeight || image.height || IMAGE_FALLBACK_SIDE;
110
+ let src = dataUrl;
111
+ const isSvg = file.type === 'image/svg+xml' || /\.svg$/i.test(name);
112
+ const tooBig = Math.max(width, height) > IMAGE_MAX_SIDE;
113
+ if (!isSvg && tooBig && file.size > IMAGE_RESIZE_THRESHOLD_BYTES && hasDocument()) {
114
+ try {
115
+ const scale = IMAGE_MAX_SIDE / Math.max(width, height);
116
+ const scaledWidth = Math.max(1, Math.round(width * scale));
117
+ const scaledHeight = Math.max(1, Math.round(height * scale));
118
+ const canvas = document.createElement('canvas');
119
+ canvas.width = scaledWidth;
120
+ canvas.height = scaledHeight;
121
+ const context = canvas.getContext('2d');
122
+ if (context) {
123
+ context.drawImage(image, 0, 0, scaledWidth, scaledHeight);
124
+ // Pictures that can have see-through parts stay PNG; photos become JPEG.
125
+ const keepsAlpha = /png|gif|webp/i.test(file.type);
126
+ src = canvas.toDataURL(keepsAlpha ? 'image/png' : 'image/jpeg', 0.88);
127
+ width = scaledWidth;
128
+ height = scaledHeight;
182
129
  }
183
- });
184
- });
130
+ }
131
+ catch (error) {
132
+ console.warn('Canvas: the picture could not be scaled down, it is stored as it came', error);
133
+ }
134
+ }
135
+ return { src, width, height, fileName: name };
185
136
  }
186
137
  /**
187
138
  * Opens the browser's file chooser for pictures and answers with what was chosen (an empty list when the person
188
139
  * cancels). Must be called while a click or a key press is being handled, or the browser refuses to open the chooser.
189
140
  * The hidden input goes into the shadow root the canvas is in, so a partner's own page never sees it.
190
141
  */
191
- export function chooseImageFiles(scope, options) {
192
- if (options === void 0) { options = {}; }
142
+ export function chooseImageFiles(scope, options = {}) {
193
143
  if (!hasDocument())
194
144
  return Promise.resolve([]);
195
- return new Promise(function (resolve) {
196
- var _a;
197
- var input = document.createElement('input');
145
+ return new Promise((resolve) => {
146
+ const input = document.createElement('input');
198
147
  input.type = 'file';
199
148
  // Every kind of picture by default; the SVG entry of the shapes menu asks for vector files only.
200
- input.accept = (_a = options.accept) !== null && _a !== void 0 ? _a : 'image/*,.svg';
149
+ input.accept = options.accept ?? 'image/*,.svg';
201
150
  input.multiple = !!options.multiple;
202
151
  input.style.display = 'none';
203
- var host = getTransientHostFor(scope);
204
- var settled = false;
205
- var finish = function (files) {
152
+ const host = getTransientHostFor(scope);
153
+ let settled = false;
154
+ const finish = (files) => {
206
155
  if (settled)
207
156
  return;
208
157
  settled = true;
209
158
  input.remove();
210
159
  resolve(files);
211
160
  };
212
- input.addEventListener('change', function () { var _a; return finish(Array.from((_a = input.files) !== null && _a !== void 0 ? _a : [])); });
161
+ input.addEventListener('change', () => finish(Array.from(input.files ?? [])));
213
162
  // The browsers that say so tell us when the chooser was closed without a file.
214
- input.addEventListener('cancel', function () { return finish([]); });
163
+ input.addEventListener('cancel', () => finish([]));
215
164
  host.appendChild(input);
216
165
  input.click();
217
166
  });
@@ -9,205 +9,117 @@
9
9
  *
10
10
  * Plain TypeScript over the engine's records and the rasterizer: runs in Node.
11
11
  */
12
- var __assign = (this && this.__assign) || function () {
13
- __assign = Object.assign || function(t) {
14
- for (var s, i = 1, n = arguments.length; i < n; i++) {
15
- s = arguments[i];
16
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
17
- t[p] = s[p];
18
- }
19
- return t;
20
- };
21
- return __assign.apply(this, arguments);
22
- };
23
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
24
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
25
- return new (P || (P = Promise))(function (resolve, reject) {
26
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
27
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
28
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
29
- step((generator = generator.apply(thisArg, _arguments || [])).next());
30
- });
31
- };
32
- var __generator = (this && this.__generator) || function (thisArg, body) {
33
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
34
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
35
- function verb(n) { return function (v) { return step([n, v]); }; }
36
- function step(op) {
37
- if (f) throw new TypeError("Generator is already executing.");
38
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
39
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
40
- if (y = 0, t) op = [op[0] & 2, t.value];
41
- switch (op[0]) {
42
- case 0: case 1: t = op; break;
43
- case 4: _.label++; return { value: op[1], done: false };
44
- case 5: _.label++; y = op[1]; op = [0]; continue;
45
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
46
- default:
47
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
48
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
49
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
50
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
51
- if (t[2]) _.ops.pop();
52
- _.trys.pop(); continue;
53
- }
54
- op = body.call(thisArg, _);
55
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
56
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
57
- }
58
- };
59
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
60
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
61
- if (ar || !(i in from)) {
62
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
63
- ar[i] = from[i];
64
- }
65
- }
66
- return to.concat(ar || Array.prototype.slice.call(from));
67
- };
68
12
  import { leafShapesOf } from '../../engine/core/scene.js';
69
13
  import { rasterBoundsOf, renderShapesToDataUrl } from '../../engine/render/rasterize.js';
70
- import { selectionConversionBounds } from '../../engine/widgets.js';
14
+ import { ConversionRegistry, selectionConversionBounds } from '../../engine/widgets.js';
71
15
  import { hostCustomTypeOf, hostObjectById, hostTypeOf, selectedHostObject } from './hostObject.js';
72
16
  /** Message key integrators pass through `translate` as `untitledShapeName` in {@link buildConversionPayload}. */
73
- export var UNTITLED_SHAPE_MESSAGE_KEY = 'canvas.defaults.untitledShape';
17
+ export const UNTITLED_SHAPE_MESSAGE_KEY = 'canvas.defaults.untitledShape';
74
18
  /** The background of a screenshot: opaque, so a model that reads a transparent PNG as black still sees the drawing. */
75
- export var SCREENSHOT_BACKGROUND = '#ffffff';
19
+ export const SCREENSHOT_BACKGROUND = '#ffffff';
76
20
  /** A screenshot is twice the size of the board (as the canvas it replaces made them), so small text stays legible. */
77
- export var SCREENSHOT_SCALE = 2;
21
+ export const SCREENSHOT_SCALE = 2;
78
22
  /** What is selected, as the conversion and the capture see it. Null when nothing is. */
79
23
  export function describeSelection(engine) {
80
- var _a;
81
- var selectedIds = engine.state.selectedIds;
24
+ const { selectedIds } = engine.state;
82
25
  if (selectedIds.length === 0)
83
26
  return null;
84
- var units = engine.selectedObjects();
85
- var shapes = leafShapesOf(engine.state.scene, selectedIds);
86
- var bounds = selectionConversionBounds(engine);
27
+ const units = engine.selectedObjects();
28
+ const shapes = leafShapesOf(engine.state.scene, selectedIds);
29
+ const bounds = selectionConversionBounds(engine);
87
30
  if (units.length === 0 || shapes.length === 0 || !bounds)
88
31
  return null;
89
- var host = selectedHostObject(engine);
90
- var name = host ? (host.id === '' ? host.type : ((_a = host._customType) !== null && _a !== void 0 ? _a : host.type)) : 'object';
91
- var kinds = new Set(shapes.map(function (shape) { var _a; return (_a = hostCustomTypeOf(shape)) !== null && _a !== void 0 ? _a : hostTypeOf(shape); }));
32
+ const host = selectedHostObject(engine);
33
+ const name = host ? (host.id === '' ? host.type : (host._customType ?? host.type)) : 'object';
34
+ const kinds = new Set(shapes.map((shape) => hostCustomTypeOf(shape) ?? hostTypeOf(shape)));
92
35
  return {
93
- units: units,
94
- shapes: shapes,
95
- bounds: bounds,
96
- name: name,
97
- shapeTypes: __spreadArray([], kinds, true),
98
- hasImages: shapes.some(function (shape) { return shape.type === 'image' && Boolean(shape.src || shape.imageRef); }),
99
- hasText: shapes.some(function (shape) { return shape.type === 'text'; })
36
+ units,
37
+ shapes,
38
+ bounds,
39
+ name,
40
+ shapeTypes: [...kinds],
41
+ hasImages: shapes.some((shape) => shape.type === 'image' && Boolean(shape.src || shape.imageRef)),
42
+ hasText: shapes.some((shape) => shape.type === 'text')
100
43
  };
101
44
  }
102
45
  /** A PNG of some shapes on a plain background, cropped to what they cover. Empty when there is nothing to draw. */
103
- export function screenshotOfShapes(shapes, deps) {
104
- return __awaiter(this, void 0, Promise, function () {
105
- var error_1;
106
- return __generator(this, function (_a) {
107
- switch (_a.label) {
108
- case 0:
109
- if (shapes.length === 0 || !rasterBoundsOf(shapes))
110
- return [2 /*return*/, ''];
111
- _a.label = 1;
112
- case 1:
113
- _a.trys.push([1, 3, , 4]);
114
- return [4 /*yield*/, renderShapesToDataUrl(shapes, deps.raster, {
115
- scale: SCREENSHOT_SCALE,
116
- background: SCREENSHOT_BACKGROUND,
117
- widgetFallbackName: deps.widgetFallbackName
118
- })];
119
- case 2: return [2 /*return*/, _a.sent()];
120
- case 3:
121
- error_1 = _a.sent();
122
- console.warn('Canvas: could not draw the screenshot', error_1);
123
- return [2 /*return*/, ''];
124
- case 4: return [2 /*return*/];
125
- }
46
+ export async function screenshotOfShapes(shapes, deps) {
47
+ if (shapes.length === 0 || !rasterBoundsOf(shapes))
48
+ return '';
49
+ try {
50
+ return await renderShapesToDataUrl(shapes, deps.raster, {
51
+ scale: SCREENSHOT_SCALE,
52
+ background: SCREENSHOT_BACKGROUND,
53
+ widgetFallbackName: deps.widgetFallbackName
126
54
  });
127
- });
55
+ }
56
+ catch (error) {
57
+ console.warn('Canvas: could not draw the screenshot', error);
58
+ return '';
59
+ }
128
60
  }
129
61
  /** What the host needs to turn a selection into a widget, or null when nothing is selected. */
130
- export function buildConversionPayload(deps) {
131
- return __awaiter(this, void 0, Promise, function () {
132
- var engine, conversions, selection, single, frameId, screenshot, frame;
133
- return __generator(this, function (_a) {
134
- switch (_a.label) {
135
- case 0:
136
- engine = deps.engine, conversions = deps.conversions;
137
- selection = describeSelection(engine);
138
- if (!selection)
139
- return [2 /*return*/, null];
140
- single = selection.units.length === 1 ? selection.units[0] : null;
141
- frameId = single ? single.id : engine.services.createId('selection');
142
- if (!single) {
143
- conversions.remember(frameId, { unitIds: selection.units.map(function (unit) { return unit.id; }), bounds: selection.bounds });
144
- }
145
- return [4 /*yield*/, screenshotOfShapes(selection.shapes, deps)];
146
- case 1:
147
- screenshot = _a.sent();
148
- frame = single ? hostObjectById(engine, single.id) : selectedHostObject(engine);
149
- return [2 /*return*/, {
150
- frameName: selection.name || deps.untitledShapeName,
151
- frameId: frameId,
152
- screenshot: screenshot,
153
- canvasData: {
154
- frame: frame ? __assign({}, frame) : {},
155
- children: [],
156
- bounds: { left: selection.bounds.x, top: selection.bounds.y, width: selection.bounds.width, height: selection.bounds.height }
157
- },
158
- metadata: {
159
- childCount: selection.shapes.length,
160
- shapeTypes: selection.shapeTypes,
161
- hasImages: selection.hasImages,
162
- hasText: selection.hasText
163
- }
164
- }];
165
- }
166
- });
167
- });
62
+ export async function buildConversionPayload(deps) {
63
+ const { engine, conversions } = deps;
64
+ const selection = describeSelection(engine);
65
+ if (!selection)
66
+ return null;
67
+ // One object is converted by its own id. Several have none: the selection gets one and is remembered under it,
68
+ // before anything (the screenshot takes a moment) can clear the selection.
69
+ const single = selection.units.length === 1 ? selection.units[0] : null;
70
+ const frameId = single ? single.id : engine.services.createId('selection');
71
+ if (!single) {
72
+ conversions.remember(frameId, { unitIds: selection.units.map((unit) => unit.id), bounds: selection.bounds });
73
+ }
74
+ const screenshot = await screenshotOfShapes(selection.shapes, deps);
75
+ const frame = single ? hostObjectById(engine, single.id) : selectedHostObject(engine);
76
+ return {
77
+ frameName: selection.name || deps.untitledShapeName,
78
+ frameId,
79
+ screenshot,
80
+ canvasData: {
81
+ frame: frame ? { ...frame } : {},
82
+ children: [],
83
+ bounds: { left: selection.bounds.x, top: selection.bounds.y, width: selection.bounds.width, height: selection.bounds.height }
84
+ },
85
+ metadata: {
86
+ childCount: selection.shapes.length,
87
+ shapeTypes: selection.shapeTypes,
88
+ hasImages: selection.hasImages,
89
+ hasText: selection.hasText
90
+ }
91
+ };
168
92
  }
169
93
  /** The extra facts the host is given about what was captured. */
170
94
  function metadataOf(selection) {
171
- var _a, _b, _c;
172
- var metadata = {};
173
- var only = selection.shapes.length === 1 && selection.units.length === 1 ? selection.shapes[0] : null;
95
+ const metadata = {};
96
+ const only = selection.shapes.length === 1 && selection.units.length === 1 ? selection.shapes[0] : null;
174
97
  if (only && only.type === 'image') {
175
98
  metadata.hasImage = Boolean(only.src || only.imageRef);
176
- metadata.imageUrl = (_a = only.src) !== null && _a !== void 0 ? _a : null;
177
- metadata.originalFilename = (_b = only.fileName) !== null && _b !== void 0 ? _b : null;
99
+ metadata.imageUrl = only.src ?? null;
100
+ metadata.originalFilename = only.fileName ?? null;
178
101
  }
179
102
  if (only && only.type === 'text')
180
103
  metadata.text = only.text;
181
- if (selection.units.length > 1 || ((_c = selection.units[0]) === null || _c === void 0 ? void 0 : _c.type) === 'group')
104
+ if (selection.units.length > 1 || selection.units[0]?.type === 'group')
182
105
  metadata.objectCount = selection.shapes.length;
183
106
  return metadata;
184
107
  }
185
108
  /** What the host is given when a selection is captured (the "capture" button of the selection panel). */
186
- export function buildCapturePayload(deps) {
187
- return __awaiter(this, void 0, Promise, function () {
188
- var engine, selection, single, screenshot, host;
189
- var _a, _b;
190
- return __generator(this, function (_c) {
191
- switch (_c.label) {
192
- case 0:
193
- engine = deps.engine;
194
- selection = describeSelection(engine);
195
- if (!selection)
196
- return [2 /*return*/, null];
197
- single = selection.units.length === 1 ? selection.units[0] : null;
198
- return [4 /*yield*/, screenshotOfShapes(selection.shapes, deps)];
199
- case 1:
200
- screenshot = _c.sent();
201
- host = selectedHostObject(engine);
202
- return [2 /*return*/, {
203
- screenshot: screenshot,
204
- objectType: (_a = host === null || host === void 0 ? void 0 : host.type) !== null && _a !== void 0 ? _a : 'unknown',
205
- customType: (_b = host === null || host === void 0 ? void 0 : host._customType) !== null && _b !== void 0 ? _b : undefined,
206
- bounds: { left: selection.bounds.x, top: selection.bounds.y, width: selection.bounds.width, height: selection.bounds.height },
207
- objectId: single ? single.id : engine.services.createId('selection'),
208
- metadata: metadataOf(selection)
209
- }];
210
- }
211
- });
212
- });
109
+ export async function buildCapturePayload(deps) {
110
+ const { engine } = deps;
111
+ const selection = describeSelection(engine);
112
+ if (!selection)
113
+ return null;
114
+ const single = selection.units.length === 1 ? selection.units[0] : null;
115
+ const screenshot = await screenshotOfShapes(selection.shapes, deps);
116
+ const host = selectedHostObject(engine);
117
+ return {
118
+ screenshot,
119
+ objectType: host?.type ?? 'unknown',
120
+ customType: host?._customType ?? undefined,
121
+ bounds: { left: selection.bounds.x, top: selection.bounds.y, width: selection.bounds.width, height: selection.bounds.height },
122
+ objectId: single ? single.id : engine.services.createId('selection'),
123
+ metadata: metadataOf(selection)
124
+ };
213
125
  }