Repository navigation
Expand file tree
/
Copy pathutils.ts
More file actions
389 lines (345 loc) · 9.53 KB
/
Copy pathutils.ts
File metadata and controls
389 lines (345 loc) · 9.53 KB
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/**
* Class Util
*/
import Dom from './dom';
/**
* Allow to use global VERSION, that will be overwritten by Webpack
*/
declare const VERSION: string;
/**
* @typedef {Object} ChainData
* @property {Object} data - data that will be passed to the success or fallback
* @property {Function} function - function's that must be called asynchronically
*/
export interface ChainData {
data?: any;
function: (...args: any[]) => any;
}
/**
* Editor.js utils
*/
export default class Util {
/**
* Custom logger
*
* @param {string} msg - message
* @param {string} type - logging type 'log'|'warn'|'error'|'info'
* @param {*} [args] - argument to log with a message
* @param {string} style - additional styling to message
*/
public static log(msg: string, type: string = 'log', args?: any, style: string = 'color: inherit'): void {
if ( !('console' in window) || !window.console[ type ] ) {
return;
}
const editorLabelText = `Editor.js ${VERSION}`;
const editorLabelStyle = `line-height: 1em;
color: #006FEA;
display: inline-block;
font-size: 11px;
line-height: 1em;
background-color: #fff;
padding: 4px 9px;
border-radius: 30px;
border: 1px solid rgba(56, 138, 229, 0.16);
margin: 4px 5px 4px 0;`;
try {
if (['time', 'timeEnd'].includes(type)) {
console[type](`( ${editorLabelText} ) ${msg}`);
} else if (args) {
console[type](`%c${editorLabelText}%c ${msg} %o`, editorLabelStyle, style, args);
} else {
console[type](`%c${editorLabelText}%c ${msg}`, editorLabelStyle, style);
}
} catch (ignored) {}
}
/**
* Returns basic keycodes as constants
* @return {{}}
*/
static get keyCodes() {
return {
BACKSPACE: 8,
TAB: 9,
ENTER: 13,
SHIFT: 16,
CTRL: 17,
ALT: 18,
ESC: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
DOWN: 40,
RIGHT: 39,
DELETE: 46,
META: 91,
};
}
/**
* Return mouse buttons codes
*/
static get mouseButtons() {
return {
LEFT: 0,
WHEEL: 1,
RIGHT: 2,
BACKWARD: 3,
FORWARD: 4,
};
}
/**
* Returns true if passed key code is printable (a-Z, 0-9, etc) character.
* @param {number} keyCode
* @return {boolean}
*/
public static isPrintableKey( keyCode: number ): boolean {
return (keyCode > 47 && keyCode < 58) || // number keys
keyCode === 32 || keyCode === 13 || // Spacebar & return key(s)
(keyCode > 64 && keyCode < 91) || // letter keys
(keyCode > 95 && keyCode < 112) || // Numpad keys
(keyCode > 185 && keyCode < 193) || // ;=,-./` (in order)
(keyCode > 218 && keyCode < 223); // [\]' (in order)
}
/**
* Fires a promise sequence asyncronically
*
* @param {ChainData[]} chains - list or ChainData's
* @param {Function} success - success callback
* @param {Function} fallback - callback that fires in case of errors
*
* @return {Promise}
*/
public static async sequence(
chains: ChainData[],
success: (data: any) => void = () => {},
fallback: (data: any) => void = () => {},
): Promise<void> {
/**
* Decorator
*
* @param {ChainData} chainData
*
* @param {Function} successCallback
* @param {Function} fallbackCallback
*
* @return {Promise}
*/
async function waitNextBlock(
chainData: ChainData,
successCallback: (data: any) => void,
fallbackCallback: (data: any) => void,
): Promise<void> {
try {
await chainData.function(chainData.data);
await successCallback(typeof chainData.data !== 'undefined' ? chainData.data : {});
} catch (e) {
fallbackCallback(typeof chainData.data !== 'undefined' ? chainData.data : {});
}
}
/**
* pluck each element from queue
* First, send resolved Promise as previous value
* Each plugins "prepare" method returns a Promise, that's why
* reduce current element will not be able to continue while can't get
* a resolved Promise
*/
return await chains.reduce(async (previousValue, currentValue) => {
await previousValue;
return waitNextBlock(currentValue, success, fallback);
}, Promise.resolve());
}
/**
* Make array from array-like collection
*
* @param {ArrayLike} collection
*
* @return {Array}
*/
public static array(collection: ArrayLike<any>): any[] {
return Array.prototype.slice.call(collection);
}
/**
* Check if passed variable is a function
* @param {*} fn
* @return {boolean}
*/
public static isFunction(fn: any): boolean {
return typeof fn === 'function';
}
/**
* Check if passed function is a class
* @param {function} fn
* @return {boolean}
*/
public static isClass(fn: any): boolean {
return typeof fn === 'function' && /^\s*class\s+/.test(fn.toString());
}
/**
* Checks if object is empty
*
* @param {Object} object
* @return {boolean}
*/
public static isEmpty(object: object): boolean {
if (!object) {
return true;
}
return Object.keys(object).length === 0 && object.constructor === Object;
}
/**
* Check if passed object is a Promise
* @param {*} object - object to check
* @return {Boolean}
*/
public static isPromise(object: any): boolean {
return Promise.resolve(object) === object;
}
/**
* Delays method execution
*
* @param {Function} method
* @param {Number} timeout
*/
public static delay(method: (...args: any[]) => any, timeout: number) {
return function() {
const context = this,
args = arguments;
window.setTimeout(() => method.apply(context, args), timeout);
};
}
/**
* Get file extension
*
* @param {File} file
* @return string
*/
public static getFileExtension(file: File): string {
return file.name.split('.').pop();
}
/**
* Check if string is MIME type
*
* @param {string} type
* @return boolean
*/
public static isValidMimeType(type: string): boolean {
return /^[-\w]+\/([-+\w]+|\*)$/.test(type);
}
/**
* Debouncing method
* Call method after passed time
*
* Note that this method returns Function and declared variable need to be called
*
* @param {Function} func - function that we're throttling
* @param {Number} wait - time in milliseconds
* @param {Boolean} immediate - call now
* @return {Function}
*/
public static debounce(func: () => void, wait?: number , immediate?: boolean): () => void {
let timeout;
return () => {
const context = this,
args = arguments;
const later = () => {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
const callNow = immediate && !timeout;
window.clearTimeout(timeout);
timeout = window.setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
}
/**
* Copies passed text to the clipboard
* @param text
*/
public static copyTextToClipboard(text) {
const el = Dom.make('div', 'codex-editor-clipboard', {
innerHTML: text,
});
document.body.appendChild(el);
const selection = window.getSelection();
const range = document.createRange();
range.selectNode(el);
window.getSelection().removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
document.body.removeChild(el);
}
/**
* Returns object with os name as key and boolean as value. Shows current user OS
*
* @return {[key: string]: boolean}
*/
public static getUserOS(): {[key: string]: boolean} {
const OS = {
win: false,
mac: false,
x11: false,
linux: false,
};
const userOS = Object.keys(OS).find((os: string) => navigator.appVersion.toLowerCase().indexOf(os) !== -1);
if (userOS) {
OS[userOS] = true;
return OS;
}
return OS;
}
/**
* Capitalizes first letter of the string
* @param {string} text
* @return {string}
*/
public static capitalize(text: string): string {
return text[0].toUpperCase() + text.slice(1);
}
/**
* Merge to objects recursively
* @param {object} target
* @param {object[]} sources
* @return {object}
*/
public static deepMerge(target, ...sources) {
const isObject = (item) => item && Util.typeof(item) === 'object';
if (!sources.length) { return target; }
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) {
Object.assign(target, { [key]: {} });
}
Util.deepMerge(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
}
}
return Util.deepMerge(target, ...sources);
}
/**
* Return true if current device supports touch events
*
* Note! This is a simple solution, it can give false-positive results.
* To detect touch devices more carefully, use 'touchstart' event listener
* @see http://www.stucox.com/blog/you-cant-detect-a-touchscreen/
*
* @return {boolean}
*/
public static isTouchSupported(): boolean {
return 'ontouchstart' in document.documentElement;
}
/**
* Return string representation of the object type
*
* @param {any} object
*/
public static typeof(object: any): string {
return Object.prototype.toString.call(object).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}
}