v1.5.0
AtheraStudio Code
- (function () {
- "use strict";
-
- var A = window.Athera;
- var util = A.util;
- var fs = A.fs;
- var tabs = A.tabs;
- var t = A.t;
- var $ = function (id) { return document.getElementById(id); };
-
- function fail(e) {
- console.error(e);
- A.ui.toast(e && e.message ? e.message : String(e), "danger");
- }
-
- async function switchWorkspace(provider) {
- if (!provider) return false;
- if (!(await tabs.closeAll())) return false;
- fs.setProvider(provider);
- A.ui.toast(t("app.folder_opened", { name: provider.name }), "success");
- return true;
- }
-
- var cmd = (A.commands = {
- openFolder: async function () {
- await switchWorkspace(await fs.pickFolder());
- },
-
- reopenLast: async function (handle) {
- try {
- if (!(await fs.grant(handle))) return A.ui.toast(t("app.no_permission"), "warning");
- await handle.values().next();
- } catch (e) {
- A.idb.del("lastRoot");
- refreshRecent();
- return A.ui.toast(t("app.reopen_failed"), "danger");
- }
- await switchWorkspace(new fs.DiskProvider(handle));
- await restoreTabs(handle.name);
- },
-
- openFile: async function () {
- for (var item of await fs.openFiles()) await tabs.openFile(item);
- },
-
- newFile: async function () {
- if (fs.provider) return A.explorer.newFile();
- var name = await A.ui.prompt(t("explorer.new_file"), t("app.new_file_label"), "", t("common.create"));
- if (name) tabs.newUntitled(util.basename(name), A.templates.forFile(name));
- },
-
- newFolder: function () {
- if (!fs.provider) return A.ui.toast(t("app.open_folder_first"), "info");
- return A.explorer.newFolder();
- },
-
- save: function () {
- if (tabs.active) return tabs.save();
- },
-
- saveAll: function () {
- return tabs.saveAll();
- },
-
- saveAs: async function () {
- var tab = tabs.active;
- if (!tab || tab.kind !== "text") return;
- var state = tabs.stateOf(tab);
- var h = await fs.saveAs(tab.name, state.doc.toString());
- if (h === undefined) return;
- if (h && tab.path == null) {
- tabs.retarget(tab, h.name, null, h);
- tab.savedDoc = state.doc;
- tab.dirty = !tabs.stateOf(tab).doc.eq(state.doc);
- tabs.render();
- }
- A.ui.toast(h ? t("app.saved_as", { name: h.name }) : t("app.downloaded", { name: tab.name }), "success");
- },
-
- closeTab: function () {
- if (tabs.active) return tabs.close();
- },
-
- reopenTab: function () {
- return tabs.reopen();
- },
-
- backup: function () {
- return A.backup.run();
- },
-
- closeFolder: async function () {
- if (!fs.provider) return;
- if (await tabs.closeAll()) fs.setProvider(null);
- },
-
- toggleSidebar: function () {
- var hidden = document.body.classList.toggle("ath-no-sidebar");
- A.store.set("sidebar", !hidden);
- A.editor.view.requestMeasure();
- },
-
- togglePreview: function () {
- A.preview.toggle();
- },
-
- toggleConsole: function () {
- if (!A.preview.open) A.preview.setOpen(true);
- A.console.toggle();
- },
-
- toggleWrap: function () {
- A.ui.toast(A.editor.toggleWrap() ? t("app.wrap_on") : t("app.wrap_off"));
- },
-
- zoomIn: function () { A.editor.zoom(1); },
- zoomOut: function () { A.editor.zoom(-1); },
- zoomReset: function () { A.editor.zoom(0); },
-
- search: function () {
- if (tabs.active && tabs.active.kind === "text") A.editor.openSearch();
- },
-
- searchInFiles: function () {
- A.search.open();
- },
-
- undoReplace: function () {
- return A.search.undoReplace();
- },
-
- nextTab: function () { tabs.move(1); },
- prevTab: function () { tabs.move(-1); },
- moveTabLeft: function () { tabs.shift(-1); },
- moveTabRight: function () { tabs.shift(1); },
-
- refreshExplorer: function () { return A.explorer.refresh(null); },
- collapseExplorer: function () { A.explorer.collapseAll(); },
-
- importLanguage: async function () {
- var files = await fs.pickFiles({ accept: ".xml,application/xml,text/xml" });
- if (!files.length) return;
- try {
- var lang = await A.i18n.import(files[0]);
- A.ui.toast(t("lang.imported", { name: lang.name }), "success");
- } catch (e) {
- A.ui.toast(t("lang.invalid", { error: e.message }), "danger");
- }
- },
-
- languageTemplate: function () {
- fs.download(t("lang.template_file"), A.i18n.template(), "application/xml;charset=utf-8");
- },
-
- removeLanguage: async function () {
- var cur = A.i18n.current();
- if (!cur || cur.source !== "imported") return;
- if (await A.ui.confirm(t("lang.remove_title"), t("lang.remove_confirm", { name: cur.name }), t("common.delete"), true)) {
- await A.i18n.removeImported(cur.id);
- }
- },
-
- settings: function () {
- A.settings.open();
- },
-
- quickOpen: function () { A.palette.open(""); },
- commandPalette: function () { A.palette.open(">"); },
- gotoLine: function () { A.palette.open(":"); },
-
- format: async function () {
- var tab = tabs.active;
- if (!tab || tab.kind !== "text") return;
- if (!A.intellisense.canFormat(tab.name)) return A.ui.toast(t("format.unsupported"), "info");
- try {
- if (!(await A.intellisense.format(A.editor.view, tab.name))) A.ui.toast(t("format.unchanged"));
- } catch (e) {
- A.ui.toast(e.message, "danger");
- }
- },
-
- problems: function () {
- if (tabs.active && tabs.active.kind === "text") A.editor.run(CM.openLintPanel);
- },
-
- nextProblem: function () {
- if (tabs.active && tabs.active.kind === "text") A.editor.run(CM.nextDiagnostic);
- },
-
- cut: function () { return A.editor.copy(true); },
- copy: function () { return A.editor.copy(false); },
- paste: function () {
- return A.editor.paste().catch(function () { A.ui.toast(t("editor.paste_blocked"), "info"); });
- },
- selectAll: function () { A.editor.run(CM.selectAll); },
- selectOccurrences: function () { A.editor.selectOccurrences(); },
- toggleComment: function () { A.editor.run(CM.toggleComment); },
- removeComments: function () { A.codetools.removeComments(); },
- trimWhitespace: function () { A.codetools.trimTrailing(); },
- removeEmptyLines: function () { A.codetools.removeEmptyLines(); },
- collapseEmptyLines: function () { A.codetools.collapseEmptyLines(); },
- sortAsc: function () { A.codetools.sortLines(false); },
- sortDesc: function () { A.codetools.sortLines(true); },
- uniqueLines: function () { A.codetools.uniqueLines(); },
- reverseLines: function () { A.codetools.reverseLines(); },
- joinLines: function () { A.codetools.joinLines(); },
- upperCase: function () { A.codetools.upperCase(); },
- lowerCase: function () { A.codetools.lowerCase(); },
- tabsToSpaces: function () { A.codetools.tabsToSpaces(); },
- spacesToTabs: function () { A.codetools.spacesToTabs(); },
- duplicateLine: function () { A.editor.run(CM.copyLineDown); },
- deleteLine: function () { A.editor.run(CM.deleteLine); },
- indentMore: function () { A.editor.run(CM.indentMore); },
- indentLess: function () { A.editor.run(CM.indentLess); },
- foldAll: function () { A.editor.run(CM.foldAll); },
- unfoldAll: function () { A.editor.run(CM.unfoldAll); },
- triggerSuggest: function () { A.editor.run(CM.startCompletion); },
-
- emmetWrap: function () { A.editor.simulateKey("w", "KeyW", { ctrlKey: true, altKey: true }); },
- emmetBalanceOut: function () { A.editor.run(CM.balanceOutward); },
- emmetBalanceIn: function () { A.editor.run(CM.balanceInward); },
- emmetRemoveTag: function () { A.editor.run(CM.removeTag); },
- emmetTagPair: function () { A.editor.run(CM.goToTagPair); },
- emmetSplitJoin: function () { A.editor.run(CM.splitJoinTag); },
- emmetMath: function () { A.editor.run(CM.evaluateMath); },
- emmetNextEdit: function () { A.editor.run(CM.goToNextEditPoint); },
- emmetPrevEdit: function () { A.editor.run(CM.goToPreviousEditPoint); },
- emmetIncrement: function () { A.editor.run(CM.incrementNumber1); },
- emmetDecrement: function () { A.editor.run(CM.decrementNumber1); },
-
- toggleTheme: function () { Orbitarium.theme.toggle(); },
- phpRestart: function () {
- A.php.restart();
- A.ui.toast(t("php.restarted"));
- if (A.preview.open) A.preview.build();
- },
- undo: function () { A.editor.run(CM.undo); },
- redo: function () { A.editor.run(CM.redo); },
-
- aiOpen: function () { A.aiUi.toggle(); },
- aiToggle: function () { return A.ai.enabled() ? A.ai.disable() : A.ai.enable(); },
- aiPick: function () { return A.ai.viewer.pick(); },
- aiAudit: async function () {
- if (!A.ai.allowed("preview")) return A.ui.toast(A.ai.t("ai.viewer.err_perm"), "info");
- A.ui.toast(A.ai.t("ai.viewer.audit_running"));
- A.ai.viewer.showAudit(await A.ai.viewer.audit({ screenshots: A.ai.allowed("screenshot") }));
- },
- aiProofread: function () { return A.ai.proofread.run(); },
- followLink: function () { return A.links.followCursor(); },
- aiDock: function () { A.aiUi.setDocked(!A.aiUi.isDocked()); },
- aiRecipes: function () { A.aiUi.open("recipes"); },
- aiEval: function () {
- A.ai.set("evalPanel", true);
- A.aiUi.open("eval");
- },
- aiPrivate: function () { A.aiUi.open("private"); },
- aiChanges: function () { A.aiUi.open("changes"); },
- aiInstructions: function () { A.aiUi.open("instructions"); },
- aiKeys: function () { A.aiUi.open("keys"); },
- aiBudget: function () { A.aiUi.open("model"); },
- aiPermissions: function () { A.aiUi.open("permissions"); },
- aiExclusions: function () { A.aiUi.open("exclusions"); },
-
- shortcuts: function () {
- var rows = [
- ["Ctrl+O", "shortcut.open_folder"], ["Ctrl+S", "shortcut.save"], ["Ctrl+Shift+S", "shortcut.save_all"],
- ["Alt+N", "shortcut.new_file"], ["Alt+W", "shortcut.close_tab"], ["Alt+PgDn / Alt+PgUp", "shortcut.switch_tab"],
- ["Alt+Shift+PgDn / PgUp", "shortcut.move_tab"], ["Alt+T", "shortcut.reopen_tab"],
- ["Ctrl+B", "shortcut.sidebar"], ["Alt+P", "shortcut.preview"], ["Alt+J", "console.toggle"], ["Alt+Z", "shortcut.wrap"],
- ["Ctrl+Space", "shortcut.complete"], ["Ctrl+F", "shortcut.search"], ["Ctrl+/", "shortcut.comment"],
- ["Alt+↑ / Alt+↓", "shortcut.move_line"], ["Shift+Alt+↓", "shortcut.copy_line"], ["Ctrl+D", "shortcut.select_next"],
- ["Alt+Click", "shortcut.multi_cursor"], ["Ctrl+Shift+[ / ]", "shortcut.fold"], ["Ctrl+= / Ctrl+-", "shortcut.zoom"],
- ["F2 / Del", "shortcut.explorer"], ["Drag", "shortcut.drag_move"], ["Ctrl+,", "shortcut.settings"],
- ["Ctrl+P", "cmd.quick_open"], ["Ctrl+Shift+F", "cmd.search_in_files"], ["Ctrl+Shift+P / F1", "cmd.command_palette"], ["Ctrl+G", "cmd.goto_line"],
- ["Shift+Alt+F", "cmd.format"], ["Tab", "shortcut.emmet"], ["Ctrl+Alt+W", "cmd.emmet_wrap"],
- ["Ctrl+Shift+L / Ctrl+F2", "cmd.select_occurrences"], ["Ctrl+Shift+K", "cmd.delete_line"],
- ["Ctrl+Shift+M", "cmd.problems"], ["F8", "cmd.next_problem"], ["Alt+A", "ai.menu.open"]
- ];
- if (window.atheraDesktop && window.atheraDesktop.isDesktop) rows.push(["Alt+Drag", "shortcut.drag_out"]);
- var keyName = function (k) {
- return k === "Space" ? t("key.space") : k === "Click" ? t("key.click") : k === "Drag" ? t("key.drag") : k;
- };
- var table = util.el("table", { class: "orb-table ath-keys-table" }, [util.el("tbody", {}, rows.map(function (r) {
- return util.el("tr", {}, [
- util.el("td", {}, r[0].split(" / ").map(function (combo, i) {
- var span = util.el("span", { class: "ath-combo" }, combo.split("+").map(function (k) {
- return util.el("span", { class: "orb-kbd" }, keyName(k));
- }));
- return i ? util.el("span", {}, [" / ", span]) : span;
- })),
- util.el("td", {}, r[1].indexOf("ai.") === 0 ? A.ai.t(r[1]) : t(r[1]))
- ]);
- }))]);
- A.ui.dialog({ title: t("menu.shortcuts"), body: table, size: "lg", actions: [{ label: t("common.close"), value: null, kind: "secondary" }] });
- },
-
- about: function () {
- var lang = A.i18n.current();
- var body = util.el("div", { class: "ath-about" }, [
- util.el("img", { class: "ath-about-logo", src: "icon.webp", alt: "" }),
- util.el("h2", { class: "orb-h3" }, ["AtheraStudio Code ", util.el("span", { class: "orb-text-muted" }, A.version)]),
- util.el("p", {}, t("about.text")),
- util.el("p", {}, t("about.license", { license: "SA-SDL" })),
- util.el("p", { class: "orb-text-muted orb-text-sm" }, [
- t("about.ui", { name: "Orbitarium Design 1.1.0" }), util.el("br"),
- t("about.engine", { name: "CodeMirror 6 (MIT)" }), util.el("br"),
- t("about.translation", { name: lang.name + (lang.author ? " · " + lang.author : "") })
- ])
- ]);
- A.ui.dialog({ title: t("menu.about"), size: "sm", body: body, actions: [{ label: t("common.close"), value: null, kind: "secondary" }] });
- }
- });
-
- var COMMANDS = [
- ["quickOpen", "cmd.quick_open", "Ctrl+P", "file", true],
- ["commandPalette", "cmd.command_palette", "Ctrl+Shift+P", "terminal", true],
- ["gotoLine", "cmd.goto_line", "Ctrl+G", "gotoLine", true],
- ["searchInFiles", "cmd.search_in_files", "Ctrl+Shift+F", "search", true],
- ["undoReplace", "search.undo_replace", "", "undo", true],
- ["openFolder", "menu.open_folder", "Ctrl+O", "folderOpen", true],
- ["openFile", "menu.open_file", "", "file", true],
- ["newFile", "menu.new_file", "Alt+N", "filePlus", true],
- ["newFolder", "menu.new_folder", "", "folderPlus", true],
- ["save", "menu.save", "Ctrl+S", "save", true],
- ["saveAll", "menu.save_all", "Ctrl+Shift+S", "saveAll", true],
- ["saveAs", "menu.save_as", "", "saveAs", true],
- ["closeTab", "menu.close_tab", "Alt+W", "x", true],
- ["reopenTab", "cmd.reopen_tab", "Alt+T", "undo", true],
- ["moveTabLeft", "tabs.move_left", "Alt+Shift+PgUp", "arrowLeft", true],
- ["moveTabRight", "tabs.move_right", "Alt+Shift+PgDn", "arrowRight", true],
- ["backup", "menu.backup", "", "download", true],
- ["closeFolder", "menu.close_folder", "", "folderX", true],
- ["format", "cmd.format", "Shift+Alt+F", "wand", false],
- ["triggerSuggest", "cmd.suggest", "Ctrl+Space", "lightbulb", false],
- ["undo", "cmd.undo", "Ctrl+Z", "undo", false],
- ["redo", "cmd.redo", "Ctrl+Y", "redo", false],
- ["selectOccurrences", "cmd.select_occurrences", "Ctrl+Shift+L", "selectText", false],
- ["toggleComment", "cmd.toggle_comment", "Ctrl+/", "comment", false],
- ["removeComments", "cmd.remove_comments", "", "trash", false],
- ["trimWhitespace", "cmd.trim_whitespace", "", "wand", false],
- ["removeEmptyLines", "cmd.remove_empty_lines", "", "trash", false],
- ["collapseEmptyLines", "cmd.collapse_empty_lines", "", "collapse", false],
- ["sortAsc", "cmd.sort_asc", "", "gotoLine", false],
- ["sortDesc", "cmd.sort_desc", "", "gotoLine", false],
- ["uniqueLines", "cmd.unique_lines", "", "duplicate", false],
- ["reverseLines", "cmd.reverse_lines", "", "refresh", false],
- ["joinLines", "cmd.join_lines", "", "wrap", false],
- ["upperCase", "cmd.upper_case", "", "type", false],
- ["lowerCase", "cmd.lower_case", "", "type", false],
- ["tabsToSpaces", "cmd.tabs_to_spaces", "", "indent", false],
- ["spacesToTabs", "cmd.spaces_to_tabs", "", "outdent", false],
- ["duplicateLine", "cmd.duplicate_line", "Shift+Alt+↓", "duplicate", false],
- ["deleteLine", "cmd.delete_line", "Ctrl+Shift+K", "trash", false],
- ["indentMore", "cmd.indent_more", "Ctrl+]", "indent", false],
- ["indentLess", "cmd.indent_less", "Ctrl+[", "outdent", false],
- ["foldAll", "cmd.fold_all", "", "foldAll", false],
- ["unfoldAll", "cmd.unfold_all", "", "collapse", false],
- ["search", "menu.search", "Ctrl+F", "search", false],
- ["problems", "cmd.problems", "Ctrl+Shift+M", "warning", false],
- ["nextProblem", "cmd.next_problem", "F8", "warning", false],
- ["emmetWrap", "cmd.emmet_wrap", "Ctrl+Alt+W", "code", "emmet"],
- ["emmetBalanceOut", "cmd.emmet_balance_out", "", "code", "emmet"],
- ["emmetBalanceIn", "cmd.emmet_balance_in", "", "code", "emmet"],
- ["emmetRemoveTag", "cmd.emmet_remove_tag", "", "code", "emmet"],
- ["emmetTagPair", "cmd.emmet_tag_pair", "", "code", "emmet"],
- ["emmetSplitJoin", "cmd.emmet_split_join", "", "code", "emmet"],
- ["emmetMath", "cmd.emmet_math", "", "code", false],
- ["emmetNextEdit", "cmd.emmet_next_edit", "", "code", "emmet"],
- ["emmetPrevEdit", "cmd.emmet_prev_edit", "", "code", "emmet"],
- ["emmetIncrement", "cmd.emmet_increment", "", "code", false],
- ["emmetDecrement", "cmd.emmet_decrement", "", "code", false],
- ["phpRestart", "cmd.php_restart", "", "refresh", true],
- ["toggleSidebar", "menu.sidebar", "Ctrl+B", "sidebar", true],
- ["togglePreview", "menu.preview", "Alt+P", "eye", true],
- ["toggleConsole", "console.toggle", "Alt+J", "terminal", true],
- ["toggleWrap", "menu.wrap", "Alt+Z", "wrap", true],
- ["toggleTheme", "cmd.toggle_theme", "", "moon", true],
- ["zoomIn", "menu.zoom_in", "Ctrl+=", "zoomIn", true],
- ["zoomOut", "menu.zoom_out", "Ctrl+-", "zoomOut", true],
- ["zoomReset", "menu.zoom_reset", "Ctrl+0", "zoomReset", true],
- ["aiOpen", "ai.menu.open", "Alt+A", "sparkles", true],
- ["aiToggle", "ai.cmd.toggle", "", "power", true],
- ["aiProofread", "ai.proof.cmd", "", "type", false],
- ["followLink", "links.cmd", "", "external", false],
- ["aiDock", "ai.cmd.dock", "", "sidebar", true],
- ["aiPick", "ai.viewer.pick", "", "target", true],
- ["aiAudit", "ai.viewer.audit", "", "layout", true],
- ["aiRecipes", "ai.menu.recipes", "", "code", true],
- ["aiEval", "ai.eval.title", "", "lightbulb", true],
- ["aiPrivate", "ai.menu.private", "", "folder", true],
- ["aiChanges", "ai.menu.changes", "", "undo", true],
- ["aiInstructions", "ai.menu.instructions", "", "pencil", true],
- ["aiKeys", "ai.menu.keys", "", "key", true],
- ["aiBudget", "ai.menu.budget", "", "coins", true],
- ["aiPermissions", "ai.menu.permissions", "", "shield", true],
- ["aiExclusions", "ai.menu.exclusions", "", "ban", true],
- ["settings", "menu.settings", "Ctrl+,", "settings", true],
- ["importLanguage", "lang.import", "", "upload", true],
- ["shortcuts", "menu.shortcuts", "", "keyboard", true],
- ["about", "menu.about", "", "info", true]
- ];
-
- function emmetLanguage() {
- var tab = tabs.active;
- return !!tab && tab.kind === "text" && /^(html|php|svg)$/.test(A.editor.langId(tab.name)) && A.settings.get("emmet");
- }
-
- A.commandList = function () {
- var editing = !!tabs.active && tabs.active.kind === "text";
- return COMMANDS.filter(function (c) {
- if (c[4] === true) return true;
- if (c[4] === "emmet") return editing && emmetLanguage();
- return editing;
- }).map(function (c) {
- var label = (c[0].indexOf("ai") === 0 ? A.ai.t(c[1]) : t(c[1])).replace(/…$/, "");
- return { id: c[0], label: label, kbd: c[2], icon: c[3], run: function () { return cmd[c[0]](); } };
- });
- };
-
- function editorMenu(e) {
- var tab = tabs.active;
- var hasSel = A.editor.view.state.selection.ranges.some(function (r) { return !r.empty; });
- var items = [
- { label: t(hasSel ? "cmd.cut" : "cmd.cut_line"), kbd: "Ctrl+X", icon: "scissors", action: cmd.cut },
- { label: t(hasSel ? "cmd.copy" : "cmd.copy_line"), kbd: "Ctrl+C", icon: "copy", action: cmd.copy },
- { label: t("cmd.paste"), kbd: "Ctrl+V", icon: "clipboard", action: cmd.paste },
- "-",
- { label: t("cmd.select_occurrences"), kbd: "Ctrl+Shift+L", icon: "selectText", action: cmd.selectOccurrences },
- { label: t("cmd.toggle_comment"), kbd: "Ctrl+/", icon: "comment", action: cmd.toggleComment },
- { label: t("cmd.remove_comments"), icon: "trash", action: cmd.removeComments },
- { label: t("cmd.suggest"), kbd: "Ctrl+Space", icon: "lightbulb", action: cmd.triggerSuggest }
- ];
- var link = A.links && A.links.atCursor();
- if (link) {
- 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 });
- items.unshift({ label: linkLabel, kbd: "Ctrl+Click", icon: link.type === "url" ? "external" : "file", action: cmd.followLink }, "-");
- }
- if (hasSel) items.push("-", { label: A.ai.t("ai.proof.cmd"), icon: "type", action: cmd.aiProofread });
- if (A.intellisense.canFormat(tab.name)) items.push({ label: t("cmd.format"), kbd: "Shift+Alt+F", icon: "wand", action: cmd.format });
- if (emmetLanguage()) {
- items.push("-",
- { label: t("cmd.emmet_wrap"), kbd: "Ctrl+Alt+W", icon: "code", action: cmd.emmetWrap },
- { label: t("cmd.emmet_balance_out"), icon: "code", action: cmd.emmetBalanceOut },
- { label: t("cmd.emmet_tag_pair"), icon: "code", action: cmd.emmetTagPair },
- { label: t("cmd.emmet_remove_tag"), icon: "code", action: cmd.emmetRemoveTag });
- }
- items.push("-",
- { label: t("cmd.goto_line"), kbd: "Ctrl+G", icon: "gotoLine", action: cmd.gotoLine },
- { label: t("menu.search"), kbd: "Ctrl+F", icon: "search", action: cmd.search },
- { label: t("cmd.fold_all"), icon: "foldAll", action: cmd.foldAll },
- { label: t("cmd.unfold_all"), icon: "collapse", action: cmd.unfoldAll },
- "-",
- { label: t("cmd.command_palette"), kbd: "Ctrl+Shift+P", icon: "terminal", action: cmd.commandPalette });
- A.ui.contextMenu(e.clientX, e.clientY, items.map(function (it) {
- if (it === "-") return it;
- var run = it.action;
- return Object.assign({}, it, { action: function () { Promise.resolve().then(run).catch(fail); } });
- }));
- }
-
- $("editor-host").addEventListener("contextmenu", function (e) {
- if (!tabs.active || tabs.active.kind !== "text") return;
- e.preventDefault();
- var view = A.editor.view;
- var pos = view.posAtCoords({ x: e.clientX, y: e.clientY });
- var sel = view.state.selection.main;
- if (pos != null && (sel.empty || pos < sel.from || pos > sel.to)) view.dispatch({ selection: { anchor: pos } });
- editorMenu(e);
- });
-
- A.on("diagnostics", function (c) {
- var el = $("st-problems");
- 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>";
- el.classList.toggle("has-errors", c.error > 0);
- });
-
- document.addEventListener("click", function (e) {
- var b = e.target.closest("[data-cmd]");
- if (!b || !cmd[b.getAttribute("data-cmd")]) return;
- e.preventDefault();
- Promise.resolve().then(function () { return cmd[b.getAttribute("data-cmd")](); }).catch(fail);
- });
-
- window.addEventListener("keydown", function (e) {
- if (e.defaultPrevented || document.querySelector(".ath-dialog") || A.palette.isOpen()) return;
- var mod = (e.ctrlKey || e.metaKey) && !e.altKey;
- var alt = e.altKey && !e.ctrlKey && !e.metaKey;
- var key = e.key.toLowerCase();
- var run = null;
- if (mod && key === "s") run = e.shiftKey ? "saveAll" : "save";
- else if (mod && !e.shiftKey && key === "o") run = "openFolder";
- else if (mod && !e.shiftKey && key === "b") run = "toggleSidebar";
- else if (mod && e.code === "Comma") run = "settings";
- else if (mod && e.shiftKey && key === "p") run = "commandPalette";
- else if (mod && !e.shiftKey && key === "p") run = "quickOpen";
- else if (mod && !e.shiftKey && key === "g") run = "gotoLine";
- else if (mod && e.shiftKey && key === "f") run = "searchInFiles";
- else if (!e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey && e.key === "F1") run = "commandPalette";
- else if (e.shiftKey && alt && e.code === "KeyF") run = "format";
- else if (mod && e.key === "F2") run = "selectOccurrences";
- else if (mod && (e.code === "Equal" || e.code === "NumpadAdd")) run = "zoomIn";
- else if (mod && (e.code === "Minus" || e.code === "NumpadSubtract")) run = "zoomOut";
- else if (mod && (e.code === "Digit0" || e.code === "Numpad0")) run = "zoomReset";
- else if (alt && !e.shiftKey && e.code === "KeyN") run = "newFile";
- else if (alt && e.code === "KeyW") run = "closeTab";
- else if (alt && !e.shiftKey && e.code === "KeyT") run = "reopenTab";
- else if (alt && e.code === "KeyP") run = "togglePreview";
- else if (alt && !e.shiftKey && e.code === "KeyJ") run = "toggleConsole";
- else if (alt && !e.shiftKey && e.code === "KeyZ") run = "toggleWrap";
- else if (alt && !e.shiftKey && e.code === "KeyA") run = "aiOpen";
- else if (alt && e.shiftKey && e.code === "PageDown") run = "moveTabRight";
- else if (alt && e.shiftKey && e.code === "PageUp") run = "moveTabLeft";
- else if (alt && e.code === "PageDown") run = "nextTab";
- else if (alt && e.code === "PageUp") run = "prevTab";
- if (!run) return;
- e.preventDefault();
- e.stopPropagation();
- Promise.resolve().then(cmd[run]).catch(fail);
- }, true);
-
- window.addEventListener("beforeunload", function (e) {
- if (tabs.anyDirty()) { e.preventDefault(); e.returnValue = ""; }
- });
-
- window.addEventListener("unhandledrejection", function (e) {
- if (e.reason && e.reason.name === "AbortError") return;
- fail(e.reason);
- });
-
- function updateStatus() {
- var p = fs.provider;
- var tab = tabs.active;
- $("root-name").textContent = p ? p.name : t("sidebar.explorer");
- $("root-name").title = p ? p.name : "";
- var mode = $("st-mode");
- mode.textContent = !p ? t("status.no_folder") : t(p.kind === "disk" ? "status.disk" : "status.memory", { name: p.name });
- mode.classList.toggle("is-limited", !!p && p.kind === "memory");
- $("st-lang").textContent = tab ? (tab.kind === "image" ? t("status.image") : A.editor.langLabel(tab.name)) : "";
- $("st-indent").textContent = t(A.settings.get("insertSpaces") ? "status.spaces" : "status.tabs", { n: A.settings.get("tabSize") });
- if (!tab || tab.kind !== "text") $("st-pos").textContent = "";
- }
-
- A.on("active-change", function (tab) {
- var view = !tab ? "welcome" : tab.kind === "image" ? "image" : "editor";
- document.body.setAttribute("data-view", view);
- var img = $("image-view").querySelector("img");
- if (view === "image") img.src = tab.imageUrl;
- else img.removeAttribute("src");
- updateStatus();
- if (view === "welcome") refreshRecent();
- });
-
- A.on("cursor", function (state) {
- var sel = state.selection.main;
- var line = state.doc.lineAt(sel.head);
- var text = t("status.position", { line: line.number, col: sel.head - line.from + 1 });
- if (!sel.empty) text += " " + t("status.selected", { n: Math.abs(sel.to - sel.from) });
- if (state.selection.ranges.length > 1) text += " · " + t("status.cursors", { n: state.selection.ranges.length });
- $("st-pos").textContent = text;
- });
-
- A.on("workspace", function (p) {
- $("explorer-actions").hidden = !p;
- $("sidebar-empty").hidden = !!p;
- $("explorer").hidden = !p;
- updateStatus();
- if (p && document.body.classList.contains("ath-no-sidebar")) cmd.toggleSidebar();
- if (!tabs.active) refreshRecent();
- });
-
- A.on("settings", updateStatus);
-
- A.on("preview-toggle", function (open) {
- $("btn-preview").setAttribute("aria-pressed", open ? "true" : "false");
- });
-
- A.on("lang", function () {
- updateStatus();
- renderLangMenu();
- refreshRecent();
- if (tabs.active && tabs.active.kind === "text") A.emit("cursor", A.editor.view.state);
- });
-
- var SESSION_KEY = "session";
- var saveTimer = 0;
-
- function writeSession() {
- clearTimeout(saveTimer);
- if (!A.settings.get("reopenLast") || !fs.provider || fs.provider.kind !== "disk") return;
- A.store.set(SESSION_KEY, {
- root: fs.provider.name,
- files: tabs.list.filter(function (x) { return x.path != null; }).map(function (x) { return x.path; }),
- active: tabs.active && tabs.active.path != null ? tabs.active.path : null
- });
- }
-
- function saveSession() {
- clearTimeout(saveTimer);
- saveTimer = setTimeout(writeSession, 400);
- }
-
- A.on("active-change", saveSession);
- A.on("workspace", saveSession);
- A.on("settings", saveSession);
- document.addEventListener("visibilitychange", function () {
- if (document.visibilityState === "hidden") writeSession();
- });
-
- async function restoreTabs(rootName) {
- if (!A.settings.get("reopenLast")) return;
- var s = A.store.get(SESSION_KEY, null);
- if (!s || s.root !== rootName) return;
- for (var p of s.files || []) await tabs.openPath(p);
- if (s.active) await tabs.openPath(s.active);
- }
-
- async function autoReopen() {
- if (!A.settings.get("reopenLast") || fs.provider || tabs.active) return;
- var h = await fs.lastFolder();
- if (!h) return;
- try {
- if ((await h.queryPermission({ mode: "readwrite" })) !== "granted") return;
- await h.values().next();
- } catch (e) {
- return;
- }
- fs.setProvider(new fs.DiskProvider(h));
- await restoreTabs(h.name);
- }
-
- var recentSeq = 0;
- async function refreshRecent() {
- var seq = ++recentSeq;
- var btn = $("welcome-recent");
- var h = fs.provider || tabs.active ? null : await fs.lastFolder();
- if (seq !== recentSeq) return;
- btn.hidden = !h;
- if (!h) return;
- btn.querySelector("span").textContent = t("welcome.reopen", { name: h.name });
- btn.onclick = function () { cmd.reopenLast(h).catch(fail); };
- }
-
- function renderLangMenu() {
- var menu = $("lang-menu");
- var cur = A.i18n.current();
- menu.innerHTML = "";
- menu.appendChild(util.el("div", { class: "ath-accent-label" }, t("lang.title")));
- A.i18n.list().forEach(function (lang) {
- var active = cur && cur.id === lang.id;
- var item = util.el("button", {
- type: "button",
- class: "orb-dropdown-item ath-lang-item" + (active ? " is-current" : ""),
- role: "menuitemradio",
- "aria-checked": active ? "true" : "false",
- html: A.icon(active ? "check" : "globe") + "<span>" + util.esc(lang.name) + "</span>" +
- '<span class="ath-lang-code">' + util.esc(lang.code) + (lang.source === "imported" ? " · " + util.esc(t("lang.imported_tag")) : "") + "</span>"
- });
- item.addEventListener("click", function () { A.i18n.use(lang.id); });
- menu.appendChild(item);
- });
- menu.appendChild(util.el("div", { class: "orb-dropdown-divider" }));
- 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>" }));
- 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>" }));
- if (cur && cur.source === "imported") {
- 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>" }));
- }
- }
-
- function initSplitters() {
- var shell = $("shell"), main = $("main");
- var sizes = A.store.get("sizes", {});
- if (sizes.sidebar) shell.style.setProperty("--ath-sidebar-w", sizes.sidebar + "px");
- if (sizes.preview) shell.style.setProperty("--ath-preview-w", sizes.preview + "px");
-
- document.querySelectorAll(".ath-splitter").forEach(function (sp) {
- var which = sp.getAttribute("data-split");
- sp.addEventListener("pointerdown", function (e) {
- if (e.button !== 0) return;
- e.preventDefault();
- sp.setPointerCapture(e.pointerId);
- document.body.classList.add("ath-resizing");
- var box = main.getBoundingClientRect();
- function move(ev) {
- var w = which === "sidebar"
- ? Math.max(170, Math.min(560, ev.clientX - box.left))
- : Math.max(260, Math.min(Math.max(260, box.width - 360), box.right - ev.clientX));
- sizes[which] = Math.round(w);
- shell.style.setProperty("--ath-" + which + "-w", sizes[which] + "px");
- }
- function up() {
- sp.removeEventListener("pointermove", move);
- sp.removeEventListener("pointerup", up);
- sp.removeEventListener("pointercancel", up);
- document.body.classList.remove("ath-resizing");
- A.store.set("sizes", sizes);
- A.editor.view.requestMeasure();
- }
- sp.addEventListener("pointermove", move);
- sp.addEventListener("pointerup", up);
- sp.addEventListener("pointercancel", up);
- });
- sp.addEventListener("dblclick", function () {
- delete sizes[which];
- shell.style.removeProperty("--ath-" + which + "-w");
- A.store.set("sizes", sizes);
- });
- });
- }
-
- function initDrop() {
- var hint = $("drop-hint"), depth = 0;
- function hasFiles(e) { return e.dataTransfer && Array.from(e.dataTransfer.types).indexOf("Files") >= 0; }
- function hide() { depth = 0; hint.classList.remove("is-visible"); }
- function overImageTarget(e) {
- var host = $("editor-host");
- return !!host && host.contains(e.target) && A.images.accepts(e);
- }
- function overExplorer(e) {
- var ex = $("explorer");
- return !!fs.provider && fs.provider.kind === "disk" && !!ex && !ex.hidden && ex.contains(e.target);
- }
- window.addEventListener("dragenter", function (e) {
- if (!hasFiles(e)) return;
- depth++;
- hint.classList.toggle("is-visible", !overExplorer(e) && !overImageTarget(e));
- });
- window.addEventListener("dragleave", function (e) {
- if (hasFiles(e) && --depth <= 0) hide();
- });
- window.addEventListener("dragover", function (e) {
- if (!hasFiles(e)) return;
- e.preventDefault();
- hint.classList.toggle("is-visible", !overExplorer(e) && !overImageTarget(e));
- });
- window.addEventListener("drop", function (e) {
- if (!hasFiles(e)) return;
- e.preventDefault();
- hide();
- if (e.athHandled) return;
- var jobs = Array.from(e.dataTransfer.items).filter(function (it) { return it.kind === "file"; }).map(function (it) {
- if (it.getAsFileSystemHandle) return it.getAsFileSystemHandle();
- var f = it.getAsFile();
- return Promise.resolve(f ? { kind: "file", _file: f } : null);
- });
- Promise.all(jobs).then(async function (handles) {
- for (var h of handles) {
- if (!h) continue;
- if (h.kind === "directory") {
- if (!(await fs.grant(h))) { A.ui.toast(t("app.no_permission"), "warning"); continue; }
- if (!(await switchWorkspace(new fs.DiskProvider(h)))) return;
- continue;
- }
- var file = h._file || (await h.getFile());
- await tabs.openFile({ name: file.name, handle: h._file ? null : h, file: file });
- }
- }).catch(fail);
- });
- }
-
- function latestVersion() {
- return fetch("version.js?t=" + Date.now(), { cache: "no-store" })
- .then(function (r) { return r.ok ? r.text() : ""; })
- .then(function (text) {
- var m = /version = "([^"]+)"/.exec(text);
- return m ? m[1] : "";
- })
- .catch(function () { return ""; });
- }
-
- function clearAndReload(version) {
- var jobs = [];
- if ("serviceWorker" in navigator) {
- jobs.push(navigator.serviceWorker.getRegistrations().then(function (list) {
- return Promise.all(list.map(function (r) { return r.unregister(); }));
- }));
- }
- if (window.caches) {
- jobs.push(caches.keys().then(function (keys) {
- return Promise.all(keys.map(function (k) { return caches.delete(k); }));
- }));
- }
- Promise.all(jobs).catch(function () { }).then(function () {
- location.replace(location.pathname + "?v=" + encodeURIComponent(version));
- });
- }
-
- var askedVersion = "";
-
- function checkUpdate() {
- if (!A.version) return;
- latestVersion().then(function (latest) {
- if (!latest || latest === A.version || askedVersion === latest) return;
- askedVersion = latest;
- A.ui.dialog({
- title: t("update.title"),
- body: t("update.body", { current: util.esc(A.version), latest: util.esc(latest) }),
- size: "sm",
- actions: [
- { label: t("update.later"), value: false, kind: "secondary" },
- { label: t("update.now"), value: true, kind: "primary" }
- ]
- }).then(function (yes) { if (yes) clearAndReload(latest); });
- });
- }
-
- function watchUpdates() {
- var last = Date.now();
- setTimeout(checkUpdate, 4000);
- document.addEventListener("visibilitychange", function () {
- if (document.visibilityState !== "visible" || Date.now() - last < 600000) return;
- last = Date.now();
- checkUpdate();
- });
- }
-
- function initPwa() {
- if (!/^https?:$/.test(location.protocol)) return;
- watchUpdates();
- document.head.appendChild(util.el("link", { rel: "manifest", href: "manifest.webmanifest" }));
- if ("serviceWorker" in navigator && (location.protocol === "https:" || location.hostname === "localhost" || location.hostname === "127.0.0.1")) {
- navigator.serviceWorker.register("sw.js" + (A.version ? "?v=" + encodeURIComponent(A.version) : "")).catch(function (e) { console.warn(e); });
- }
- }
-
- function reveal() {
- document.body.classList.add("is-ready");
- }
-
- try {
- A.i18n.init();
- A.settings.init();
- A.hydrateIcons();
- A.editor.init($("editor-host"));
- tabs.init($("tabs"));
- A.explorer.init($("explorer"));
- A.search.init();
- A.preview.init($("preview"));
- A.aiUi.init();
- initSplitters();
- initDrop();
- initPwa();
-
- if (!A.store.get("sidebar", true)) document.body.classList.add("ath-no-sidebar");
- A.preview.setOpen(A.store.get("preview", window.innerWidth > 1100));
- $("welcome-limited").hidden = fs.supported;
- renderLangMenu();
- A.emit("workspace", null);
- A.emit("active-change", null);
- autoReopen().catch(function (e) { console.warn(e); });
-
- var fontsReady = document.fonts
- ? 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")))])
- : Promise.resolve();
- Promise.race([
- Promise.all([fontsReady, refreshRecent()]),
- new Promise(function (r) { setTimeout(r, 800); })
- ]).then(reveal, reveal);
- } catch (e) {
- reveal();
- throw e;
- }
- A.i18n.loadExternal().catch(function (e) { console.warn(e); });
- })();
-