js-draw 1.18.0 → 1.20.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (146) hide show
  1. package/README.md +51 -0
  2. package/dist/Editor.css +78 -5
  3. package/dist/bundle.js +2 -2
  4. package/dist/bundledStyles.js +1 -1
  5. package/dist/cjs/Editor.d.ts +20 -1
  6. package/dist/cjs/Editor.js +6 -0
  7. package/dist/cjs/{SVGLoader.d.ts → SVGLoader/index.d.ts} +1 -1
  8. package/dist/cjs/{SVGLoader.js → SVGLoader/index.js} +15 -30
  9. package/dist/cjs/SVGLoader/utils/determineFontSize.d.ts +3 -0
  10. package/dist/cjs/SVGLoader/utils/determineFontSize.js +27 -0
  11. package/dist/cjs/Viewport.d.ts +33 -1
  12. package/dist/cjs/components/TextComponent.js +3 -1
  13. package/dist/cjs/image/EditorImage.d.ts +2 -1
  14. package/dist/cjs/image/EditorImage.js +101 -5
  15. package/dist/cjs/rendering/caching/RenderingCacheNode.js +20 -15
  16. package/dist/cjs/rendering/renderers/CanvasRenderer.js +4 -4
  17. package/dist/cjs/testing/findNodeWithText.d.ts +3 -0
  18. package/dist/cjs/testing/findNodeWithText.js +16 -0
  19. package/dist/cjs/testing/firstElementAncestorOfNode.d.ts +3 -0
  20. package/dist/cjs/testing/firstElementAncestorOfNode.js +13 -0
  21. package/dist/cjs/testing/sendKeyPressRelease.d.ts +3 -0
  22. package/dist/cjs/testing/sendKeyPressRelease.js +8 -0
  23. package/dist/cjs/testing/sendPenEvent.d.ts +2 -2
  24. package/dist/cjs/testing/sendPenEvent.js +26 -3
  25. package/dist/cjs/toolbar/localization.d.ts +3 -0
  26. package/dist/cjs/toolbar/localization.js +3 -0
  27. package/dist/cjs/toolbar/widgets/BaseWidget.d.ts +1 -0
  28. package/dist/cjs/toolbar/widgets/BaseWidget.js +1 -0
  29. package/dist/cjs/toolbar/widgets/InsertImageWidget/ImageWrapper.d.ts +23 -0
  30. package/dist/cjs/toolbar/widgets/InsertImageWidget/ImageWrapper.js +65 -0
  31. package/dist/cjs/toolbar/widgets/InsertImageWidget/fileToImages.d.ts +3 -0
  32. package/dist/cjs/toolbar/widgets/InsertImageWidget/fileToImages.js +21 -0
  33. package/dist/cjs/toolbar/widgets/InsertImageWidget/index.d.ts +37 -0
  34. package/dist/cjs/toolbar/widgets/InsertImageWidget/index.js +289 -0
  35. package/dist/cjs/toolbar/widgets/TextToolWidget.js +5 -3
  36. package/dist/cjs/toolbar/widgets/TextToolWidget.test.d.ts +1 -0
  37. package/dist/cjs/toolbar/widgets/components/makeFileInput.d.ts +12 -2
  38. package/dist/cjs/toolbar/widgets/components/makeFileInput.js +113 -45
  39. package/dist/cjs/toolbar/widgets/components/makeFileInput.test.d.ts +1 -0
  40. package/dist/cjs/toolbar/widgets/components/makeSnappedList.d.ts +15 -0
  41. package/dist/cjs/toolbar/widgets/components/makeSnappedList.js +168 -0
  42. package/dist/cjs/tools/Eraser.d.ts +7 -2
  43. package/dist/cjs/tools/Eraser.js +76 -6
  44. package/dist/cjs/tools/PanZoom.d.ts +54 -0
  45. package/dist/cjs/tools/PanZoom.js +54 -2
  46. package/dist/cjs/tools/SelectionTool/Selection.d.ts +2 -2
  47. package/dist/cjs/tools/SelectionTool/Selection.js +20 -20
  48. package/dist/cjs/tools/SelectionTool/SelectionHandle.d.ts +8 -2
  49. package/dist/cjs/tools/SelectionTool/SelectionHandle.js +6 -0
  50. package/dist/cjs/tools/SelectionTool/SelectionTool.js +1 -1
  51. package/dist/cjs/tools/SelectionTool/types.d.ts +19 -0
  52. package/dist/cjs/tools/TextTool.js +2 -1
  53. package/dist/cjs/tools/TextTool.test.d.ts +1 -0
  54. package/dist/cjs/tools/ToolController.d.ts +2 -0
  55. package/dist/cjs/tools/ToolController.js +10 -1
  56. package/dist/cjs/util/ReactiveValue.d.ts +6 -0
  57. package/dist/cjs/util/ReactiveValue.js +16 -0
  58. package/dist/cjs/util/bytesToSizeString.d.ts +8 -0
  59. package/dist/cjs/util/bytesToSizeString.js +26 -0
  60. package/dist/cjs/util/bytesToSizeString.test.d.ts +1 -0
  61. package/dist/cjs/util/stopPropagationOfScrollingWheelEvents.js +10 -6
  62. package/dist/cjs/util/waitForAll.d.ts +2 -0
  63. package/dist/cjs/util/waitForAll.js +2 -0
  64. package/dist/cjs/util/waitForImageLoaded.js +3 -0
  65. package/dist/cjs/util/waitForTimeout.d.ts +1 -0
  66. package/dist/cjs/util/waitForTimeout.js +1 -1
  67. package/dist/cjs/version.js +1 -1
  68. package/dist/mjs/Editor.d.ts +20 -1
  69. package/dist/mjs/Editor.mjs +6 -0
  70. package/dist/mjs/{SVGLoader.d.ts → SVGLoader/index.d.ts} +1 -1
  71. package/dist/mjs/{SVGLoader.mjs → SVGLoader/index.mjs} +15 -30
  72. package/dist/mjs/SVGLoader/index.test.d.ts +1 -0
  73. package/dist/mjs/SVGLoader/utils/determineFontSize.d.ts +3 -0
  74. package/dist/mjs/SVGLoader/utils/determineFontSize.mjs +25 -0
  75. package/dist/mjs/Viewport.d.ts +33 -1
  76. package/dist/mjs/components/TextComponent.mjs +3 -1
  77. package/dist/mjs/image/EditorImage.d.ts +2 -1
  78. package/dist/mjs/image/EditorImage.mjs +101 -5
  79. package/dist/mjs/rendering/caching/RenderingCacheNode.mjs +20 -15
  80. package/dist/mjs/rendering/renderers/CanvasRenderer.mjs +4 -4
  81. package/dist/mjs/testing/findNodeWithText.d.ts +3 -0
  82. package/dist/mjs/testing/findNodeWithText.mjs +14 -0
  83. package/dist/mjs/testing/firstElementAncestorOfNode.d.ts +3 -0
  84. package/dist/mjs/testing/firstElementAncestorOfNode.mjs +11 -0
  85. package/dist/mjs/testing/sendKeyPressRelease.d.ts +3 -0
  86. package/dist/mjs/testing/sendKeyPressRelease.mjs +6 -0
  87. package/dist/mjs/testing/sendPenEvent.d.ts +2 -2
  88. package/dist/mjs/testing/sendPenEvent.mjs +3 -3
  89. package/dist/mjs/toolbar/localization.d.ts +3 -0
  90. package/dist/mjs/toolbar/localization.mjs +3 -0
  91. package/dist/mjs/toolbar/widgets/BaseWidget.d.ts +1 -0
  92. package/dist/mjs/toolbar/widgets/BaseWidget.mjs +1 -0
  93. package/dist/mjs/toolbar/widgets/InsertImageWidget/ImageWrapper.d.ts +23 -0
  94. package/dist/mjs/toolbar/widgets/InsertImageWidget/ImageWrapper.mjs +61 -0
  95. package/dist/mjs/toolbar/widgets/InsertImageWidget/fileToImages.d.ts +3 -0
  96. package/dist/mjs/toolbar/widgets/InsertImageWidget/fileToImages.mjs +16 -0
  97. package/dist/mjs/toolbar/widgets/InsertImageWidget/index.d.ts +37 -0
  98. package/dist/mjs/toolbar/widgets/InsertImageWidget/index.mjs +284 -0
  99. package/dist/mjs/toolbar/widgets/InsertImageWidget/index.test.d.ts +1 -0
  100. package/dist/mjs/toolbar/widgets/TextToolWidget.mjs +5 -3
  101. package/dist/mjs/toolbar/widgets/TextToolWidget.test.d.ts +1 -0
  102. package/dist/mjs/toolbar/widgets/components/makeFileInput.d.ts +12 -2
  103. package/dist/mjs/toolbar/widgets/components/makeFileInput.mjs +113 -45
  104. package/dist/mjs/toolbar/widgets/components/makeFileInput.test.d.ts +1 -0
  105. package/dist/mjs/toolbar/widgets/components/makeSnappedList.d.ts +15 -0
  106. package/dist/mjs/toolbar/widgets/components/makeSnappedList.mjs +163 -0
  107. package/dist/mjs/tools/Eraser.d.ts +7 -2
  108. package/dist/mjs/tools/Eraser.mjs +76 -6
  109. package/dist/mjs/tools/PanZoom.d.ts +54 -0
  110. package/dist/mjs/tools/PanZoom.mjs +54 -2
  111. package/dist/mjs/tools/SelectionTool/Selection.d.ts +2 -2
  112. package/dist/mjs/tools/SelectionTool/Selection.mjs +20 -20
  113. package/dist/mjs/tools/SelectionTool/SelectionHandle.d.ts +8 -2
  114. package/dist/mjs/tools/SelectionTool/SelectionHandle.mjs +6 -0
  115. package/dist/mjs/tools/SelectionTool/SelectionTool.mjs +1 -1
  116. package/dist/mjs/tools/SelectionTool/types.d.ts +19 -0
  117. package/dist/mjs/tools/TextTool.mjs +2 -1
  118. package/dist/mjs/tools/TextTool.test.d.ts +1 -0
  119. package/dist/mjs/tools/ToolController.d.ts +2 -0
  120. package/dist/mjs/tools/ToolController.mjs +10 -1
  121. package/dist/mjs/util/ReactiveValue.d.ts +6 -0
  122. package/dist/mjs/util/ReactiveValue.mjs +16 -0
  123. package/dist/mjs/util/bytesToSizeString.d.ts +8 -0
  124. package/dist/mjs/util/bytesToSizeString.mjs +24 -0
  125. package/dist/mjs/util/bytesToSizeString.test.d.ts +1 -0
  126. package/dist/mjs/util/stopPropagationOfScrollingWheelEvents.mjs +10 -6
  127. package/dist/mjs/util/waitForAll.d.ts +2 -0
  128. package/dist/mjs/util/waitForAll.mjs +2 -0
  129. package/dist/mjs/util/waitForImageLoaded.mjs +3 -0
  130. package/dist/mjs/util/waitForTimeout.d.ts +1 -0
  131. package/dist/mjs/util/waitForTimeout.mjs +1 -1
  132. package/dist/mjs/version.mjs +1 -1
  133. package/package.json +4 -4
  134. package/src/toolbar/EdgeToolbar.scss +8 -3
  135. package/src/toolbar/toolbar.scss +1 -7
  136. package/src/toolbar/widgets/{InsertImageWidget.scss → InsertImageWidget/index.scss} +3 -2
  137. package/src/toolbar/widgets/components/components.scss +2 -1
  138. package/src/toolbar/widgets/components/makeFileInput.scss +14 -1
  139. package/src/toolbar/widgets/components/makeSnappedList.scss +74 -0
  140. package/src/toolbar/widgets/widgets.scss +7 -0
  141. package/dist/cjs/toolbar/widgets/InsertImageWidget.d.ts +0 -22
  142. package/dist/cjs/toolbar/widgets/InsertImageWidget.js +0 -269
  143. package/dist/mjs/toolbar/widgets/InsertImageWidget.d.ts +0 -22
  144. package/dist/mjs/toolbar/widgets/InsertImageWidget.mjs +0 -264
  145. /package/dist/cjs/{SVGLoader.test.d.ts → SVGLoader/index.test.d.ts} +0 -0
  146. /package/dist/{mjs/SVGLoader.test.d.ts → cjs/toolbar/widgets/InsertImageWidget/index.test.d.ts} +0 -0
