forked from Acode-Foundation/Acode
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsettings.js
More file actions
425 lines (382 loc) · 10.4 KB
/
settings.js
File metadata and controls
425 lines (382 loc) · 10.4 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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import fsOperation from "fileSystem";
import ThemeBuilder from "theme/builder";
import themes from "theme/list";
import { getSystemEditorTheme } from "theme/preInstalled";
import helpers from "utils/helpers";
import Url from "utils/Url";
import constants from "./constants";
import lang from "./lang";
import { isDeviceDarkTheme } from "./systemConfiguration";
/**
* @typedef {object} fileBrowserSettings
* @property {string} showHiddenFiles
* @property {string} sortByName
*/
/**
* @typedef {object} searchAndFindSettings
* @property {boolean} wrap
* @property {boolean} caseSensitive
* @property {boolean} regExp
*/
class Settings {
#customTheme = new ThemeBuilder("Custom").toJSON();
#defaultSettings;
#oldSettings;
#initialized = false;
#on = {
update: [],
"update:after": [],
reset: [],
};
#searchSettings = {
caseSensitive: false,
regExp: false,
wholeWord: false,
};
#fileBrowserSettings = {
showHiddenFiles: false,
sortByName: true,
};
#excludeFolders = [
"**/node_modules/**",
"**/bower_components/**",
"**/jspm_packages/**",
"**/.npm/**",
"**/flow-typed/**",
"**/vendor/**",
"**/composer/**",
"**/venv/**",
"**/.virtualenv/**",
"**/__pycache__/**",
"**/.pytest_cache/**",
"**/.eggs/**",
"**/*.egg-info/**",
"**/.git/**",
"**/.svn/**",
"**/.hg/**",
"**/.vscode/**",
"**/.idea/**",
"**/.vs/**",
"**/.project/**",
"**/.settings/**",
"**/.classpath/**",
"**/dist/**",
"**/build/**",
"**/out/**",
"**/target/**",
"**/bin/**",
"**/obj/**",
"**/coverage/**",
"**/.nyc_output/**",
"**/htmlcov/**",
"**/temp/**",
"**/tmp/**",
"**/.cache/**",
"**/logs/**",
"**/.sass-cache/**",
"**/.DS_Store/**",
"**/Thumbs.db/**",
];
#IS_TABLET = innerWidth > 768;
QUICKTOOLS_ROWS = 2;
QUICKTOOLS_GROUP_CAPACITY = 8;
QUICKTOOLS_GROUPS = 2;
#QUICKTOOLS_SIZE =
this.QUICKTOOLS_GROUP_CAPACITY * // items per group
this.QUICKTOOLS_GROUPS * // number of groups
this.QUICKTOOLS_ROWS; // number of rows
QUICKTOOLS_TRIGGER_MODE_TOUCH = "touch";
QUICKTOOLS_TRIGGER_MODE_CLICK = "click";
OPEN_FILE_LIST_POS_HEADER = "header";
OPEN_FILE_LIST_POS_SIDEBAR = "sidebar";
OPEN_FILE_LIST_POS_BOTTOM = "bottom";
KEYBOARD_MODE_NO_SUGGESTIONS = "NO_SUGGESTIONS";
KEYBOARD_MODE_NO_SUGGESTIONS_AGGRESSIVE = "NO_SUGGESTIONS_AGGRESSIVE";
KEYBOARD_MODE_NORMAL = "NORMAL";
CONSOLE_ERUDA = "eruda";
CONSOLE_LEGACY = "legacy";
PREVIEW_MODE_INAPP = "inapp";
PREVIEW_MODE_BROWSER = "browser";
/**@type {{[key: string]: import('components/settingsPage').SettingsPage}} */
uiSettings = {};
constructor() {
this.#defaultSettings = {
animation: "system",
appTheme: "dark",
autosave: 0,
fileBrowser: this.#fileBrowserSettings,
formatter: {},
prettier: {},
maxFileSize: 12,
serverPort: constants.SERVER_PORT,
previewPort: constants.PREVIEW_PORT,
showConsoleToggler: true,
previewMode: this.PREVIEW_MODE_INAPP,
disableCache: false,
useCurrentFileForPreview: false,
host: "localhost",
search: this.#searchSettings,
lang: "en-us",
fontSize: "12px",
editorTheme: "one_dark",
textWrap: true,
softTab: true,
tabSize: 2,
retryRemoteFsAfterFail: true,
linenumbers: true,
formatOnSave: false,
fadeFoldWidgets: false,
autoCorrect: true,
openFileListPos: this.OPEN_FILE_LIST_POS_HEADER,
quickTools: this.#IS_TABLET ? 0 : 1,
quickToolsTriggerMode: this.QUICKTOOLS_TRIGGER_MODE_TOUCH,
appFont: "",
editorFont: "Roboto Mono",
vibrateOnTap: true,
fullscreen: false,
floatingButton: !this.#IS_TABLET,
liveAutoCompletion: true,
showPrintMargin: false,
printMargin: 80,
scrollbarSize: 20,
showSpaces: false,
confirmOnExit: true,
lineHeight: 2,
leftMargin: 50,
checkFiles: true,
checkForAppUpdates: false,
desktopMode: false,
console: this.CONSOLE_LEGACY,
keyboardMode: this.KEYBOARD_MODE_NO_SUGGESTIONS_AGGRESSIVE,
rememberFiles: true,
rememberFolders: true,
diagonalScrolling: false,
reverseScrolling: false,
scrollSpeed: constants.SCROLL_SPEED_NORMAL,
customTheme: this.#customTheme,
relativeLineNumbers: false,
elasticTabstops: false,
rtlText: false,
hardWrap: false,
useTextareaForIME: false,
touchMoveThreshold: Math.round((1 / devicePixelRatio) * 10) / 20,
quicktoolsItems: [...Array(this.#QUICKTOOLS_SIZE).keys()],
excludeFolders: this.#excludeFolders,
defaultFileEncoding: "UTF-8",
inlineAutoCompletion: true,
colorPreview: true,
maxRetryCount: 3,
showRetryToast: false,
showSideButtons: true,
showSponsorSidebarApp: true,
showAnnotations: false,
lintGutter: true,
indentGuides: true,
rainbowBrackets: true,
pluginsDisabled: {}, // pluginId: true/false
lsp: {
servers: {},
},
developerMode: false,
shiftClickSelection: false,
};
this.value = structuredClone(this.#defaultSettings);
}
async init() {
if (this.#initialized) return;
this.settingsFile = Url.join(DATA_STORAGE, "settings.json");
this.#defaultSettings.appTheme = "system";
this.#defaultSettings.editorTheme = getSystemEditorTheme(
isDeviceDarkTheme(),
);
this.#initialized = true;
const fs = fsOperation(this.settingsFile);
if (!(await fs.exists())) {
await this.#save();
this.value = structuredClone(this.#defaultSettings);
this.#oldSettings = structuredClone(this.#defaultSettings);
this.value.lang = navigator.language || "en-us";
return;
}
const settings = helpers.parseJSON(await fs.readFile("utf8"));
if (settings) {
// make sure that all the settings are present
Object.keys(this.#defaultSettings).forEach((setting) => {
const value = settings[setting];
if (
value === undefined ||
typeof value !== typeof this.#defaultSettings[setting]
) {
settings[setting] = this.#defaultSettings[setting];
}
});
this.value = structuredClone(settings);
this.#oldSettings = structuredClone(settings);
try {
themes.update(ThemeBuilder.fromJSON(this.value.customTheme));
} catch (error) {
themes.update(new ThemeBuilder("Custom").toJSON());
}
// Ensure pluginsDisabled exists
if (!this.value.pluginsDisabled) this.value.pluginsDisabled = {};
return;
}
await this.reset();
}
async #save() {
const fs = fsOperation(this.settingsFile);
const settingsText = JSON.stringify(this.value, undefined, 4);
if (!(await fs.exists())) {
const dirFs = fsOperation(DATA_STORAGE);
await dirFs.createFile("settings.json");
}
await fs.writeFile(settingsText);
this.#oldSettings = structuredClone(this.value);
}
/**
*
* @param {Object} [settings] - if provided, the settings will be updated
* @param {Boolean} [showToast] - if false, the toast will not be shown
* default is true
* @param {Boolean} [saveFile] - if false, the settings will not be saved to the file,
* default is true
*/
async update(settings, showToast = true, saveFile = true) {
if (typeof settings === "boolean") {
showToast = settings;
settings = undefined;
}
const onupdate = [...this.#on.update];
const onupdateAfter = [...this.#on["update:after"]];
if (settings) {
Object.keys(settings).forEach((key) => {
if (key in this.value) this.value[key] = settings[key];
});
}
const changedSettings = this.#getChangedKeys();
changedSettings.forEach((setting) => {
this.#applySettings(setting);
const listeners = this.#on[`update:${setting}`];
if (Array.isArray(listeners)) {
onupdate.push(...listeners);
}
onupdate.forEach((listener) => listener(this.value[setting]));
});
if (saveFile) await this.#save();
if (showToast) toast(strings["settings saved"]);
changedSettings.forEach((setting) => {
const listeners = this.#on[`update:${setting}:after`];
if (Array.isArray(listeners)) {
onupdateAfter.push(...listeners);
}
onupdateAfter.forEach((listener) => listener(this.value[setting]));
});
}
async reset(setting) {
if (setting) {
if (setting in this.#defaultSettings) {
this.value[setting] = this.#defaultSettings[setting];
await this.update();
} else {
return false;
}
} else {
this.value = this.#defaultSettings;
await this.update(false);
}
this.#on.reset.forEach((onreset) => onreset(this.value));
}
/**
* Adds a listener for the given event
* @param {'update:<setting>' | 'update:<setting>:after' | 'reset'} event
* @param {function():void} callback
*/
on(event, callback) {
if (!this.#on[event]) this.#on[event] = [];
this.#on[event].push(callback);
}
/**
* Removes the given callback from the given event
* @param {'update' | 'reset'} event
* @param {function():void} callback
*/
off(event, callback) {
if (!this.#on[event]) this.#on[event] = [];
this.#on[event].splice(this.#on[event].indexOf(callback), 1);
}
/**
* Gets a setting with the given key
* @param {String} key
* @returns
*/
get(key) {
return this.value[key];
}
/**
* Returns changed settings
* @returns {Array<String>}
*/
#getChangedKeys() {
if (!this.#oldSettings) return [];
const keys = [];
Object.keys(this.#oldSettings).forEach((key) => {
const value = this.#oldSettings[key];
if (typeof value === "object") {
if (!areEqual(value, this.value[key])) keys.push(key);
return;
}
if (value !== this.value[key]) keys.push(key);
});
return keys;
}
#applySettings(setting) {
switch (setting) {
case "animation":
this.applyAnimationSetting();
break;
case "lang":
this.applyLangSetting();
break;
default:
break;
}
}
async applyAnimationSetting() {
let value = this.value.animation;
if (value === "system") {
const res = await new Promise((resolve, reject) => {
system.getGlobalSetting("animator_duration_scale", resolve, reject);
});
if (res) value = "yes";
else value = "no";
}
if (value === "yes") {
app.classList.remove("no-animation");
} else if (value === "no") {
app.classList.add("no-animation");
}
}
async applyLangSetting() {
const value = this.value.lang;
lang.set(value);
}
}
/**
* Checks whether given objects are equal or not
* @param {Object} obj1
* @param {Object} obj2
* @returns
*/
function areEqual(obj1, obj2) {
if (obj1 === obj2) return true;
if (obj1 == null || obj2 == null) return false;
if (obj1.constructor !== obj2.constructor) return false;
for (let key in obj1) {
if (!obj2.hasOwnProperty(key)) return false;
if (obj1[key] === obj2[key]) continue;
if (typeof obj1[key] !== "object") return false;
if (!areEqual(obj1[key], obj2[key])) return false;
}
return true;
}
export default new Settings();