@windwalker-io/unicorn-next 0.1.0

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 (175) hide show
  1. package/.editorconfig +18 -0
  2. package/.gulp.json +7 -0
  3. package/bin/release.mjs +47 -0
  4. package/dist/chunks/_arrayPush.js +168 -0
  5. package/dist/chunks/_arrayPush.js.map +1 -0
  6. package/dist/chunks/_baseRest.js +73 -0
  7. package/dist/chunks/_baseRest.js.map +1 -0
  8. package/dist/chunks/_commonjsHelpers.js +7 -0
  9. package/dist/chunks/_commonjsHelpers.js.map +1 -0
  10. package/dist/chunks/_getPrototype.js +130 -0
  11. package/dist/chunks/_getPrototype.js.map +1 -0
  12. package/dist/chunks/button-radio.js +147 -0
  13. package/dist/chunks/button-radio.js.map +1 -0
  14. package/dist/chunks/checkboxes-multi-select.js +44 -0
  15. package/dist/chunks/checkboxes-multi-select.js.map +1 -0
  16. package/dist/chunks/cloneDeep.js +287 -0
  17. package/dist/chunks/cloneDeep.js.map +1 -0
  18. package/dist/chunks/cropper.min.js +5 -0
  19. package/dist/chunks/cropper.min.js.map +1 -0
  20. package/dist/chunks/field-cascade-select.js +256 -0
  21. package/dist/chunks/field-cascade-select.js.map +1 -0
  22. package/dist/chunks/field-file-drag.js +218 -0
  23. package/dist/chunks/field-file-drag.js.map +1 -0
  24. package/dist/chunks/field-flatpickr.js +893 -0
  25. package/dist/chunks/field-flatpickr.js.map +1 -0
  26. package/dist/chunks/field-modal-select.js +403 -0
  27. package/dist/chunks/field-modal-select.js.map +1 -0
  28. package/dist/chunks/field-modal-tree.js +790 -0
  29. package/dist/chunks/field-modal-tree.js.map +1 -0
  30. package/dist/chunks/field-multi-uploader.js +256 -0
  31. package/dist/chunks/field-multi-uploader.js.map +1 -0
  32. package/dist/chunks/field-repeatable.js +132 -0
  33. package/dist/chunks/field-repeatable.js.map +1 -0
  34. package/dist/chunks/field-single-image-drag.js +338 -0
  35. package/dist/chunks/field-single-image-drag.js.map +1 -0
  36. package/dist/chunks/form.js +154 -0
  37. package/dist/chunks/form.js.map +1 -0
  38. package/dist/chunks/grid.js +345 -0
  39. package/dist/chunks/grid.js.map +1 -0
  40. package/dist/chunks/http-client.js +229 -0
  41. package/dist/chunks/http-client.js.map +1 -0
  42. package/dist/chunks/iframe-modal.js +124 -0
  43. package/dist/chunks/iframe-modal.js.map +1 -0
  44. package/dist/chunks/index.js +309 -0
  45. package/dist/chunks/index.js.map +1 -0
  46. package/dist/chunks/isArguments.js +146 -0
  47. package/dist/chunks/isArguments.js.map +1 -0
  48. package/dist/chunks/keep-tab.js +101 -0
  49. package/dist/chunks/keep-tab.js.map +1 -0
  50. package/dist/chunks/legacy.js +210 -0
  51. package/dist/chunks/legacy.js.map +1 -0
  52. package/dist/chunks/list-dependent.js +231 -0
  53. package/dist/chunks/list-dependent.js.map +1 -0
  54. package/dist/chunks/s3-multipart-uploader.js +172 -0
  55. package/dist/chunks/s3-multipart-uploader.js.map +1 -0
  56. package/dist/chunks/s3-uploader.js +136 -0
  57. package/dist/chunks/s3-uploader.js.map +1 -0
  58. package/dist/chunks/show-on.js +237 -0
  59. package/dist/chunks/show-on.js.map +1 -0
  60. package/dist/chunks/tinymce.js +196 -0
  61. package/dist/chunks/tinymce.js.map +1 -0
  62. package/dist/chunks/ui-bootstrap5.js +71 -0
  63. package/dist/chunks/ui-bootstrap5.js.map +1 -0
  64. package/dist/chunks/unicorn.js +2202 -0
  65. package/dist/chunks/unicorn.js.map +1 -0
  66. package/dist/chunks/validation.js +854 -0
  67. package/dist/chunks/validation.js.map +1 -0
  68. package/dist/editor.css +1 -0
  69. package/dist/index.d.ts +1427 -0
  70. package/dist/multi-level-menu.css +1 -0
  71. package/dist/switcher.css +1 -0
  72. package/dist/unicorn-next.css +12 -0
  73. package/dist/unicorn.js +125 -0
  74. package/dist/unicorn.js.map +1 -0
  75. package/fusionfile.mjs +155 -0
  76. package/images/ajax-loader.gif +0 -0
  77. package/images/placeholder/avatar.png +0 -0
  78. package/images/placeholder/image-16x10.png +0 -0
  79. package/images/placeholder/image-16x9.png +0 -0
  80. package/images/placeholder/image-1x1.png +0 -0
  81. package/images/placeholder/image-4x3.png +0 -0
  82. package/package.json +102 -0
  83. package/scss/bootstrap/multi-level-menu.scss +121 -0
  84. package/scss/editor.scss +116 -0
  85. package/scss/field/file-drag.scss +102 -0
  86. package/scss/field/single-image-drag.scss +88 -0
  87. package/scss/field/vue-drag-uploader.scss +160 -0
  88. package/scss/switcher.scss +156 -0
  89. package/src/app.ts +128 -0
  90. package/src/bootstrap/button-radio.ts +208 -0
  91. package/src/bootstrap/keep-tab.ts +155 -0
  92. package/src/composable/index.ts +21 -0
  93. package/src/composable/useCheckboxesMultiSelect.ts +22 -0
  94. package/src/composable/useFieldCascadeSelect.ts +9 -0
  95. package/src/composable/useFieldFileDrag.ts +9 -0
  96. package/src/composable/useFieldFlatpickr.ts +3 -0
  97. package/src/composable/useFieldModalSelect.ts +6 -0
  98. package/src/composable/useFieldModalTree.ts +3 -0
  99. package/src/composable/useFieldMultiUploader.ts +3 -0
  100. package/src/composable/useFieldRepeatable.ts +9 -0
  101. package/src/composable/useFieldSingleImageDrag.ts +5 -0
  102. package/src/composable/useForm.ts +43 -0
  103. package/src/composable/useGrid.ts +57 -0
  104. package/src/composable/useHttp.ts +8 -0
  105. package/src/composable/useIframeModal.ts +9 -0
  106. package/src/composable/useListDependent.ts +26 -0
  107. package/src/composable/useQueue.ts +13 -0
  108. package/src/composable/useS3Uploader.ts +32 -0
  109. package/src/composable/useShowOn.ts +9 -0
  110. package/src/composable/useStack.ts +13 -0
  111. package/src/composable/useTinymce.ts +29 -0
  112. package/src/composable/useTomSelect.ts +72 -0
  113. package/src/composable/useUIBootstrap5.ts +48 -0
  114. package/src/composable/useUniDirective.ts +32 -0
  115. package/src/composable/useValidation.ts +39 -0
  116. package/src/data.ts +36 -0
  117. package/src/events.ts +73 -0
  118. package/src/legacy/legacy.ts +186 -0
  119. package/src/legacy/loader.ts +125 -0
  120. package/src/module/checkboxes-multi-select.ts +54 -0
  121. package/src/module/field-cascade-select.ts +292 -0
  122. package/src/module/field-file-drag.ts +292 -0
  123. package/src/module/field-flatpickr.ts +127 -0
  124. package/src/module/field-modal-select.ts +174 -0
  125. package/src/module/field-modal-tree.ts +27 -0
  126. package/src/module/field-multi-uploader.ts +361 -0
  127. package/src/module/field-repeatable.ts +202 -0
  128. package/src/module/field-single-image-drag.ts +468 -0
  129. package/src/module/form.ts +223 -0
  130. package/src/module/grid.ts +465 -0
  131. package/src/module/http-client.ts +243 -0
  132. package/src/module/iframe-modal.ts +167 -0
  133. package/src/module/list-dependent.ts +321 -0
  134. package/src/module/s3-multipart-uploader.ts +300 -0
  135. package/src/module/s3-uploader.ts +234 -0
  136. package/src/module/show-on.ts +173 -0
  137. package/src/module/tinymce.ts +263 -0
  138. package/src/module/ui-bootstrap5.ts +107 -0
  139. package/src/module/validation.ts +1019 -0
  140. package/src/plugin/index.ts +1 -0
  141. package/src/plugin/php-adapter.ts +65 -0
  142. package/src/polyfill/form-request-submit.ts +31 -0
  143. package/src/polyfill/index.ts +9 -0
  144. package/src/service/animate.ts +58 -0
  145. package/src/service/crypto.ts +27 -0
  146. package/src/service/dom-watcher.ts +62 -0
  147. package/src/service/dom.ts +265 -0
  148. package/src/service/helper.ts +48 -0
  149. package/src/service/index.ts +10 -0
  150. package/src/service/lang.ts +122 -0
  151. package/src/service/loader.ts +152 -0
  152. package/src/service/router.ts +118 -0
  153. package/src/service/ui.ts +497 -0
  154. package/src/service/uri.ts +106 -0
  155. package/src/types/base.ts +9 -0
  156. package/src/types/index.ts +4 -0
  157. package/src/types/modal-tree.ts +12 -0
  158. package/src/types/plugin.ts +6 -0
  159. package/src/types/shims.d.ts +18 -0
  160. package/src/types/ui.ts +6 -0
  161. package/src/unicorn.ts +63 -0
  162. package/src/utilities/arr.ts +25 -0
  163. package/src/utilities/base.ts +9 -0
  164. package/src/utilities/data.ts +48 -0
  165. package/src/utilities/index.ts +5 -0
  166. package/src/utilities/tree.ts +20 -0
  167. package/src/vue/components/ModalTree/ModalTreeApp.vue +175 -0
  168. package/src/vue/components/ModalTree/TreeItem.vue +262 -0
  169. package/src/vue/components/ModalTree/TreeModal.vue +225 -0
  170. package/tests/test.js +4 -0
  171. package/tsconfig.js.json +25 -0
  172. package/tsconfig.json +17 -0
  173. package/vite.assets.config.ts +61 -0
  174. package/vite.config.test.ts +36 -0
  175. package/vite.config.ts +112 -0
