@widgetic/canvas 0.5.45 → 0.5.47

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 (137) hide show
  1. package/README.md +3 -2
  2. package/dist/canvas/DomCanvas.svelte +1 -2
  3. package/dist/canvas/autosaveScheduler.js +37 -89
  4. package/dist/canvas/boardFrame.js +1 -1
  5. package/dist/canvas/boardSurface.js +1 -1
  6. package/dist/canvas/canvasLogger.js +7 -19
  7. package/dist/canvas/chromeLayout.js +19 -21
  8. package/dist/canvas/eventScope.js +10 -14
  9. package/dist/canvas/host/CanvasHost.d.ts +6 -5
  10. package/dist/canvas/host/CanvasHost.js +1664 -1861
  11. package/dist/canvas/host/CanvasHostApi.js +4 -19
  12. package/dist/canvas/host/boardFiles.js +35 -51
  13. package/dist/canvas/host/browserServices.js +108 -196
  14. package/dist/canvas/host/conversion.js +82 -170
  15. package/dist/canvas/host/hostObject.js +7 -7
  16. package/dist/canvas/host/nearCards.js +18 -21
  17. package/dist/canvas/host/pageEvents.js +5 -5
  18. package/dist/canvas/host/pauseCollector.d.ts +18 -0
  19. package/dist/canvas/host/pauseCollector.js +45 -0
  20. package/dist/canvas/host/pictureSaves.js +9 -11
  21. package/dist/canvas/host/screenRects.js +28 -31
  22. package/dist/canvas/host/storedPictures.js +149 -243
  23. package/dist/canvas/host/strokeSnap.js +88 -143
  24. package/dist/canvas/index.d.ts +1 -1
  25. package/dist/canvas/openMarks.js +2 -2
  26. package/dist/canvas/outsideClickDeselect.js +6 -7
  27. package/dist/canvas/panZoomPosition.js +2 -2
  28. package/dist/canvas/preferredTextFont.js +13 -25
  29. package/dist/canvas/shapes/ShapeLibrary.js +138 -148
  30. package/dist/canvas/shapes/shapeImageStore.js +4 -4
  31. package/dist/canvas/shapes/strokeShapeSnap.js +188 -233
  32. package/dist/canvas/toolbarPosition.js +2 -2
  33. package/dist/canvas/types.d.ts +7 -1
  34. package/dist/canvas/ui/CanvasContextMenu.svelte +40 -3
  35. package/dist/canvas/ui/CanvasHint.svelte +10 -9
  36. package/dist/canvas/ui/SelectionPanel.svelte +14 -12
  37. package/dist/canvas/ui/SelectionPanel.svelte.d.ts +0 -2
  38. package/dist/canvas/ui/ShapesMenu.svelte +6 -4
  39. package/dist/canvas/ui/ToolButton.svelte +7 -6
  40. package/dist/canvas/ui/colorModel.js +21 -32
  41. package/dist/canvas/ui/colorPickerMessages.js +5 -5
  42. package/dist/canvas/ui/floatingCard.d.ts +28 -8
  43. package/dist/canvas/ui/floatingCard.js +48 -28
  44. package/dist/canvas/ui/floatingLayer.js +5 -6
  45. package/dist/canvas/ui/keyHints.js +9 -11
  46. package/dist/canvas/ui/popoverSide.js +2 -3
  47. package/dist/canvas/ui/selectionTraits.d.ts +8 -4
  48. package/dist/canvas/ui/selectionTraits.js +44 -58
  49. package/dist/canvas/view/CanvasStage.svelte +1 -1
  50. package/dist/canvas/view/SelectionOverlay.svelte +2 -2
  51. package/dist/canvas/view/erasingMarks.js +7 -7
  52. package/dist/canvas/view/geometry.d.ts +1 -1
  53. package/dist/canvas/view/geometry.js +72 -91
  54. package/dist/canvas/view/liftedScene.js +24 -36
  55. package/dist/canvas/view/mountedScene.js +76 -79
  56. package/dist/components/CanvasBoardPlaceholder.svelte +68 -10
  57. package/dist/components/CanvasBoardPlaceholder.svelte.d.ts +10 -2
  58. package/dist/components/CanvasToolbarPlaceholder.svelte +25 -11
  59. package/dist/components/CanvasToolbarPlaceholder.svelte.d.ts +6 -0
  60. package/dist/components/boardLoaderDelay.d.ts +39 -0
  61. package/dist/components/boardLoaderDelay.js +71 -0
  62. package/dist/components/input-controls/ColorIC.svelte +1 -1
  63. package/dist/components/input-controls/FontSelectorIC.svelte +1 -1
  64. package/dist/components/preferenceStorage.js +2 -2
  65. package/dist/engine/EngineCore.d.ts +42 -10
  66. package/dist/engine/EngineCore.js +843 -916
  67. package/dist/engine/codec/canvasDocument.js +192 -155
  68. package/dist/engine/codec/hostReadableKeys.js +1 -1
  69. package/dist/engine/core/arrange.js +26 -38
  70. package/dist/engine/core/arrow.js +79 -92
  71. package/dist/engine/core/arrowBinding.js +98 -116
  72. package/dist/engine/core/arrowBindingRecords.js +23 -38
  73. package/dist/engine/core/brush.d.ts +24 -0
  74. package/dist/engine/core/brush.js +223 -103
  75. package/dist/engine/core/cameraMove.js +39 -51
  76. package/dist/engine/core/defaults.js +92 -51
  77. package/dist/engine/core/freehand.js +147 -163
  78. package/dist/engine/core/geometry.js +47 -54
  79. package/dist/engine/core/history.js +38 -55
  80. package/dist/engine/core/hitTest.js +68 -81
  81. package/dist/engine/core/matrix.js +18 -20
  82. package/dist/engine/core/pathData.js +183 -210
  83. package/dist/engine/core/rotationReset.js +5 -6
  84. package/dist/engine/core/scene.js +160 -224
  85. package/dist/engine/core/scribble.js +59 -84
  86. package/dist/engine/core/shapePaths.js +12 -15
  87. package/dist/engine/core/shapeTools.d.ts +23 -18
  88. package/dist/engine/core/shapeTools.js +104 -67
  89. package/dist/engine/core/snapping.js +65 -117
  90. package/dist/engine/core/style.d.ts +18 -2
  91. package/dist/engine/core/style.js +79 -80
  92. package/dist/engine/core/styleMemory.d.ts +88 -0
  93. package/dist/engine/core/styleMemory.js +189 -0
  94. package/dist/engine/core/transform.js +84 -95
  95. package/dist/engine/core/types.js +4 -4
  96. package/dist/engine/core/viewport.js +23 -36
  97. package/dist/engine/input/PointerController.js +513 -526
  98. package/dist/engine/input/arrowHandles.js +12 -12
  99. package/dist/engine/input/gestures.d.ts +8 -3
  100. package/dist/engine/input/gestures.js +378 -346
  101. package/dist/engine/input/hoverCursor.js +1 -1
  102. package/dist/engine/input/keyboard.js +42 -41
  103. package/dist/engine/input/selectionHandles.js +45 -50
  104. package/dist/engine/input/types.js +1 -1
  105. package/dist/engine/render/rasterize.js +86 -158
  106. package/dist/engine/state.js +6 -17
  107. package/dist/engine/text/layoutText.js +43 -62
  108. package/dist/engine/text/textMetrics.js +8 -10
  109. package/dist/engine/widgets.js +101 -137
  110. package/dist/fonts/interFont.js +30 -83
  111. package/dist/fonts/workspaceFonts.js +33 -92
  112. package/dist/i18n/labels.js +4 -4
  113. package/dist/i18n/language.js +4 -4
  114. package/dist/i18n/messages.js +1 -1
  115. package/dist/i18n/shortcuts.js +14 -14
  116. package/dist/index.d.ts +1 -1
  117. package/dist/poster/boardPlacement.d.ts +4 -1
  118. package/dist/poster/boardPlacement.js +34 -33
  119. package/dist/poster/boardPoster.js +58 -83
  120. package/dist/poster/paintBoardPoster.js +16 -39
  121. package/dist/poster/posterPictures.js +27 -43
  122. package/dist/settings/rememberedStyles.d.ts +22 -0
  123. package/dist/settings/rememberedStyles.js +47 -0
  124. package/dist/settings/rememberedTool.d.ts +50 -0
  125. package/dist/settings/rememberedTool.js +68 -0
  126. package/dist/settings/workspaceToolSettings.d.ts +25 -0
  127. package/dist/settings/workspaceToolSettings.js +38 -48
  128. package/dist/tools/components/catalog.js +64 -74
  129. package/dist/tools/components/grouping.js +6 -28
  130. package/dist/tools/definitions.js +5 -5
  131. package/dist/tools/executors.js +137 -169
  132. package/dist/tools/hostAdapter.js +10 -13
  133. package/dist/tools/sceneSummary.js +43 -57
  134. package/dist/tools/sketchIntent.js +13 -21
  135. package/dist/tools/styleArguments.js +19 -21
  136. package/dist/tools/types.js +1 -1
  137. package/package.json +5 -5
