-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
mixins.ts
262 lines (212 loc) · 6.93 KB
/
mixins.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import { isArray, isElement, isFunction, isUndefined, keys } from 'underscore';
import ComponentView from '../dom_components/view/ComponentView';
import EditorModel from '../editor/model/Editor';
import { isTextNode } from './dom';
import Component from '../dom_components/model/Component';
import { ObjectAny } from '../common';
const obj: ObjectAny = {};
export const isBultInMethod = (key: string) => isFunction(obj[key]);
export const normalizeKey = (key: string) => (isBultInMethod(key) ? `_${key}` : key);
export const wait = (mls: number = 0) => new Promise(res => setTimeout(res, mls));
export const isDef = (value: any) => typeof value !== 'undefined';
export const hasWin = () => typeof window !== 'undefined';
export const getGlobal = () =>
typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : global;
export const toLowerCase = (str: string) => (str || '').toLowerCase();
const elProt = hasWin() ? window.Element.prototype : {};
// @ts-ignore
const matches = elProt.matches || elProt.webkitMatchesSelector || elProt.mozMatchesSelector || elProt.msMatchesSelector;
export const getUiClass = (em: EditorModel, defCls: string) => {
const { stylePrefix, customUI } = em.getConfig();
return [customUI && `${stylePrefix}cui`, defCls].filter(i => i).join(' ');
};
/**
* Import styles asynchronously
* @param {String|Array<String>} styles
*/
const appendStyles = (styles: {}, opts: { unique?: boolean; prepand?: boolean } = {}) => {
const stls = isArray(styles) ? [...styles] : [styles];
if (stls.length) {
const href = stls.shift();
if (href && (!opts.unique || !document.querySelector(`link[href="${href}"]`))) {
const { head } = document;
const link = document.createElement('link');
link.href = href;
link.rel = 'stylesheet';
if (opts.prepand) {
head.insertBefore(link, head.firstChild);
} else {
head.appendChild(link);
}
}
appendStyles(stls);
}
};
/**
* Returns shallow diff between 2 objects
* @param {Object} objOrig
* @param {Objec} objNew
* @return {Object}
* @example
* var a = {foo: 'bar', baz: 1, faz: 'sop'};
* var b = {foo: 'bar', baz: 2, bar: ''};
* shallowDiff(a, b);
* // -> {baz: 2, faz: null, bar: ''};
*/
const shallowDiff = (objOrig: ObjectAny, objNew: ObjectAny) => {
const result: ObjectAny = {};
const keysNew = keys(objNew);
for (let prop in objOrig) {
if (objOrig.hasOwnProperty(prop)) {
const origValue = objOrig[prop];
const newValue = objNew[prop];
if (keysNew.indexOf(prop) >= 0) {
if (origValue !== newValue) {
result[prop] = newValue;
}
} else {
result[prop] = null;
}
}
}
for (let prop in objNew) {
if (objNew.hasOwnProperty(prop)) {
if (isUndefined(objOrig[prop])) {
result[prop] = objNew[prop];
}
}
}
return result;
};
const getUnitFromValue = (value: any) => {
return value.replace(parseFloat(value), '');
};
const upFirst = (value: string) => value[0].toUpperCase() + value.toLowerCase().slice(1);
const camelCase = (value: string) => {
return value.replace(/-./g, x => x[1].toUpperCase());
};
const normalizeFloat = (value: any, step = 1, valueDef = 0) => {
let stepDecimals = 0;
if (isNaN(value)) return valueDef;
value = parseFloat(value);
if (Math.floor(value) !== value) {
const side = step.toString().split('.')[1];
stepDecimals = side ? side.length : 0;
}
return stepDecimals ? parseFloat(value.toFixed(stepDecimals)) : value;
};
const hasDnd = (em: EditorModel) => {
return 'draggable' in document.createElement('i') && (em ? em.config.nativeDnD! : true);
};
/**
* Ensure to fetch the element from the input argument
* @param {HTMLElement|Component} el Component or HTML element
* @return {HTMLElement}
*/
const getElement = (el: HTMLElement) => {
if (isElement(el) || isTextNode(el)) {
return el;
// @ts-ignore
} else if (el && el.getEl) {
// @ts-ignore
return el.getEl();
}
};
export const find = (arr: any[], test: (item: any, i: number, arr: any[]) => boolean) => {
let result = null;
arr.some((el, i) => (test(el, i, arr) ? ((result = el), 1) : 0));
return result;
};
export const escape = (str = '') => {
return `${str}`
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/`/g, '`');
};
export const escapeNodeContent = (str = '') => {
return `${str}`.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
};
export const deepMerge = (...args: ObjectAny[]) => {
const target = { ...args[0] };
for (let i = 1; i < args.length; i++) {
const source = { ...args[i] };
for (let key in source) {
const targValue = target[key];
const srcValue = source[key];
if (isObject(targValue) && isObject(srcValue)) {
target[key] = deepMerge(targValue, srcValue);
} else {
target[key] = srcValue;
}
}
}
return target;
};
/**
* Ensure to fetch the model from the input argument
* @param {HTMLElement|Component} el Component or HTML element
* @return {Component}
*/
const getModel = (el: any, $?: any): Component => {
let model = el;
if (!$ && el && el.__cashData) {
model = el.__cashData.model;
} else if (isElement(el)) {
model = $(el).data('model');
}
return model;
};
const isObject = (val: any): val is ObjectAny => val && !Array.isArray(val) && typeof val === 'object';
const isEmptyObj = (val: ObjectAny) => Object.keys(val).length <= 0;
const capitalize = (str: string = '') => str && str.charAt(0).toUpperCase() + str.substring(1);
const isRule = (obj: any) => obj && obj.toCSS;
const getViewEl = <T extends any>(el?: Node): T | undefined => (el as any)?.__gjsv;
export const isComponent = (obj: any): obj is Component => !!obj?.toHTML;
export const getComponentView = (el?: Node) => getViewEl<ComponentView>(el);
export const getComponentModel = (el?: Node) => getComponentView(el)?.model;
const setViewEl = (el: any, view: any) => {
el.__gjsv = view;
};
const createId = (length = 16) => {
let result = '';
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const len = chars.length;
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * len));
}
return result;
};
export const buildBase64UrlFromSvg = (svg: string) => {
if (svg && svg.substr(0, 4) === '<svg') {
let base64Str = '';
if (hasWin()) {
base64Str = window.btoa(svg);
} else if (typeof Buffer !== 'undefined') {
base64Str = Buffer.from(svg, 'utf8').toString('base64');
}
return base64Str ? `data:image/svg+xml;base64,${base64Str}` : svg;
}
return svg;
};
export {
hasDnd,
upFirst,
matches,
getModel,
camelCase,
getElement,
shallowDiff,
normalizeFloat,
getUnitFromValue,
capitalize,
getViewEl,
setViewEl,
appendStyles,
isObject,
isEmptyObj,
createId,
isRule,
};