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