@@ -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',
@@ -111,18 +102,12 @@ export var CANVAS_ADDED_FUNCTION_NAMES = [
111
102
  'setPictureLibraryFile'
112
103
  ];
113
104
  /** Every function the shell exports. */
114
- export var CANVAS_EXPORTED_FUNCTION_NAMES = __spreadArray(__spreadArray([], CANVAS_CONTRACT_FUNCTION_NAMES, true), CANVAS_ADDED_FUNCTION_NAMES, true);
105
+ export const CANVAS_EXPORTED_FUNCTION_NAMES = [...CANVAS_CONTRACT_FUNCTION_NAMES, ...CANVAS_ADDED_FUNCTION_NAMES];
115
106
  /**
116
107
  * One exported function of the shell: it calls the host's method of that name, with the host as `this`, and has the
117
108
  * method's own type. A page that holds the shell's reference calls it exactly as it calls the host's method.
118
109
  */
119
110
  export function forwardToHost(host, name) {
120
- var forwarded = function () {
121
- var values = [];
122
- for (var _i = 0; _i < arguments.length; _i++) {
123
- values[_i] = arguments[_i];
124
- }
125
- return host[name].apply(host, values);
126
- };
111
+ const forwarded = (...values) => host[name].apply(host, values);
127
112
  return forwarded;
128
113
  }
