WebOrbiton
v1.5.0

AtheraStudio Code

864 lines · 37.7 KB
  1. (function () {
  2. "use strict";
  3. ​
  4. var A = window.Athera;
  5. var util = A.util;
  6. var fs = A.fs;
  7. var tabs = A.tabs;
  8. var t = A.t;
  9. var $ = function (id) { return document.getElementById(id); };
  10. ​
  11. function fail(e) {
  12. console.error(e);
  13. A.ui.toast(e && e.message ? e.message : String(e), "danger");
  14. }
  15. ​
  16. async function switchWorkspace(provider) {
  17. if (!provider) return false;
  18. if (!(await tabs.closeAll())) return false;
  19. fs.setProvider(provider);
  20. A.ui.toast(t("app.folder_opened", { name: provider.name }), "success");
  21. return true;
  22. }
  23. ​
  24. var cmd = (A.commands = {
  25. openFolder: async function () {
  26. await switchWorkspace(await fs.pickFolder());
  27. },
  28. ​
  29. reopenLast: async function (handle) {
  30. try {
  31. if (!(await fs.grant(handle))) return A.ui.toast(t("app.no_permission"), "warning");
  32. await handle.values().next();
  33. } catch (e) {
  34. A.idb.del("lastRoot");
  35. refreshRecent();
  36. return A.ui.toast(t("app.reopen_failed"), "danger");
  37. }
  38. await switchWorkspace(new fs.DiskProvider(handle));
  39. await restoreTabs(handle.name);
  40. },
  41. ​
  42. openFile: async function () {
  43. for (var item of await fs.openFiles()) await tabs.openFile(item);
  44. },
  45. ​
  46. newFile: async function () {
  47. if (fs.provider) return A.explorer.newFile();
  48. var name = await A.ui.prompt(t("explorer.new_file"), t("app.new_file_label"), "", t("common.create"));
  49. if (name) tabs.newUntitled(util.basename(name), A.templates.forFile(name));
  50. },
  51. ​
  52. newFolder: function () {
  53. if (!fs.provider) return A.ui.toast(t("app.open_folder_first"), "info");
  54. return A.explorer.newFolder();
  55. },
  56. ​
  57. save: function () {
  58. if (tabs.active) return tabs.save();
  59. },
  60. ​
  61. saveAll: function () {
  62. return tabs.saveAll();
  63. },
  64. ​
  65. saveAs: async function () {
  66. var tab = tabs.active;
  67. if (!tab || tab.kind !== "text") return;
  68. var state = tabs.stateOf(tab);
  69. var h = await fs.saveAs(tab.name, state.doc.toString());
  70. if (h === undefined) return;
  71. if (h && tab.path == null) {
  72. tabs.retarget(tab, h.name, null, h);
  73. tab.savedDoc = state.doc;
  74. tab.dirty = !tabs.stateOf(tab).doc.eq(state.doc);
  75. tabs.render();
  76. }
  77. A.ui.toast(h ? t("app.saved_as", { name: h.name }) : t("app.downloaded", { name: tab.name }), "success");
  78. },
  79. ​
  80. closeTab: function () {
  81. if (tabs.active) return tabs.close();
  82. },
  83. ​
  84. reopenTab: function () {
  85. return tabs.reopen();
  86. },
  87. ​
  88. backup: function () {
  89. return A.backup.run();
  90. },
  91. ​
  92. closeFolder: async function () {
  93. if (!fs.provider) return;
  94. if (await tabs.closeAll()) fs.setProvider(null);
  95. },
  96. ​
  97. toggleSidebar: function () {
  98. var hidden = document.body.classList.toggle("ath-no-sidebar");
  99. A.store.set("sidebar", !hidden);
  100. A.editor.view.requestMeasure();
  101. },
  102. ​
  103. togglePreview: function () {
  104. A.preview.toggle();
  105. },
  106. ​
  107. toggleConsole: function () {
  108. if (!A.preview.open) A.preview.setOpen(true);
  109. A.console.toggle();
  110. },
  111. ​
  112. toggleWrap: function () {
  113. A.ui.toast(A.editor.toggleWrap() ? t("app.wrap_on") : t("app.wrap_off"));
  114. },
  115. ​
  116. zoomIn: function () { A.editor.zoom(1); },
  117. zoomOut: function () { A.editor.zoom(-1); },
  118. zoomReset: function () { A.editor.zoom(0); },
  119. ​
  120. search: function () {
  121. if (tabs.active && tabs.active.kind === "text") A.editor.openSearch();
  122. },
  123. ​
  124. searchInFiles: function () {
  125. A.search.open();
  126. },
  127. ​
  128. undoReplace: function () {
  129. return A.search.undoReplace();
  130. },
  131. ​
  132. nextTab: function () { tabs.move(1); },
  133. prevTab: function () { tabs.move(-1); },
  134. moveTabLeft: function () { tabs.shift(-1); },
  135. moveTabRight: function () { tabs.shift(1); },
  136. ​
  137. refreshExplorer: function () { return A.explorer.refresh(null); },
  138. collapseExplorer: function () { A.explorer.collapseAll(); },
  139. ​
  140. importLanguage: async function () {
  141. var files = await fs.pickFiles({ accept: ".xml,application/xml,text/xml" });
  142. if (!files.length) return;
  143. try {
  144. var lang = await A.i18n.import(files[0]);
  145. A.ui.toast(t("lang.imported", { name: lang.name }), "success");
  146. } catch (e) {
  147. A.ui.toast(t("lang.invalid", { error: e.message }), "danger");
  148. }
  149. },
  150. ​
  151. languageTemplate: function () {
  152. fs.download(t("lang.template_file"), A.i18n.template(), "application/xml;charset=utf-8");
  153. },
  154. ​
  155. removeLanguage: async function () {
  156. var cur = A.i18n.current();
  157. if (!cur || cur.source !== "imported") return;
  158. if (await A.ui.confirm(t("lang.remove_title"), t("lang.remove_confirm", { name: cur.name }), t("common.delete"), true)) {
  159. await A.i18n.removeImported(cur.id);
  160. }
  161. },
  162. ​
  163. settings: function () {
  164. A.settings.open();
  165. },
  166. ​
  167. quickOpen: function () { A.palette.open(""); },
  168. commandPalette: function () { A.palette.open(">"); },
  169. gotoLine: function () { A.palette.open(":"); },
  170. ​
  171. format: async function () {
  172. var tab = tabs.active;
  173. if (!tab || tab.kind !== "text") return;
  174. if (!A.intellisense.canFormat(tab.name)) return A.ui.toast(t("format.unsupported"), "info");
  175. try {
  176. if (!(await A.intellisense.format(A.editor.view, tab.name))) A.ui.toast(t("format.unchanged"));
  177. } catch (e) {
  178. A.ui.toast(e.message, "danger");
  179. }
  180. },
  181. ​
  182. problems: function () {
  183. if (tabs.active && tabs.active.kind === "text") A.editor.run(CM.openLintPanel);
  184. },
  185. ​
  186. nextProblem: function () {
  187. if (tabs.active && tabs.active.kind === "text") A.editor.run(CM.nextDiagnostic);
  188. },
  189. ​
  190. cut: function () { return A.editor.copy(true); },
  191. copy: function () { return A.editor.copy(false); },
  192. paste: function () {
  193. return A.editor.paste().catch(function () { A.ui.toast(t("editor.paste_blocked"), "info"); });
  194. },
  195. selectAll: function () { A.editor.run(CM.selectAll); },
  196. selectOccurrences: function () { A.editor.selectOccurrences(); },
  197. toggleComment: function () { A.editor.run(CM.toggleComment); },
  198. removeComments: function () { A.codetools.removeComments(); },
  199. trimWhitespace: function () { A.codetools.trimTrailing(); },
  200. removeEmptyLines: function () { A.codetools.removeEmptyLines(); },
  201. collapseEmptyLines: function () { A.codetools.collapseEmptyLines(); },
  202. sortAsc: function () { A.codetools.sortLines(false); },
  203. sortDesc: function () { A.codetools.sortLines(true); },
  204. uniqueLines: function () { A.codetools.uniqueLines(); },
  205. reverseLines: function () { A.codetools.reverseLines(); },
  206. joinLines: function () { A.codetools.joinLines(); },
  207. upperCase: function () { A.codetools.upperCase(); },
  208. lowerCase: function () { A.codetools.lowerCase(); },
  209. tabsToSpaces: function () { A.codetools.tabsToSpaces(); },
  210. spacesToTabs: function () { A.codetools.spacesToTabs(); },
  211. duplicateLine: function () { A.editor.run(CM.copyLineDown); },
  212. deleteLine: function () { A.editor.run(CM.deleteLine); },
  213. indentMore: function () { A.editor.run(CM.indentMore); },
  214. indentLess: function () { A.editor.run(CM.indentLess); },
  215. foldAll: function () { A.editor.run(CM.foldAll); },
  216. unfoldAll: function () { A.editor.run(CM.unfoldAll); },
  217. triggerSuggest: function () { A.editor.run(CM.startCompletion); },
  218. ​
  219. emmetWrap: function () { A.editor.simulateKey("w", "KeyW", { ctrlKey: true, altKey: true }); },
  220. emmetBalanceOut: function () { A.editor.run(CM.balanceOutward); },
  221. emmetBalanceIn: function () { A.editor.run(CM.balanceInward); },
  222. emmetRemoveTag: function () { A.editor.run(CM.removeTag); },
  223. emmetTagPair: function () { A.editor.run(CM.goToTagPair); },
  224. emmetSplitJoin: function () { A.editor.run(CM.splitJoinTag); },
  225. emmetMath: function () { A.editor.run(CM.evaluateMath); },
  226. emmetNextEdit: function () { A.editor.run(CM.goToNextEditPoint); },
  227. emmetPrevEdit: function () { A.editor.run(CM.goToPreviousEditPoint); },
  228. emmetIncrement: function () { A.editor.run(CM.incrementNumber1); },
  229. emmetDecrement: function () { A.editor.run(CM.decrementNumber1); },
  230. ​
  231. toggleTheme: function () { Orbitarium.theme.toggle(); },
  232. phpRestart: function () {
  233. A.php.restart();
  234. A.ui.toast(t("php.restarted"));
  235. if (A.preview.open) A.preview.build();
  236. },
  237. undo: function () { A.editor.run(CM.undo); },
  238. redo: function () { A.editor.run(CM.redo); },
  239. ​
  240. aiOpen: function () { A.aiUi.toggle(); },
  241. aiToggle: function () { return A.ai.enabled() ? A.ai.disable() : A.ai.enable(); },
  242. aiPick: function () { return A.ai.viewer.pick(); },
  243. aiAudit: async function () {
  244. if (!A.ai.allowed("preview")) return A.ui.toast(A.ai.t("ai.viewer.err_perm"), "info");
  245. A.ui.toast(A.ai.t("ai.viewer.audit_running"));
  246. A.ai.viewer.showAudit(await A.ai.viewer.audit({ screenshots: A.ai.allowed("screenshot") }));
  247. },
  248. aiProofread: function () { return A.ai.proofread.run(); },
  249. followLink: function () { return A.links.followCursor(); },
  250. aiDock: function () { A.aiUi.setDocked(!A.aiUi.isDocked()); },
  251. aiRecipes: function () { A.aiUi.open("recipes"); },
  252. aiEval: function () {
  253. A.ai.set("evalPanel", true);
  254. A.aiUi.open("eval");
  255. },
  256. aiPrivate: function () { A.aiUi.open("private"); },
  257. aiChanges: function () { A.aiUi.open("changes"); },
  258. aiInstructions: function () { A.aiUi.open("instructions"); },
  259. aiKeys: function () { A.aiUi.open("keys"); },
  260. aiBudget: function () { A.aiUi.open("model"); },
  261. aiPermissions: function () { A.aiUi.open("permissions"); },
  262. aiExclusions: function () { A.aiUi.open("exclusions"); },
  263. ​
  264. shortcuts: function () {
  265. var rows = [
  266. ["Ctrl+O", "shortcut.open_folder"], ["Ctrl+S", "shortcut.save"], ["Ctrl+Shift+S", "shortcut.save_all"],
  267. ["Alt+N", "shortcut.new_file"], ["Alt+W", "shortcut.close_tab"], ["Alt+PgDn / Alt+PgUp", "shortcut.switch_tab"],
  268. ["Alt+Shift+PgDn / PgUp", "shortcut.move_tab"], ["Alt+T", "shortcut.reopen_tab"],
  269. ["Ctrl+B", "shortcut.sidebar"], ["Alt+P", "shortcut.preview"], ["Alt+J", "console.toggle"], ["Alt+Z", "shortcut.wrap"],
  270. ["Ctrl+Space", "shortcut.complete"], ["Ctrl+F", "shortcut.search"], ["Ctrl+/", "shortcut.comment"],
  271. ["Alt+↑ / Alt+↓", "shortcut.move_line"], ["Shift+Alt+↓", "shortcut.copy_line"], ["Ctrl+D", "shortcut.select_next"],
  272. ["Alt+Click", "shortcut.multi_cursor"], ["Ctrl+Shift+[ / ]", "shortcut.fold"], ["Ctrl+= / Ctrl+-", "shortcut.zoom"],
  273. ["F2 / Del", "shortcut.explorer"], ["Drag", "shortcut.drag_move"], ["Ctrl+,", "shortcut.settings"],
  274. ["Ctrl+P", "cmd.quick_open"], ["Ctrl+Shift+F", "cmd.search_in_files"], ["Ctrl+Shift+P / F1", "cmd.command_palette"], ["Ctrl+G", "cmd.goto_line"],
  275. ["Shift+Alt+F", "cmd.format"], ["Tab", "shortcut.emmet"], ["Ctrl+Alt+W", "cmd.emmet_wrap"],
  276. ["Ctrl+Shift+L / Ctrl+F2", "cmd.select_occurrences"], ["Ctrl+Shift+K", "cmd.delete_line"],
  277. ["Ctrl+Shift+M", "cmd.problems"], ["F8", "cmd.next_problem"], ["Alt+A", "ai.menu.open"]
  278. ];
  279. if (window.atheraDesktop && window.atheraDesktop.isDesktop) rows.push(["Alt+Drag", "shortcut.drag_out"]);
  280. var keyName = function (k) {
  281. return k === "Space" ? t("key.space") : k === "Click" ? t("key.click") : k === "Drag" ? t("key.drag") : k;
  282. };
  283. var table = util.el("table", { class: "orb-table ath-keys-table" }, [util.el("tbody", {}, rows.map(function (r) {
  284. return util.el("tr", {}, [
  285. util.el("td", {}, r[0].split(" / ").map(function (combo, i) {
  286. var span = util.el("span", { class: "ath-combo" }, combo.split("+").map(function (k) {
  287. return util.el("span", { class: "orb-kbd" }, keyName(k));
  288. }));
  289. return i ? util.el("span", {}, [" / ", span]) : span;
  290. })),
  291. util.el("td", {}, r[1].indexOf("ai.") === 0 ? A.ai.t(r[1]) : t(r[1]))
  292. ]);
  293. }))]);
  294. A.ui.dialog({ title: t("menu.shortcuts"), body: table, size: "lg", actions: [{ label: t("common.close"), value: null, kind: "secondary" }] });
  295. },
  296. ​
  297. about: function () {
  298. var lang = A.i18n.current();
  299. var body = util.el("div", { class: "ath-about" }, [
  300. util.el("img", { class: "ath-about-logo", src: "icon.webp", alt: "" }),
  301. util.el("h2", { class: "orb-h3" }, ["AtheraStudio Code ", util.el("span", { class: "orb-text-muted" }, A.version)]),
  302. util.el("p", {}, t("about.text")),
  303. util.el("p", {}, t("about.license", { license: "SA-SDL" })),
  304. util.el("p", { class: "orb-text-muted orb-text-sm" }, [
  305. t("about.ui", { name: "Orbitarium Design 1.1.0" }), util.el("br"),
  306. t("about.engine", { name: "CodeMirror 6 (MIT)" }), util.el("br"),
  307. t("about.translation", { name: lang.name + (lang.author ? " · " + lang.author : "") })
  308. ])
  309. ]);
  310. A.ui.dialog({ title: t("menu.about"), size: "sm", body: body, actions: [{ label: t("common.close"), value: null, kind: "secondary" }] });
  311. }
  312. });
  313. ​
  314. var COMMANDS = [
  315. ["quickOpen", "cmd.quick_open", "Ctrl+P", "file", true],
  316. ["commandPalette", "cmd.command_palette", "Ctrl+Shift+P", "terminal", true],
  317. ["gotoLine", "cmd.goto_line", "Ctrl+G", "gotoLine", true],
  318. ["searchInFiles", "cmd.search_in_files", "Ctrl+Shift+F", "search", true],
  319. ["undoReplace", "search.undo_replace", "", "undo", true],
  320. ["openFolder", "menu.open_folder", "Ctrl+O", "folderOpen", true],
  321. ["openFile", "menu.open_file", "", "file", true],
  322. ["newFile", "menu.new_file", "Alt+N", "filePlus", true],
  323. ["newFolder", "menu.new_folder", "", "folderPlus", true],
  324. ["save", "menu.save", "Ctrl+S", "save", true],
  325. ["saveAll", "menu.save_all", "Ctrl+Shift+S", "saveAll", true],
  326. ["saveAs", "menu.save_as", "", "saveAs", true],
  327. ["closeTab", "menu.close_tab", "Alt+W", "x", true],
  328. ["reopenTab", "cmd.reopen_tab", "Alt+T", "undo", true],
  329. ["moveTabLeft", "tabs.move_left", "Alt+Shift+PgUp", "arrowLeft", true],
  330. ["moveTabRight", "tabs.move_right", "Alt+Shift+PgDn", "arrowRight", true],
  331. ["backup", "menu.backup", "", "download", true],
  332. ["closeFolder", "menu.close_folder", "", "folderX", true],
  333. ["format", "cmd.format", "Shift+Alt+F", "wand", false],
  334. ["triggerSuggest", "cmd.suggest", "Ctrl+Space", "lightbulb", false],
  335. ["undo", "cmd.undo", "Ctrl+Z", "undo", false],
  336. ["redo", "cmd.redo", "Ctrl+Y", "redo", false],
  337. ["selectOccurrences", "cmd.select_occurrences", "Ctrl+Shift+L", "selectText", false],
  338. ["toggleComment", "cmd.toggle_comment", "Ctrl+/", "comment", false],
  339. ["removeComments", "cmd.remove_comments", "", "trash", false],
  340. ["trimWhitespace", "cmd.trim_whitespace", "", "wand", false],
  341. ["removeEmptyLines", "cmd.remove_empty_lines", "", "trash", false],
  342. ["collapseEmptyLines", "cmd.collapse_empty_lines", "", "collapse", false],
  343. ["sortAsc", "cmd.sort_asc", "", "gotoLine", false],
  344. ["sortDesc", "cmd.sort_desc", "", "gotoLine", false],
  345. ["uniqueLines", "cmd.unique_lines", "", "duplicate", false],
  346. ["reverseLines", "cmd.reverse_lines", "", "refresh", false],
  347. ["joinLines", "cmd.join_lines", "", "wrap", false],
  348. ["upperCase", "cmd.upper_case", "", "type", false],
  349. ["lowerCase", "cmd.lower_case", "", "type", false],
  350. ["tabsToSpaces", "cmd.tabs_to_spaces", "", "indent", false],
  351. ["spacesToTabs", "cmd.spaces_to_tabs", "", "outdent", false],
  352. ["duplicateLine", "cmd.duplicate_line", "Shift+Alt+↓", "duplicate", false],
  353. ["deleteLine", "cmd.delete_line", "Ctrl+Shift+K", "trash", false],
  354. ["indentMore", "cmd.indent_more", "Ctrl+]", "indent", false],
  355. ["indentLess", "cmd.indent_less", "Ctrl+[", "outdent", false],
  356. ["foldAll", "cmd.fold_all", "", "foldAll", false],
  357. ["unfoldAll", "cmd.unfold_all", "", "collapse", false],
  358. ["search", "menu.search", "Ctrl+F", "search", false],
  359. ["problems", "cmd.problems", "Ctrl+Shift+M", "warning", false],
  360. ["nextProblem", "cmd.next_problem", "F8", "warning", false],
  361. ["emmetWrap", "cmd.emmet_wrap", "Ctrl+Alt+W", "code", "emmet"],
  362. ["emmetBalanceOut", "cmd.emmet_balance_out", "", "code", "emmet"],
  363. ["emmetBalanceIn", "cmd.emmet_balance_in", "", "code", "emmet"],
  364. ["emmetRemoveTag", "cmd.emmet_remove_tag", "", "code", "emmet"],
  365. ["emmetTagPair", "cmd.emmet_tag_pair", "", "code", "emmet"],
  366. ["emmetSplitJoin", "cmd.emmet_split_join", "", "code", "emmet"],
  367. ["emmetMath", "cmd.emmet_math", "", "code", false],
  368. ["emmetNextEdit", "cmd.emmet_next_edit", "", "code", "emmet"],
  369. ["emmetPrevEdit", "cmd.emmet_prev_edit", "", "code", "emmet"],
  370. ["emmetIncrement", "cmd.emmet_increment", "", "code", false],
  371. ["emmetDecrement", "cmd.emmet_decrement", "", "code", false],
  372. ["phpRestart", "cmd.php_restart", "", "refresh", true],
  373. ["toggleSidebar", "menu.sidebar", "Ctrl+B", "sidebar", true],
  374. ["togglePreview", "menu.preview", "Alt+P", "eye", true],
  375. ["toggleConsole", "console.toggle", "Alt+J", "terminal", true],
  376. ["toggleWrap", "menu.wrap", "Alt+Z", "wrap", true],
  377. ["toggleTheme", "cmd.toggle_theme", "", "moon", true],
  378. ["zoomIn", "menu.zoom_in", "Ctrl+=", "zoomIn", true],
  379. ["zoomOut", "menu.zoom_out", "Ctrl+-", "zoomOut", true],
  380. ["zoomReset", "menu.zoom_reset", "Ctrl+0", "zoomReset", true],
  381. ["aiOpen", "ai.menu.open", "Alt+A", "sparkles", true],
  382. ["aiToggle", "ai.cmd.toggle", "", "power", true],
  383. ["aiProofread", "ai.proof.cmd", "", "type", false],
  384. ["followLink", "links.cmd", "", "external", false],
  385. ["aiDock", "ai.cmd.dock", "", "sidebar", true],
  386. ["aiPick", "ai.viewer.pick", "", "target", true],
  387. ["aiAudit", "ai.viewer.audit", "", "layout", true],
  388. ["aiRecipes", "ai.menu.recipes", "", "code", true],
  389. ["aiEval", "ai.eval.title", "", "lightbulb", true],
  390. ["aiPrivate", "ai.menu.private", "", "folder", true],
  391. ["aiChanges", "ai.menu.changes", "", "undo", true],
  392. ["aiInstructions", "ai.menu.instructions", "", "pencil", true],
  393. ["aiKeys", "ai.menu.keys", "", "key", true],
  394. ["aiBudget", "ai.menu.budget", "", "coins", true],
  395. ["aiPermissions", "ai.menu.permissions", "", "shield", true],
  396. ["aiExclusions", "ai.menu.exclusions", "", "ban", true],
  397. ["settings", "menu.settings", "Ctrl+,", "settings", true],
  398. ["importLanguage", "lang.import", "", "upload", true],
  399. ["shortcuts", "menu.shortcuts", "", "keyboard", true],
  400. ["about", "menu.about", "", "info", true]
  401. ];
  402. ​
  403. function emmetLanguage() {
  404. var tab = tabs.active;
  405. return !!tab && tab.kind === "text" && /^(html|php|svg)$/.test(A.editor.langId(tab.name)) && A.settings.get("emmet");
  406. }
  407. ​
  408. A.commandList = function () {
  409. var editing = !!tabs.active && tabs.active.kind === "text";
  410. return COMMANDS.filter(function (c) {
  411. if (c[4] === true) return true;
  412. if (c[4] === "emmet") return editing && emmetLanguage();
  413. return editing;
  414. }).map(function (c) {
  415. var label = (c[0].indexOf("ai") === 0 ? A.ai.t(c[1]) : t(c[1])).replace(/…$/, "");
  416. return { id: c[0], label: label, kbd: c[2], icon: c[3], run: function () { return cmd[c[0]](); } };
  417. });
  418. };
  419. ​
  420. function editorMenu(e) {
  421. var tab = tabs.active;
  422. var hasSel = A.editor.view.state.selection.ranges.some(function (r) { return !r.empty; });
  423. var items = [
  424. { label: t(hasSel ? "cmd.cut" : "cmd.cut_line"), kbd: "Ctrl+X", icon: "scissors", action: cmd.cut },
  425. { label: t(hasSel ? "cmd.copy" : "cmd.copy_line"), kbd: "Ctrl+C", icon: "copy", action: cmd.copy },
  426. { label: t("cmd.paste"), kbd: "Ctrl+V", icon: "clipboard", action: cmd.paste },
  427. "-",
  428. { label: t("cmd.select_occurrences"), kbd: "Ctrl+Shift+L", icon: "selectText", action: cmd.selectOccurrences },
  429. { label: t("cmd.toggle_comment"), kbd: "Ctrl+/", icon: "comment", action: cmd.toggleComment },
  430. { label: t("cmd.remove_comments"), icon: "trash", action: cmd.removeComments },
  431. { label: t("cmd.suggest"), kbd: "Ctrl+Space", icon: "lightbulb", action: cmd.triggerSuggest }
  432. ];
  433. var link = A.links && A.links.atCursor();
  434. if (link) {
  435. var linkLabel = link.type === "url" ? t("links.menu_url") : link.type === "anchor" ? t("links.menu_anchor", { id: link.id }) : t("links.menu_file", { name: link.ref });
  436. items.unshift({ label: linkLabel, kbd: "Ctrl+Click", icon: link.type === "url" ? "external" : "file", action: cmd.followLink }, "-");
  437. }
  438. if (hasSel) items.push("-", { label: A.ai.t("ai.proof.cmd"), icon: "type", action: cmd.aiProofread });
  439. if (A.intellisense.canFormat(tab.name)) items.push({ label: t("cmd.format"), kbd: "Shift+Alt+F", icon: "wand", action: cmd.format });
  440. if (emmetLanguage()) {
  441. items.push("-",
  442. { label: t("cmd.emmet_wrap"), kbd: "Ctrl+Alt+W", icon: "code", action: cmd.emmetWrap },
  443. { label: t("cmd.emmet_balance_out"), icon: "code", action: cmd.emmetBalanceOut },
  444. { label: t("cmd.emmet_tag_pair"), icon: "code", action: cmd.emmetTagPair },
  445. { label: t("cmd.emmet_remove_tag"), icon: "code", action: cmd.emmetRemoveTag });
  446. }
  447. items.push("-",
  448. { label: t("cmd.goto_line"), kbd: "Ctrl+G", icon: "gotoLine", action: cmd.gotoLine },
  449. { label: t("menu.search"), kbd: "Ctrl+F", icon: "search", action: cmd.search },
  450. { label: t("cmd.fold_all"), icon: "foldAll", action: cmd.foldAll },
  451. { label: t("cmd.unfold_all"), icon: "collapse", action: cmd.unfoldAll },
  452. "-",
  453. { label: t("cmd.command_palette"), kbd: "Ctrl+Shift+P", icon: "terminal", action: cmd.commandPalette });
  454. A.ui.contextMenu(e.clientX, e.clientY, items.map(function (it) {
  455. if (it === "-") return it;
  456. var run = it.action;
  457. return Object.assign({}, it, { action: function () { Promise.resolve().then(run).catch(fail); } });
  458. }));
  459. }
  460. ​
  461. $("editor-host").addEventListener("contextmenu", function (e) {
  462. if (!tabs.active || tabs.active.kind !== "text") return;
  463. e.preventDefault();
  464. var view = A.editor.view;
  465. var pos = view.posAtCoords({ x: e.clientX, y: e.clientY });
  466. var sel = view.state.selection.main;
  467. if (pos != null && (sel.empty || pos < sel.from || pos > sel.to)) view.dispatch({ selection: { anchor: pos } });
  468. editorMenu(e);
  469. });
  470. ​
  471. A.on("diagnostics", function (c) {
  472. var el = $("st-problems");
  473. el.innerHTML = '<span class="ath-st-err">' + A.icon("x") + c.error + '</span><span class="ath-st-warn">' + A.icon("warning") + (c.warning + c.info) + "</span>";
  474. el.classList.toggle("has-errors", c.error > 0);
  475. });
  476. ​
  477. document.addEventListener("click", function (e) {
  478. var b = e.target.closest("[data-cmd]");
  479. if (!b || !cmd[b.getAttribute("data-cmd")]) return;
  480. e.preventDefault();
  481. Promise.resolve().then(function () { return cmd[b.getAttribute("data-cmd")](); }).catch(fail);
  482. });
  483. ​
  484. window.addEventListener("keydown", function (e) {
  485. if (e.defaultPrevented || document.querySelector(".ath-dialog") || A.palette.isOpen()) return;
  486. var mod = (e.ctrlKey || e.metaKey) && !e.altKey;
  487. var alt = e.altKey && !e.ctrlKey && !e.metaKey;
  488. var key = e.key.toLowerCase();
  489. var run = null;
  490. if (mod && key === "s") run = e.shiftKey ? "saveAll" : "save";
  491. else if (mod && !e.shiftKey && key === "o") run = "openFolder";
  492. else if (mod && !e.shiftKey && key === "b") run = "toggleSidebar";
  493. else if (mod && e.code === "Comma") run = "settings";
  494. else if (mod && e.shiftKey && key === "p") run = "commandPalette";
  495. else if (mod && !e.shiftKey && key === "p") run = "quickOpen";
  496. else if (mod && !e.shiftKey && key === "g") run = "gotoLine";
  497. else if (mod && e.shiftKey && key === "f") run = "searchInFiles";
  498. else if (!e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey && e.key === "F1") run = "commandPalette";
  499. else if (e.shiftKey && alt && e.code === "KeyF") run = "format";
  500. else if (mod && e.key === "F2") run = "selectOccurrences";
  501. else if (mod && (e.code === "Equal" || e.code === "NumpadAdd")) run = "zoomIn";
  502. else if (mod && (e.code === "Minus" || e.code === "NumpadSubtract")) run = "zoomOut";
  503. else if (mod && (e.code === "Digit0" || e.code === "Numpad0")) run = "zoomReset";
  504. else if (alt && !e.shiftKey && e.code === "KeyN") run = "newFile";
  505. else if (alt && e.code === "KeyW") run = "closeTab";
  506. else if (alt && !e.shiftKey && e.code === "KeyT") run = "reopenTab";
  507. else if (alt && e.code === "KeyP") run = "togglePreview";
  508. else if (alt && !e.shiftKey && e.code === "KeyJ") run = "toggleConsole";
  509. else if (alt && !e.shiftKey && e.code === "KeyZ") run = "toggleWrap";
  510. else if (alt && !e.shiftKey && e.code === "KeyA") run = "aiOpen";
  511. else if (alt && e.shiftKey && e.code === "PageDown") run = "moveTabRight";
  512. else if (alt && e.shiftKey && e.code === "PageUp") run = "moveTabLeft";
  513. else if (alt && e.code === "PageDown") run = "nextTab";
  514. else if (alt && e.code === "PageUp") run = "prevTab";
  515. if (!run) return;
  516. e.preventDefault();
  517. e.stopPropagation();
  518. Promise.resolve().then(cmd[run]).catch(fail);
  519. }, true);
  520. ​
  521. window.addEventListener("beforeunload", function (e) {
  522. if (tabs.anyDirty()) { e.preventDefault(); e.returnValue = ""; }
  523. });
  524. ​
  525. window.addEventListener("unhandledrejection", function (e) {
  526. if (e.reason && e.reason.name === "AbortError") return;
  527. fail(e.reason);
  528. });
  529. ​
  530. function updateStatus() {
  531. var p = fs.provider;
  532. var tab = tabs.active;
  533. $("root-name").textContent = p ? p.name : t("sidebar.explorer");
  534. $("root-name").title = p ? p.name : "";
  535. var mode = $("st-mode");
  536. mode.textContent = !p ? t("status.no_folder") : t(p.kind === "disk" ? "status.disk" : "status.memory", { name: p.name });
  537. mode.classList.toggle("is-limited", !!p && p.kind === "memory");
  538. $("st-lang").textContent = tab ? (tab.kind === "image" ? t("status.image") : A.editor.langLabel(tab.name)) : "";
  539. $("st-indent").textContent = t(A.settings.get("insertSpaces") ? "status.spaces" : "status.tabs", { n: A.settings.get("tabSize") });
  540. if (!tab || tab.kind !== "text") $("st-pos").textContent = "";
  541. }
  542. ​
  543. A.on("active-change", function (tab) {
  544. var view = !tab ? "welcome" : tab.kind === "image" ? "image" : "editor";
  545. document.body.setAttribute("data-view", view);
  546. var img = $("image-view").querySelector("img");
  547. if (view === "image") img.src = tab.imageUrl;
  548. else img.removeAttribute("src");
  549. updateStatus();
  550. if (view === "welcome") refreshRecent();
  551. });
  552. ​
  553. A.on("cursor", function (state) {
  554. var sel = state.selection.main;
  555. var line = state.doc.lineAt(sel.head);
  556. var text = t("status.position", { line: line.number, col: sel.head - line.from + 1 });
  557. if (!sel.empty) text += " " + t("status.selected", { n: Math.abs(sel.to - sel.from) });
  558. if (state.selection.ranges.length > 1) text += " · " + t("status.cursors", { n: state.selection.ranges.length });
  559. $("st-pos").textContent = text;
  560. });
  561. ​
  562. A.on("workspace", function (p) {
  563. $("explorer-actions").hidden = !p;
  564. $("sidebar-empty").hidden = !!p;
  565. $("explorer").hidden = !p;
  566. updateStatus();
  567. if (p && document.body.classList.contains("ath-no-sidebar")) cmd.toggleSidebar();
  568. if (!tabs.active) refreshRecent();
  569. });
  570. ​
  571. A.on("settings", updateStatus);
  572. ​
  573. A.on("preview-toggle", function (open) {
  574. $("btn-preview").setAttribute("aria-pressed", open ? "true" : "false");
  575. });
  576. ​
  577. A.on("lang", function () {
  578. updateStatus();
  579. renderLangMenu();
  580. refreshRecent();
  581. if (tabs.active && tabs.active.kind === "text") A.emit("cursor", A.editor.view.state);
  582. });
  583. ​
  584. var SESSION_KEY = "session";
  585. var saveTimer = 0;
  586. ​
  587. function writeSession() {
  588. clearTimeout(saveTimer);
  589. if (!A.settings.get("reopenLast") || !fs.provider || fs.provider.kind !== "disk") return;
  590. A.store.set(SESSION_KEY, {
  591. root: fs.provider.name,
  592. files: tabs.list.filter(function (x) { return x.path != null; }).map(function (x) { return x.path; }),
  593. active: tabs.active && tabs.active.path != null ? tabs.active.path : null
  594. });
  595. }
  596. ​
  597. function saveSession() {
  598. clearTimeout(saveTimer);
  599. saveTimer = setTimeout(writeSession, 400);
  600. }
  601. ​
  602. A.on("active-change", saveSession);
  603. A.on("workspace", saveSession);
  604. A.on("settings", saveSession);
  605. document.addEventListener("visibilitychange", function () {
  606. if (document.visibilityState === "hidden") writeSession();
  607. });
  608. ​
  609. async function restoreTabs(rootName) {
  610. if (!A.settings.get("reopenLast")) return;
  611. var s = A.store.get(SESSION_KEY, null);
  612. if (!s || s.root !== rootName) return;
  613. for (var p of s.files || []) await tabs.openPath(p);
  614. if (s.active) await tabs.openPath(s.active);
  615. }
  616. ​
  617. async function autoReopen() {
  618. if (!A.settings.get("reopenLast") || fs.provider || tabs.active) return;
  619. var h = await fs.lastFolder();
  620. if (!h) return;
  621. try {
  622. if ((await h.queryPermission({ mode: "readwrite" })) !== "granted") return;
  623. await h.values().next();
  624. } catch (e) {
  625. return;
  626. }
  627. fs.setProvider(new fs.DiskProvider(h));
  628. await restoreTabs(h.name);
  629. }
  630. ​
  631. var recentSeq = 0;
  632. async function refreshRecent() {
  633. var seq = ++recentSeq;
  634. var btn = $("welcome-recent");
  635. var h = fs.provider || tabs.active ? null : await fs.lastFolder();
  636. if (seq !== recentSeq) return;
  637. btn.hidden = !h;
  638. if (!h) return;
  639. btn.querySelector("span").textContent = t("welcome.reopen", { name: h.name });
  640. btn.onclick = function () { cmd.reopenLast(h).catch(fail); };
  641. }
  642. ​
  643. function renderLangMenu() {
  644. var menu = $("lang-menu");
  645. var cur = A.i18n.current();
  646. menu.innerHTML = "";
  647. menu.appendChild(util.el("div", { class: "ath-accent-label" }, t("lang.title")));
  648. A.i18n.list().forEach(function (lang) {
  649. var active = cur && cur.id === lang.id;
  650. var item = util.el("button", {
  651. type: "button",
  652. class: "orb-dropdown-item ath-lang-item" + (active ? " is-current" : ""),
  653. role: "menuitemradio",
  654. "aria-checked": active ? "true" : "false",
  655. html: A.icon(active ? "check" : "globe") + "<span>" + util.esc(lang.name) + "</span>" +
  656. '<span class="ath-lang-code">' + util.esc(lang.code) + (lang.source === "imported" ? " · " + util.esc(t("lang.imported_tag")) : "") + "</span>"
  657. });
  658. item.addEventListener("click", function () { A.i18n.use(lang.id); });
  659. menu.appendChild(item);
  660. });
  661. menu.appendChild(util.el("div", { class: "orb-dropdown-divider" }));
  662. menu.appendChild(util.el("button", { type: "button", class: "orb-dropdown-item", "data-cmd": "importLanguage", html: A.icon("upload") + "<span>" + util.esc(t("lang.import")) + "</span>" }));
  663. menu.appendChild(util.el("button", { type: "button", class: "orb-dropdown-item", "data-cmd": "languageTemplate", html: A.icon("download") + "<span>" + util.esc(t("lang.template")) + "</span>" }));
  664. if (cur && cur.source === "imported") {
  665. menu.appendChild(util.el("button", { type: "button", class: "orb-dropdown-item is-danger", "data-cmd": "removeLanguage", html: A.icon("trash") + "<span>" + util.esc(t("lang.remove", { name: cur.name })) + "</span>" }));
  666. }
  667. }
  668. ​
  669. function initSplitters() {
  670. var shell = $("shell"), main = $("main");
  671. var sizes = A.store.get("sizes", {});
  672. if (sizes.sidebar) shell.style.setProperty("--ath-sidebar-w", sizes.sidebar + "px");
  673. if (sizes.preview) shell.style.setProperty("--ath-preview-w", sizes.preview + "px");
  674. ​
  675. document.querySelectorAll(".ath-splitter").forEach(function (sp) {
  676. var which = sp.getAttribute("data-split");
  677. sp.addEventListener("pointerdown", function (e) {
  678. if (e.button !== 0) return;
  679. e.preventDefault();
  680. sp.setPointerCapture(e.pointerId);
  681. document.body.classList.add("ath-resizing");
  682. var box = main.getBoundingClientRect();
  683. function move(ev) {
  684. var w = which === "sidebar"
  685. ? Math.max(170, Math.min(560, ev.clientX - box.left))
  686. : Math.max(260, Math.min(Math.max(260, box.width - 360), box.right - ev.clientX));
  687. sizes[which] = Math.round(w);
  688. shell.style.setProperty("--ath-" + which + "-w", sizes[which] + "px");
  689. }
  690. function up() {
  691. sp.removeEventListener("pointermove", move);
  692. sp.removeEventListener("pointerup", up);
  693. sp.removeEventListener("pointercancel", up);
  694. document.body.classList.remove("ath-resizing");
  695. A.store.set("sizes", sizes);
  696. A.editor.view.requestMeasure();
  697. }
  698. sp.addEventListener("pointermove", move);
  699. sp.addEventListener("pointerup", up);
  700. sp.addEventListener("pointercancel", up);
  701. });
  702. sp.addEventListener("dblclick", function () {
  703. delete sizes[which];
  704. shell.style.removeProperty("--ath-" + which + "-w");
  705. A.store.set("sizes", sizes);
  706. });
  707. });
  708. }
  709. ​
  710. function initDrop() {
  711. var hint = $("drop-hint"), depth = 0;
  712. function hasFiles(e) { return e.dataTransfer && Array.from(e.dataTransfer.types).indexOf("Files") >= 0; }
  713. function hide() { depth = 0; hint.classList.remove("is-visible"); }
  714. function overImageTarget(e) {
  715. var host = $("editor-host");
  716. return !!host && host.contains(e.target) && A.images.accepts(e);
  717. }
  718. function overExplorer(e) {
  719. var ex = $("explorer");
  720. return !!fs.provider && fs.provider.kind === "disk" && !!ex && !ex.hidden && ex.contains(e.target);
  721. }
  722. window.addEventListener("dragenter", function (e) {
  723. if (!hasFiles(e)) return;
  724. depth++;
  725. hint.classList.toggle("is-visible", !overExplorer(e) && !overImageTarget(e));
  726. });
  727. window.addEventListener("dragleave", function (e) {
  728. if (hasFiles(e) && --depth <= 0) hide();
  729. });
  730. window.addEventListener("dragover", function (e) {
  731. if (!hasFiles(e)) return;
  732. e.preventDefault();
  733. hint.classList.toggle("is-visible", !overExplorer(e) && !overImageTarget(e));
  734. });
  735. window.addEventListener("drop", function (e) {
  736. if (!hasFiles(e)) return;
  737. e.preventDefault();
  738. hide();
  739. if (e.athHandled) return;
  740. var jobs = Array.from(e.dataTransfer.items).filter(function (it) { return it.kind === "file"; }).map(function (it) {
  741. if (it.getAsFileSystemHandle) return it.getAsFileSystemHandle();
  742. var f = it.getAsFile();
  743. return Promise.resolve(f ? { kind: "file", _file: f } : null);
  744. });
  745. Promise.all(jobs).then(async function (handles) {
  746. for (var h of handles) {
  747. if (!h) continue;
  748. if (h.kind === "directory") {
  749. if (!(await fs.grant(h))) { A.ui.toast(t("app.no_permission"), "warning"); continue; }
  750. if (!(await switchWorkspace(new fs.DiskProvider(h)))) return;
  751. continue;
  752. }
  753. var file = h._file || (await h.getFile());
  754. await tabs.openFile({ name: file.name, handle: h._file ? null : h, file: file });
  755. }
  756. }).catch(fail);
  757. });
  758. }
  759. ​
  760. function latestVersion() {
  761. return fetch("version.js?t=" + Date.now(), { cache: "no-store" })
  762. .then(function (r) { return r.ok ? r.text() : ""; })
  763. .then(function (text) {
  764. var m = /version = "([^"]+)"/.exec(text);
  765. return m ? m[1] : "";
  766. })
  767. .catch(function () { return ""; });
  768. }
  769. ​
  770. function clearAndReload(version) {
  771. var jobs = [];
  772. if ("serviceWorker" in navigator) {
  773. jobs.push(navigator.serviceWorker.getRegistrations().then(function (list) {
  774. return Promise.all(list.map(function (r) { return r.unregister(); }));
  775. }));
  776. }
  777. if (window.caches) {
  778. jobs.push(caches.keys().then(function (keys) {
  779. return Promise.all(keys.map(function (k) { return caches.delete(k); }));
  780. }));
  781. }
  782. Promise.all(jobs).catch(function () { }).then(function () {
  783. location.replace(location.pathname + "?v=" + encodeURIComponent(version));
  784. });
  785. }
  786. ​
  787. var askedVersion = "";
  788. ​
  789. function checkUpdate() {
  790. if (!A.version) return;
  791. latestVersion().then(function (latest) {
  792. if (!latest || latest === A.version || askedVersion === latest) return;
  793. askedVersion = latest;
  794. A.ui.dialog({
  795. title: t("update.title"),
  796. body: t("update.body", { current: util.esc(A.version), latest: util.esc(latest) }),
  797. size: "sm",
  798. actions: [
  799. { label: t("update.later"), value: false, kind: "secondary" },
  800. { label: t("update.now"), value: true, kind: "primary" }
  801. ]
  802. }).then(function (yes) { if (yes) clearAndReload(latest); });
  803. });
  804. }
  805. ​
  806. function watchUpdates() {
  807. var last = Date.now();
  808. setTimeout(checkUpdate, 4000);
  809. document.addEventListener("visibilitychange", function () {
  810. if (document.visibilityState !== "visible" || Date.now() - last < 600000) return;
  811. last = Date.now();
  812. checkUpdate();
  813. });
  814. }
  815. ​
  816. function initPwa() {
  817. if (!/^https?:$/.test(location.protocol)) return;
  818. watchUpdates();
  819. document.head.appendChild(util.el("link", { rel: "manifest", href: "manifest.webmanifest" }));
  820. if ("serviceWorker" in navigator && (location.protocol === "https:" || location.hostname === "localhost" || location.hostname === "127.0.0.1")) {
  821. navigator.serviceWorker.register("sw.js" + (A.version ? "?v=" + encodeURIComponent(A.version) : "")).catch(function (e) { console.warn(e); });
  822. }
  823. }
  824. ​
  825. function reveal() {
  826. document.body.classList.add("is-ready");
  827. }
  828. ​
  829. try {
  830. A.i18n.init();
  831. A.settings.init();
  832. A.hydrateIcons();
  833. A.editor.init($("editor-host"));
  834. tabs.init($("tabs"));
  835. A.explorer.init($("explorer"));
  836. A.search.init();
  837. A.preview.init($("preview"));
  838. A.aiUi.init();
  839. initSplitters();
  840. initDrop();
  841. initPwa();
  842. ​
  843. if (!A.store.get("sidebar", true)) document.body.classList.add("ath-no-sidebar");
  844. A.preview.setOpen(A.store.get("preview", window.innerWidth > 1100));
  845. $("welcome-limited").hidden = fs.supported;
  846. renderLangMenu();
  847. A.emit("workspace", null);
  848. A.emit("active-change", null);
  849. autoReopen().catch(function (e) { console.warn(e); });
  850. ​
  851. var fontsReady = document.fonts
  852. ? Promise.all([A.fonts.init(), document.fonts.load("1em " + JSON.stringify(A.settings.get("uiFont"))), document.fonts.load("1em " + JSON.stringify(A.settings.get("codeFont")))])
  853. : Promise.resolve();
  854. Promise.race([
  855. Promise.all([fontsReady, refreshRecent()]),
  856. new Promise(function (r) { setTimeout(r, 800); })
  857. ]).then(reveal, reveal);
  858. } catch (e) {
  859. reveal();
  860. throw e;
  861. }
  862. A.i18n.loadExternal().catch(function (e) { console.warn(e); });
  863. })();
  864. ​