@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
package/src/service/ui.ts CHANGED
@@ -1,497 +1,525 @@
1
- import { AlertAdapter, deleteConfirm, simpleAlert, simpleConfirm } from '@lyrasoft/ts-toolkit/generic';
2
- import type { Alpine as AlpineGlobal } from 'alpinejs';
3
- import type { default as SpectrumGlobal } from 'spectrum-vanilla';
4
- import type { SpectrumOptions } from 'spectrum-vanilla/dist/types/types';
5
- import type { default as TomSelectGlobal } from 'tom-select';
6
- import { useStack } from '../composable';
7
- import { data, removeData } from '../data';
8
- import type { Constructor, MaybePromise, Nullable, UIThemeInterface } from '../types';
9
- import { animateTo } from './animate';
10
- import { html, module, selectAll, selectOne } from './dom';
11
- import { nextTick } from './helper';
12
- import { useCssImport, useImport } from './loader';
13
-
14
- let ui: UnicornUI;
15
-
16
- AlertAdapter.alert = (title: string, text = '', type = 'info'): Promise<void> => {
17
- if (text) {
18
- title += ' | ' + text;
19
- }
20
-
21
- window.alert(title);
22
-
23
- return Promise.resolve();
24
- };
25
-
26
- AlertAdapter.confirm = (message: string): Promise<boolean> => {
27
- message = message || 'Are you sure?';
28
-
29
- return new Promise((resolve) => {
30
- resolve(window.confirm(message));
31
- });
32
- };
33
-
34
- AlertAdapter.confirmText = () => 'OK';
35
- AlertAdapter.cancelText = () => 'Cancel';
36
- AlertAdapter.deleteText = () => 'Delete';
37
-
38
- export { simpleAlert, simpleConfirm, deleteConfirm, AlertAdapter };
39
-
40
- export function useUI(instance?: UnicornUI): UnicornUI {
41
- if (instance) {
42
- ui = instance;
43
- }
44
-
45
- return ui ??= new UnicornUI();
46
- }
47
-
48
- export function useUITheme<T extends UIThemeInterface>(theme?: T | Constructor<T>): T {
49
- const ui = useUI();
50
-
51
- if (ui.theme && !theme) {
52
- return ui.theme;
53
- }
54
-
55
- if (typeof theme === 'function') {
56
- theme = new theme();
57
- }
58
-
59
- ui.installTheme(theme);
60
-
61
- return ui.theme;
62
- }
63
-
64
- export class UnicornUI {
65
- theme?: any;
66
- aliveHandle?: any;
67
-
68
- static get defaultOptions() {
69
- return {
70
- messageSelector: '.message-wrap',
71
- };
72
- }
73
-
74
- installTheme(theme: any) {
75
- this.theme = theme;
76
- }
77
-
78
- // confirm(message: string): Promise<boolean> {
79
- // message = message || 'Are you sure?';
80
- //
81
- // return new Promise((resolve) => {
82
- // resolve(window.confirm(message));
83
- // });
84
- // }
85
- //
86
- // alert(title: string, text = '', type = 'info'): Promise<boolean> {
87
- // if (text) {
88
- // title += ' | ' + text;
89
- // }
90
- //
91
- // window.alert(title);
92
- //
93
- // return Promise.resolve(true);
94
- // }
95
- }
96
-
97
- const prepares: AlpinePrepareCallback[] = [];
98
- type AlpinePrepareCallback = (Alpine: AlpineGlobal) => MaybePromise<any>;
99
- const { promise: alpineLoaded, resolve: alpineResolve } = Promise.withResolvers<AlpineGlobal>();
100
-
101
- export async function loadAlpine(callback?: Nullable<AlpinePrepareCallback>): Promise<AlpineGlobal> {
102
- if (callback && !window.Alpine) {
103
- prepares.push(callback);
104
- }
105
-
106
- const { default: Alpine }: { default: AlpineGlobal } = await useImport('@alpinejs');
107
-
108
- if (!window.Alpine) {
109
- await Promise.all(prepares.map((callback) => Promise.resolve(callback(Alpine))));
110
-
111
- Alpine.start();
112
-
113
- window.Alpine = Alpine;
114
-
115
- alpineResolve(Alpine);
116
- } else if (callback) {
117
- await callback(Alpine);
118
- }
119
-
120
- return Alpine;
121
- }
122
-
123
- export async function initAlpineComponent(directive: string) {
124
- const Alpine = await alpineLoaded;
125
-
126
- await nextTick();
127
-
128
- selectAll<HTMLElement>(`[${directive}]`, (el) => {
129
- const code = el.getAttribute(directive) || '';
130
- el.removeAttribute(directive);
131
-
132
- // @see https://github.com/alpinejs/alpine/issues/359#issuecomment-973688464
133
- Alpine.mutateDom(() => {
134
- el.setAttribute('x-data', code);
135
- });
136
-
137
- Alpine.initTree(el);
138
- });
139
- }
140
-
141
- /**
142
- * Before Alpine init
143
- */
144
- export async function prepareAlpine(callback: AlpinePrepareCallback) {
145
- if (window.Alpine) {
146
- await callback(window.Alpine);
147
- } else {
148
- prepares.push(callback);
149
- }
150
- }
151
- export async function prepareAlpineDefer(callback: AlpinePrepareCallback) {
152
- const Alpine = await alpineLoaded;
153
-
154
- await callback(window.Alpine);
155
- }
156
-
157
- /**
158
- * Render Messages.
159
- */
160
- export function renderMessage(messages: string | string[], type: string = 'info') {
161
- ui.theme.renderMessage(messages, type);
162
- }
163
-
164
- /**
165
- * Clear messages.
166
- */
167
- export function clearMessages() {
168
- ui.theme.clearMessages();
169
- }
170
-
171
- /**
172
- * Show notify.
173
- */
174
- export function notify(messages: string | string[], type: string = 'info') {
175
- ui.theme.renderMessage(messages, type);
176
- }
177
-
178
- /**
179
- * Clear notifies.
180
- */
181
- export function clearNotifies() {
182
- ui.theme.clearMessages();
183
- }
184
-
185
- export async function mark(selector?: string | HTMLElement, keyword: string = '', options: Record<string, any> = {}) {
186
- const modules = await useImport('@vendor/mark.js/dist/mark.min.js');
187
-
188
- if (selector != null) {
189
- const instance = new Mark(selector);
190
- instance.mark(keyword, options);
191
- }
192
-
193
- return modules;
194
- }
195
-
196
- export async function slideUp(target: string | HTMLElement, duration: number = 300): Promise<Animation | void> {
197
- const ele = selectOne(target);
198
-
199
- if (!ele) {
200
- return Promise.resolve();
201
- }
202
-
203
- ele.style.overflow = 'hidden';
204
-
205
- const animation = animateTo(
206
- ele,
207
- { height: 0, paddingTop: 0, paddingBottom: 0 },
208
- { duration, easing: 'ease-out' }
209
- );
210
-
211
- data(ele, 'animation.sliding.up', true);
212
-
213
- const r = await animation.finished;
214
-
215
- if (!data(ele, 'animation.sliding.down')) {
216
- ele.style.display = 'none';
217
- }
218
-
219
- removeData(ele, 'animation.sliding.up');
220
-
221
- return r;
222
- }
223
-
224
- export function slideDown(
225
- target: string | HTMLElement,
226
- duration: number = 300,
227
- display: string = 'block'): Promise<Animation | void> {
228
- const ele = selectOne(target);
229
-
230
- if (!ele) {
231
- return Promise.resolve();
232
- }
233
-
234
- data(ele, 'animation.sliding.down', true);
235
-
236
- ele.style.display = display;
237
-
238
- // Get height
239
- let maxHeight = 0;
240
- for (const child of Array.from(ele.children) as HTMLElement[]) {
241
- maxHeight = Math.max(child.offsetHeight, maxHeight);
242
- }
243
-
244
- const animation = animateTo(
245
- ele,
246
- {
247
- height: [
248
- 0,
249
- maxHeight + 'px'
250
- ]
251
- },
252
- { duration, easing: 'ease-out' }
253
- );
254
-
255
- animation.addEventListener('finish', () => {
256
- ele.style.height = '';
257
-
258
- if (!data(ele, 'animation.sliding.up')) {
259
- ele.style.overflow = 'visible';
260
- }
261
-
262
- removeData(ele, 'animation.sliding.down');
263
- });
264
-
265
- return animation.finished;
266
- }
267
-
268
- /**
269
- * slideToggle
270
- */
271
- export function slideToggle(
272
- target: string | HTMLElement,
273
- duration: number = 500,
274
- display: string = 'block'): Promise<Animation | void> {
275
- const ele = selectOne(target);
276
-
277
- if (!ele) {
278
- return Promise.resolve();
279
- }
280
-
281
- if (window.getComputedStyle(ele).display === 'none') {
282
- return slideDown(ele, duration, display);
283
- } else {
284
- return slideUp(ele, duration);
285
- }
286
- }
287
-
288
- export async function fadeOut(selector: string | HTMLElement, duration: number = 500): Promise<Animation | void> {
289
- const el = selectOne(selector);
290
-
291
- if (!el) {
292
- return;
293
- }
294
-
295
- const animation = animateTo(el, { opacity: 0 }, { duration, easing: 'ease-out' });
296
-
297
- const p = await animation.finished;
298
- el.style.display = 'none';
299
-
300
- return p;
301
- };
302
-
303
- export async function fadeIn(
304
- selector: string | HTMLElement,
305
- duration: number = 500,
306
- display: string = 'block'
307
- ): Promise<Animation | void> {
308
- const el = selectOne(selector);
309
-
310
- if (!el) {
311
- return;
312
- }
313
-
314
- el.style.display = '';
315
-
316
- if (window.getComputedStyle(el).display !== display) {
317
- el.style.display = display;
318
- }
319
-
320
- const animation = animateTo(el, { opacity: 1 }, { duration, easing: 'ease-out' });
321
-
322
- return animation.finished;
323
- };
324
-
325
- export async function highlight(
326
- selector: string | HTMLElement,
327
- color: string = '#ffff99',
328
- duration: number = 600
329
- ): Promise<Animation | void> {
330
- const ele = selectOne(selector);
331
-
332
- if (!ele) {
333
- return;
334
- }
335
-
336
- duration /= 2;
337
- const bg = window.getComputedStyle(ele).backgroundColor;
338
-
339
- const animation = animateTo(ele, { backgroundColor: color }, { duration });
340
-
341
- await animation.finished;
342
-
343
- return animateTo(ele, { backgroundColor: bg }, { duration });
344
- }
345
-
346
- /**
347
- * Color Picker.
348
- */
349
- export async function useColorPicker(
350
- selector?: Nullable<string | HTMLElement | NodeListOf<HTMLElement>>,
351
- options: Partial<SpectrumOptions> = {}
352
- ): Promise<any> {
353
- if (options?.theme === 'dark') {
354
- useCssImport('@spectrum/spectrum-dark.min.css');
355
- } else if (!options?.theme) {
356
- useCssImport('@spectrum/spectrum.min.css');
357
- }
358
-
359
- const m = await useImport('@spectrum');
360
-
361
- // Locale
362
- if (typeof options.locale === 'string') {
363
- let ls: any = options.locale.split('-').map((l) => l.toLowerCase());
364
-
365
- if (ls[0] === ls[1]) {
366
- ls = [ls];
367
- }
368
-
369
- ls = ls.join('-');
370
- try {
371
- await useImport(`@spectrum/i18n/${ls}.js`);
372
- } catch (e) {
373
- console.warn(`Unable to load Spectrum locale "${ls}" (${options.locale})`);
374
- }
375
- }
376
-
377
- if (selector) {
378
- module<any, HTMLElement>(selector, 'spectrum', (ele) => Spectrum.getInstance(ele, options));
379
- }
380
-
381
- return m;
382
- }
383
-
384
- export function useDisableOnSubmit(
385
- formSelector: string | HTMLFormElement = '#admin-form',
386
- buttonSelector: string = '',
387
- options: Record<string, any> = {}
388
- ) {
389
- // Todo: Use object to handle it
390
- buttonSelector = buttonSelector || [
391
- '#admin-toolbar button',
392
- '#admin-toolbar a',
393
- formSelector + ' .disable-on-submit',
394
- formSelector + ' .js-dos',
395
- formSelector + ' [data-dos]',
396
- ].join(',');
397
-
398
- const iconSelector = options.iconSelector || [
399
- '[class*="fa-"]',
400
- '[data-spin]',
401
- '[data-spinner]',
402
- ].join(',');
403
-
404
- const event = options.event || 'submit';
405
- const spinnerClass = options.spinnerClass || 'spinner-border spinner-border-sm';
406
-
407
- selectAll<HTMLElement>(buttonSelector, (button) => {
408
- button.addEventListener('click', (e) => {
409
- button.dataset.clicked = '1';
410
-
411
- setTimeout(() => {
412
- delete button.dataset.clicked;
413
- }, 1500);
414
- });
415
- });
416
-
417
- const form = selectOne<HTMLFormElement>(formSelector);
418
- form?.addEventListener(event, (e: SubmitEvent) => {
419
- setTimeout(() => {
420
- if (!form.checkValidity()) {
421
- return;
422
- }
423
-
424
- selectAll<HTMLElement>(buttonSelector, (button) => {
425
- button.style.pointerEvents = 'none';
426
- button.setAttribute('disabled', 'disabled');
427
- button.classList.add('disabled');
428
-
429
- if (button.dataset.clicked) {
430
- let icon = button.querySelector(iconSelector);
431
-
432
- if (icon) {
433
- const i = html('<i></i>');
434
- icon.parentNode.replaceChild(i, icon);
435
-
436
- i.setAttribute('class', spinnerClass);
437
- // icon.styles.width = '1em';
438
- // icon.styles.height = '1em';
439
- // icon.styles.borderWith = '.15em';
440
- }
441
- }
442
- });
443
- }, 0);
444
- });
445
- }
446
-
447
- export function useDisableIfStackNotEmpty(buttonSelector: string = '[data-task=save]',
448
- stackName: string = 'uploading') {
449
- const stack = useStack(stackName);
450
-
451
- stack.observe((stack, length) => {
452
- for (const button of selectAll<HTMLElement>(buttonSelector)) {
453
- if (length > 0) {
454
- button.setAttribute('disabled', 'disabled');
455
- button.classList.add('disabled');
456
- } else {
457
- button.removeAttribute('disabled');
458
- button.classList.remove('disabled');
459
- }
460
- }
461
- });
462
- }
463
-
464
- /**
465
- * Keep alive.
466
- */
467
- export function useKeepAlive(url: string, time: number = 60000): () => void {
468
- const aliveHandle = window.setInterval(() => fetch(url), time);
469
-
470
- return () => {
471
- clearInterval(aliveHandle);
472
- };
473
- }
474
-
475
- /**
476
- * Vue component field.
477
- */
478
- export async function useVueComponentField(
479
- selector?: Nullable<string | HTMLElement>,
480
- value?: any,
481
- options: Record<string, any> = {}
482
- ): Promise<any> {
483
- const m = await useImport('@unicorn/field/vue-component-field.js');
484
-
485
- if (selector) {
486
- m.VueComponentField.init(selector, value, options);
487
- }
488
-
489
- return m;
490
- }
491
-
492
- declare global {
493
- var Alpine: AlpineGlobal;
494
- var TomSelect: typeof TomSelectGlobal;
495
- var Spectrum: typeof SpectrumGlobal;
496
- var Mark: any;
497
- }
1
+ import {
2
+ AlertAdapter,
3
+ deleteConfirm,
4
+ simpleAlert,
5
+ simpleConfirm,
6
+ simpleNotify,
7
+ clearNotifies
8
+ } from '@lyrasoft/ts-toolkit/generic';
9
+ import type { Alpine as AlpineGlobal } from 'alpinejs';
10
+ import type { default as SpectrumGlobal } from 'spectrum-vanilla';
11
+ import type { SpectrumOptions } from 'spectrum-vanilla/dist/types/types';
12
+ import type { default as TomSelectGlobal } from 'tom-select';
13
+ import { useStack } from '../composable';
14
+ import { data, removeData } from '../data';
15
+ import type { Constructor, MaybePromise, Nullable, UIThemeInterface } from '../types';
16
+ import { animateTo } from './animate';
17
+ import { html, module, selectAll, selectOne } from './dom';
18
+ import { nextTick } from './helper';
19
+ import { useCssImport, useImport } from './loader';
20
+
21
+ let ui: UnicornUI;
22
+
23
+ AlertAdapter.alert = (title: string, text = '', type = 'info'): Promise<void> => {
24
+ if (text) {
25
+ title += ' | ' + text;
26
+ }
27
+
28
+ window.alert(title);
29
+
30
+ return Promise.resolve();
31
+ };
32
+
33
+ AlertAdapter.confirm = (message: string, text = '', type = 'info'): Promise<boolean> => {
34
+ message = message || 'Are you sure?';
35
+
36
+ if (text) {
37
+ message += ' | ' + text;
38
+ }
39
+
40
+ return new Promise((resolve) => {
41
+ resolve(window.confirm(message));
42
+ });
43
+ };
44
+
45
+ AlertAdapter.notify = async (title: string, text?: string, type: string = 'log'): Promise<() => any> => {
46
+ if (text) {
47
+ title += ' | ' + text;
48
+ }
49
+
50
+ return ui.theme?.renderMessage(title, type) ?? (() => null);
51
+ };
52
+
53
+ AlertAdapter.clearNotifies = async (): Promise<void> => {
54
+ ui.theme?.clearMessages();
55
+ };
56
+
57
+ AlertAdapter.confirmText = () => 'OK';
58
+ AlertAdapter.cancelText = () => 'Cancel';
59
+ AlertAdapter.deleteText = () => 'Delete';
60
+
61
+ export { simpleAlert, simpleConfirm, deleteConfirm, simpleNotify, clearNotifies };
62
+
63
+ export interface AlertAdapterConfig {
64
+ alert?: typeof AlertAdapter['alert'];
65
+ confirm?: typeof AlertAdapter['confirm'];
66
+ deleteConfirm?: typeof AlertAdapter['deleteConfirm'];
67
+ confirmText?: typeof AlertAdapter['confirmText'];
68
+ cancelText?: typeof AlertAdapter['cancelText'];
69
+ deleteText?: typeof AlertAdapter['deleteText'];
70
+ notify?: typeof AlertAdapter['notify'];
71
+ clearNotifies?: typeof AlertAdapter['clearNotifies'];
72
+ }
73
+
74
+ export function useAlertAdapter(config?: AlertAdapterConfig): typeof AlertAdapter {
75
+ if (config) {
76
+ Object.assign(AlertAdapter, config);
77
+ }
78
+
79
+ return AlertAdapter;
80
+ }
81
+
82
+ export function useUI(instance?: UnicornUI): UnicornUI {
83
+ if (instance) {
84
+ ui = instance;
85
+ }
86
+
87
+ return ui ??= new UnicornUI();
88
+ }
89
+
90
+ export function useUITheme<T extends UIThemeInterface>(theme?: T | Constructor<T>): UIThemeInterface {
91
+ const ui = useUI();
92
+
93
+ if (ui.theme && !theme) {
94
+ return ui.theme;
95
+ }
96
+
97
+ if (typeof theme === 'function') {
98
+ theme = new theme();
99
+ }
100
+
101
+ ui.installTheme(theme);
102
+
103
+ return ui.theme!;
104
+ }
105
+
106
+ export class UnicornUI {
107
+ theme?: UIThemeInterface;
108
+
109
+ static get defaultOptions() {
110
+ return {
111
+ messageSelector: '.message-wrap',
112
+ };
113
+ }
114
+
115
+ installTheme(theme: any) {
116
+ this.theme = theme;
117
+ }
118
+
119
+ // confirm(message: string): Promise<boolean> {
120
+ // message = message || 'Are you sure?';
121
+ //
122
+ // return new Promise((resolve) => {
123
+ // resolve(window.confirm(message));
124
+ // });
125
+ // }
126
+ //
127
+ // alert(title: string, text = '', type = 'info'): Promise<boolean> {
128
+ // if (text) {
129
+ // title += ' | ' + text;
130
+ // }
131
+ //
132
+ // window.alert(title);
133
+ //
134
+ // return Promise.resolve(true);
135
+ // }
136
+ }
137
+
138
+ const prepares: AlpinePrepareCallback[] = [];
139
+ type AlpinePrepareCallback = (Alpine: AlpineGlobal) => MaybePromise<any>;
140
+ const { promise: alpineLoaded, resolve: alpineResolve } = Promise.withResolvers<AlpineGlobal>();
141
+
142
+ export async function loadAlpine(callback?: Nullable<AlpinePrepareCallback>): Promise<AlpineGlobal> {
143
+ if (callback && !window.Alpine) {
144
+ prepares.push(callback);
145
+ }
146
+
147
+ const { default: Alpine }: { default: AlpineGlobal } = await useImport('@alpinejs');
148
+
149
+ if (!window.Alpine) {
150
+ await Promise.all(prepares.map((callback) => Promise.resolve(callback(Alpine))));
151
+
152
+ Alpine.start();
153
+
154
+ window.Alpine = Alpine;
155
+
156
+ alpineResolve(Alpine);
157
+ } else if (callback) {
158
+ await callback(Alpine);
159
+ }
160
+
161
+ return Alpine;
162
+ }
163
+
164
+ export async function initAlpineComponent(directive: string) {
165
+ const Alpine = await alpineLoaded;
166
+
167
+ await nextTick();
168
+
169
+ selectAll<HTMLElement>(`[${directive}]`, (el) => {
170
+ const code = el.getAttribute(directive) || '';
171
+ el.removeAttribute(directive);
172
+
173
+ // @see https://github.com/alpinejs/alpine/issues/359#issuecomment-973688464
174
+ Alpine.mutateDom(() => {
175
+ el.setAttribute('x-data', code);
176
+ });
177
+
178
+ Alpine.initTree(el);
179
+ });
180
+ }
181
+
182
+ /**
183
+ * Before Alpine init
184
+ */
185
+ export async function prepareAlpine(callback: AlpinePrepareCallback) {
186
+ if (window.Alpine) {
187
+ await callback(window.Alpine);
188
+ } else {
189
+ prepares.push(callback);
190
+ }
191
+ }
192
+
193
+ export async function prepareAlpineDefer(callback: AlpinePrepareCallback) {
194
+ const Alpine = await alpineLoaded;
195
+
196
+ await callback(window.Alpine);
197
+ }
198
+
199
+ /**
200
+ * Render Messages.
201
+ */
202
+ export function renderMessage(messages: string | string[], type: string = 'info') {
203
+ return ui.theme?.renderMessage(messages, type);
204
+ }
205
+
206
+ /**
207
+ * Clear messages.
208
+ */
209
+ export function clearMessages() {
210
+ ui.theme?.clearMessages();
211
+ }
212
+
213
+ export async function mark(selector?: string | HTMLElement, keyword: string = '', options: Record<string, any> = {}) {
214
+ const modules = await useImport('@vendor/mark.js/dist/mark.min.js');
215
+
216
+ if (selector != null) {
217
+ const instance = new Mark(selector);
218
+ instance.mark(keyword, options);
219
+ }
220
+
221
+ return modules;
222
+ }
223
+
224
+ export async function slideUp(target: string | HTMLElement, duration: number = 300): Promise<Animation | void> {
225
+ const ele = selectOne(target);
226
+
227
+ if (!ele) {
228
+ return Promise.resolve();
229
+ }
230
+
231
+ ele.style.overflow = 'hidden';
232
+
233
+ const animation = animateTo(
234
+ ele,
235
+ { height: 0, paddingTop: 0, paddingBottom: 0 },
236
+ { duration, easing: 'ease-out' }
237
+ );
238
+
239
+ data(ele, 'animation.sliding.up', true);
240
+
241
+ const r = await animation.finished;
242
+
243
+ if (!data(ele, 'animation.sliding.down')) {
244
+ ele.style.display = 'none';
245
+ }
246
+
247
+ removeData(ele, 'animation.sliding.up');
248
+
249
+ return r;
250
+ }
251
+
252
+ export function slideDown(
253
+ target: string | HTMLElement,
254
+ duration: number = 300,
255
+ display: string = 'block'): Promise<Animation | void> {
256
+ const ele = selectOne(target);
257
+
258
+ if (!ele) {
259
+ return Promise.resolve();
260
+ }
261
+
262
+ data(ele, 'animation.sliding.down', true);
263
+
264
+ ele.style.display = display;
265
+
266
+ // Get height
267
+ let maxHeight = 0;
268
+ for (const child of Array.from(ele.children) as HTMLElement[]) {
269
+ maxHeight = Math.max(child.offsetHeight, maxHeight);
270
+ }
271
+
272
+ const animation = animateTo(
273
+ ele,
274
+ {
275
+ height: [
276
+ 0,
277
+ maxHeight + 'px'
278
+ ]
279
+ },
280
+ { duration, easing: 'ease-out' }
281
+ );
282
+
283
+ animation.addEventListener('finish', () => {
284
+ ele.style.height = '';
285
+
286
+ if (!data(ele, 'animation.sliding.up')) {
287
+ ele.style.overflow = 'visible';
288
+ }
289
+
290
+ removeData(ele, 'animation.sliding.down');
291
+ });
292
+
293
+ return animation.finished;
294
+ }
295
+
296
+ /**
297
+ * slideToggle
298
+ */
299
+ export function slideToggle(
300
+ target: string | HTMLElement,
301
+ duration: number = 500,
302
+ display: string = 'block'): Promise<Animation | void> {
303
+ const ele = selectOne(target);
304
+
305
+ if (!ele) {
306
+ return Promise.resolve();
307
+ }
308
+
309
+ if (window.getComputedStyle(ele).display === 'none') {
310
+ return slideDown(ele, duration, display);
311
+ } else {
312
+ return slideUp(ele, duration);
313
+ }
314
+ }
315
+
316
+ export async function fadeOut(selector: string | HTMLElement, duration: number = 500): Promise<Animation | void> {
317
+ const el = selectOne(selector);
318
+
319
+ if (!el) {
320
+ return;
321
+ }
322
+
323
+ const animation = animateTo(el, { opacity: 0 }, { duration, easing: 'ease-out' });
324
+
325
+ const p = await animation.finished;
326
+ el.style.display = 'none';
327
+
328
+ return p;
329
+ };
330
+
331
+ export async function fadeIn(
332
+ selector: string | HTMLElement,
333
+ duration: number = 500,
334
+ display: string = 'block'
335
+ ): Promise<Animation | void> {
336
+ const el = selectOne(selector);
337
+
338
+ if (!el) {
339
+ return;
340
+ }
341
+
342
+ el.style.display = '';
343
+
344
+ if (window.getComputedStyle(el).display !== display) {
345
+ el.style.display = display;
346
+ }
347
+
348
+ const animation = animateTo(el, { opacity: 1 }, { duration, easing: 'ease-out' });
349
+
350
+ return animation.finished;
351
+ };
352
+
353
+ export async function highlight(
354
+ selector: string | HTMLElement,
355
+ color: string = '#ffff99',
356
+ duration: number = 600
357
+ ): Promise<Animation | void> {
358
+ const ele = selectOne(selector);
359
+
360
+ if (!ele) {
361
+ return;
362
+ }
363
+
364
+ duration /= 2;
365
+ const bg = window.getComputedStyle(ele).backgroundColor;
366
+
367
+ const animation = animateTo(ele, { backgroundColor: color }, { duration });
368
+
369
+ await animation.finished;
370
+
371
+ return animateTo(ele, { backgroundColor: bg }, { duration });
372
+ }
373
+
374
+ /**
375
+ * Color Picker.
376
+ */
377
+ export async function useColorPicker(
378
+ selector?: Nullable<string | HTMLElement | NodeListOf<HTMLElement>>,
379
+ options: Partial<SpectrumOptions> = {}
380
+ ): Promise<any> {
381
+ if (options?.theme === 'dark') {
382
+ useCssImport('@spectrum/spectrum-dark.min.css');
383
+ } else if (!options?.theme) {
384
+ useCssImport('@spectrum/spectrum.min.css');
385
+ }
386
+
387
+ const m = await useImport('@spectrum');
388
+
389
+ // Locale
390
+ if (typeof options.locale === 'string') {
391
+ let ls: any = options.locale.split('-').map((l) => l.toLowerCase());
392
+
393
+ if (ls[0] === ls[1]) {
394
+ ls = [ls];
395
+ }
396
+
397
+ ls = ls.join('-');
398
+ try {
399
+ await useImport(`@spectrum/i18n/${ls}.js`);
400
+ } catch (e) {
401
+ console.warn(`Unable to load Spectrum locale "${ls}" (${options.locale})`);
402
+ }
403
+ }
404
+
405
+ if (selector) {
406
+ module<any, HTMLElement>(selector, 'spectrum', (ele) => Spectrum.getInstance(ele, options));
407
+ }
408
+
409
+ return m;
410
+ }
411
+
412
+ export function useDisableOnSubmit(
413
+ formSelector: string | HTMLFormElement = '#admin-form',
414
+ buttonSelector: string = '',
415
+ options: Record<string, any> = {}
416
+ ) {
417
+ // Todo: Use object to handle it
418
+ buttonSelector = buttonSelector || [
419
+ '#admin-toolbar button',
420
+ '#admin-toolbar a',
421
+ formSelector + ' .disable-on-submit',
422
+ formSelector + ' .js-dos',
423
+ formSelector + ' [data-dos]',
424
+ ].join(',');
425
+
426
+ const iconSelector = options.iconSelector || [
427
+ '[class*="fa-"]',
428
+ '[data-spin]',
429
+ '[data-spinner]',
430
+ ].join(',');
431
+
432
+ const event = options.event || 'submit';
433
+ const spinnerClass = options.spinnerClass || 'spinner-border spinner-border-sm';
434
+
435
+ selectAll<HTMLElement>(buttonSelector, (button) => {
436
+ button.addEventListener('click', (e) => {
437
+ button.dataset.clicked = '1';
438
+
439
+ setTimeout(() => {
440
+ delete button.dataset.clicked;
441
+ }, 1500);
442
+ });
443
+ });
444
+
445
+ const form = selectOne<HTMLFormElement>(formSelector);
446
+ form?.addEventListener(event, (e: SubmitEvent) => {
447
+ setTimeout(() => {
448
+ if (!form.checkValidity()) {
449
+ return;
450
+ }
451
+
452
+ selectAll<HTMLElement>(buttonSelector, (button) => {
453
+ button.style.pointerEvents = 'none';
454
+ button.setAttribute('disabled', 'disabled');
455
+ button.classList.add('disabled');
456
+
457
+ if (button.dataset.clicked) {
458
+ let icon = button.querySelector(iconSelector);
459
+
460
+ if (icon) {
461
+ const i = html('<i></i>');
462
+ icon.parentNode.replaceChild(i, icon);
463
+
464
+ i.setAttribute('class', spinnerClass);
465
+ // icon.styles.width = '1em';
466
+ // icon.styles.height = '1em';
467
+ // icon.styles.borderWith = '.15em';
468
+ }
469
+ }
470
+ });
471
+ }, 0);
472
+ });
473
+ }
474
+
475
+ export function useDisableIfStackNotEmpty(buttonSelector: string = '[data-task=save]',
476
+ stackName: string = 'uploading') {
477
+ const stack = useStack(stackName);
478
+
479
+ stack.observe((stack, length) => {
480
+ for (const button of selectAll<HTMLElement>(buttonSelector)) {
481
+ if (length > 0) {
482
+ button.setAttribute('disabled', 'disabled');
483
+ button.classList.add('disabled');
484
+ } else {
485
+ button.removeAttribute('disabled');
486
+ button.classList.remove('disabled');
487
+ }
488
+ }
489
+ });
490
+ }
491
+
492
+ /**
493
+ * Keep alive.
494
+ */
495
+ export function useKeepAlive(url: string, time: number = 60000): () => void {
496
+ const aliveHandle = window.setInterval(() => fetch(url), time);
497
+
498
+ return () => {
499
+ clearInterval(aliveHandle);
500
+ };
501
+ }
502
+
503
+ /**
504
+ * Vue component field.
505
+ */
506
+ export async function useVueComponentField(
507
+ selector?: Nullable<string | HTMLElement>,
508
+ value?: any,
509
+ options: Record<string, any> = {}
510
+ ): Promise<any> {
511
+ const m = await useImport('@unicorn/field/vue-component-field.js');
512
+
513
+ if (selector) {
514
+ m.VueComponentField.init(selector, value, options);
515
+ }
516
+
517
+ return m;
518
+ }
519
+
520
+ declare global {
521
+ var Alpine: AlpineGlobal;
522
+ var TomSelect: typeof TomSelectGlobal;
523
+ var Spectrum: typeof SpectrumGlobal;
524
+ var Mark: any;
525
+ }