@@ -13,21 +13,10 @@
13
13
  *
14
14
  * Plain TypeScript: runs in Node.
15
15
  */
16
- var __assign = (this && this.__assign) || function () {
17
- __assign = Object.assign || function(t) {
18
- for (var s, i = 1, n = arguments.length; i < n; i++) {
19
- s = arguments[i];
20
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
21
- t[p] = s[p];
22
- }
23
- return t;
24
- };
25
- return __assign.apply(this, arguments);
26
- };
27
16
  import { readLibraryFileAddress } from '../../engine/codec/canvasDocument.js';
28
17
  /** The kinds the board asks the picker for, in the order the File Browser lists them. */
29
- export var BOARD_FILE_KINDS = ['image', 'svg'];
30
- var PICTURE_EXTENSIONS = {
18
+ export const BOARD_FILE_KINDS = ['image', 'svg'];
19
+ const PICTURE_EXTENSIONS = {
31
20
  svg: 'svg',
32
21
  png: 'image',
33
22
  jpg: 'image',
@@ -38,53 +27,49 @@ var PICTURE_EXTENSIONS = {
38
27
  bmp: 'image'
39
28
  };
40
29
  /** What a library address is allowed to be: an http(s) address, or a path of the page (never `data:`, `javascript:`, `//host`). */
41
- var LIBRARY_URL_PATTERN = /^(?:https?:\/\/|\/(?!\/))/i;
42
- var MAX_URL_LENGTH = 2000;
43
- var MAX_NAME_LENGTH = 300;
44
- var MAX_ID_LENGTH = 200;
30
+ const LIBRARY_URL_PATTERN = /^(?:https?:\/\/|\/(?!\/))/i;
31
+ const MAX_URL_LENGTH = 2000;
32
+ const MAX_NAME_LENGTH = 300;
33
+ const MAX_ID_LENGTH = 200;
45
34
  /** A picked list longer than this is cut: one dialog is not for a hundred files, and each is fetched. */
46
- export var MAX_PICKED_FILES = 40;
35
+ export const MAX_PICKED_FILES = 40;
47
36
  /** The extension of a file name or an address, lower-cased, without the query or the hash. Empty when there is none. */
48
37
  export function fileExtensionOf(nameOrUrl) {
49
- var _a;
50
- var withoutQuery = (_a = nameOrUrl.split(/[?#]/, 1)[0]) !== null && _a !== void 0 ? _a : '';
51
- var lastSegment = withoutQuery.slice(withoutQuery.lastIndexOf('/') + 1);
52
- var dot = lastSegment.lastIndexOf('.');
38
+ const withoutQuery = nameOrUrl.split(/[?#]/, 1)[0] ?? '';
39
+ const lastSegment = withoutQuery.slice(withoutQuery.lastIndexOf('/') + 1);
40
+ const dot = lastSegment.lastIndexOf('.');
53
41
  return dot > 0 ? lastSegment.slice(dot + 1).toLowerCase() : '';
54
42
  }
55
43
  /** The kind of a file by what the library says it is, else by its name; null when it is not a picture the board can draw. */
56
44
  export function boardFileKindOf(file) {
57
- var _a, _b, _c, _d;
58
- var mimeType = ((_a = file.mimeType) !== null && _a !== void 0 ? _a : '').toLowerCase();
45
+ const mimeType = (file.mimeType ?? '').toLowerCase();
59
46
  if (mimeType === 'image/svg+xml')
60
47
  return 'svg';
61
48
  if (mimeType.startsWith('image/'))
62
49
  return 'image';
63
- return (_d = (_b = PICTURE_EXTENSIONS[fileExtensionOf(file.name)]) !== null && _b !== void 0 ? _b : PICTURE_EXTENSIONS[fileExtensionOf((_c = file.url) !== null && _c !== void 0 ? _c : '')]) !== null && _d !== void 0 ? _d : null;
50
+ return PICTURE_EXTENSIONS[fileExtensionOf(file.name)] ?? PICTURE_EXTENSIONS[fileExtensionOf(file.url ?? '')] ?? null;
64
51
  }
65
52
  /** The media type the browser needs to draw the file: the library's own when it is a picture's, else the one its extension says. */
66
53
  export function pictureMimeTypeOf(file) {
67
- var _a, _b;
68
- var mimeType = ((_a = file.mimeType) !== null && _a !== void 0 ? _a : '').toLowerCase();
54
+ const mimeType = (file.mimeType ?? '').toLowerCase();
69
55
  if (mimeType.startsWith('image/'))
70
56
  return mimeType;
71
- var kind = boardFileKindOf(file);
57
+ const kind = boardFileKindOf(file);
72
58
  if (kind === 'svg')
73
59
  return 'image/svg+xml';
74
- var extension = fileExtensionOf(file.name) || fileExtensionOf((_b = file.url) !== null && _b !== void 0 ? _b : '');
60
+ const extension = fileExtensionOf(file.name) || fileExtensionOf(file.url ?? '');
75
61
  if (extension === 'jpg' || extension === 'jpeg')
76
62
  return 'image/jpeg';
77
- return extension ? "image/".concat(extension) : 'image/png';
63
+ return extension ? `image/${extension}` : 'image/png';
78
64
  }
79
65
  /** A readable name for a file whose picker did not give one: the last part of its address. */
80
66
  function nameFromUrl(url) {
81
- var _a;
82
- var withoutQuery = (_a = url.split(/[?#]/, 1)[0]) !== null && _a !== void 0 ? _a : '';
83
- var last = withoutQuery.slice(withoutQuery.lastIndexOf('/') + 1);
67
+ const withoutQuery = url.split(/[?#]/, 1)[0] ?? '';
68
+ const last = withoutQuery.slice(withoutQuery.lastIndexOf('/') + 1);
84
69
  try {
85
70
  return decodeURIComponent(last).slice(0, MAX_NAME_LENGTH) || 'picture';
86
71
  }
87
- catch (_b) {
72
+ catch {
88
73
  return last.slice(0, MAX_NAME_LENGTH) || 'picture';
89
74
  }
90
75
  }
@@ -103,28 +88,27 @@ function readId(value) {
103
88
  export function normalizeLibraryFiles(answer) {
104
89
  if (!Array.isArray(answer))
105
90
  return [];
106
- var files = [];
107
- var seen = new Set();
108
- for (var _i = 0, answer_1 = answer; _i < answer_1.length; _i++) {
109
- var entry = answer_1[_i];
91
+ const files = [];
92
+ const seen = new Set();
93
+ for (const entry of answer) {
110
94
  if (files.length >= MAX_PICKED_FILES)
111
95
  break;
112
96
  if (typeof entry !== 'object' || entry === null)
113
97
  continue;
114
- var raw = entry;
115
- var url = typeof raw.url === 'string' ? raw.url.trim() : '';
98
+ const raw = entry;
99
+ const url = typeof raw.url === 'string' ? raw.url.trim() : '';
116
100
  if (url === '' || url.length > MAX_URL_LENGTH || !LIBRARY_URL_PATTERN.test(url))
117
101
  continue;
118
- var name = (typeof raw.name === 'string' && raw.name.trim() !== '' ? raw.name.trim() : nameFromUrl(url)).slice(0, MAX_NAME_LENGTH);
119
- var mimeType = typeof raw.mimeType === 'string' && raw.mimeType !== '' ? raw.mimeType.slice(0, 100) : null;
120
- if (!boardFileKindOf({ name: name, url: url, mimeType: mimeType }))
102
+ const name = (typeof raw.name === 'string' && raw.name.trim() !== '' ? raw.name.trim() : nameFromUrl(url)).slice(0, MAX_NAME_LENGTH);
103
+ const mimeType = typeof raw.mimeType === 'string' && raw.mimeType !== '' ? raw.mimeType.slice(0, 100) : null;
104
+ if (!boardFileKindOf({ name, url, mimeType }))
121
105
  continue;
122
- var id = readId(raw.id);
123
- var identity = id ? "id:".concat(id) : "url:".concat(url);
106
+ const id = readId(raw.id);
107
+ const identity = id ? `id:${id}` : `url:${url}`;
124
108
  if (seen.has(identity))
125
109
  continue;
126
110
  seen.add(identity);
127
- files.push({ id: id, name: name, url: url, mimeType: mimeType });
111
+ files.push({ id, name, url, mimeType });
128
112
  }
129
113
  return files;
130
114
  }
@@ -138,18 +122,18 @@ export function isInLibrary(picture) {
138
122
  * so a partner's bug cannot put an address of its choosing on the board.
139
123
  */
140
124
  export function applyLibraryFile(scene, objectId, file) {
141
- var id = readId(file === null || file === void 0 ? void 0 : file.id);
142
- var url = readLibraryFileAddress(file === null || file === void 0 ? void 0 : file.url);
125
+ const id = readId(file?.id);
126
+ const url = readLibraryFileAddress(file?.url);
143
127
  if (!id || !url)
144
128
  return scene;
145
- var changed = false;
146
- var next = scene.map(function (object) {
129
+ let changed = false;
130
+ const next = scene.map((object) => {
147
131
  if (object.id !== objectId || object.type !== 'image')
148
132
  return object;
149
133
  if (object.libraryFileId === id && object.libraryFileUrl === url)
150
134
  return object;
151
135
  changed = true;
152
- return __assign(__assign({}, object), { libraryFileId: id, libraryFileUrl: url });
136
+ return { ...object, libraryFileId: id, libraryFileUrl: url };
153
137
  });
154
138
  return changed ? next : scene;
155
139
  }
@@ -6,69 +6,22 @@
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 __assign = (this && this.__assign) || function () {
10
- __assign = Object.assign || function(t) {
11
- for (var s, i = 1, n = arguments.length; i < n; i++) {
12
- s = arguments[i];
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
14
- t[p] = s[p];
15
- }
16
- return t;
17
- };
18
- return __assign.apply(this, arguments);
19
- };
20
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
21
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
22
- return new (P || (P = Promise))(function (resolve, reject) {
23
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
24
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
25
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
26
- step((generator = generator.apply(thisArg, _arguments || [])).next());
27
- });
28
- };
29
- var __generator = (this && this.__generator) || function (thisArg, body) {
30
- 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);
31
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
32
- function verb(n) { return function (v) { return step([n, v]); }; }
33
- function step(op) {
34
- if (f) throw new TypeError("Generator is already executing.");
35
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
36
- 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;
37
- if (y = 0, t) op = [op[0] & 2, t.value];
38
- switch (op[0]) {
39
- case 0: case 1: t = op; break;
40
- case 4: _.label++; return { value: op[1], done: false };
41
- case 5: _.label++; y = op[1]; op = [0]; continue;
42
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
43
- default:
44
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
45
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
46
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
47
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
48
- if (t[2]) _.ops.pop();
49
- _.trys.pop(); continue;
50
- }
51
- op = body.call(thisArg, _);
52
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
53
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
54
- }
55
- };
56
9
  import { createFixedAdvanceMeasure } from '../../engine/text/layoutText.js';
57
10
  import { getTransientHostFor } from '../eventScope.js';
58
11
  import { pictureMimeTypeOf } from './boardFiles.js';
59
- var hasDocument = function () { return typeof document !== 'undefined' && typeof document.createElement === 'function'; };
12
+ const hasDocument = () => typeof document !== 'undefined' && typeof document.createElement === 'function';
60
13
  /** A text measurer that uses the browser's canvas, or a fixed advance where there is none (the server, a test). */
61
14
  export function createBrowserMeasureText() {
62
15
  if (!hasDocument())
63
16
  return createFixedAdvanceMeasure();
64
- var context;
65
- var fallback = createFixedAdvanceMeasure();
66
- return function (text, font) {
17
+ let context;
18
+ const fallback = createFixedAdvanceMeasure();
19
+ return (text, font) => {
67
20
  if (context === undefined) {
68
21
  try {
69
22
  context = document.createElement('canvas').getContext('2d');
70
23
  }
71
- catch (_a) {
24
+ catch {
72
25
  context = null;
73
26
  }
74
27
  }
@@ -83,63 +36,62 @@ export function createBrowserMeasureText() {
83
36
  export function loadImageElement(source) {
84
37
  if (typeof Image === 'undefined')
85
38
  return Promise.resolve(null);
86
- return new Promise(function (resolve) {
87
- var image = new Image();
39
+ return new Promise((resolve) => {
40
+ const image = new Image();
88
41
  // A picture from another site is only usable in a canvas when that site allows it; a data address needs nothing.
89
42
  if (/^https?:/i.test(source))
90
43
  image.crossOrigin = 'anonymous';
91
- image.onload = function () {
44
+ image.onload = () => {
92
45
  if (typeof image.decode === 'function') {
93
- image.decode().then(function () { return resolve(image); }, function () { return resolve(image.naturalWidth > 0 ? image : null); });
46
+ image.decode().then(() => resolve(image), () => resolve(image.naturalWidth > 0 ? image : null));
94
47
  }
95
48
  else {
96
49
  resolve(image);
97
50
  }
98
51
  };
99
- image.onerror = function () { return resolve(null); };
52
+ image.onerror = () => resolve(null);
100
53
  image.src = source;
101
54
  });
102
55
  }
103
56
  /** The services the rasterizer needs, made of the browser. */
104
57
  export function createBrowserRasterServices(measureText) {
105
58
  return {
106
- createCanvas: function (width, height) {
59
+ createCanvas(width, height) {
107
60
  if (!hasDocument())
108
61
  return null;
109
62
  try {
110
- var canvas = document.createElement('canvas');
63
+ const canvas = document.createElement('canvas');
111
64
  canvas.width = width;
112
65
  canvas.height = height;
113
66
  return canvas;
114
67
  }
115
- catch (_a) {
68
+ catch {
116
69
  return null;
117
70
  }
118
71
  },
119
72
  loadImage: loadImageElement,
120
- createPath: function (data) { return new Path2D(data); },
121
- measureText: measureText
73
+ createPath: (data) => new Path2D(data),
74
+ measureText
122
75
  };
123
76
  }
124
77
  /** Whether the person's keyboard says Cmd rather than Ctrl. */
125
78
  export function isApplePlatform() {
126
- var _a;
127
79
  if (typeof navigator === 'undefined')
128
80
  return false;
129
- var platform = ((_a = navigator.userAgentData) === null || _a === void 0 ? void 0 : _a.platform) || navigator.platform || navigator.userAgent || '';
81
+ const platform = navigator.userAgentData?.platform || navigator.platform || navigator.userAgent || '';
130
82
  return /Mac|iPhone|iPad|iPod/i.test(platform);
131
83
  }
132
84
  /** The longest side a picture keeps when it is large; a bigger one is scaled down before it is stored in the board. */
133
- export var IMAGE_MAX_SIDE = 2048;
85
+ export const IMAGE_MAX_SIDE = 2048;
134
86
  /** Pictures smaller than this are stored as they came. */
135
- export var IMAGE_RESIZE_THRESHOLD_BYTES = 2.5 * 1024 * 1024;
87
+ export const IMAGE_RESIZE_THRESHOLD_BYTES = 2.5 * 1024 * 1024;
136
88
  /** What a picture without a size of its own (an SVG with no width and height) is given. */
137
- export var IMAGE_FALLBACK_SIDE = 300;
89
+ export const IMAGE_FALLBACK_SIDE = 300;
138
90
  function readAsDataUrl(file) {
139
- return new Promise(function (resolve, reject) {
140
- var reader = new FileReader();
141
- reader.onload = function () { return (typeof reader.result === 'string' ? resolve(reader.result) : reject(new Error('The file could not be read'))); };
142
- reader.onerror = function () { var _a; return reject((_a = reader.error) !== null && _a !== void 0 ? _a : new Error('The file could not be read')); };
91
+ return new Promise((resolve, reject) => {
92
+ const reader = new FileReader();
93
+ reader.onload = () => (typeof reader.result === 'string' ? resolve(reader.result) : reject(new Error('The file could not be read')));
94
+ reader.onerror = () => reject(reader.error ?? new Error('The file could not be read'));
143
95
  reader.readAsDataURL(file);
144
96
  });
145
97
  }
@@ -148,78 +100,57 @@ function readAsDataUrl(file) {
148
100
  * `IMAGE_MAX_SIDE` so the saved board does not grow by megabytes; small files, and every SVG, are kept as they are.
149
101
  * Rejects when the file is not a picture the browser can show.
150
102
  */
151
- export function readImageFile(file_1) {
152
- return __awaiter(this, arguments, Promise, function (file, fileName) {
153
- var name, dataUrl, image, width, height, src, isSvg, tooBig, scale, scaledWidth, scaledHeight, canvas, context, keepsAlpha;
154
- if (fileName === void 0) { fileName = ''; }
155
- return __generator(this, function (_a) {
156
- switch (_a.label) {
157
- case 0:
158
- name = fileName || file.name || '';
159
- return [4 /*yield*/, readAsDataUrl(file)];
160
- case 1:
161
- dataUrl = _a.sent();
162
- return [4 /*yield*/, loadImageElement(dataUrl)];
163
- case 2:
164
- image = _a.sent();
165
- if (!image)
166
- throw new Error('The file is not a picture the browser can show');
167
- width = image.naturalWidth || image.width || IMAGE_FALLBACK_SIDE;
168
- height = image.naturalHeight || image.height || IMAGE_FALLBACK_SIDE;
169
- src = dataUrl;
170
- isSvg = file.type === 'image/svg+xml' || /\.svg$/i.test(name);
171
- tooBig = Math.max(width, height) > IMAGE_MAX_SIDE;
172
- if (!isSvg && tooBig && file.size > IMAGE_RESIZE_THRESHOLD_BYTES && hasDocument()) {
173
- try {
174
- scale = IMAGE_MAX_SIDE / Math.max(width, height);
175
- scaledWidth = Math.max(1, Math.round(width * scale));
176
- scaledHeight = Math.max(1, Math.round(height * scale));
177
- canvas = document.createElement('canvas');
178
- canvas.width = scaledWidth;
179
- canvas.height = scaledHeight;
180
- context = canvas.getContext('2d');
181
- if (context) {
182
- context.drawImage(image, 0, 0, scaledWidth, scaledHeight);
183
- keepsAlpha = /png|gif|webp/i.test(file.type);
184
- src = canvas.toDataURL(keepsAlpha ? 'image/png' : 'image/jpeg', 0.88);
185
- width = scaledWidth;
186
- height = scaledHeight;
187
- }
188
- }
189
- catch (error) {
190
- console.warn('Canvas: the picture could not be scaled down, it is stored as it came', error);
191
- }
192
- }
193
- return [2 /*return*/, { src: src, width: width, height: height, fileName: name }];
103
+ export async function readImageFile(file, fileName = '') {
104
+ const name = fileName || file.name || '';
105
+ const dataUrl = await readAsDataUrl(file);
106
+ const image = await loadImageElement(dataUrl);
107
+ if (!image)
108
+ throw new Error('The file is not a picture the browser can show');
109
+ let width = image.naturalWidth || image.width || IMAGE_FALLBACK_SIDE;
110
+ let height = image.naturalHeight || image.height || IMAGE_FALLBACK_SIDE;
111
+ let src = dataUrl;
112
+ const isSvg = file.type === 'image/svg+xml' || /\.svg$/i.test(name);
113
+ const tooBig = Math.max(width, height) > IMAGE_MAX_SIDE;
114
+ if (!isSvg && tooBig && file.size > IMAGE_RESIZE_THRESHOLD_BYTES && hasDocument()) {
115
+ try {
116
+ const scale = IMAGE_MAX_SIDE / Math.max(width, height);
117
+ const scaledWidth = Math.max(1, Math.round(width * scale));
118
+ const scaledHeight = Math.max(1, Math.round(height * scale));
119
+ const canvas = document.createElement('canvas');
120
+ canvas.width = scaledWidth;
121
+ canvas.height = scaledHeight;
122
+ const context = canvas.getContext('2d');
123
+ if (context) {
124
+ context.drawImage(image, 0, 0, scaledWidth, scaledHeight);
125
+ // Pictures that can have see-through parts stay PNG; photos become JPEG.
126
+ const keepsAlpha = /png|gif|webp/i.test(file.type);
127
+ src = canvas.toDataURL(keepsAlpha ? 'image/png' : 'image/jpeg', 0.88);
128
+ width = scaledWidth;
129
+ height = scaledHeight;
194
130
  }
195
- });
196
- });
131
+ }
132
+ catch (error) {
133
+ console.warn('Canvas: the picture could not be scaled down, it is stored as it came', error);
134
+ }
135
+ }
136
+ return { src, width, height, fileName: name };
197
137
  }
198
138
  /** How long the library gets to hand over a picture's bytes before the board settles for its address. */
199
- export var LIBRARY_PICTURE_TIMEOUT_MS = 10000;
139
+ export const LIBRARY_PICTURE_TIMEOUT_MS = 10_000;
200
140
  /** A library picture bigger than this is not read into the board: the board holds its address (a photo of 40 MB is not board material). */
201
- export var LIBRARY_PICTURE_MAX_BYTES = 30 * 1024 * 1024;
141
+ export const LIBRARY_PICTURE_MAX_BYTES = 30 * 1024 * 1024;
202
142
  /** The size of the picture behind an address: read with the CORS mode first, then as a plain picture (to be shown, not to be drawn on a canvas). */
203
- function measureImageAddress(source) {
204
- return __awaiter(this, void 0, Promise, function () {
205
- var image;
206
- return __generator(this, function (_a) {
207
- switch (_a.label) {
208
- case 0: return [4 /*yield*/, loadImageElement(source)];
209
- case 1:
210
- image = _a.sent();
211
- if (image)
212
- return [2 /*return*/, { width: image.naturalWidth || IMAGE_FALLBACK_SIDE, height: image.naturalHeight || IMAGE_FALLBACK_SIDE }];
213
- if (typeof Image === 'undefined')
214
- return [2 /*return*/, null];
215
- return [2 /*return*/, new Promise(function (resolve) {
216
- var plain = new Image();
217
- plain.onload = function () { return resolve({ width: plain.naturalWidth || IMAGE_FALLBACK_SIDE, height: plain.naturalHeight || IMAGE_FALLBACK_SIDE }); };
218
- plain.onerror = function () { return resolve(null); };
219
- plain.src = source;
220
- })];
221
- }
222
- });
143
+ async function measureImageAddress(source) {
144
+ const image = await loadImageElement(source);
145
+ if (image)
146
+ return { width: image.naturalWidth || IMAGE_FALLBACK_SIDE, height: image.naturalHeight || IMAGE_FALLBACK_SIDE };
147
+ if (typeof Image === 'undefined')
148
+ return null;
149
+ return new Promise((resolve) => {
150
+ const plain = new Image();
151
+ plain.onload = () => resolve({ width: plain.naturalWidth || IMAGE_FALLBACK_SIDE, height: plain.naturalHeight || IMAGE_FALLBACK_SIDE });
152
+ plain.onerror = () => resolve(null);
153
+ plain.src = source;
223
154
  });
224
155
  }
225
156
  /**
@@ -230,83 +161,64 @@ function measureImageAddress(source) {
230
161
  * error, too slow, too big) the board holds the file's address instead: it still shows the picture, and the library stays the owner.
231
162
  * Null when the browser cannot show the file at all.
232
163
  */
233
- export function readLibraryPicture(file) {
234
- return __awaiter(this, void 0, Promise, function () {
235
- var library, controller_1, timer, response, blob, typed, _a, error_1, size;
236
- var _b;
237
- return __generator(this, function (_c) {
238
- switch (_c.label) {
239
- case 0:
240
- library = { libraryFileId: file.id, libraryFileUrl: file.url };
241
- if (!(typeof fetch === 'function')) return [3 /*break*/, 7];
242
- controller_1 = typeof AbortController === 'function' ? new AbortController() : null;
243
- timer = controller_1 ? setTimeout(function () { return controller_1.abort(); }, LIBRARY_PICTURE_TIMEOUT_MS) : null;
244
- _c.label = 1;
245
- case 1:
246
- _c.trys.push([1, 5, 6, 7]);
247
- return [4 /*yield*/, fetch(file.url, controller_1 ? { signal: controller_1.signal } : undefined)];
248
- case 2:
249
- response = _c.sent();
250
- if (!response.ok)
251
- throw new Error("The library answered ".concat(response.status));
252
- return [4 /*yield*/, response.blob()];
253
- case 3:
254
- blob = _c.sent();
255
- if (blob.size > LIBRARY_PICTURE_MAX_BYTES)
256
- throw new Error('The file is too big to be kept in the board');
257
- typed = new Blob([blob], { type: pictureMimeTypeOf({ name: file.name, url: file.url, mimeType: (_b = file.mimeType) !== null && _b !== void 0 ? _b : (blob.type || null) }) });
258
- _a = [{}];
259
- return [4 /*yield*/, readImageFile(typed, file.name)];
260
- case 4: return [2 /*return*/, __assign.apply(void 0, [__assign.apply(void 0, _a.concat([(_c.sent())])), library])];
261
- case 5:
262
- error_1 = _c.sent();
263
- console.warn('Canvas: the library file could not be read into the board, it is shown from its address', file.name, error_1);
264
- return [3 /*break*/, 7];
265
- case 6:
266
- if (timer)
267
- clearTimeout(timer);
268
- return [7 /*endfinally*/];
269
- case 7: return [4 /*yield*/, measureImageAddress(file.url)];
270
- case 8:
271
- size = _c.sent();
272
- if (!size) {
273
- console.warn('Canvas: the library file is not a picture the browser can show', file.name);
274
- return [2 /*return*/, null];
275
- }
276
- return [2 /*return*/, __assign({ src: file.url, width: size.width, height: size.height, fileName: file.name }, library)];
277
- }
278
- });
279
- });
164
+ export async function readLibraryPicture(file) {
165
+ const library = { libraryFileId: file.id, libraryFileUrl: file.url };
166
+ if (typeof fetch === 'function') {
167
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
168
+ const timer = controller ? setTimeout(() => controller.abort(), LIBRARY_PICTURE_TIMEOUT_MS) : null;
169
+ try {
170
+ const response = await fetch(file.url, controller ? { signal: controller.signal } : undefined);
171
+ if (!response.ok)
172
+ throw new Error(`The library answered ${response.status}`);
173
+ const blob = await response.blob();
174
+ if (blob.size > LIBRARY_PICTURE_MAX_BYTES)
175
+ throw new Error('The file is too big to be kept in the board');
176
+ // A CDN may call a vector file `application/octet-stream`; the browser only draws a picture that is called one.
177
+ const typed = new Blob([blob], { type: pictureMimeTypeOf({ name: file.name, url: file.url, mimeType: file.mimeType ?? (blob.type || null) }) });
178
+ return { ...(await readImageFile(typed, file.name)), ...library };
179
+ }
180
+ catch (error) {
181
+ console.warn('Canvas: the library file could not be read into the board, it is shown from its address', file.name, error);
182
+ }
183
+ finally {
184
+ if (timer)
185
+ clearTimeout(timer);
186
+ }
187
+ }
188
+ const size = await measureImageAddress(file.url);
189
+ if (!size) {
190
+ console.warn('Canvas: the library file is not a picture the browser can show', file.name);
191
+ return null;
192
+ }
193
+ return { src: file.url, width: size.width, height: size.height, fileName: file.name, ...library };
280
194
  }
281
195
  /**
282
196
  * Opens the browser's file chooser for pictures and answers with what was chosen (an empty list when the person
283
197
  * cancels). Must be called while a click or a key press is being handled, or the browser refuses to open the chooser.
284
198
  * The hidden input goes into the shadow root the canvas is in, so a partner's own page never sees it.
285
199
  */
286
- export function chooseImageFiles(scope, options) {
287
- if (options === void 0) { options = {}; }
200
+ export function chooseImageFiles(scope, options = {}) {
288
201
  if (!hasDocument())
289
202
  return Promise.resolve([]);
290
- return new Promise(function (resolve) {
291
- var _a;
292
- var input = document.createElement('input');
203
+ return new Promise((resolve) => {
204
+ const input = document.createElement('input');
293
205
  input.type = 'file';
294
206
  // Every kind of picture by default; the SVG entry of the shapes menu asks for vector files only.
295
- input.accept = (_a = options.accept) !== null && _a !== void 0 ? _a : 'image/*,.svg';
207
+ input.accept = options.accept ?? 'image/*,.svg';
296
208
  input.multiple = !!options.multiple;
297
209
  input.style.display = 'none';
298
- var host = getTransientHostFor(scope);
299
- var settled = false;
300
- var finish = function (files) {
210
+ const host = getTransientHostFor(scope);
211
+ let settled = false;
212
+ const finish = (files) => {
301
213
  if (settled)
302
214
  return;
303
215
  settled = true;
304
216
  input.remove();
305
217
  resolve(files);
306
218
  };
307
- input.addEventListener('change', function () { var _a; return finish(Array.from((_a = input.files) !== null && _a !== void 0 ? _a : [])); });
219
+ input.addEventListener('change', () => finish(Array.from(input.files ?? [])));
308
220
  // The browsers that say so tell us when the chooser was closed without a file.
309
- input.addEventListener('cancel', function () { return finish([]); });
221
+ input.addEventListener('cancel', () => finish([]));
310
222
  host.appendChild(input);
311
223
  input.click();
312
224
  });