@windwalker-io/unicorn-next 0.1.2 → 0.1.4

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 (132) hide show
  1. package/.editorconfig +18 -18
  2. package/.gulp.json +7 -7
  3. package/bin/release.mjs +47 -47
  4. package/dist/chunks/button-radio.js.map +1 -1
  5. package/dist/chunks/checkboxes-multi-select.js.map +1 -1
  6. package/dist/chunks/field-cascade-select.js.map +1 -1
  7. package/dist/chunks/field-file-drag.js +34 -31
  8. package/dist/chunks/field-file-drag.js.map +1 -1
  9. package/dist/chunks/field-flatpickr.js +10 -3
  10. package/dist/chunks/field-flatpickr.js.map +1 -1
  11. package/dist/chunks/field-modal-select.js +6 -2
  12. package/dist/chunks/field-modal-select.js.map +1 -1
  13. package/dist/chunks/field-modal-tree.js +10 -4
  14. package/dist/chunks/field-modal-tree.js.map +1 -1
  15. package/dist/chunks/field-multi-uploader.js +10 -3
  16. package/dist/chunks/field-multi-uploader.js.map +1 -1
  17. package/dist/chunks/field-repeatable.js.map +1 -1
  18. package/dist/chunks/field-single-image-drag.js +12 -7
  19. package/dist/chunks/field-single-image-drag.js.map +1 -1
  20. package/dist/chunks/form.js.map +1 -1
  21. package/dist/chunks/grid.js.map +1 -1
  22. package/dist/chunks/http-client.js.map +1 -1
  23. package/dist/chunks/iframe-modal.js +27 -24
  24. package/dist/chunks/iframe-modal.js.map +1 -1
  25. package/dist/chunks/keep-tab.js.map +1 -1
  26. package/dist/chunks/legacy.js.map +1 -1
  27. package/dist/chunks/list-dependent.js.map +1 -1
  28. package/dist/chunks/s3-multipart-uploader.js.map +1 -1
  29. package/dist/chunks/s3-uploader.js.map +1 -1
  30. package/dist/chunks/show-on.js.map +1 -1
  31. package/dist/chunks/tinymce.js.map +1 -1
  32. package/dist/chunks/ui-bootstrap5.js.map +1 -1
  33. package/dist/chunks/unicorn.js +10 -6
  34. package/dist/chunks/unicorn.js.map +1 -1
  35. package/dist/chunks/validation.js.map +1 -1
  36. package/dist/index.d.ts +47 -26
  37. package/dist/unicorn.js +3 -3
  38. package/fusionfile.mjs +155 -155
  39. package/package.json +103 -103
  40. package/scss/bootstrap/multi-level-menu.scss +121 -121
  41. package/scss/editor.scss +116 -116
  42. package/scss/field/file-drag.scss +102 -102
  43. package/scss/field/single-image-drag.scss +88 -88
  44. package/scss/field/vue-drag-uploader.scss +160 -160
  45. package/scss/switcher.scss +156 -156
  46. package/src/app.ts +128 -128
  47. package/src/bootstrap/button-radio.ts +208 -208
  48. package/src/bootstrap/keep-tab.ts +155 -155
  49. package/src/composable/index.ts +21 -21
  50. package/src/composable/useCheckboxesMultiSelect.ts +22 -22
  51. package/src/composable/useFieldCascadeSelect.ts +9 -9
  52. package/src/composable/useFieldFileDrag.ts +9 -9
  53. package/src/composable/useFieldFlatpickr.ts +3 -3
  54. package/src/composable/useFieldModalSelect.ts +6 -6
  55. package/src/composable/useFieldModalTree.ts +3 -3
  56. package/src/composable/useFieldMultiUploader.ts +9 -3
  57. package/src/composable/useFieldRepeatable.ts +9 -9
  58. package/src/composable/useFieldSingleImageDrag.ts +9 -5
  59. package/src/composable/useForm.ts +43 -43
  60. package/src/composable/useGrid.ts +57 -57
  61. package/src/composable/useHttp.ts +9 -9
  62. package/src/composable/useIframeModal.ts +10 -10
  63. package/src/composable/useListDependent.ts +26 -26
  64. package/src/composable/useQueue.ts +13 -13
  65. package/src/composable/useS3Uploader.ts +32 -32
  66. package/src/composable/useShowOn.ts +9 -9
  67. package/src/composable/useStack.ts +13 -13
  68. package/src/composable/useTinymce.ts +29 -29
  69. package/src/composable/useTomSelect.ts +72 -72
  70. package/src/composable/useUIBootstrap5.ts +48 -48
  71. package/src/composable/useUniDirective.ts +32 -32
  72. package/src/composable/useValidation.ts +39 -39
  73. package/src/data.ts +34 -34
  74. package/src/events.ts +82 -82
  75. package/src/legacy/legacy.ts +190 -190
  76. package/src/legacy/loader.ts +125 -125
  77. package/src/module/checkboxes-multi-select.ts +54 -54
  78. package/src/module/field-cascade-select.ts +292 -292
  79. package/src/module/field-file-drag.ts +295 -292
  80. package/src/module/field-flatpickr.ts +130 -127
  81. package/src/module/field-modal-select.ts +179 -174
  82. package/src/module/field-modal-tree.ts +31 -27
  83. package/src/module/field-multi-uploader.ts +368 -361
  84. package/src/module/field-repeatable.ts +202 -202
  85. package/src/module/field-single-image-drag.ts +475 -468
  86. package/src/module/form.ts +223 -223
  87. package/src/module/grid.ts +465 -465
  88. package/src/module/http-client.ts +248 -248
  89. package/src/module/iframe-modal.ts +170 -167
  90. package/src/module/list-dependent.ts +321 -321
  91. package/src/module/s3-multipart-uploader.ts +300 -300
  92. package/src/module/s3-uploader.ts +234 -234
  93. package/src/module/show-on.ts +175 -175
  94. package/src/module/tinymce.ts +276 -276
  95. package/src/module/ui-bootstrap5.ts +116 -116
  96. package/src/module/validation.ts +1026 -1026
  97. package/src/plugin/index.ts +1 -1
  98. package/src/plugin/php-adapter.ts +72 -72
  99. package/src/polyfill/form-request-submit.ts +31 -31
  100. package/src/polyfill/index.ts +9 -9
  101. package/src/service/animate.ts +58 -58
  102. package/src/service/crypto.ts +27 -27
  103. package/src/service/dom-watcher.ts +62 -62
  104. package/src/service/dom.ts +265 -265
  105. package/src/service/helper.ts +48 -48
  106. package/src/service/index.ts +10 -10
  107. package/src/service/lang.ts +122 -122
  108. package/src/service/loader.ts +152 -152
  109. package/src/service/router.ts +118 -118
  110. package/src/service/ui.ts +525 -525
  111. package/src/service/uri.ts +106 -106
  112. package/src/types/base.ts +9 -9
  113. package/src/types/index.ts +4 -4
  114. package/src/types/modal-tree.ts +12 -12
  115. package/src/types/plugin.ts +6 -6
  116. package/src/types/shims.d.ts +18 -18
  117. package/src/types/ui.ts +6 -6
  118. package/src/unicorn.ts +79 -79
  119. package/src/utilities/arr.ts +25 -25
  120. package/src/utilities/base.ts +9 -9
  121. package/src/utilities/data.ts +48 -48
  122. package/src/utilities/index.ts +5 -5
  123. package/src/utilities/tree.ts +20 -20
  124. package/src/vue/components/ModalTree/ModalTreeApp.vue +175 -175
  125. package/src/vue/components/ModalTree/TreeItem.vue +262 -262
  126. package/src/vue/components/ModalTree/TreeModal.vue +225 -225
  127. package/tests/test.js +4 -4
  128. package/tsconfig.js.json +25 -25
  129. package/tsconfig.json +17 -17
  130. package/vite.assets.config.ts +61 -61
  131. package/vite.config.test.ts +36 -36
  132. package/vite.config.ts +112 -112