@@ -0,0 +1,284 @@
1
+ import ImageComponent from '../../../components/ImageComponent.mjs';
2
+ import Erase from '../../../commands/Erase.mjs';
3
+ import EditorImage from '../../../image/EditorImage.mjs';
4
+ import uniteCommands from '../../../commands/uniteCommands.mjs';
5
+ import SelectionTool from '../../../tools/SelectionTool/SelectionTool.mjs';
6
+ import { Mat33, Vec2 } from '@js-draw/math';
7
+ import BaseWidget from '../BaseWidget.mjs';
8
+ import { EditorEventType } from '../../../types.mjs';
9
+ import { toolbarCSSPrefix } from '../../constants.mjs';
10
+ import makeFileInput from '../components/makeFileInput.mjs';
11
+ import { MutableReactiveValue } from '../../../util/ReactiveValue.mjs';
12
+ import bytesToSizeString from '../../../util/bytesToSizeString.mjs';
13
+ import { ImageWrapper } from './ImageWrapper.mjs';
14
+ import makeSnappedList from '../components/makeSnappedList.mjs';
15
+ import fileToImages from './fileToImages.mjs';
16
+ /**
17
+ * Provides a widget that allows inserting or modifying raster images.
18
+ *
19
+ * It's possible to customize the file picker used by this widget through {@link EditorSettings.image}.
20
+ *
21
+ * @example
22
+ * ```ts,runnable
23
+ * import { Editor, makeEdgeToolbar, InsertImageWidget } from 'js-draw';
24
+ *
25
+ * const editor = new Editor(document.body);
26
+ * const toolbar = makeEdgeToolbar(editor);
27
+ *
28
+ * toolbar.addWidget(new InsertImageWidget(editor));
29
+ * ```
30
+ */
31
+ class InsertImageWidget extends BaseWidget {
32
+ constructor(editor, localization) {
33
+ localization ??= editor.localization;
34
+ super(editor, 'insert-image-widget', localization);
35
+ // Make the dropdown showable
36
+ this.container.classList.add('dropdownShowable');
37
+ editor.notifier.on(EditorEventType.SelectionUpdated, event => {
38
+ if (event.kind === EditorEventType.SelectionUpdated && this.isDropdownVisible()) {
39
+ this.updateInputs();
40
+ }
41
+ });
42
+ this.images = MutableReactiveValue.fromInitialValue([]);
43
+ this.images.onUpdateAndNow(() => {
44
+ this.onImageDataUpdate();
45
+ });
46
+ }
47
+ getTitle() {
48
+ return this.localizationTable.image;
49
+ }
50
+ createIcon() {
51
+ return this.editor.icons.makeInsertImageIcon();
52
+ }
53
+ setDropdownVisible(visible) {
54
+ super.setDropdownVisible(visible);
55
+ // Update the dropdown just before showing.
56
+ if (this.isDropdownVisible()) {
57
+ this.updateInputs();
58
+ }
59
+ else {
60
+ // Allow any previously-selected files to be freed.
61
+ this.selectedFiles?.set([]);
62
+ }
63
+ }
64
+ handleClick() {
65
+ this.setDropdownVisible(!this.isDropdownVisible());
66
+ }
67
+ fillDropdown(dropdown) {
68
+ const container = document.createElement('div');
69
+ container.classList.add('insert-image-widget-dropdown-content', `${toolbarCSSPrefix}spacedList`, `${toolbarCSSPrefix}nonbutton-controls-main-list`);
70
+ const { container: chooseImageRow, selectedFiles, } = makeFileInput(this.localizationTable.chooseFile, this.editor, {
71
+ accepts: 'image/*',
72
+ allowMultiSelect: true,
73
+ customPickerAction: this.editor.getCurrentSettings().image?.showImagePicker,
74
+ });
75
+ const altTextRow = document.createElement('div');
76
+ this.imagesPreview = makeSnappedList(this.images);
77
+ this.statusView = document.createElement('div');
78
+ const actionButtonRow = document.createElement('div');
79
+ actionButtonRow.classList.add('action-button-row');
80
+ this.statusView.classList.add('insert-image-image-status-view');
81
+ this.submitButton = document.createElement('button');
82
+ this.selectedFiles = selectedFiles;
83
+ this.imageAltTextInput = document.createElement('input');
84
+ // Label the alt text input
85
+ const imageAltTextLabel = document.createElement('label');
86
+ const altTextInputId = `insert-image-alt-text-input-${InsertImageWidget.nextInputId++}`;
87
+ this.imageAltTextInput.setAttribute('id', altTextInputId);
88
+ imageAltTextLabel.htmlFor = altTextInputId;
89
+ imageAltTextLabel.innerText = this.localizationTable.inputAltText;
90
+ this.imageAltTextInput.type = 'text';
91
+ this.imageAltTextInput.placeholder = this.localizationTable.describeTheImage;
92
+ this.statusView.setAttribute('aria-live', 'polite');
93
+ this.submitButton.innerText = this.localizationTable.submit;
94
+ this.imagesPreview.visibleItem.onUpdateAndNow(() => this.onImageDataUpdate());
95
+ this.imageAltTextInput.oninput = () => {
96
+ const currentImage = this.imagesPreview.visibleItem.get();
97
+ if (currentImage) {
98
+ currentImage.setAltText(this.imageAltTextInput.value);
99
+ this.submitButton.style.display = '';
100
+ }
101
+ };
102
+ this.selectedFiles.onUpdateAndNow(async (files) => {
103
+ if (files.length === 0) {
104
+ this.images.set([]);
105
+ return;
106
+ }
107
+ const previews = (await Promise.all(files.map(async (imageFile) => {
108
+ let renderableImages;
109
+ try {
110
+ renderableImages = await fileToImages(imageFile);
111
+ }
112
+ catch (error) {
113
+ console.error('Image load error', error);
114
+ const errorMessage = this.localizationTable.imageLoadError(error);
115
+ this.statusView.innerText = errorMessage;
116
+ return [];
117
+ }
118
+ return renderableImages.map(image => {
119
+ const { wrapper, preview } = ImageWrapper.fromRenderable(image, () => this.onImageDataUpdate());
120
+ return {
121
+ data: wrapper,
122
+ element: preview,
123
+ };
124
+ });
125
+ }))).flat();
126
+ this.images.set(previews);
127
+ });
128
+ altTextRow.replaceChildren(imageAltTextLabel, this.imageAltTextInput);
129
+ actionButtonRow.replaceChildren(this.submitButton);
130
+ container.replaceChildren(chooseImageRow, altTextRow, this.imagesPreview.container, this.statusView, actionButtonRow);
131
+ dropdown.replaceChildren(container);
132
+ return true;
133
+ }
134
+ onImageDataUpdate() {
135
+ if (!this.imagesPreview)
136
+ return;
137
+ const currentImage = this.imagesPreview.visibleItem.get();
138
+ const base64Data = currentImage?.getBase64Url();
139
+ this.imageAltTextInput.value = currentImage?.getAltText() ?? '';
140
+ if (base64Data) {
141
+ this.submitButton.disabled = false;
142
+ this.submitButton.style.display = '';
143
+ this.updateImageSizeDisplay();
144
+ }
145
+ else {
146
+ this.submitButton.disabled = true;
147
+ this.submitButton.style.display = 'none';
148
+ this.statusView.innerText = '';
149
+ this.submitButton.disabled = true;
150
+ }
151
+ if (this.images.get().length <= 1) {
152
+ this.submitButton.innerText = this.localizationTable.submit;
153
+ }
154
+ else {
155
+ this.submitButton.innerText = this.localizationTable.addAll;
156
+ }
157
+ }
158
+ hideDialog() {
159
+ this.setDropdownVisible(false);
160
+ }
161
+ updateImageSizeDisplay() {
162
+ const currentImage = this.imagesPreview.visibleItem.get();
163
+ const imageData = currentImage?.getBase64Url() ?? '';
164
+ const { size, units } = bytesToSizeString(imageData.length);
165
+ const sizeText = document.createElement('span');
166
+ sizeText.innerText = this.localizationTable.imageSize(Math.round(size), units);
167
+ // Add a button to allow decreasing the size of large images.
168
+ const decreaseSizeButton = document.createElement('button');
169
+ decreaseSizeButton.innerText = this.localizationTable.decreaseImageSize;
170
+ decreaseSizeButton.onclick = () => {
171
+ currentImage?.decreaseSize();
172
+ };
173
+ const resetSizeButton = document.createElement('button');
174
+ resetSizeButton.innerText = this.localizationTable.resetImage;
175
+ resetSizeButton.onclick = () => {
176
+ currentImage?.reset();
177
+ };
178
+ this.statusView.replaceChildren(sizeText);
179
+ if (currentImage?.isLarge()) {
180
+ this.statusView.appendChild(decreaseSizeButton);
181
+ }
182
+ else if (currentImage?.isChanged()) {
183
+ this.statusView.appendChild(resetSizeButton);
184
+ }
185
+ else {
186
+ const hasLargeOrChangedImages = this.images.get().some(image => image.data?.isChanged() || image.data?.isLarge());
187
+ if (hasLargeOrChangedImages) {
188
+ // Still show the button -- prevents the layout from readjusting while
189
+ // scrolling through the image list
190
+ decreaseSizeButton.disabled = true;
191
+ this.statusView.appendChild(decreaseSizeButton);
192
+ }
193
+ }
194
+ }
195
+ updateInputs() {
196
+ const resetInputs = () => {
197
+ this.selectedFiles?.set([]);
198
+ this.imageAltTextInput.value = '';
199
+ this.submitButton.disabled = true;
200
+ this.statusView.innerText = '';
201
+ this.submitButton.style.display = '';
202
+ };
203
+ resetInputs();
204
+ const selectionTools = this.editor.toolController.getMatchingTools(SelectionTool);
205
+ const selectedObjects = selectionTools.map(tool => tool.getSelectedObjects()).flat();
206
+ // Check: Is there a selected image that can be edited?
207
+ let editingImage = null;
208
+ if (selectedObjects.length === 1 && selectedObjects[0] instanceof ImageComponent) {
209
+ editingImage = selectedObjects[0];
210
+ const image = new Image();
211
+ const imageWrapper = ImageWrapper.fromSrcAndPreview(editingImage.getURL(), image, () => this.onImageDataUpdate());
212
+ imageWrapper.setAltText(editingImage.getAltText() ?? '');
213
+ this.images.set([{ data: imageWrapper, element: image }]);
214
+ }
215
+ else if (selectedObjects.length > 0) {
216
+ // If not, clear the selection.
217
+ selectionTools.forEach(tool => tool.clearSelection());
218
+ }
219
+ // Show the submit button only when there is data to submit.
220
+ this.submitButton.style.display = 'none';
221
+ this.submitButton.onclick = async () => {
222
+ const newComponents = [];
223
+ let transform = Mat33.identity;
224
+ let fullBBox = null;
225
+ for (const { data: imageWrapper } of this.images.get()) {
226
+ if (!imageWrapper) {
227
+ continue;
228
+ }
229
+ const image = new Image();
230
+ image.src = imageWrapper.getBase64Url();
231
+ image.setAttribute('alt', this.imageAltTextInput.value);
232
+ let component;
233
+ try {
234
+ component = await ImageComponent.fromImage(image, transform);
235
+ }
236
+ catch (error) {
237
+ console.error('Error loading image', error);
238
+ this.statusView.innerText = this.localizationTable.imageLoadError(error);
239
+ return;
240
+ }
241
+ const componentBBox = component.getBBox();
242
+ if (componentBBox.area === 0) {
243
+ this.statusView.innerText = this.localizationTable.errorImageHasZeroSize;
244
+ return;
245
+ }
246
+ newComponents.push(component);
247
+ fullBBox ??= componentBBox;
248
+ fullBBox.union(componentBBox);
249
+ // Update the transform for the next item.
250
+ const shift = Vec2.of(0, componentBBox.height);
251
+ transform = transform.rightMul(Mat33.translation(shift));
252
+ }
253
+ if (newComponents.length) {
254
+ if (!fullBBox) {
255
+ throw new Error('Logic error: Full bounding box must be calculated when components are to be added.');
256
+ }
257
+ this.hideDialog();
258
+ if (editingImage) {
259
+ const eraseCommand = new Erase([editingImage]);
260
+ // Try to preserve the original width
261
+ const originalTransform = editingImage.getTransformation();
262
+ // || 1: Prevent division by zero
263
+ const originalWidth = editingImage.getBBox().width || 1;
264
+ const newWidth = fullBBox.transformedBoundingBox(originalTransform).width || 1;
265
+ const widthAdjustTransform = Mat33.scaling2D(originalWidth / newWidth);
266
+ const commands = [];
267
+ for (const component of newComponents) {
268
+ commands.push(EditorImage.addElement(component), component.transformBy(originalTransform.rightMul(widthAdjustTransform)), component.setZIndex(editingImage.getZIndex()));
269
+ }
270
+ this.editor.dispatch(uniteCommands([
271
+ ...commands,
272
+ eraseCommand,
273
+ ]));
274
+ selectionTools[0]?.setSelection(newComponents);
275
+ }
276
+ else {
277
+ await this.editor.addAndCenterComponents(newComponents);
278
+ }
279
+ }
280
+ };
281
+ }
282
+ }
283
+ InsertImageWidget.nextInputId = 0;
284
+ export default InsertImageWidget;
@@ -54,9 +54,11 @@ class TextToolWidget extends BaseToolWidget {
54
54
  colorLabel.setAttribute('for', colorInput.id);
55
55
  sizeInput.id = `${toolbarCSSPrefix}-text-size-input-${TextToolWidget.idCounter++}`;
56
56
  sizeLabel.setAttribute('for', sizeInput.id);
57
- addFontToInput('monospace');
58
- addFontToInput('serif');
59
- addFontToInput('sans-serif');
57
+ const defaultFonts = this.editor.getCurrentSettings().text?.fonts ?? [];
58
+ for (const font of defaultFonts) {
59
+ addFontToInput(font);
60
+ }
61
+ fontInput.classList.add('font-selector');
60
62
  fontInput.id = `${toolbarCSSPrefix}-text-font-input-${TextToolWidget.idCounter++}`;
61
63
  fontLabel.setAttribute('for', fontInput.id);
62
64
  fontInput.onchange = () => {
@@ -0,0 +1 @@
1
+ export {};
@@ -1,9 +1,19 @@
1
1
  import { MutableReactiveValue } from '../../../util/ReactiveValue';
2
2
  import { ToolbarContext } from '../../types';
3
+ export interface CustomFilePickerProps {
4
+ setOnCancelCallback(onCancel: () => void): void;
5
+ }
6
+ export type ShowCustomFilePickerCallback = (props: CustomFilePickerProps) => Promise<File[] | null>;
7
+ export interface FileInputOptions {
8
+ readonly accepts?: string;
9
+ readonly allowMultiSelect?: boolean;
10
+ readonly customPickerAction?: ShowCustomFilePickerCallback;
11
+ }
3
12
  /**
4
- * Creates a stylized file input.
13
+ * Creates a stylized file input. This file input can either use the system file picker, or a custom
14
+ * one specified by `customPickerAction`.
5
15
  */
6
- declare const makeFileInput: (labelText: string, context: ToolbarContext, accepts?: string) => {
16
+ declare const makeFileInput: (labelText: string, context: ToolbarContext, { accepts, allowMultiSelect, customPickerAction }?: FileInputOptions) => {
7
17
  container: HTMLDivElement;
8
18
  input: HTMLInputElement;
9
19
  selectedFiles: MutableReactiveValue<File[]>;
@@ -1,9 +1,10 @@
1
1
  import ReactiveValue from '../../../util/ReactiveValue.mjs';
2
2
  let idCounter = 0;
3
3
  /**
4
- * Creates a stylized file input.
4
+ * Creates a stylized file input. This file input can either use the system file picker, or a custom
5
+ * one specified by `customPickerAction`.
5
6
  */
6
- const makeFileInput = (labelText, context, accepts = '*') => {
7
+ const makeFileInput = (labelText, context, { accepts = '*', allowMultiSelect = false, customPickerAction } = {}) => {
7
8
  const container = document.createElement('div');
8
9
  const label = document.createElement('label');
9
10
  const input = document.createElement('input');
@@ -13,7 +14,9 @@ const makeFileInput = (labelText, context, accepts = '*') => {
13
14
  container.classList.add('toolbar--file-input-container');
14
15
  label.appendChild(document.createTextNode(labelText));
15
16
  input.accept = accepts;
16
- input.type = 'file';
17
+ input.type = customPickerAction ? 'button' : 'file';
18
+ input.classList.add('file-input');
19
+ input.multiple = allowMultiSelect;
17
20
  // Associate the label with the input
18
21
  const inputId = `js-draw-file-input-${idCounter++}`;
19
22
  input.setAttribute('id', inputId);
@@ -24,48 +27,33 @@ const makeFileInput = (labelText, context, accepts = '*') => {
24
27
  label.appendChild(descriptionBox);
25
28
  container.replaceChildren(label, input);
26
29
  const selectedFiles = ReactiveValue.fromInitialValue([]);
27
- // Support droping files
28
- label.addEventListener('dragover', event => {
29
- event.preventDefault();
30
- label.classList.add('drag-target');
31
- });
32
- label.addEventListener('dragenter', event => {
33
- event.preventDefault();
34
- label.classList.add('drag-target');
35
- });
36
- label.addEventListener('dragleave', event => {
37
- event.preventDefault();
38
- // Ensure the event wasn't targeting a child.
39
- // See https://stackoverflow.com/a/54271161 and
40
- // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget
41
- const enteringElement = event.relatedTarget;
42
- if (!enteringElement || !label.contains(enteringElement)) {
43
- label.classList.remove('drag-target');
44
- }
45
- });
46
- // See https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop#process_the_drop
47
- label.addEventListener('drop', event => {
48
- event.preventDefault();
49
- label.classList.remove('drag-target');
50
- const fileList = [];
51
- if (event.dataTransfer) {
52
- fileList.push(...event.dataTransfer.files);
53
- }
54
- selectedFiles.set(fileList);
55
- });
56
- input.addEventListener('change', () => {
57
- const fileList = input.files ?? [];
58
- selectedFiles.set([...fileList]);
59
- });
60
- selectedFiles.onUpdate(files => {
61
- if (files.length === 0 && input.files && input.files.length > 0) {
62
- input.value = '';
30
+ let loading = false;
31
+ let cancelLoading = null;
32
+ const updateStatusText = () => {
33
+ const files = selectedFiles.get();
34
+ if (loading) {
35
+ descriptionText.textContent = context.localization.fileInput__loading;
36
+ if (cancelLoading) {
37
+ const cancelText = document.createElement('b');
38
+ cancelText.textContent = context.localization.cancel;
39
+ cancelText.classList.add('cancel-button');
40
+ descriptionText.appendChild(cancelText);
41
+ }
42
+ icon.style.display = 'none';
63
43
  }
64
- });
65
- // Update the status text and hide/show the icon.
66
- selectedFiles.onUpdateAndNow(files => {
67
- if (files.length > 0) {
68
- descriptionText.innerText = files.map(file => file.name).join('\n');
44
+ else if (files.length > 0) {
45
+ const fileNames = files.map(file => file.name);
46
+ const maxNames = 5;
47
+ if (fileNames.length <= maxNames) {
48
+ descriptionText.textContent = fileNames.join('\n');
49
+ }
50
+ else {
51
+ const fileNamesToShow = fileNames.slice(0, maxNames - 1);
52
+ descriptionText.textContent = [
53
+ ...fileNamesToShow,
54
+ context.localization.fileInput__andNMoreFiles(fileNames.length - fileNamesToShow.length),
55
+ ].join('\n');
56
+ }
69
57
  // Only show the icon when there are files
70
58
  icon.style.display = 'none';
71
59
  }
@@ -85,7 +73,7 @@ const makeFileInput = (labelText, context, accepts = '*') => {
85
73
  // Inside a {{pair of curly braces}}?
86
74
  if (i % 2 === 1) {
87
75
  const boldedText = document.createElement('b');
88
- boldedText.innerText = segments[i];
76
+ boldedText.textContent = segments[i];
89
77
  descriptionText.appendChild(boldedText);
90
78
  }
91
79
  else {
@@ -93,7 +81,87 @@ const makeFileInput = (labelText, context, accepts = '*') => {
93
81
  }
94
82
  }
95
83
  }
84
+ };
85
+ const addFileEventListeners = () => {
86
+ // Support dropping files
87
+ label.addEventListener('dragover', event => {
88
+ event.preventDefault();
89
+ label.classList.add('drag-target');
90
+ });
91
+ label.addEventListener('dragenter', event => {
92
+ event.preventDefault();
93
+ label.classList.add('drag-target');
94
+ });
95
+ label.addEventListener('dragleave', event => {
96
+ event.preventDefault();
97
+ // Ensure the event wasn't targeting a child.
98
+ // See https://stackoverflow.com/a/54271161 and
99
+ // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget
100
+ const enteringElement = event.relatedTarget;
101
+ if (!enteringElement || !label.contains(enteringElement)) {
102
+ label.classList.remove('drag-target');
103
+ }
104
+ });
105
+ // See https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop#process_the_drop
106
+ label.addEventListener('drop', event => {
107
+ event.preventDefault();
108
+ label.classList.remove('drag-target');
109
+ const fileList = [];
110
+ if (event.dataTransfer) {
111
+ fileList.push(...event.dataTransfer.files);
112
+ }
113
+ selectedFiles.set(fileList);
114
+ });
115
+ input.addEventListener('change', () => {
116
+ const fileList = input.files ?? [];
117
+ selectedFiles.set([...fileList]);
118
+ });
119
+ };
120
+ addFileEventListeners();
121
+ // Support for custom file pickers
122
+ if (customPickerAction) {
123
+ const promptForFiles = async () => {
124
+ if (loading) {
125
+ cancelLoading?.();
126
+ return;
127
+ }
128
+ container.classList.add('-loading');
129
+ loading = true;
130
+ updateStatusText();
131
+ try {
132
+ const data = await customPickerAction({
133
+ setOnCancelCallback: (onCancel) => {
134
+ if (!loading) {
135
+ throw new Error('Task already completed. Can\'t register cancel handler.');
136
+ }
137
+ cancelLoading = () => {
138
+ cancelLoading = null;
139
+ updateStatusText();
140
+ onCancel();
141
+ };
142
+ updateStatusText();
143
+ },
144
+ });
145
+ if (data) {
146
+ selectedFiles.set(data);
147
+ }
148
+ }
149
+ finally {
150
+ container.classList.remove('-loading');
151
+ loading = false;
152
+ updateStatusText();
153
+ }
154
+ };
155
+ input.onclick = promptForFiles;
156
+ }
157
+ selectedFiles.onUpdate(files => {
158
+ if (files.length === 0 && input.files && input.files.length > 0) {
159
+ input.value = '';
160
+ }
161
+ cancelLoading?.();
96
162
  });
163
+ // Update the status text and hide/show the icon.
164
+ selectedFiles.onUpdateAndNow(updateStatusText);
97
165
  return {
98
166
  container,
99
167
  input,
@@ -0,0 +1,15 @@
1
+ import { ReactiveValue } from '../../../util/ReactiveValue';
2
+ export interface SnappedListItem<DataType> {
3
+ element: HTMLElement;
4
+ data: DataType;
5
+ }
6
+ type SnappedListItems<DataType> = Array<SnappedListItem<DataType>>;
7
+ export interface SnappedListControl<DataType> {
8
+ container: HTMLElement;
9
+ visibleItem: ReactiveValue<DataType | null>;
10
+ }
11
+ /**
12
+ * Creates a list that snaps to each item and reports the selected item.
13
+ */
14
+ declare const makeSnappedList: <DataType>(itemsValue: ReactiveValue<SnappedListItems<DataType>>) => SnappedListControl<DataType>;
15
+ export default makeSnappedList;