forked from Acode-Foundation/Acode
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.js
More file actions
654 lines (578 loc) · 17.1 KB
/
main.js
File metadata and controls
654 lines (578 loc) · 17.1 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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
import "core-js/stable";
import "html-tag-js/dist/polyfill";
import "styles/main.scss";
import "styles/page.scss";
import "styles/list.scss";
import "styles/overrideAceStyle.scss";
import "lib/polyfill";
import "ace/supportedModes";
import "components/WebComponents";
import ajax from "@deadlyjack/ajax";
import Contextmenu from "components/contextmenu";
import Sidebar from "components/sidebar";
import tile from "components/tile";
import toast from "components/toast";
import tutorial from "components/tutorial";
import fsOperation from "fileSystem";
import intentHandler from "handlers/intent";
import keyboardHandler from "handlers/keyboard";
import quickToolsInit from "handlers/quickToolsInit";
import windowResize from "handlers/windowResize";
import Acode from "lib/acode";
import actionStack from "lib/actionStack";
import applySettings from "lib/applySettings";
import checkFiles from "lib/checkFiles";
import checkPluginsUpdate from "lib/checkPluginsUpdate";
import EditorFile from "lib/editorFile";
import EditorManager from "lib/editorManager";
import lang from "lib/lang";
import loadPlugins from "lib/loadPlugins";
import Logger from "lib/logger";
import openFolder from "lib/openFolder";
import restoreFiles from "lib/restoreFiles";
import settings from "lib/settings";
import startAd from "lib/startAd";
import mustache from "mustache";
import plugins from "pages/plugins";
import otherSettings from "settings/appSettings";
import sidebarApps from "sidebarApps";
import themes from "theme/list";
import Url from "utils/Url";
import helpers from "utils/helpers";
import loadPolyFill from "utils/polyfill";
import $_fileMenu from "views/file-menu.hbs";
import $_menu from "views/menu.hbs";
import { setKeyBindings } from "ace/commands";
import { initModes } from "ace/modelist";
import { keydownState } from "handlers/keyboard";
import { initFileList } from "lib/fileList";
import NotificationManager from "lib/notificationManager";
import { addedFolder } from "lib/openFolder";
import { getEncoding, initEncodings } from "utils/encodings";
import constants from "./constants";
const previousVersionCode = Number.parseInt(localStorage.versionCode, 10);
window.onload = Main;
const logger = new Logger();
async function Main() {
const oldPreventDefault = TouchEvent.prototype.preventDefault;
ajax.response = (xhr) => {
return xhr.response;
};
loadPolyFill.apply(window);
TouchEvent.prototype.preventDefault = function () {
if (this.cancelable) {
oldPreventDefault.bind(this)();
}
};
window.addEventListener("resize", windowResize);
document.addEventListener("pause", pauseHandler);
document.addEventListener("resume", resumeHandler);
document.addEventListener("keydown", keyboardHandler);
document.addEventListener("deviceready", onDeviceReady);
document.addEventListener("backbutton", backButtonHandler);
document.addEventListener("menubutton", menuButtonHandler);
}
async function onDeviceReady() {
await initEncodings(); // important to load encodings before anything else
const isFreePackage = /(free)$/.test(BuildInfo.packageName);
const oldResolveURL = window.resolveLocalFileSystemURL;
const {
externalCacheDirectory, //
externalDataDirectory,
cacheDirectory,
dataDirectory,
} = cordova.file;
window.app = document.body;
window.root = tag.get("#root");
window.addedFolder = addedFolder;
window.editorManager = null;
window.toast = toast;
window.ASSETS_DIRECTORY = Url.join(cordova.file.applicationDirectory, "www");
window.DATA_STORAGE = externalDataDirectory || dataDirectory;
window.CACHE_STORAGE = externalCacheDirectory || cacheDirectory;
window.PLUGIN_DIR = Url.join(DATA_STORAGE, "plugins");
window.KEYBINDING_FILE = Url.join(DATA_STORAGE, ".key-bindings.json");
window.IS_FREE_VERSION = isFreePackage;
window.log = logger.log.bind(logger);
// Capture synchronous errors
window.addEventListener("error", (event) => {
const errorMsg = `Error: ${event.message}, Source: ${event.filename}, Line: ${event.lineno}, Column: ${event.colno}, Stack: ${event.error?.stack || "N/A"}`;
window.log("error", errorMsg);
});
// Capture unhandled promise rejections
window.addEventListener("unhandledrejection", (event) => {
window.log(
"error",
`Unhandled rejection: ${event.reason ? event.reason.message : "Unknown reason"}\nStack: ${event.reason ? event.reason.stack : "No stack available"}`,
);
});
startAd();
try {
await helpers.promisify(iap.startConnection).catch((e) => {
window.log("error", "connection error");
window.log("error", e);
});
if (localStorage.acode_pro === "true") {
window.IS_FREE_VERSION = false;
}
if (navigator.onLine) {
const purchases = await helpers.promisify(iap.getPurchases);
const isPro = purchases.find((p) =>
p.productIds.includes("acode_pro_new"),
);
if (isPro) {
window.IS_FREE_VERSION = false;
} else {
window.IS_FREE_VERSION = isFreePackage;
}
}
} catch (error) {
window.log("error", "Purchase error");
window.log("error", error);
}
try {
window.ANDROID_SDK_INT = await new Promise((resolve, reject) =>
system.getAndroidVersion(resolve, reject),
);
} catch (error) {
window.ANDROID_SDK_INT = Number.parseInt(device.version);
}
window.DOES_SUPPORT_THEME = (() => {
const $testEl = (
<div
style={{
height: "var(--test-height)",
width: "var(--test-height)",
}}
/>
);
document.body.append($testEl);
const client = $testEl.getBoundingClientRect();
$testEl.remove();
if (client.height === 0) return false;
return true;
})();
window.acode = new Acode();
system.requestPermission("android.permission.READ_EXTERNAL_STORAGE");
system.requestPermission("android.permission.WRITE_EXTERNAL_STORAGE");
const { versionCode } = BuildInfo;
if (previousVersionCode !== versionCode) {
system.clearCache();
}
if (!(await fsOperation(PLUGIN_DIR).exists())) {
await fsOperation(DATA_STORAGE).createDirectory("plugins");
}
localStorage.versionCode = versionCode;
document.body.setAttribute(
"data-version",
`v${BuildInfo.version} (${versionCode})`,
);
acode.setLoadingMessage("Loading settings...");
window.resolveLocalFileSystemURL = function (url, ...args) {
oldResolveURL.call(this, Url.safe(url), ...args);
};
setTimeout(async () => {
if (document.body.classList.contains("loading")) {
window.log("warn", "App is taking unexpectedly long time!");
document.body.setAttribute(
"data-small-msg",
"This is taking unexpectedly long time!",
);
// share the log file (but currently doesn't work)
// system.fileAction(
// Url.join(DATA_STORAGE, constants.LOG_FILE_NAME),
// constants.LOG_FILE_NAME,
// "SEND",
// "text/plain",
// () => {
// toast(strings["no app found to handle this file"]);
// },
// );
}
}, 1000 * 10);
acode.setLoadingMessage("Loading settings...");
await settings.init();
themes.init();
acode.setLoadingMessage("Loading language...");
await lang.set(settings.value.lang);
try {
await loadApp();
} catch (error) {
window.log("error", error);
toast(`Error: ${error.message}`);
} finally {
setTimeout(async () => {
document.body.removeAttribute("data-small-msg");
app.classList.remove("loading", "splash");
// load plugins
try {
await loadPlugins();
} catch (error) {
window.log("error", "Failed to load theme plugins!");
window.log("error", error);
toast("Failed to load theme plugins!");
}
applySettings.afterRender();
}, 500);
}
// Check for app updates
if (navigator.onLine) {
cordova.plugin.http.sendRequest(
"https://api.github.com/repos/Acode-Foundation/Acode/releases/latest",
{
method: "GET",
responseType: "json",
},
(response) => {
const release = response.data;
// assuming version is in format v1.2.3
const latestVersion = release.tag_name
.replace("v", "")
.split(".")
.map(Number);
const currentVersion = BuildInfo.version.split(".").map(Number);
const hasUpdate = latestVersion.some(
(num, i) => num > currentVersion[i],
);
if (hasUpdate) {
acode.pushNotification(
"Update Available",
`Acode ${release.tag_name} is now available! Click here to checkout.`,
{
icon: "update",
type: "warning",
action: () => {
system.openInBrowser(release.html_url);
},
},
);
}
},
(err) => {
window.log("error", "Failed to check for updates");
window.log("error", err);
},
);
}
checkPluginsUpdate()
.then((updates) => {
if (!updates.length) return;
acode.pushNotification(
"Plugin Updates",
`${updates.length} plugin${updates.length > 1 ? "s" : ""} ${updates.length > 1 ? "have" : "has"} new version${updates.length > 1 ? "s" : ""} available.`,
{
icon: "extension",
action: () => {
plugins(updates);
},
},
);
})
.catch(console.error);
}
async function loadApp() {
let $mainMenu;
let $fileMenu;
const $editMenuToggler = (
<span
className="icon edit"
attr-action="toggle-edit-menu"
style={{ fontSize: "1.2em" }}
/>
);
const $navToggler = (
<span className="icon menu" attr-action="toggle-sidebar" />
);
const $menuToggler = (
<span className="icon more_vert" attr-action="toggle-menu" />
);
const $header = tile({
type: "header",
text: "Acode",
lead: $navToggler,
tail: $menuToggler,
});
const $main = <main />;
const $sidebar = <Sidebar container={$main} toggler={$navToggler} />;
const $runBtn = (
<span
style={{ fontSize: "1.2em" }}
className="icon play_arrow"
attr-action="run"
onclick={() => acode.exec("run")}
oncontextmenu={() => acode.exec("run-file")}
/>
);
const $floatingNavToggler = (
<span
id="sidebar-toggler"
className="floating icon menu"
onclick={() => acode.exec("toggle-sidebar")}
/>
);
const $headerToggler = (
<span className="floating icon keyboard_arrow_left" id="header-toggler" />
);
const folders = helpers.parseJSON(localStorage.folders);
const files = helpers.parseJSON(localStorage.files) || [];
const editorManager = await EditorManager($header, $main);
const setMainMenu = () => {
if ($mainMenu) {
$mainMenu.removeEventListener("click", handleMenu);
$mainMenu.destroy();
}
const { openFileListPos, fullscreen } = settings.value;
if (openFileListPos === settings.OPEN_FILE_LIST_POS_BOTTOM && fullscreen) {
$mainMenu = createMainMenu({ bottom: "6px", toggler: $menuToggler });
} else {
$mainMenu = createMainMenu({ top: "6px", toggler: $menuToggler });
}
$mainMenu.addEventListener("click", handleMenu);
};
const setFileMenu = () => {
if ($fileMenu) {
$fileMenu.removeEventListener("click", handleMenu);
$fileMenu.destroy();
}
const { openFileListPos, fullscreen } = settings.value;
if (openFileListPos === settings.OPEN_FILE_LIST_POS_BOTTOM && fullscreen) {
$fileMenu = createFileMenu({ bottom: "6px", toggler: $editMenuToggler });
} else {
$fileMenu = createFileMenu({ top: "6px", toggler: $editMenuToggler });
}
$fileMenu.addEventListener("click", handleMenu);
};
acode.$headerToggler = $headerToggler;
window.actionStack = actionStack.windowCopy();
window.editorManager = editorManager;
setMainMenu(settings.value.openFileListPos);
setFileMenu(settings.value.openFileListPos);
actionStack.onCloseApp = () => acode.exec("save-state");
$headerToggler.onclick = function () {
root.classList.toggle("show-header");
this.classList.toggle("keyboard_arrow_left");
this.classList.toggle("keyboard_arrow_right");
};
//#region rendering
applySettings.beforeRender();
root.appendOuter($header, $main, $floatingNavToggler, $headerToggler);
//#endregion
//#region Add event listeners
initModes();
quickToolsInit();
sidebarApps.init($sidebar);
await sidebarApps.loadApps();
editorManager.onupdate = onEditorUpdate;
root.on("show", mainPageOnShow);
app.addEventListener("click", onClickApp);
editorManager.on("rename-file", onFileUpdate);
editorManager.on("switch-file", onFileUpdate);
editorManager.on("file-loaded", onFileUpdate);
navigator.app.overrideButton("menubutton", true);
system.setIntentHandler(intentHandler, intentHandler.onError);
system.getCordovaIntent(intentHandler, intentHandler.onError);
setTimeout(showTutorials, 1000);
settings.on("update:openFileListPos", () => {
setMainMenu();
setFileMenu();
});
settings.on("update:fullscreen", () => {
setMainMenu();
setFileMenu();
});
$sidebar.onshow = () => {
const activeFile = editorManager.activeFile;
if (activeFile) editorManager.editor.blur();
};
sdcard.watchFile(KEYBINDING_FILE, async () => {
await setKeyBindings(editorManager.editor);
toast(strings["key bindings updated"]);
});
//#endregion
const notificationManager = new NotificationManager();
notificationManager.init();
window.log("info", "Started app and its services...");
new EditorFile();
// load theme plugins
try {
await loadPlugins(true);
} catch (error) {
window.log("error", "Failed to load theme plugins!");
window.log("error", error);
toast("Failed to load theme plugins!");
}
acode.setLoadingMessage("Loading folders...");
if (Array.isArray(folders)) {
for (const folder of folders) {
folder.opts.listFiles = !!folder.opts.listFiles;
openFolder(folder.url, folder.opts);
}
}
if (Array.isArray(files) && files.length) {
try {
await restoreFiles(files);
} catch (error) {
window.log("error", "File loading failed!");
window.log("error", error);
toast("File loading failed!");
}
} else {
onEditorUpdate(undefined, false);
}
initFileList();
/**
*
* @param {MouseEvent} e
*/
function handleMenu(e) {
const $target = e.target;
const action = $target.getAttribute("action");
const value = $target.getAttribute("value") || undefined;
if (!action) return;
if ($mainMenu.contains($target)) $mainMenu.hide();
if ($fileMenu.contains($target)) $fileMenu.hide();
acode.exec(action, value);
}
function onEditorUpdate(mode, saveState = true) {
const { activeFile } = editorManager;
if (!$editMenuToggler.isConnected) {
$header.insertBefore($editMenuToggler, $header.lastChild);
}
if (mode === "switch-file") {
if (settings.value.rememberFiles && activeFile) {
localStorage.setItem("lastfile", activeFile.id);
}
return;
}
if (saveState) acode.exec("save-state");
}
async function onFileUpdate() {
try {
const { serverPort, previewPort } = settings.value;
let canRun = false;
if (serverPort !== previewPort) {
canRun = true;
} else {
const { activeFile } = editorManager;
canRun = await activeFile?.canRun();
}
if (canRun) {
$header.insertBefore($runBtn, $header.lastChild);
} else {
$runBtn.remove();
}
} catch (error) {
$runBtn.removeAttribute("run-file");
$runBtn.remove();
}
}
}
function onClickApp(e) {
let el = e.target;
if (el instanceof HTMLAnchorElement || checkIfInsideAnchor()) {
e.preventDefault();
e.stopPropagation();
system.openInBrowser(el.href);
}
function checkIfInsideAnchor() {
const allAs = [...document.body.getAll("a")];
for (const a of allAs) {
if (a.contains(el)) {
el = a;
return true;
}
}
return false;
}
}
function mainPageOnShow() {
const { editor } = editorManager;
editor.resize(true);
}
function createMainMenu({ top, bottom, toggler }) {
return Contextmenu({
right: "6px",
top,
bottom,
toggler,
transformOrigin: top ? "top right" : "bottom right",
innerHTML: () => {
return mustache.render($_menu, strings);
},
});
}
function createFileMenu({ top, bottom, toggler }) {
const $menu = Contextmenu({
top,
bottom,
toggler,
transformOrigin: top ? "top right" : "bottom right",
innerHTML: () => {
const file = window.editorManager.activeFile;
if (file.type === "page") {
return "";
}
if (file.loading) {
$menu.classList.add("disabled");
} else {
$menu.classList.remove("disabled");
}
const { label: encoding } = getEncoding(file.encoding);
const isEditorFile = file.type === "editor";
return mustache.render($_fileMenu, {
...strings,
file_mode: isEditorFile
? (file.session?.getMode()?.$id || "").split("/").pop()
: "",
file_encoding: isEditorFile ? encoding : "",
file_read_only: !file.editable,
file_on_disk: !!file.uri,
file_eol: isEditorFile ? file.eol : "",
copy_text: !!window.editorManager.editor.getCopyText(),
is_editor: isEditorFile,
});
},
});
return $menu;
}
function showTutorials() {
if (window.innerWidth > 750) {
tutorial("quicktools-tutorials", (hide) => {
const onclick = () => {
otherSettings();
hide();
};
return (
<p>
Quicktools has been <strong>disabled</strong> because it seems like
you are on a bigger screen and probably using a keyboard. To enable
it,{" "}
<span className="link" onclick={onclick}>
click here
</span>{" "}
or press <kbd>Ctrl + Shift + P</kbd> and search for{" "}
<code>quicktools</code>.
</p>
);
});
}
}
function backButtonHandler() {
if (keydownState.esc) {
keydownState.esc = false;
return;
}
actionStack.pop();
}
function menuButtonHandler() {
const { acode } = window;
acode?.exec("toggle-sidebar");
}
function pauseHandler() {
const { acode } = window;
acode?.exec("save-state");
}
function resumeHandler() {
if (!settings.value.checkFiles) return;
checkFiles();
}