-
Notifications
You must be signed in to change notification settings - Fork 409
/
helpers.js
372 lines (345 loc) · 9.69 KB
/
helpers.js
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
import ajax from '@deadlyjack/ajax';
import escapeStringRegexp from 'escape-string-regexp';
import Url from './Url';
import Uri from './Uri';
import path from './Path';
import alert from 'dialogs/alert';
import constants from 'lib/constants';
/**
* Gets programming language name according to filename
* @param {String} filename
* @returns
*/
function getFileType(filename) {
const regex = {
babel: /\.babelrc$/i,
jsmap: /\.js\.map$/i,
yarn: /^yarn\.lock$/i,
testjs: /\.test\.js$/i,
testts: /\.test\.ts$/i,
cssmap: /\.css\.map$/i,
typescriptdef: /\.d\.ts$/i,
clojurescript: /\.cljs$/i,
cppheader: /\.(hh|hpp)$/i,
jsconfig: /^jsconfig.json$/i,
tsconfig: /^tsconfig.json$/i,
android: /\.(apk|aab|slim)$/i,
jsbeautify: /^\.jsbeautifyrc$/i,
webpack: /^webpack\.config\.js$/i,
audio: /\.(mp3|wav|ogg|flac|aac)$/i,
git: /(^\.gitignore$)|(^\.gitmodules$)/i,
video: /\.(mp4|m4a|mov|3gp|wmv|flv|avi)$/i,
image: /\.(png|jpg|jpeg|gif|bmp|ico|webp)$/i,
npm: /(^package\.json$)|(^package\-lock\.json$)/i,
compressed: /\.(zip|rar|7z|tar|gz|gzip|dmg|iso)$/i,
eslint: /(^\.eslintrc(\.(json5?|ya?ml|toml))?$|eslint\.config\.(c?js|json)$)/i,
postcssconfig: /(^\.postcssrc(\.(json5?|ya?ml|toml))?$|postcss\.config\.(c?js|json)$)/i,
prettier: /(^\.prettierrc(\.(json5?|ya?ml|toml))?$|prettier\.config\.(c?js|json)$)/i,
};
const fileType = Object.keys(regex).find((type) => regex[type].test(filename));
if (fileType) return fileType;
return Url.extname(filename).substring(1);
}
export default {
/**
* @deprecated This method is deprecated, use 'encodings.decode' instead.
* Decodes arrayBuffer to String according given encoding type
* @param {ArrayBuffer} arrayBuffer
* @param {String} [encoding='utf-8']
*/
decodeText(arrayBuffer, encoding = 'utf-8') {
const isJson = encoding === 'json';
if (isJson) encoding = 'utf-8';
const uint8Array = new Uint8Array(arrayBuffer);
const result = new TextDecoder(encoding).decode(uint8Array);
if (isJson) {
return this.parseJSON(result);
}
return result;
},
/**
* Gets icon according to filename
* @param {string} filename
*/
getIconForFile(filename) {
const { getModeForPath } = ace.require('ace/ext/modelist');
const type = getFileType(filename);
const { name } = getModeForPath(filename);
const iconForMode = `file_type_${name}`;
const iconForType = `file_type_${type}`;
return `file file_type_default ${iconForMode} ${iconForType}`;
},
/**
*
* @param {FileEntry[]} list
* @param {object} fileBrowser settings
* @param {'both'|'file'|'folder'}
*/
sortDir(list, fileBrowser, mode = 'both') {
const dir = [];
const file = [];
const sortByName = fileBrowser.sortByName;
const showHiddenFile = fileBrowser.showHiddenFiles;
list.forEach((item) => {
let hidden;
item.name = item.name || path.basename(item.url || '');
hidden = item.name[0] === '.';
if (typeof item.isDirectory !== 'boolean') {
if (this.isDir(item.type)) item.isDirectory = true;
}
if (!item.type) item.type = item.isDirectory ? 'dir' : 'file';
if (!item.url) item.url = item.url || item.uri;
if ((hidden && showHiddenFile) || !hidden) {
if (item.isDirectory) {
dir.push(item);
} else if (item.isFile) {
file.push(item);
}
}
if (item.isDirectory) {
item.icon = 'folder';
} else {
if (mode === 'folder') {
item.disabled = true;
}
item.icon = this.getIconForFile(item.name);
}
});
if (sortByName) {
dir.sort(compare);
file.sort(compare);
}
return dir.concat(file);
function compare(a, b) {
return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1;
}
},
/**
* Gets error message from error object
* @param {Error} err
* @param {...string} args
*/
errorMessage(err, ...args) {
args.forEach((arg, i) => {
if (/^(content|file|ftp|sftp|https?):/.test(arg)) {
args[i] = this.getVirtualPath(arg);
}
});
const extra = args.join('<br>');
let msg;
if (typeof err === 'string' && err) {
msg = err;
} else if (err instanceof Error) {
msg = err.message;
} else {
msg = strings['an error occurred'];
}
return msg + (extra ? '<br>' + extra : '');
},
/**
*
* @param {Error} err
* @param {...string} args
* @returns {PromiseLike<void>}
*/
error(err, ...args) {
if (err.code === 0) {
toast(err);
return;
}
let hide = null;
const onhide = () => {
if (hide) hide();
};
const promise = {
then(fun) {
if (typeof fun === 'function') {
hide = fun;
}
},
};
const msg = this.errorMessage(err, ...args);
alert(strings.error, msg, onhide);
return promise;
},
/**
* Returns unique ID
* @returns {string}
*/
uuid() {
return (
new Date().getTime() + parseInt(Math.random() * 100000000000)
).toString(36);
},
/**
* Parses JSON string, if fails returns null
* @param {Object|Array} string
*/
parseJSON(string) {
if (!string) return null;
try {
return JSON.parse(string);
} catch (e) {
return null;
}
},
/**
* Checks whether given type is directory or not
* @param {'dir'|'directory'|'folder'} type
* @returns {Boolean}
*/
isDir(type) {
return /^(dir|directory|folder)$/.test(type);
},
/**
* Checks whether given type is file or not
* @param {'file'|'link'} type
* @returns {Boolean}
*/
isFile(type) {
return /^(file|link)$/.test(type);
},
/**
* Replace matching part of url to alias name by which storage is added
* @param {String} url
* @returns {String}
*/
getVirtualPath(url) {
url = Url.parse(url).url;
if (/^content:/.test(url)) {
const primary = Uri.getPrimaryAddress(url);
if (primary) {
return primary;
}
}
/**@type {string[]} */
const storageList = JSON.parse(localStorage.storageList || '[]');
const storageListLen = storageList.length;
for (let i = 0; i < storageListLen; ++i) {
const uuid = storageList[i];
let storageUrl = Url.parse(uuid.uri || uuid.url || '').url;
if (!storageUrl) continue;
if (storageUrl.endsWith('/')) {
storageUrl = storageUrl.slice(0, -1);
}
const regex = new RegExp('^' + escapeStringRegexp(storageUrl));
if (regex.test(url)) {
url = url.replace(regex, uuid.name);
break;
}
}
return url;
},
/**
* Updates uri of all active which matches the oldUrl as location
* of the file
* @param {String} oldUrl
* @param {String} newUrl
*/
updateUriOfAllActiveFiles(oldUrl, newUrl) {
const files = editorManager.files;
const { url } = Url.parse(oldUrl);
for (let file of files) {
if (!file.uri) continue;
const fileUrl = Url.parse(file.uri).url;
if (new RegExp('^' + escapeStringRegexp(url)).test(fileUrl)) {
if (newUrl) {
file.uri = Url.join(newUrl, file.filename);
} else {
file.uri = null;
}
}
}
editorManager.onupdate('file-delete');
editorManager.emit('update', 'file-delete');
},
/**
* Displays ad on the current page
*/
showAd() {
const { ad } = window;
if (
IS_FREE_VERSION
&& (innerHeight * devicePixelRatio) > 600 && ad
) {
const $page = tag.getAll('wc-page:not(#root)').pop();
if ($page) {
ad.active = true;
ad.show();
}
}
},
/**
* Hides the ad
* @param {Boolean} [force=false]
*/
hideAd(force = false) {
const { ad } = window;
if (IS_FREE_VERSION && ad?.active) {
const $pages = tag.getAll('.page-replacement');
const hide = $pages.length === 1;
if (force || hide) {
ad.active = false;
ad.hide();
}
}
},
async toInternalUri(uri) {
return new Promise((resolve, reject) => {
window.resolveLocalFileSystemURL(uri, (entry) => {
resolve(entry.toInternalURL());
}, reject);
});
},
promisify(func, ...args) {
return new Promise((resolve, reject) => {
func(...args, resolve, reject);
});
},
async checkAPIStatus() {
try {
const { status } = await ajax.get(Url.join(constants.API_BASE, 'status'));
return status === 'ok';
} catch (error) {
return false;
}
},
fixFilename(name) {
if (!name) return name;
return name.replace(/(\r\n)+|\r+|\n+|\t+/g, '').trim();
},
/**
* Creates a debounced function that delays invoking the input function until after 'wait' milliseconds have elapsed
* since the last time the debounced function was invoked. Useful for implementing behavior that should only happen
* after the input is complete.
*
* @param {Function} func - The function to debounce.
* @param {number} wait - The number of milliseconds to delay.
* @returns {Function} The new debounced function.
* @example
* window.addEventListener('resize', debounce(myFunction, 200));
*/
debounce(func, wait) {
let timeout;
return function debounced(...args) {
const later = () => {
clearTimeout(timeout);
func.apply(this, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
},
defineDeprecatedProperty(obj, name, getter, setter) {
Object.defineProperty(obj, name, {
get: function () {
console.warn(`Property '${name}' is deprecated.`);
return getter.call(this);
},
set: function (value) {
console.warn(`Property '${name}' is deprecated.`);
setter.call(this, value);
}
});
}
};;;