@@ -0,0 +1,234 @@
1
+ import { useHttpClient } from '../composable';
2
+ import { data } from '../data';
3
+ import { EventAwareInterface, EventHandler, EventMixin } from '../events';
4
+ import type { UnicornHttpClient } from './http-client';
5
+ import { mergeDeep } from '../utilities';
6
+ import { AxiosProgressEvent, AxiosResponse } from 'axios';
7
+ import { Mixin } from 'ts-mixer';
8
+
9
+ const instances: Record<string, S3Uploader> = {};
10
+ export function get(name: string, options?: Partial<S3UploaderGlobalOptions>): S3Uploader;
11
+ export function get(
12
+ name: string,
13
+ options: Partial<S3UploaderGlobalOptions> = {}
14
+ ): S3Uploader | void {
15
+ return instances[name] ??= create(name, options);
16
+ }
17
+
18
+ export function create(name: string, options: Partial<S3UploaderGlobalOptions> = {}): S3Uploader {
19
+ return new S3Uploader(name, options);
20
+ }
21
+
22
+ export function destroy(name: string) {
23
+ delete instances[name];
24
+ }
25
+
26
+ const defaultOptions: S3UploaderGlobalOptions = {
27
+ endpoint: '',
28
+ subfolder: '',
29
+ viewerHost: '',
30
+ starts_with: [],
31
+ formInputs: {
32
+ acl: '',
33
+ bucket: '',
34
+ key: '',
35
+ Policy: '',
36
+ 'X-Amz-Algorithm': '',
37
+ 'X-Amz-Credential': '',
38
+ 'X-Amz-Date': '',
39
+ 'X-Amz-Signature': '',
40
+ }
41
+ };
42
+
43
+ export class S3Uploader extends Mixin(EventMixin) implements EventAwareInterface {
44
+ options: S3UploaderGlobalOptions;
45
+ http?: UnicornHttpClient;
46
+
47
+ constructor(protected name: string, options: Partial<S3UploaderGlobalOptions> = {}) {
48
+ super();
49
+
50
+ const awsOptions = data('@s3.uploader.' + name) || {};
51
+
52
+ this.options = mergeDeep<S3UploaderGlobalOptions>({}, defaultOptions, awsOptions, options);
53
+ }
54
+
55
+ async getHttpClient() {
56
+ return this.http ??= await useHttpClient();
57
+ }
58
+
59
+ /**
60
+ * Do upload.
61
+ */
62
+ async upload(
63
+ file: string | File | Blob,
64
+ path: string,
65
+ options: Partial<S3UploaderRequestOptions> = {}
66
+ ): Promise<S3UploaderResponse> {
67
+ const httpClient = await this.getHttpClient();
68
+
69
+ const fileData = new FormData();
70
+ const inputs = mergeDeep({}, this.options.formInputs, options.formInputs || {});
71
+
72
+ if (typeof file === 'string') {
73
+ file = new Blob([file], { type: options['Content-Type'] || 'text/plain' });
74
+ }
75
+
76
+ if (file instanceof Blob && path.endsWith('.{ext}')) {
77
+ throw new Error('If using Blob or file data string, you must provide a valid file extension in the path.');
78
+ }
79
+
80
+ if ((file instanceof Blob) || (file as any) instanceof File) {
81
+ options['Content-Type'] = options['Content-Type'] || file.type;
82
+ }
83
+
84
+ if (options['filename']) {
85
+ const filename = this.replaceExt(options['filename'], file);
86
+ options['Content-Disposition'] = 'attachment; filename*=UTF-8\'\'' + encodeURIComponent(filename);
87
+ }
88
+
89
+ path = this.replaceExt(path, file);
90
+
91
+ options['key'] = trimSlashes(this.options.subfolder || '') + '/'
92
+ + trimSlashes(path);
93
+ options['key'] = trimSlashes(options['key']);
94
+ options['Content-Type'] = options['Content-Type'] || undefined;
95
+ options['Content-Disposition'] = options['Content-Disposition'] || undefined;
96
+
97
+ // Prepare pre-signed data
98
+ for (let key in inputs) {
99
+ fileData.set(key, inputs[key]);
100
+ }
101
+
102
+ // Prepare custom data
103
+ for (let key of Object.keys(this.options.starts_with)) {
104
+ if (options[key]) {
105
+ fileData.set(key, options[key]);
106
+ }
107
+ }
108
+
109
+ fileData.append('file', file);
110
+
111
+ this.trigger('start', fileData);
112
+
113
+ try {
114
+ let res = await httpClient.post(
115
+ this.options.endpoint || '',
116
+ fileData,
117
+ {
118
+ onUploadProgress: (e) => {
119
+ if (options.onUploadProgress) {
120
+ options.onUploadProgress(e);
121
+ }
122
+
123
+ this.trigger('upload-progress', e);
124
+
125
+ if (e.total != null) {
126
+ this.trigger('progress', e.loaded / e.total, e);
127
+ }
128
+ }
129
+ }
130
+ ) as S3UploaderResponse;
131
+
132
+ const url = this.options.viewerHost + '/'
133
+ + trimSlashes(path);
134
+
135
+ this.trigger('success', url, res);
136
+
137
+ res.url = url;
138
+
139
+ return res;
140
+ } finally {
141
+ this.trigger('end');
142
+ }
143
+ }
144
+
145
+ replaceExt(path: string, file: File | Blob): string {
146
+ if (file instanceof File) {
147
+ const fileExt = file.name.split('.').pop();
148
+
149
+ if (path.endsWith('.{ext}')) {
150
+ return path.replace(/\.{ext}$/, fileExt ? '.' + fileExt : '');
151
+ }
152
+ }
153
+
154
+ return path;
155
+ }
156
+
157
+ on(event: 'start', handler: StartEventHandler): this;
158
+ on(event: 'success', handler: SuccessEventHandler): this;
159
+ on(event: 'end', handler: EndEventHandler): this;
160
+ on(event: 'upload-progress', handler: UploadProgressEventHandler): this;
161
+ on(event: 'progress', handler: ProgressEventHandler): this;
162
+ on(event: string | string[], handler: EventHandler): this {
163
+ return super.on(event, handler);
164
+ }
165
+
166
+ onStart(handler: StartEventHandler): this {
167
+ return this.on('start', handler);
168
+ }
169
+
170
+ onSuccess(handler: SuccessEventHandler): this {
171
+ return this.on('success', handler);
172
+ }
173
+
174
+ onEnd(handler: EndEventHandler): this {
175
+ return this.on('end', handler);
176
+ }
177
+
178
+ onProgress(handler: UploadProgressEventHandler): this {
179
+ return this.on('upload-progress', handler);
180
+ }
181
+
182
+ onProgressWithTotal(handler: ProgressEventHandler): this {
183
+ return this.on('progress', handler);
184
+ }
185
+ }
186
+
187
+ type EndEventHandler = () => void;
188
+ type SuccessEventHandler = (url: string, res: S3UploaderResponse) => void;
189
+ type StartEventHandler = (fileData: FormData) => void;
190
+ type UploadProgressEventHandler = (e: AxiosProgressEvent) => void;
191
+ type ProgressEventHandler = (total: number, e: AxiosProgressEvent) => void;
192
+
193
+ function trimSlashes(str: string) {
194
+ return str.replace(/^\/+|\/+$/g, '');
195
+ }
196
+
197
+ export interface S3UploaderResponse extends AxiosResponse {
198
+ url: string;
199
+ }
200
+
201
+ export interface S3UploaderGlobalOptions {
202
+ endpoint?: string;
203
+ subfolder?: string;
204
+ viewerHost?: string;
205
+ starts_with: any[];
206
+ formInputs?: {
207
+ acl: string;
208
+ bucket: string;
209
+ key: string;
210
+ Policy: string;
211
+ 'X-Amz-Algorithm': string;
212
+ 'X-Amz-Credential': string;
213
+ 'X-Amz-Date': string;
214
+ 'X-Amz-Signature': string;
215
+ [name: string]: any
216
+ },
217
+ }
218
+
219
+ export interface S3UploaderRequestOptions {
220
+ formInputs?: { [name: string]: any };
221
+ onUploadProgress?: (e: AxiosProgressEvent) => void;
222
+ 'Content-Type'?: string;
223
+ 'Content-Disposition'?: string;
224
+ key?: string;
225
+
226
+ [name: string]: any;
227
+ }
228
+
229
+ export interface S3UploaderModule {
230
+ get(name: string, options?: Partial<S3UploaderGlobalOptions>): S3Uploader;
231
+ create(name: string, options?: Partial<S3UploaderGlobalOptions>): S3Uploader;
232
+ destroy(name: string): void;
233
+ S3Uploader: typeof S3Uploader;
234
+ }
@@ -0,0 +1,173 @@
1
+
2
+ import { useUniDirective } from '../composable';
3
+ import { fadeIn, fadeOut, selectAll, selectOne, module } from '../service';
4
+ import { difference } from 'lodash-es';
5
+
6
+ type HTMLInputTypes = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
7
+ type Conditions = Record<string, any>;
8
+
9
+ export class ShowOn {
10
+ el!: HTMLElement;
11
+ input!: HTMLInputTypes;
12
+ conditions: Conditions = {};
13
+ targets = {};
14
+ defaultReadonly = false;
15
+ initialDisplay!: string;
16
+
17
+ constructor(el: HTMLElement, conditions: Conditions) {
18
+ this.el = el;
19
+ this.input = this.el.querySelector<HTMLInputTypes>(
20
+ this.el.dataset.inputSelector || '[data-field-input]'
21
+ )!;
22
+ this.conditions = conditions;
23
+
24
+ this.init();
25
+ }
26
+
27
+ init() {
28
+ this.initialDisplay = window.getComputedStyle(this.el).display || 'block';
29
+
30
+ for (const selector in this.conditions) {
31
+ const value = this.conditions[selector];
32
+
33
+ const target = selectOne<HTMLElement>(selector)!;
34
+
35
+ if (this.input) {
36
+ this.defaultReadonly = this.input.hasAttribute('readonly');
37
+ }
38
+
39
+ let listenTarget: HTMLInputTypes[];
40
+
41
+ if (target.nodeName === 'DIV') {
42
+ listenTarget = Array.from(target.querySelectorAll<HTMLInputTypes>('input, select, textarea'));
43
+ } else {
44
+ listenTarget = [target as HTMLInputTypes];
45
+ }
46
+
47
+ selectAll(listenTarget, (ele) => {
48
+ ele.addEventListener('change', () => {
49
+ this.updateShowState(target, value);
50
+ });
51
+ });
52
+
53
+ this.updateShowState(target, value, 1);
54
+ }
55
+ }
56
+
57
+ updateShowState(target: HTMLElement, value: any, duration = 300) {
58
+ const matched = this.isValueMatched(target, value);
59
+
60
+ if (matched) {
61
+ setTimeout(() => {
62
+ fadeIn(this.el, duration, this.initialDisplay);
63
+ }, duration + 30);
64
+ } else {
65
+ if (this.input) {
66
+ this.defaultReadonly = this.input.hasAttribute('readonly');
67
+ }
68
+
69
+ fadeOut(this.el, duration);
70
+ }
71
+
72
+ if (this.input) {
73
+ if (matched) {
74
+ if (!this.defaultReadonly) {
75
+ this.input.removeAttribute('readonly');
76
+ }
77
+ } else {
78
+ this.input.setAttribute('readonly', 'readonly');
79
+ }
80
+ }
81
+ }
82
+
83
+ isValueMatched(target: HTMLElement, value: any) {
84
+ let targetValue: any = null;
85
+
86
+ const type = this.nodeType(target);
87
+
88
+ switch (type) {
89
+ case 'input':
90
+ case 'textarea':
91
+ targetValue = (target as HTMLInputElement).value;
92
+ break;
93
+ case 'select':
94
+ if (!(target as HTMLSelectElement).multiple) {
95
+ targetValue = (target as HTMLSelectElement).value;
96
+ } else {
97
+ targetValue = selectAll(target.querySelectorAll('option'))
98
+ .filter(option => option.selected)
99
+ .map(option => option.value);
100
+ }
101
+ break;
102
+
103
+ case 'checkbox':
104
+ targetValue = (target as HTMLInputElement).checked ? (target as HTMLInputElement).value : [null, false];
105
+ break;
106
+
107
+ case 'radio':
108
+ targetValue = target.querySelector<HTMLInputElement>('input[type=radio]:checked')?.value;
109
+ break;
110
+ }
111
+
112
+ if (Array.isArray(value)) {
113
+ if (Array.isArray(targetValue)) {
114
+ return difference(value, targetValue).length === 0;
115
+ }
116
+
117
+ return value.indexOf(targetValue) !== -1;
118
+ }
119
+
120
+ if (targetValue && Array.isArray(targetValue)) {
121
+ return targetValue.indexOf(value) !== -1;
122
+ }
123
+
124
+ return value == targetValue;
125
+ }
126
+
127
+ /**
128
+ * @see https://github.com/nickjackson/val/blob/master/index.js#L55
129
+ * @param el
130
+ * @returns {string}
131
+ */
132
+ nodeType(el: HTMLElement): "select" | "textarea" | "checkbox" | "input" | "radio" {
133
+ var node = el.nodeName.toLowerCase();
134
+ var type = (el as HTMLInputElement).type;
135
+
136
+ if (node === 'select') {
137
+ return 'select';
138
+ }
139
+
140
+ if (node === 'textarea') {
141
+ return 'textarea';
142
+ }
143
+
144
+ if (node === 'input') {
145
+ if (type === 'checkbox') {
146
+ return 'checkbox';
147
+ }
148
+
149
+ return 'input';
150
+ }
151
+
152
+ if (node === 'div') {
153
+ if (el.querySelector('input[type=radio]')) {
154
+ return 'radio';
155
+ }
156
+ }
157
+
158
+ return 'input';
159
+ }
160
+ }
161
+
162
+ export const ready = useUniDirective('show-on', {
163
+ mounted(el, { value }) {
164
+ module<HTMLElement, HTMLElement>(el, 'show.on', (el) => {
165
+ return new ShowOn(el, JSON.parse(value));
166
+ });
167
+ }
168
+ });
169
+
170
+ export interface ShowOnModule {
171
+ ShowOn: typeof ShowOn;
172
+ ready: typeof ready;
173
+ }
@@ -0,0 +1,263 @@
1
+ import type { Editor, EditorOptions, TinyMCE } from 'tinymce';
2
+ import { useHttpClient, useStack } from '../composable';
3
+ import { useImport } from '../service';
4
+ import { Dictionary, MaybePromise } from '../types';
5
+ import { mergeDeep } from '../utilities';
6
+
7
+ const instances: Dictionary<TinymceController> = {};
8
+ let hooks: ((tinymce: TinyMCE) => MaybePromise<any>)[] = [];
9
+
10
+ let imported = false;
11
+
12
+ declare type UploadHandlerParams = Parameters<NonNullable<EditorOptions['images_upload_handler']>>;
13
+
14
+ export async function get(
15
+ selector: string,
16
+ options: Record<string, any> = {}
17
+ ): Promise<TinymceController> {
18
+ const tinymce = await loadTinymce();
19
+
20
+ return instances[selector] ??= new TinymceController(tinymce, document.querySelector(selector)!, options);
21
+ }
22
+
23
+ export function destroy(selector: string): void {
24
+ delete instances[selector];
25
+ }
26
+
27
+ export function addHook(handler: ((tinymce: TinyMCE) => MaybePromise<any>)) {
28
+ hooks.push(handler);
29
+ }
30
+
31
+ export function clearHooks() {
32
+ hooks = [];
33
+ }
34
+
35
+ async function loadTinymce(): Promise<TinyMCE> {
36
+ await useImport('@tinymce');
37
+
38
+ if (imported) {
39
+ return tinymce;
40
+ }
41
+ imported = true;
42
+ for (const hook of hooks) {
43
+ hook(tinymce);
44
+ }
45
+ await registerDragPlugin(tinymce);
46
+ return tinymce;
47
+ }
48
+
49
+ const defaultOptions: Record<string, any> = {};
50
+
51
+ export class TinymceController {
52
+ editor?: Editor;
53
+ options: Record<string, any> = {};
54
+
55
+ constructor(protected tinymce: TinyMCE, public element: HTMLElement, options: Record<string, any>) {
56
+ options.target = element;
57
+
58
+ this.options = mergeDeep(
59
+ {
60
+ unicorn: {
61
+ stack_name: 'uploading'
62
+ }
63
+ },
64
+ defaultOptions,
65
+ this.prepareOptions(options, tinymce.majorVersion),
66
+ );
67
+
68
+ tinymce.EditorManager.init(this.options).then((editor) => {
69
+ this.editor = editor[0];
70
+ });
71
+ }
72
+
73
+ prepareOptions(options: Record<string, any>, version = '6') {
74
+ const defaults: Partial<EditorOptions> = {};
75
+
76
+ if (options.images_upload_url) {
77
+ defaults.paste_data_images = true;
78
+ defaults.remove_script_host = false;
79
+ defaults.relative_urls = false;
80
+
81
+ if (Number(version) >= 6) {
82
+ defaults.images_upload_handler = (blobInfo, progress) =>
83
+ this.imageUploadHandler(blobInfo, progress);
84
+ } else {
85
+ options.plugins.push('paste');
86
+
87
+ // @ts-ignore
88
+ defaults.images_upload_handler = (blobInfo, success, failure, progress) =>
89
+ this.imageUploadHandler(blobInfo, progress)
90
+ .then((url) => {
91
+ success(url);
92
+ return url;
93
+ })
94
+ .catch((e) => {
95
+ failure(e.message, { remove: true });
96
+ throw e;
97
+ });
98
+ }
99
+ }
100
+
101
+ // defaults.file_picker_callback = (...args) => this.filePickerCallback(...args);
102
+
103
+ defaults.plugins = defaults.plugins || [];
104
+
105
+ defaults.setup = (editor) => {
106
+ editor.on('change', () => {
107
+ this.tinymce.triggerSave();
108
+ });
109
+ };
110
+
111
+ options = mergeDeep({}, defaults, options);
112
+
113
+ if (options.plugins.indexOf('unicorndragdrop') === -1) {
114
+ options.plugins.push('unicorndragdrop');
115
+ }
116
+
117
+ return options;
118
+ }
119
+
120
+ insert(text: string) {
121
+ this.editor?.insertContent(text);
122
+ }
123
+
124
+ getValue(): string {
125
+ return this.editor?.getContent() ?? '';
126
+ }
127
+
128
+ setValue(text: string): void {
129
+ this.editor?.setContent(text);
130
+ }
131
+
132
+ // filePickerCallback(callback, value, meta) {
133
+ // const input = document.createElement('input');
134
+ // input.setAttribute('type', 'file');
135
+ // input.style.display = 'none';
136
+ //
137
+ // if (meta.filetype === 'image') {
138
+ // input.setAttribute('accept', `image/\*`);
139
+ // }
140
+ //
141
+ // document.body.appendChild(input);
142
+ //
143
+ // input.onchange = function () {
144
+ // const file = this.files[0];
145
+ //
146
+ // const reader = new FileReader();
147
+ // reader.onload = function () {
148
+ // const id = 'blobid' + (new Date()).getTime();
149
+ // const blobCache = tinymce.activeEditor.editorUpload.blobCache;
150
+ // const base64 = reader.result.split(',')[1];
151
+ // const blobInfo = blobCache.create(id, file, base64);
152
+ // blobCache.add(blobInfo);
153
+ //
154
+ // /* call the callback and populate the Title field with the file name */
155
+ // callback(blobInfo.blobUri(), { title: file.name, text: file.name });
156
+ // };
157
+ // reader.readAsDataURL(file);
158
+ // input.remove();
159
+ // };
160
+ //
161
+ // input.click();
162
+ // }
163
+
164
+ async imageUploadHandler(blobInfo: UploadHandlerParams[0], progress: UploadHandlerParams[1]) {
165
+ const element = this.element;
166
+
167
+ element.dispatchEvent(new CustomEvent('upload-start'));
168
+
169
+ const formData = new FormData();
170
+ formData.append('file', blobInfo.blob(), blobInfo.filename());
171
+
172
+ const stack = useStack(this.options.unicorn.stack_name);
173
+ stack.push(true);
174
+
175
+ const { post, isAxiosError } = await useHttpClient();
176
+
177
+ try {
178
+ let res = await post(
179
+ this.options.images_upload_url,
180
+ formData,
181
+ {
182
+ withCredentials: false,
183
+ onUploadProgress: (e) => {
184
+ progress(e.loaded / e.total! * 100);
185
+ }
186
+ }
187
+ );
188
+ element.dispatchEvent(new CustomEvent('upload-success'));
189
+
190
+ return res.data.data.url;
191
+ } catch (err) {
192
+ if (isAxiosError(err)) {
193
+ const message = err?.response?.data?.message || err.message;
194
+ console.error(err?.response?.data?.message || err.message, err);
195
+ element.dispatchEvent(new CustomEvent('upload-error', { detail: err }));
196
+
197
+ return Promise.reject({ message, remove: true });
198
+ }
199
+
200
+ throw err;
201
+ } finally {
202
+ element.dispatchEvent(new CustomEvent('upload-complete'));
203
+ stack.pop();
204
+ }
205
+ }
206
+ }
207
+
208
+ function registerDragPlugin(tinymce: TinyMCE) {
209
+ tinymce.PluginManager.add('unicorndragdrop', function (editor) {
210
+ // Reset the drop area border
211
+ tinymce.DOM.bind(document, 'dragleave', function (e) {
212
+ e.stopPropagation();
213
+ e.preventDefault();
214
+
215
+ if (tinymce.activeEditor) {
216
+ tinymce.activeEditor.contentAreaContainer.style.transition = 'all .3s';
217
+ tinymce.activeEditor.contentAreaContainer.style.borderWidth = '';
218
+ }
219
+
220
+ return false;
221
+ });
222
+
223
+ if (typeof FormData !== 'undefined') {
224
+
225
+ // Fix for Chrome
226
+ editor.on('dragenter', e => {
227
+ e.stopPropagation();
228
+ return false;
229
+ });
230
+
231
+ // Notify user when file is over the drop area
232
+ editor.on('dragover', e => {
233
+ e.preventDefault();
234
+
235
+ if (tinymce.activeEditor) {
236
+ tinymce.activeEditor.contentAreaContainer.style.transition = 'all .3s';
237
+ tinymce.activeEditor.contentAreaContainer.style.border = '3px dashed rgba(0, 0, 0, .35)';
238
+ }
239
+
240
+ return false;
241
+ });
242
+
243
+ editor.on('drop', e => {
244
+ editor.contentAreaContainer.style.borderWidth = '';
245
+ editor.contentAreaContainer.style.borderWidth = '';
246
+ });
247
+ }
248
+ });
249
+
250
+ return Promise.resolve();
251
+ }
252
+
253
+ export interface TinymceModule {
254
+ get: typeof get;
255
+ destroy: typeof destroy;
256
+ addHook: typeof addHook;
257
+ clearHooks: typeof clearHooks;
258
+ TinymceController: typeof TinymceController;
259
+ }
260
+
261
+ declare global {
262
+ var tinymce: TinyMCE;
263
+ }