@@ -1,468 +1,475 @@
1
-
2
- import { useHttpClient } from '../composable';
3
- import { __, injectCssToDocument, selectAll, simpleAlert } from '../service';
4
- import { mergeDeep } from '../utilities';
5
- import css from '../../scss/field/single-image-drag.scss?inline';
6
- import { Modal } from 'bootstrap';
7
- import type Cropper from 'cropperjs';
8
- import { ApiReturn } from './http-client';
9
-
10
- injectCssToDocument(css);
11
-
12
- export interface SingleImageDragOptions {
13
- accept: string | string[];
14
- ajax_url?: string;
15
- crop: boolean;
16
- width: number;
17
- height: number;
18
- max_width?: number;
19
- min_width?: number;
20
- max_height?: number;
21
- min_height?: number;
22
- modalTarget: string;
23
- }
24
-
25
- const defaultOptions: Partial<SingleImageDragOptions> = {
26
- accept: [
27
- 'image/jpeg',
28
- 'image/png',
29
- 'image/webp',
30
- 'image/avif',
31
- 'image/gif',
32
- ],
33
- crop: false,
34
- width: 800,
35
- height: 800,
36
- };
37
-
38
- export class SingleImageDragElement extends HTMLElement {
39
- static is = 'uni-sid';
40
-
41
- currentImage = '';
42
- currentFile: File | undefined = undefined;
43
- lastZoom = 0;
44
- valueBackup = '';
45
-
46
- private options!: SingleImageDragOptions;
47
- private valueInput!: HTMLInputElement;
48
- private fileInput!: HTMLInputElement;
49
- private selectButton!: HTMLButtonElement;
50
- private pasteButton!: HTMLButtonElement;
51
- private dragarea!: HTMLDivElement;
52
- private previewImage!: HTMLImageElement;
53
- private removeCheckbox!: HTMLInputElement;
54
- private modalElement!: HTMLDivElement;
55
- private modal!: Modal;
56
- private cropContainer!: HTMLDivElement;
57
- private savebutton!: HTMLButtonElement;
58
- private modalToolbarButtons!: NodeListOf<HTMLButtonElement>;
59
- private cropper!: Cropper;
60
-
61
- constructor() {
62
- super();
63
- }
64
-
65
- connectedCallback() {
66
- this.options = mergeDeep(
67
- {},
68
- defaultOptions,
69
- JSON.parse(this.getAttribute('options') || '{}')
70
- );
71
-
72
- this.valueInput = this.querySelector<HTMLInputElement>('[data-field-input]')!;
73
- this.fileInput = this.querySelector<HTMLInputElement>('[data-sid=file]')!;
74
- this.selectButton = this.querySelector<HTMLButtonElement>('[data-sid=select]')!;
75
- this.pasteButton = this.querySelector<HTMLButtonElement>('[data-sid=paste]')!;
76
- this.dragarea = this.querySelector<HTMLDivElement>('[data-sid=dragarea]')!;
77
- this.previewImage = this.querySelector<HTMLImageElement>('[data-sid=preview]')!;
78
- this.removeCheckbox = this.querySelector<HTMLInputElement>('[data-sid=remove]')!;
79
-
80
- this.modalElement = document.querySelector<HTMLDivElement>(this.options.modalTarget)!;
81
- this.modal = Modal.getOrCreateInstance(this.modalElement);
82
- this.cropContainer = this.modalElement.querySelector<HTMLDivElement>('[data-sid="crop-container"]')!;
83
- this.savebutton = this.modalElement.querySelector<HTMLButtonElement>('[data-sid=save-button]')!;
84
- this.modalToolbarButtons = this.modalElement.querySelectorAll<HTMLButtonElement>('[data-sid-toolbar]');
85
-
86
- const modalShown = async () => {
87
- const cropper = await this.getCropper();
88
- cropper.replace(this.currentImage);
89
- this.cropContainer.style.visibility = '';
90
- this.currentImage = '';
91
- };
92
-
93
- this.modalElement.addEventListener('shown.bs.modal', modalShown.bind(this));
94
-
95
- this.savebutton.addEventListener('click', () => {
96
- this.saveCropped();
97
- this.modal.hide();
98
- });
99
-
100
- this.bindEvents();
101
-
102
- this.style.visibility = '';
103
- }
104
-
105
- bindEvents() {
106
- this.dragarea.addEventListener('dragover', (event) => {
107
- event.stopPropagation();
108
- event.preventDefault();
109
-
110
- this.dragarea.classList.add('hover');
111
- });
112
-
113
- this.dragarea.addEventListener('dragleave', (event) => {
114
- event.stopPropagation();
115
- event.preventDefault();
116
-
117
- this.dragarea.classList.remove('hover');
118
- });
119
-
120
- this.dragarea.addEventListener('drop', (event) => {
121
- event.stopPropagation();
122
- event.preventDefault();
123
-
124
- this.dragarea.classList.remove('hover');
125
-
126
- const files = (event.target as HTMLInputElement).files || event.dataTransfer?.files || [];
127
- this.handleFileSelect(files[0]);
128
- });
129
-
130
- // Select button
131
- this.selectButton.addEventListener('click', () => {
132
- const input = document.createElement('input');
133
- input.setAttribute('type', 'file');
134
- input.setAttribute('accept', this.getInputAccept());
135
- input.style.display = 'none';
136
- input.addEventListener('change', (e) => {
137
- this.handleFileSelect(input.files![0]!);
138
-
139
- input.remove();
140
- });
141
-
142
- document.body.appendChild(input);
143
- input.click();
144
- });
145
-
146
- this.pasteButton.addEventListener('click', () => {
147
- navigator.clipboard.read().then((items) => {
148
- let types = items[0].types;
149
-
150
- if (types.length === 0) {
151
- this.alert('This browser unable to get clipboard data.');
152
- return;
153
- }
154
-
155
- types = types.slice().sort();
156
-
157
- const type = types[0];
158
-
159
- items[0].getType(type).then((blob) => {
160
- this.handleFileSelect(new File([ blob ], 'image.png', { type }));
161
- });
162
- });
163
- });
164
-
165
- // Delete
166
- this.removeCheckbox?.addEventListener('click', () => {
167
- if (this.removeCheckbox.checked) {
168
- this.valueBackup = this.valueInput.value;
169
- this.valueInput.value = '';
170
- } else {
171
- this.valueInput.value = this.valueBackup;
172
- this.valueBackup = '';
173
- }
174
- });
175
-
176
- // Zoom slider
177
- selectAll(this.modalToolbarButtons, (button) => {
178
- button.addEventListener('click', (event) => {
179
- this.toolbarClicked(button, event);
180
- });
181
- });
182
- }
183
-
184
- getInputAccept() {
185
- let accept = this.options.accept;
186
-
187
- if (Array.isArray(accept)) {
188
- accept = accept.join(',');
189
- }
190
-
191
- return accept;
192
- }
193
-
194
- handleFileSelect(file: File) {
195
- if (!this.checkFile(file)) {
196
- return;
197
- }
198
-
199
- if (this.options.crop) {
200
- const reader = new FileReader();
201
-
202
- reader.addEventListener('load', (event) => {
203
- this.cropContainer.style.visibility = 'hidden';
204
- this.currentImage = event.target!.result as string;
205
- this.currentFile = file;
206
-
207
- // After modal shown, cropper will auto load.
208
- this.modal.show();
209
- });
210
-
211
- reader.readAsDataURL(file);
212
- return;
213
- }
214
-
215
- this.saveImage(file);
216
- }
217
-
218
- async saveCropped() {
219
- const Cropper = await this.getCropper();
220
-
221
- Cropper.getCroppedCanvas({
222
- width: this.options.width,
223
- height: this.options.height,
224
- imageSmoothingEnabled: true
225
- })
226
- .toBlob((blob) => {
227
- const file = new File([ blob! ], this.currentFile!.name, { type: 'image/png' });
228
- this.saveImage(file);
229
- }, 'image/png');
230
- }
231
-
232
- async getCropper() {
233
- if (this.cropper) {
234
- return this.cropper;
235
- }
236
-
237
- const Cropper = await loadCropper();
238
-
239
- return this.cropper = new Cropper(this.cropContainer.querySelector('img')!, {
240
- aspectRatio: this.options.width / this.options.height,
241
- autoCropArea: 1,
242
- viewMode: 1,
243
- dragMode: 'move',
244
- cropBoxMovable: false,
245
- cropBoxResizable: false,
246
- ready: (e) => {
247
- //
248
- },
249
- });
250
- }
251
-
252
- async toolbarClicked(button: HTMLButtonElement, event: MouseEvent) {
253
- const cropper = await this.getCropper();
254
-
255
- const data = cropper.getData();
256
-
257
- switch (button.dataset.sidToolbar) {
258
- case 'zoom-in':
259
- cropper.zoom(0.1);
260
- break;
261
-
262
- case 'zoom-out':
263
- cropper.zoom(-0.1);
264
- break;
265
-
266
- case 'rotate-left':
267
- cropper.rotate(-90);
268
- break;
269
-
270
- case 'rotate-right':
271
- cropper.rotate(90);
272
- break;
273
-
274
- case 'scale-x':
275
- cropper.scaleX(-data.scaleX);
276
- break;
277
-
278
- case 'scale-y':
279
- cropper.scaleY(-data.scaleY);
280
- break;
281
- }
282
- }
283
-
284
- checkFile(file: File): boolean {
285
- let accept = this.options.accept;
286
-
287
- if (typeof accept === 'string') {
288
- accept = accept.split(',').map(v => v.trim());
289
- }
290
-
291
- if (!accept.length) {
292
- return true;
293
- }
294
-
295
- let allow = false;
296
-
297
- for (const type of accept) {
298
- if (type.indexOf('/') !== -1) {
299
- allow = allow || this.compareMimeType(type, file.type);
300
- } else {
301
- allow = allow || type.toLowerCase() === getFileExtension(file)?.toLowerCase();
302
- }
303
- }
304
-
305
- if (allow) {
306
- return true;
307
- }
308
-
309
- this.alert(
310
- __('unicorn.field.sid.message.invalid.image.title'),
311
- __('unicorn.field.sid.message.invalid.image.desc'),
312
- 'error'
313
- );
314
-
315
- return false;
316
- }
317
-
318
- compareMimeType(accept: string, mime: string) {
319
- const accept2 = accept.split('/');
320
- const mime2 = mime.split('/');
321
-
322
- if (accept2[1] === '*') {
323
- return accept2[0] === mime2[0];
324
- }
325
-
326
- return accept === mime;
327
- }
328
-
329
- checkSize(image: HTMLImageElement): boolean {
330
- try {
331
- if (this.options.max_width && this.options.max_width < image.width) {
332
- throw new Error(__('unicorn.field.sid.message.invalid.size.max.width', this.options.max_width));
333
- }
334
-
335
- if (this.options.min_width && this.options.min_width > image.width) {
336
- throw new Error(__('unicorn.field.sid.message.invalid.size.min.width', this.options.min_width));
337
- }
338
-
339
- if (this.options.max_height && this.options.max_height < image.height) {
340
- throw new Error(__('unicorn.field.sid.message.invalid.size.max.height', this.options.max_height));
341
- }
342
-
343
- if (this.options.min_height && this.options.min_height > image.height) {
344
- throw new Error(__('unicorn.field.sid.message.invalid.size.min.height', this.options.min_height));
345
- }
346
- } catch (e) {
347
- this.alert(
348
- __('unicorn.field.sid.message.invalid.size.title'),
349
- (e as Error).message,
350
- 'error'
351
- );
352
-
353
- return false;
354
- }
355
-
356
- return true;
357
- }
358
-
359
- alert(title: string, text = '', type = 'info') {
360
- return simpleAlert(title, text, type);
361
- }
362
-
363
- async saveImage(file: File) {
364
- if (this.options.ajax_url) {
365
- const loading = this.querySelector<HTMLImageElement>('[data-sid=file-uploading]')!;
366
-
367
- this.previewImage.src = '';
368
- this.previewImage.style.display = 'none';
369
- loading.style.display = 'flex';
370
-
371
- try {
372
- const res = await this.uploadImage(file);
373
-
374
- this.storeValue(res.data.data.url, res.data.data.url);
375
- } catch (e) {
376
- console.error(e);
377
- simpleAlert((e as Error).message);
378
- return;
379
- } finally {
380
- loading.style.display = 'none';
381
- }
382
-
383
- return;
384
- }
385
-
386
- // @see https://stackoverflow.com/a/47172409
387
- // @see https://stackoverflow.com/a/47522812
388
- const dt = new DataTransfer();
389
- dt.items.add(file);
390
-
391
- // No required for value input to remove validation message
392
- this.valueInput.required = false;
393
-
394
- this.fileInput.files = dt.files;
395
- this.fileInput.dispatchEvent(new CustomEvent('change', { bubbles: true }));
396
- this.fileInput.dispatchEvent(new CustomEvent('input', { bubbles: true }));
397
-
398
- this.storeValue('', URL.createObjectURL(file));
399
- }
400
-
401
- async uploadImage(file: File) {
402
- const formData = new FormData();
403
- formData.append('file', file);
404
-
405
- const { post } = await useHttpClient();
406
-
407
- return post<ApiReturn<{ url: string; }>>(this.options.ajax_url!, formData, {
408
- headers: {
409
- 'Content-Type': 'multipart/form-data'
410
- }
411
- });
412
- }
413
-
414
- storeValue(url: string, preview: string) {
415
- this.previewImage.src = preview;
416
- this.previewImage.style.display = 'inline-block';
417
-
418
- // Make delete box unchecked
419
- if (this.removeCheckbox) {
420
- this.removeCheckbox.checked = false;
421
- }
422
-
423
- if (url) {
424
- this.valueInput.value = url;
425
- }
426
-
427
- // Trigger change
428
- this.previewImage.dispatchEvent(new CustomEvent('change', { bubbles: true }));
429
- this.valueInput.dispatchEvent(new CustomEvent('change', { bubbles: true }));
430
- this.valueInput.dispatchEvent(new CustomEvent('input', { bubbles: true }));
431
- }
432
- }
433
-
434
- // Promise.all([
435
- // import('@cropperjs/cropper.min.js'),
436
- // import('@cropperjs/cropper.css'),
437
- // ])
438
- // .then((service) => {
439
- // const styleSheet = service[1].default;
440
- // document.adoptedStyleSheets = [...document.adoptedStyleSheets, styleSheet];
441
- // });
442
-
443
- customElements.define(SingleImageDragElement.is, SingleImageDragElement);
444
-
445
- function getFileExtension(file: File): string | undefined {
446
- const parts = file.name.split('.');
447
- if (parts.length > 1) {
448
- return parts.pop();
449
- }
450
- return undefined;
451
- }
452
-
453
- async function loadCropper(): Promise<typeof Cropper> {
454
- const [module] = await Promise.all([
455
- import('cropperjs'),
456
- import('cropperjs/dist/cropper.min.css?inline').then(({ default: css }) => {
457
- injectCssToDocument(css);
458
- })
459
- ]);
460
-
461
- return module.default;
462
- }
463
-
464
- loadCropper();
465
-
466
- export interface SingleImageDragModule {
467
- SingleImageDragElement: typeof SingleImageDragElement;
468
- }
1
+
2
+ import { useHttpClient } from '../composable';
3
+ import { __, injectCssToDocument, selectAll, simpleAlert } from '../service';
4
+ import { mergeDeep } from '../utilities';
5
+ import css from '../../scss/field/single-image-drag.scss?inline';
6
+ import { Modal } from 'bootstrap';
7
+ import type Cropper from 'cropperjs';
8
+ import { ApiReturn } from './http-client';
9
+
10
+ export interface SingleImageDragOptions {
11
+ accept: string | string[];
12
+ ajax_url?: string;
13
+ crop: boolean;
14
+ width: number;
15
+ height: number;
16
+ max_width?: number;
17
+ min_width?: number;
18
+ max_height?: number;
19
+ min_height?: number;
20
+ modalTarget: string;
21
+ }
22
+
23
+ const defaultOptions: Partial<SingleImageDragOptions> = {
24
+ accept: [
25
+ 'image/jpeg',
26
+ 'image/png',
27
+ 'image/webp',
28
+ 'image/avif',
29
+ 'image/gif',
30
+ ],
31
+ crop: false,
32
+ width: 800,
33
+ height: 800,
34
+ };
35
+
36
+ export class SingleImageDragElement extends HTMLElement {
37
+ static is = 'uni-sid';
38
+
39
+ currentImage = '';
40
+ currentFile: File | undefined = undefined;
41
+ lastZoom = 0;
42
+ valueBackup = '';
43
+
44
+ private options!: SingleImageDragOptions;
45
+ private valueInput!: HTMLInputElement;
46
+ private fileInput!: HTMLInputElement;
47
+ private selectButton!: HTMLButtonElement;
48
+ private pasteButton!: HTMLButtonElement;
49
+ private dragarea!: HTMLDivElement;
50
+ private previewImage!: HTMLImageElement;
51
+ private removeCheckbox!: HTMLInputElement;
52
+ private modalElement!: HTMLDivElement;
53
+ private modal!: Modal;
54
+ private cropContainer!: HTMLDivElement;
55
+ private savebutton!: HTMLButtonElement;
56
+ private modalToolbarButtons!: NodeListOf<HTMLButtonElement>;
57
+ private cropper!: Cropper;
58
+
59
+ constructor() {
60
+ super();
61
+ }
62
+
63
+ connectedCallback() {
64
+ this.options = mergeDeep(
65
+ {},
66
+ defaultOptions,
67
+ JSON.parse(this.getAttribute('options') || '{}')
68
+ );
69
+
70
+ this.valueInput = this.querySelector<HTMLInputElement>('[data-field-input]')!;
71
+ this.fileInput = this.querySelector<HTMLInputElement>('[data-sid=file]')!;
72
+ this.selectButton = this.querySelector<HTMLButtonElement>('[data-sid=select]')!;
73
+ this.pasteButton = this.querySelector<HTMLButtonElement>('[data-sid=paste]')!;
74
+ this.dragarea = this.querySelector<HTMLDivElement>('[data-sid=dragarea]')!;
75
+ this.previewImage = this.querySelector<HTMLImageElement>('[data-sid=preview]')!;
76
+ this.removeCheckbox = this.querySelector<HTMLInputElement>('[data-sid=remove]')!;
77
+
78
+ this.modalElement = document.querySelector<HTMLDivElement>(this.options.modalTarget)!;
79
+ this.modal = Modal.getOrCreateInstance(this.modalElement);
80
+ this.cropContainer = this.modalElement.querySelector<HTMLDivElement>('[data-sid="crop-container"]')!;
81
+ this.savebutton = this.modalElement.querySelector<HTMLButtonElement>('[data-sid=save-button]')!;
82
+ this.modalToolbarButtons = this.modalElement.querySelectorAll<HTMLButtonElement>('[data-sid-toolbar]');
83
+
84
+ const modalShown = async () => {
85
+ const cropper = await this.getCropper();
86
+ cropper.replace(this.currentImage);
87
+ this.cropContainer.style.visibility = '';
88
+ this.currentImage = '';
89
+ };
90
+
91
+ this.modalElement.addEventListener('shown.bs.modal', modalShown.bind(this));
92
+
93
+ this.savebutton.addEventListener('click', () => {
94
+ this.saveCropped();
95
+ this.modal.hide();
96
+ });
97
+
98
+ this.bindEvents();
99
+
100
+ this.style.visibility = '';
101
+ }
102
+
103
+ bindEvents() {
104
+ this.dragarea.addEventListener('dragover', (event) => {
105
+ event.stopPropagation();
106
+ event.preventDefault();
107
+
108
+ this.dragarea.classList.add('hover');
109
+ });
110
+
111
+ this.dragarea.addEventListener('dragleave', (event) => {
112
+ event.stopPropagation();
113
+ event.preventDefault();
114
+
115
+ this.dragarea.classList.remove('hover');
116
+ });
117
+
118
+ this.dragarea.addEventListener('drop', (event) => {
119
+ event.stopPropagation();
120
+ event.preventDefault();
121
+
122
+ this.dragarea.classList.remove('hover');
123
+
124
+ const files = (event.target as HTMLInputElement).files || event.dataTransfer?.files || [];
125
+ this.handleFileSelect(files[0]);
126
+ });
127
+
128
+ // Select button
129
+ this.selectButton.addEventListener('click', () => {
130
+ const input = document.createElement('input');
131
+ input.setAttribute('type', 'file');
132
+ input.setAttribute('accept', this.getInputAccept());
133
+ input.style.display = 'none';
134
+ input.addEventListener('change', (e) => {
135
+ this.handleFileSelect(input.files![0]!);
136
+
137
+ input.remove();
138
+ });
139
+
140
+ document.body.appendChild(input);
141
+ input.click();
142
+ });
143
+
144
+ this.pasteButton.addEventListener('click', () => {
145
+ navigator.clipboard.read().then((items) => {
146
+ let types = items[0].types;
147
+
148
+ if (types.length === 0) {
149
+ this.alert('This browser unable to get clipboard data.');
150
+ return;
151
+ }
152
+
153
+ types = types.slice().sort();
154
+
155
+ const type = types[0];
156
+
157
+ items[0].getType(type).then((blob) => {
158
+ this.handleFileSelect(new File([ blob ], 'image.png', { type }));
159
+ });
160
+ });
161
+ });
162
+
163
+ // Delete
164
+ this.removeCheckbox?.addEventListener('click', () => {
165
+ if (this.removeCheckbox.checked) {
166
+ this.valueBackup = this.valueInput.value;
167
+ this.valueInput.value = '';
168
+ } else {
169
+ this.valueInput.value = this.valueBackup;
170
+ this.valueBackup = '';
171
+ }
172
+ });
173
+
174
+ // Zoom slider
175
+ selectAll(this.modalToolbarButtons, (button) => {
176
+ button.addEventListener('click', (event) => {
177
+ this.toolbarClicked(button, event);
178
+ });
179
+ });
180
+ }
181
+
182
+ getInputAccept() {
183
+ let accept = this.options.accept;
184
+
185
+ if (Array.isArray(accept)) {
186
+ accept = accept.join(',');
187
+ }
188
+
189
+ return accept;
190
+ }
191
+
192
+ handleFileSelect(file: File) {
193
+ if (!this.checkFile(file)) {
194
+ return;
195
+ }
196
+
197
+ if (this.options.crop) {
198
+ const reader = new FileReader();
199
+
200
+ reader.addEventListener('load', (event) => {
201
+ this.cropContainer.style.visibility = 'hidden';
202
+ this.currentImage = event.target!.result as string;
203
+ this.currentFile = file;
204
+
205
+ // After modal shown, cropper will auto load.
206
+ this.modal.show();
207
+ });
208
+
209
+ reader.readAsDataURL(file);
210
+ return;
211
+ }
212
+
213
+ this.saveImage(file);
214
+ }
215
+
216
+ async saveCropped() {
217
+ const Cropper = await this.getCropper();
218
+
219
+ Cropper.getCroppedCanvas({
220
+ width: this.options.width,
221
+ height: this.options.height,
222
+ imageSmoothingEnabled: true
223
+ })
224
+ .toBlob((blob) => {
225
+ const file = new File([ blob! ], this.currentFile!.name, { type: 'image/png' });
226
+ this.saveImage(file);
227
+ }, 'image/png');
228
+ }
229
+
230
+ async getCropper() {
231
+ if (this.cropper) {
232
+ return this.cropper;
233
+ }
234
+
235
+ const Cropper = await loadCropper();
236
+
237
+ return this.cropper = new Cropper(this.cropContainer.querySelector('img')!, {
238
+ aspectRatio: this.options.width / this.options.height,
239
+ autoCropArea: 1,
240
+ viewMode: 1,
241
+ dragMode: 'move',
242
+ cropBoxMovable: false,
243
+ cropBoxResizable: false,
244
+ ready: (e) => {
245
+ //
246
+ },
247
+ });
248
+ }
249
+
250
+ async toolbarClicked(button: HTMLButtonElement, event: MouseEvent) {
251
+ const cropper = await this.getCropper();
252
+
253
+ const data = cropper.getData();
254
+
255
+ switch (button.dataset.sidToolbar) {
256
+ case 'zoom-in':
257
+ cropper.zoom(0.1);
258
+ break;
259
+
260
+ case 'zoom-out':
261
+ cropper.zoom(-0.1);
262
+ break;
263
+
264
+ case 'rotate-left':
265
+ cropper.rotate(-90);
266
+ break;
267
+
268
+ case 'rotate-right':
269
+ cropper.rotate(90);
270
+ break;
271
+
272
+ case 'scale-x':
273
+ cropper.scaleX(-data.scaleX);
274
+ break;
275
+
276
+ case 'scale-y':
277
+ cropper.scaleY(-data.scaleY);
278
+ break;
279
+ }
280
+ }
281
+
282
+ checkFile(file: File): boolean {
283
+ let accept = this.options.accept;
284
+
285
+ if (typeof accept === 'string') {
286
+ accept = accept.split(',').map(v => v.trim());
287
+ }
288
+
289
+ if (!accept.length) {
290
+ return true;
291
+ }
292
+
293
+ let allow = false;
294
+
295
+ for (const type of accept) {
296
+ if (type.indexOf('/') !== -1) {
297
+ allow = allow || this.compareMimeType(type, file.type);
298
+ } else {
299
+ allow = allow || type.toLowerCase() === getFileExtension(file)?.toLowerCase();
300
+ }
301
+ }
302
+
303
+ if (allow) {
304
+ return true;
305
+ }
306
+
307
+ this.alert(
308
+ __('unicorn.field.sid.message.invalid.image.title'),
309
+ __('unicorn.field.sid.message.invalid.image.desc'),
310
+ 'error'
311
+ );
312
+
313
+ return false;
314
+ }
315
+
316
+ compareMimeType(accept: string, mime: string) {
317
+ const accept2 = accept.split('/');
318
+ const mime2 = mime.split('/');
319
+
320
+ if (accept2[1] === '*') {
321
+ return accept2[0] === mime2[0];
322
+ }
323
+
324
+ return accept === mime;
325
+ }
326
+
327
+ checkSize(image: HTMLImageElement): boolean {
328
+ try {
329
+ if (this.options.max_width && this.options.max_width < image.width) {
330
+ throw new Error(__('unicorn.field.sid.message.invalid.size.max.width', this.options.max_width));
331
+ }
332
+
333
+ if (this.options.min_width && this.options.min_width > image.width) {
334
+ throw new Error(__('unicorn.field.sid.message.invalid.size.min.width', this.options.min_width));
335
+ }
336
+
337
+ if (this.options.max_height && this.options.max_height < image.height) {
338
+ throw new Error(__('unicorn.field.sid.message.invalid.size.max.height', this.options.max_height));
339
+ }
340
+
341
+ if (this.options.min_height && this.options.min_height > image.height) {
342
+ throw new Error(__('unicorn.field.sid.message.invalid.size.min.height', this.options.min_height));
343
+ }
344
+ } catch (e) {
345
+ this.alert(
346
+ __('unicorn.field.sid.message.invalid.size.title'),
347
+ (e as Error).message,
348
+ 'error'
349
+ );
350
+
351
+ return false;
352
+ }
353
+
354
+ return true;
355
+ }
356
+
357
+ alert(title: string, text = '', type = 'info') {
358
+ return simpleAlert(title, text, type);
359
+ }
360
+
361
+ async saveImage(file: File) {
362
+ if (this.options.ajax_url) {
363
+ const loading = this.querySelector<HTMLImageElement>('[data-sid=file-uploading]')!;
364
+
365
+ this.previewImage.src = '';
366
+ this.previewImage.style.display = 'none';
367
+ loading.style.display = 'flex';
368
+
369
+ try {
370
+ const res = await this.uploadImage(file);
371
+
372
+ this.storeValue(res.data.data.url, res.data.data.url);
373
+ } catch (e) {
374
+ console.error(e);
375
+ simpleAlert((e as Error).message);
376
+ return;
377
+ } finally {
378
+ loading.style.display = 'none';
379
+ }
380
+
381
+ return;
382
+ }
383
+
384
+ // @see https://stackoverflow.com/a/47172409
385
+ // @see https://stackoverflow.com/a/47522812
386
+ const dt = new DataTransfer();
387
+ dt.items.add(file);
388
+
389
+ // No required for value input to remove validation message
390
+ this.valueInput.required = false;
391
+
392
+ this.fileInput.files = dt.files;
393
+ this.fileInput.dispatchEvent(new CustomEvent('change', { bubbles: true }));
394
+ this.fileInput.dispatchEvent(new CustomEvent('input', { bubbles: true }));
395
+
396
+ this.storeValue('', URL.createObjectURL(file));
397
+ }
398
+
399
+ async uploadImage(file: File) {
400
+ const formData = new FormData();
401
+ formData.append('file', file);
402
+
403
+ const { post } = await useHttpClient();
404
+
405
+ return post<ApiReturn<{ url: string; }>>(this.options.ajax_url!, formData, {
406
+ headers: {
407
+ 'Content-Type': 'multipart/form-data'
408
+ }
409
+ });
410
+ }
411
+
412
+ storeValue(url: string, preview: string) {
413
+ this.previewImage.src = preview;
414
+ this.previewImage.style.display = 'inline-block';
415
+
416
+ // Make delete box unchecked
417
+ if (this.removeCheckbox) {
418
+ this.removeCheckbox.checked = false;
419
+ }
420
+
421
+ if (url) {
422
+ this.valueInput.value = url;
423
+ }
424
+
425
+ // Trigger change
426
+ this.previewImage.dispatchEvent(new CustomEvent('change', { bubbles: true }));
427
+ this.valueInput.dispatchEvent(new CustomEvent('change', { bubbles: true }));
428
+ this.valueInput.dispatchEvent(new CustomEvent('input', { bubbles: true }));
429
+ }
430
+ }
431
+
432
+ // Promise.all([
433
+ // import('@cropperjs/cropper.min.js'),
434
+ // import('@cropperjs/cropper.css'),
435
+ // ])
436
+ // .then((service) => {
437
+ // const styleSheet = service[1].default;
438
+ // document.adoptedStyleSheets = [...document.adoptedStyleSheets, styleSheet];
439
+ // });
440
+
441
+ function getFileExtension(file: File): string | undefined {
442
+ const parts = file.name.split('.');
443
+ if (parts.length > 1) {
444
+ return parts.pop();
445
+ }
446
+ return undefined;
447
+ }
448
+
449
+ let loadingCropper: Promise<any>;
450
+
451
+ async function loadCropper(): Promise<typeof Cropper> {
452
+ loadingCropper ??= Promise.all([
453
+ import('cropperjs'),
454
+ import('cropperjs/dist/cropper.min.css?inline').then(({ default: css }) => {
455
+ injectCssToDocument(css);
456
+ })
457
+ ]);
458
+
459
+ return (await loadingCropper)[0];
460
+ }
461
+
462
+ async function init() {
463
+ injectCssToDocument(css);
464
+
465
+ customElements.define(SingleImageDragElement.is, SingleImageDragElement);
466
+
467
+ await loadCropper();
468
+ }
469
+
470
+ export const ready = init();
471
+
472
+ export interface SingleImageDragModule {
473
+ SingleImageDragElement: typeof SingleImageDragElement;
474
+ ready: typeof ready;
475
+ }