@windwalker-io/unicorn-next 0.1.4 → 0.1.6

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 (129) 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.map +1 -1
  8. package/dist/chunks/field-flatpickr.js.map +1 -1
  9. package/dist/chunks/field-modal-select.js.map +1 -1
  10. package/dist/chunks/field-modal-tree.js +2 -2
  11. package/dist/chunks/field-modal-tree.js.map +1 -1
  12. package/dist/chunks/field-multi-uploader.js.map +1 -1
  13. package/dist/chunks/field-repeatable.js.map +1 -1
  14. package/dist/chunks/field-single-image-drag.js.map +1 -1
  15. package/dist/chunks/form.js.map +1 -1
  16. package/dist/chunks/grid.js.map +1 -1
  17. package/dist/chunks/http-client.js.map +1 -1
  18. package/dist/chunks/iframe-modal.js.map +1 -1
  19. package/dist/chunks/keep-tab.js.map +1 -1
  20. package/dist/chunks/legacy.js +2 -2
  21. package/dist/chunks/legacy.js.map +1 -1
  22. package/dist/chunks/list-dependent.js.map +1 -1
  23. package/dist/chunks/s3-multipart-uploader.js.map +1 -1
  24. package/dist/chunks/s3-uploader.js.map +1 -1
  25. package/dist/chunks/show-on.js.map +1 -1
  26. package/dist/chunks/tinymce.js +1 -1
  27. package/dist/chunks/tinymce.js.map +1 -1
  28. package/dist/chunks/ui-bootstrap5.js.map +1 -1
  29. package/dist/chunks/unicorn.js +22 -16
  30. package/dist/chunks/unicorn.js.map +1 -1
  31. package/dist/chunks/validation.js +1 -1
  32. package/dist/chunks/validation.js.map +1 -1
  33. package/dist/index.d.ts +39 -30
  34. package/dist/unicorn.js +11 -9
  35. package/fusionfile.mjs +155 -155
  36. package/package.json +103 -103
  37. package/scss/bootstrap/multi-level-menu.scss +121 -121
  38. package/scss/editor.scss +116 -116
  39. package/scss/field/file-drag.scss +102 -102
  40. package/scss/field/single-image-drag.scss +88 -88
  41. package/scss/field/vue-drag-uploader.scss +160 -160
  42. package/scss/switcher.scss +156 -156
  43. package/src/app.ts +128 -128
  44. package/src/bootstrap/button-radio.ts +208 -208
  45. package/src/bootstrap/keep-tab.ts +155 -155
  46. package/src/composable/index.ts +22 -21
  47. package/src/composable/useCheckboxesMultiSelect.ts +22 -22
  48. package/src/composable/useFieldCascadeSelect.ts +9 -9
  49. package/src/composable/useFieldFileDrag.ts +9 -9
  50. package/src/composable/useFieldFlatpickr.ts +3 -3
  51. package/src/composable/useFieldModalSelect.ts +6 -6
  52. package/src/composable/useFieldModalTree.ts +3 -3
  53. package/src/composable/useFieldMultiUploader.ts +9 -9
  54. package/src/composable/useFieldRepeatable.ts +9 -9
  55. package/src/composable/useFieldSingleImageDrag.ts +9 -9
  56. package/src/composable/useForm.ts +43 -43
  57. package/src/composable/useGrid.ts +57 -57
  58. package/src/composable/useHttp.ts +9 -9
  59. package/src/composable/useIframeModal.ts +10 -10
  60. package/src/composable/useListDependent.ts +26 -26
  61. package/src/composable/useQueue.ts +13 -13
  62. package/src/composable/useS3Uploader.ts +32 -32
  63. package/src/composable/useShowOn.ts +9 -9
  64. package/src/composable/useStack.ts +13 -13
  65. package/src/composable/useTinymce.ts +29 -29
  66. package/src/composable/useTomSelect.ts +72 -72
  67. package/src/composable/useUIBootstrap5.ts +48 -48
  68. package/src/composable/useUniDirective.ts +32 -32
  69. package/src/composable/useValidation.ts +50 -39
  70. package/src/data.ts +34 -34
  71. package/src/events.ts +82 -82
  72. package/src/legacy/legacy.ts +190 -190
  73. package/src/legacy/loader.ts +125 -125
  74. package/src/module/checkboxes-multi-select.ts +54 -54
  75. package/src/module/field-cascade-select.ts +292 -292
  76. package/src/module/field-file-drag.ts +295 -295
  77. package/src/module/field-flatpickr.ts +130 -130
  78. package/src/module/field-modal-select.ts +179 -179
  79. package/src/module/field-modal-tree.ts +31 -31
  80. package/src/module/field-multi-uploader.ts +368 -368
  81. package/src/module/field-repeatable.ts +202 -202
  82. package/src/module/field-single-image-drag.ts +475 -475
  83. package/src/module/form.ts +223 -223
  84. package/src/module/grid.ts +465 -465
  85. package/src/module/http-client.ts +248 -248
  86. package/src/module/iframe-modal.ts +170 -170
  87. package/src/module/list-dependent.ts +321 -321
  88. package/src/module/s3-multipart-uploader.ts +300 -300
  89. package/src/module/s3-uploader.ts +234 -234
  90. package/src/module/show-on.ts +175 -175
  91. package/src/module/tinymce.ts +276 -276
  92. package/src/module/ui-bootstrap5.ts +116 -116
  93. package/src/module/validation.ts +1046 -1026
  94. package/src/plugin/index.ts +1 -1
  95. package/src/plugin/php-adapter.ts +72 -72
  96. package/src/polyfill/form-request-submit.ts +31 -31
  97. package/src/polyfill/index.ts +9 -9
  98. package/src/service/animate.ts +58 -58
  99. package/src/service/crypto.ts +27 -27
  100. package/src/service/dom-watcher.ts +62 -62
  101. package/src/service/dom.ts +265 -265
  102. package/src/service/helper.ts +48 -48
  103. package/src/service/index.ts +10 -10
  104. package/src/service/lang.ts +122 -122
  105. package/src/service/loader.ts +152 -152
  106. package/src/service/router.ts +118 -118
  107. package/src/service/ui.ts +525 -525
  108. package/src/service/uri.ts +106 -106
  109. package/src/types/base.ts +9 -9
  110. package/src/types/index.ts +4 -4
  111. package/src/types/modal-tree.ts +12 -12
  112. package/src/types/plugin.ts +6 -6
  113. package/src/types/shims.d.ts +18 -18
  114. package/src/types/ui.ts +6 -6
  115. package/src/unicorn.ts +79 -79
  116. package/src/utilities/arr.ts +25 -25
  117. package/src/utilities/base.ts +9 -9
  118. package/src/utilities/data.ts +48 -48
  119. package/src/utilities/index.ts +5 -5
  120. package/src/utilities/tree.ts +20 -20
  121. package/src/vue/components/ModalTree/ModalTreeApp.vue +175 -175
  122. package/src/vue/components/ModalTree/TreeItem.vue +262 -262
  123. package/src/vue/components/ModalTree/TreeModal.vue +225 -225
  124. package/tests/test.js +4 -4
  125. package/tsconfig.js.json +25 -25
  126. package/tsconfig.json +17 -17
  127. package/vite.assets.config.ts +61 -61
  128. package/vite.config.test.ts +36 -36
  129. package/vite.config.ts +112 -112
@@ -1,475 +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
- 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
- }
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
+ }