@windwalker-io/unicorn-next 0.1.0 → 0.1.1

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