v1.5.0
AtheraStudio Code
- (function () {
- "use strict";
-
- var A = window.Athera;
- var util = A.util;
- var fs = A.fs;
-
- var BADGES = {
- html: ["html", "<>"], htm: ["html", "<>"], php: ["php", "php"], css: ["css", "#"], scss: ["css", "S"],
- js: ["js", "JS"], mjs: ["js", "JS"], jsx: ["js", "JSX"], ts: ["ts", "TS"], tsx: ["ts", "TSX"],
- json: ["json", "{}"], jsonc: ["json", "{}"], xml: ["xml", "</>"], md: ["md", "M↓"], svg: ["img", "svg"], txt: ["txt", "≡"]
- };
- var NAMED = {
- "sitemap.xml": ["sitemap", "sitemap"], "sitemap_index.xml": ["sitemap", "sitemap"],
- "rss.xml": ["rss", "rss"], "feed.xml": ["rss", "rss"], "atom.xml": ["rss", "rss"]
- };
- A.fileBadge = function (name) {
- var named = NAMED[util.basename(name).toLowerCase()];
- if (named) return '<span class="ath-ficon" data-type="' + named[0] + '">' + A.icon(named[1]) + "</span>";
- var ext = util.ext(name);
- var b = BADGES[ext] || (fs.isImage(name) ? ["img", "▣"] : null);
- if (!b) return '<span class="ath-ficon ath-ficon-file">' + A.icon("file") + "</span>";
- return '<span class="ath-ficon" data-type="' + b[0] + '">' + util.esc(b[1]) + "</span>";
- };
-
- function isRasterImage(name) {
- return fs.isImage(name) && util.ext(name) !== "svg";
- }
-
- function canAutoSave(tab) {
- if (!tab || tab.kind !== "text" || !tab.dirty || tabs.list.indexOf(tab) < 0) return false;
- if (tab.path != null) return !!fs.provider && fs.provider.kind === "disk";
- return !!tab.handle;
- }
-
- var pending = new Set();
- var flushAutoSave = util.debounce(function () {
- var list = Array.from(pending);
- pending.clear();
- list.forEach(function (tab) { if (canAutoSave(tab)) tabs.save(tab, true); });
- }, 1000);
-
- var dragTab = null;
- var dropAt = -1;
- var marker = null;
-
- function reduced() {
- return window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
- }
-
- function onEnterEnd(e) {
- if (e.animationName !== "ath-tab-in") return;
- var n = e.currentTarget;
- n.classList.remove("is-entering");
- n.removeEventListener("animationend", onEnterEnd);
- if (n.classList.contains("is-active")) n.scrollIntoView({ block: "nearest", inline: "nearest" });
- }
-
- function leave(node, animate) {
- node.removeAttribute("draggable");
- if (!animate) { node.remove(); return; }
- node.style.setProperty("--w", node.offsetWidth + "px");
- node.classList.remove("is-entering");
- node.classList.add("is-leaving");
- var done = false;
- function finish() {
- if (done) return;
- done = true;
- node.remove();
- }
- node.addEventListener("animationend", function (e) {
- if (e.animationName === "ath-tab-out") finish();
- });
- setTimeout(finish, 600);
- }
-
- function buildTab(tab) {
- var node = util.el("div", { class: "ath-tab", role: "tab", draggable: "true" });
- node._tab = tab;
- node.innerHTML = A.fileBadge(tab.name) + '<span class="ath-tab-name"></span>';
- var close = util.el("button", { type: "button", class: "ath-tab-close", html: '<span class="ath-tab-dot"></span>' + A.icon("x") });
- close.addEventListener("click", function (e) { e.stopPropagation(); tabs.close(tab); });
- node.appendChild(close);
- node.addEventListener("mousedown", function (e) {
- if (e.button === 1) { e.preventDefault(); tabs.close(tab); }
- });
- node.addEventListener("click", function () { if (tab !== tabs.active) tabs.activate(tab); });
- node.addEventListener("contextmenu", function (e) {
- e.preventDefault();
- var i = tabs.list.indexOf(tab);
- var items = [
- { label: A.t("common.save"), icon: "save", kbd: "Ctrl+S", action: function () { tabs.save(tab); } },
- "-",
- { label: A.t("tabs.close"), icon: "x", kbd: "Alt+W", action: function () { tabs.close(tab); } },
- { label: A.t("tabs.close_others"), icon: "xCircle", action: function () { tabs.closeAll(tab); } },
- { label: A.t("tabs.close_all"), icon: "closeAll", action: function () { tabs.closeAll(); } }
- ];
- if (tabs.canReopen()) items.push("-", { label: A.t("cmd.reopen_tab"), icon: "undo", kbd: "Alt+T", action: function () { tabs.reopen(); } });
- var moves = [];
- if (i > 0) moves.push({ label: A.t("tabs.move_left"), kbd: "Alt+Shift+PgUp", icon: "arrowLeft", action: function () { tabs.shift(-1, tab); } });
- if (i >= 0 && i < tabs.list.length - 1) moves.push({ label: A.t("tabs.move_right"), kbd: "Alt+Shift+PgDn", icon: "arrowRight", action: function () { tabs.shift(1, tab); } });
- if (moves.length) items.push.apply(items, ["-"].concat(moves));
- A.ui.contextMenu(e.clientX, e.clientY, items);
- });
- node._name = null;
- return node;
- }
-
- function syncTab(node, tab) {
- var c = node.classList;
- c.toggle("is-active", tab === tabs.active);
- c.toggle("is-dirty", !!tab.dirty);
- node.setAttribute("aria-selected", tab === tabs.active ? "true" : "false");
- node.title = tab.path != null ? tab.path : tab.name + (tab.handle ? "" : " " + A.t("tabs.not_on_disk"));
- if (node._name !== tab.name) {
- node._name = tab.name;
- node.firstChild.outerHTML = A.fileBadge(tab.name);
- node.querySelector(".ath-tab-name").textContent = tab.name;
- }
- node.querySelector(".ath-tab-close").setAttribute("aria-label", A.t("tabs.close_named", { name: tab.name }));
- }
-
- function liveNodes() {
- return tabs.list.map(function (t) { return t._node; }).filter(Boolean);
- }
-
- function indexAt(x) {
- var nodes = liveNodes();
- for (var i = 0; i < nodes.length; i++) {
- var r = nodes[i].getBoundingClientRect();
- if (x < r.left + r.width / 2) return i;
- }
- return nodes.length;
- }
-
- function showMarker(index) {
- var nodes = liveNodes();
- if (!nodes.length) return hideMarker();
- var from = tabs.list.indexOf(dragTab);
- if (index === from || index === from + 1) return hideMarker();
- var host = tabs.el.getBoundingClientRect();
- var x = index < nodes.length ? nodes[index].getBoundingClientRect().left : nodes[nodes.length - 1].getBoundingClientRect().right;
- if (x < host.left - 1 || x > host.right + 1) return hideMarker();
- if (!marker) {
- marker = document.createElement("div");
- marker.className = "ath-tab-marker";
- document.body.appendChild(marker);
- }
- marker.style.top = host.top + "px";
- marker.style.height = host.height + "px";
- marker.style.transform = "translateX(" + Math.round(x) + "px)";
- marker.classList.add("is-visible");
- }
-
- function hideMarker() {
- if (marker) marker.classList.remove("is-visible");
- }
-
- function endTabDrag() {
- if (!dragTab) return;
- if (dragTab._node) dragTab._node.classList.remove("is-dragging");
- dragTab = null;
- dropAt = -1;
- hideMarker();
- if (tabs.el) tabs.el.classList.remove("is-reordering");
- }
-
- function initDrag(el) {
- el.addEventListener("dragstart", function (e) {
- var node = e.target.closest && e.target.closest(".ath-tab");
- if (!node || !node._tab || node.classList.contains("is-leaving")) return;
- dragTab = node._tab;
- e.dataTransfer.effectAllowed = "move";
- e.dataTransfer.setData("text/plain", dragTab.name);
- requestAnimationFrame(function () {
- if (dragTab && dragTab._node) dragTab._node.classList.add("is-dragging");
- el.classList.add("is-reordering");
- });
- });
- el.addEventListener("dragover", function (e) {
- if (!dragTab) return;
- e.preventDefault();
- e.dataTransfer.dropEffect = "move";
- var r = el.getBoundingClientRect();
- if (e.clientX < r.left + 48) el.scrollLeft -= 16;
- else if (e.clientX > r.right - 48) el.scrollLeft += 16;
- dropAt = indexAt(e.clientX);
- showMarker(dropAt);
- });
- el.addEventListener("dragleave", function (e) {
- if (dragTab && !el.contains(e.relatedTarget)) hideMarker();
- });
- el.addEventListener("drop", function (e) {
- if (!dragTab) return;
- e.preventDefault();
- e.stopPropagation();
- var tab = dragTab, to = indexAt(e.clientX);
- endTabDrag();
- tabs.reorder(tab, to);
- });
- el.addEventListener("dragend", endTabDrag);
- window.addEventListener("dragend", endTabDrag, true);
- window.addEventListener("drop", function () { setTimeout(endTabDrag, 0); }, true);
- }
-
- var seq = 0;
- var CLOSED_MAX = 20;
- var closed = [];
-
- function remember(tab) {
- if (tab.kind === "image" && tab.path == null && !tab.handle) return;
- var entry = { name: tab.name, path: tab.path, handle: tab.handle, kind: tab.kind, scrollTop: tab.scrollTop };
- if (tab.kind === "text") {
- var st = tabs.stateOf(tab);
- var sel = st.selection.main;
- entry.anchor = sel.anchor;
- entry.head = sel.head;
- if (tab.path == null && !tab.handle) entry.text = st.doc.toString();
- }
- closed = closed.filter(function (c) { return !(c.path != null && c.path === entry.path); });
- closed.push(entry);
- if (closed.length > CLOSED_MAX) closed.shift();
- }
-
- function restoreView(tab, entry) {
- if (!tab || tab.kind !== "text" || entry.anchor == null) return;
- var len = tabs.stateOf(tab).doc.length;
- var anchor = Math.min(entry.anchor, len), head = Math.min(entry.head, len);
- var view = A.editor.view;
- view.dispatch({ selection: { anchor: anchor, head: head } });
- requestAnimationFrame(function () { view.scrollDOM.scrollTop = entry.scrollTop || 0; });
- }
-
- var tabs = (A.tabs = {
- list: [],
- active: null,
- el: null,
-
- init: function (el) {
- tabs.el = el;
- initDrag(el);
- el.addEventListener("wheel", function (e) {
- if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) { el.scrollLeft += e.deltaY; e.preventDefault(); }
- }, { passive: false });
- A.on("doc-change", function (state) {
- var tab = tabs.active;
- if (!tab || tab.kind !== "text") return;
- var dirty = state.doc.length !== tab.savedDoc.length || !state.doc.eq(tab.savedDoc);
- if (dirty !== tab.dirty) { tab.dirty = dirty; tabs.render(); }
- if (dirty && A.settings.get("autoSave")) { pending.add(tab); flushAutoSave(); }
- });
- window.addEventListener("blur", function () {
- if (!A.settings.get("autoSave")) return;
- tabs.list.forEach(function (tab) { if (canAutoSave(tab)) tabs.save(tab, true); });
- });
- A.on("lang", function () { tabs.render(); });
- A.on("workspace", function () { tabs.clearClosed(); });
- tabs.render();
- },
-
- stateOf: function (tab) {
- return tab === tabs.active ? A.editor.view.state : tab.state;
- },
-
- textOf: function (tab) {
- return tabs.stateOf(tab).doc.toString();
- },
-
- byPath: function (path) {
- return tabs.list.find(function (t) { return t.path === path; }) || null;
- },
-
- contentOf: function (path) {
- var tab = tabs.byPath(path);
- return tab && tab.kind === "text" ? tabs.textOf(tab) : null;
- },
-
- canReopen: function () {
- return closed.length > 0;
- },
-
- clearClosed: function () {
- closed = [];
- },
-
- reopen: async function () {
- while (closed.length) {
- var entry = closed.pop();
- var tab = null;
- try {
- if (entry.path != null) {
- if (!fs.provider) continue;
- if (!(await fs.provider.exists(entry.path))) continue;
- tab = await tabs.openPath(entry.path);
- } else if (entry.handle) {
- var file = await entry.handle.getFile();
- tab = await tabs.openFile({ name: entry.name, handle: entry.handle, file: file });
- } else if (entry.kind === "text") {
- tab = tabs.create({ name: entry.name, text: entry.text || "", dirty: !!entry.text });
- }
- } catch (e) {
- continue;
- }
- if (tab) {
- restoreView(tab, entry);
- return tab;
- }
- }
- A.ui.toast(A.t("tabs.nothing_to_reopen"), "info");
- return null;
- },
-
- anyDirty: function () {
- return tabs.list.some(function (t) { return t.dirty; });
- },
-
- create: function (desc, options) {
- var tab = {
- id: ++seq,
- name: desc.name,
- path: desc.path == null ? null : desc.path,
- handle: desc.handle || null,
- kind: desc.imageUrl ? "image" : "text",
- imageUrl: desc.imageUrl || null,
- dirty: !!desc.dirty,
- scrollTop: 0
- };
- if (tab.kind === "text") {
- tab.state = A.editor.createState(desc.text || "", tab.name);
- tab.savedDoc = desc.dirty ? CM.EditorState.create({ doc: "" }).doc : tab.state.doc;
- }
- var at = tabs.active ? tabs.list.indexOf(tabs.active) + 1 : tabs.list.length;
- tabs.list.splice(at, 0, tab);
- tabs.activate(tab, options);
- return tab;
- },
-
- openPath: async function (path, options) {
- var existing = tabs.byPath(path);
- if (existing) return tabs.activate(existing, options);
- var name = util.basename(path);
- try {
- if (isRasterImage(name)) {
- var blob = await fs.provider.readFile(path);
- return tabs.byPath(path) || tabs.create({ name: name, path: path, imageUrl: URL.createObjectURL(blob) }, options);
- }
- if (fs.isBinary(name)) {
- A.ui.toast(A.t("tabs.binary", { name: name }), "warning");
- return null;
- }
- var text = await fs.provider.readText(path);
- return tabs.byPath(path) || tabs.create({ name: name, path: path, text: text }, options);
- } catch (e) {
- A.ui.toast(A.t("tabs.open_failed", { name: name, error: e.message }), "danger");
- return null;
- }
- },
-
- openFile: async function (item) {
- if (item.handle) {
- for (var t of tabs.list) {
- if (t.handle && await t.handle.isSameEntry(item.handle)) return tabs.activate(t);
- }
- }
- if (isRasterImage(item.name)) {
- return tabs.create({ name: item.name, handle: item.handle, imageUrl: URL.createObjectURL(item.file) });
- }
- if (fs.isBinary(item.name)) {
- A.ui.toast(A.t("tabs.binary", { name: item.name }), "warning");
- return null;
- }
- return tabs.create({ name: item.name, handle: item.handle, text: await item.file.text() });
- },
-
- newUntitled: function (name, text) {
- return tabs.create({ name: name, text: text || "", dirty: !!text });
- },
-
- activate: function (tab, options) {
- var prev = tabs.active;
- var view = A.editor.view;
- if (prev && prev !== tab && prev.kind === "text" && tabs.list.indexOf(prev) >= 0) {
- prev.state = view.state;
- prev.scrollTop = view.scrollDOM.scrollTop;
- }
- tabs.active = tab;
- if (tab && tab.kind === "text" && prev !== tab) {
- view.setState(A.editor.syncState(tab.state, tab.name));
- requestAnimationFrame(function () { view.scrollDOM.scrollTop = tab.scrollTop; });
- }
- tabs.render();
- A.emit("active-change", tab);
- if (tab && tab.kind === "text") {
- A.emit("cursor", view.state);
- if (!options || options.focusEditor !== false) A.editor.focus();
- }
- return tab;
- },
-
- move: function (dir) {
- if (tabs.list.length < 2) return;
- var i = tabs.list.indexOf(tabs.active);
- tabs.activate(tabs.list[(i + dir + tabs.list.length) % tabs.list.length]);
- },
-
- save: async function (tab, auto) {
- tab = tab || tabs.active;
- if (!tab || tab.kind !== "text") return false;
- if (!auto && tab === tabs.active && A.settings.get("formatOnSave") && A.intellisense.canFormat(tab.name)) {
- try { await A.intellisense.format(A.editor.view, tab.name); } catch (e) { A.ui.toast(e.message, "warning"); }
- }
- var state = tabs.stateOf(tab);
- var text = state.doc.toString();
- try {
- if (tab.path != null && fs.provider) {
- await fs.provider.write(tab.path, text);
- if (fs.provider.kind === "memory") {
- fs.download(tab.name, text);
- A.ui.toast(A.t("tabs.memory_saved", { name: tab.name }), "info");
- }
- } else if (tab.handle) {
- await fs.writeHandle(tab.handle, text);
- } else {
- var h = await fs.saveAs(tab.name, text);
- if (h === undefined) return false;
- if (h) tabs.retarget(tab, h.name, null, h);
- }
- } catch (e) {
- A.ui.toast(A.t("tabs.save_failed", { name: tab.name, error: e.message }), "danger");
- return false;
- }
- tab.savedDoc = state.doc;
- tab.dirty = !tabs.stateOf(tab).doc.eq(state.doc);
- tabs.render();
- A.emit("saved", tab);
- return true;
- },
-
- saveAll: async function () {
- var dirty = tabs.list.filter(function (t) { return t.dirty; });
- var ok = 0;
- for (var t of dirty) if (await tabs.save(t)) ok++;
- if (ok) A.ui.toast(A.tn("tabs.saved_count", ok), "success");
- },
-
- close: async function (tab, force) {
- tab = tab || tabs.active;
- if (!tab || tabs.list.indexOf(tab) < 0) return true;
- if (tab.dirty && !force) {
- tabs.activate(tab);
- var choice = await A.ui.dialog({
- title: A.t("tabs.unsaved_title"),
- body: util.el("p", { class: "ath-dialog-text" }, A.t("tabs.unsaved_text", { name: tab.name })),
- size: "sm",
- actions: [
- { label: A.t("common.cancel"), value: null, kind: "ghost" },
- { label: A.t("tabs.dont_save"), value: "discard", kind: "secondary" },
- { label: A.t("common.save"), value: "save", kind: "primary" }
- ]
- });
- if (!choice) return false;
- if (choice === "save" && !(await tabs.save(tab))) return false;
- }
- var i = tabs.list.indexOf(tab);
- if (i < 0) return true;
- if (!force) remember(tab);
- tabs.list.splice(i, 1);
- if (tab.imageUrl) URL.revokeObjectURL(tab.imageUrl);
- if (dragTab === tab) endTabDrag();
- if (tabs.active === tab) {
- tabs.active = null;
- tabs.activate(tabs.list[Math.min(i, tabs.list.length - 1)] || null);
- } else {
- tabs.render();
- }
- return true;
- },
-
- closeAll: async function (except) {
- for (var t of tabs.list.slice()) {
- if (t !== except && !(await tabs.close(t))) return false;
- }
- return true;
- },
-
- renamePath: function (oldPath, newPath) {
- tabs.list.forEach(function (t) {
- if (t.path == null) return;
- if (t.path === oldPath) tabs.retarget(t, util.basename(newPath), newPath);
- else if (t.path.indexOf(oldPath + "/") === 0) t.path = newPath + t.path.slice(oldPath.length);
- });
- tabs.render();
- },
-
- removePath: function (path) {
- tabs.list.slice().forEach(function (t) {
- if (t.path != null && (t.path === path || t.path.indexOf(path + "/") === 0)) tabs.close(t, true);
- });
- },
-
- retarget: function (tab, name, path, handle) {
- var langChanged = A.editor.langId(name) !== A.editor.langId(tab.name);
- tab.name = name;
- if (path !== undefined) tab.path = path;
- if (handle) tab.handle = handle;
- if (langChanged && tab.kind === "text") {
- var s = A.editor.setLanguage(tabs.stateOf(tab), name);
- if (tab === tabs.active) A.editor.view.setState(s);
- else tab.state = s;
- }
- if (tab === tabs.active) A.emit("active-change", tab);
- },
-
- reorder: function (tab, to) {
- var from = tabs.list.indexOf(tab);
- if (from < 0) return false;
- if (to > from) to--;
- to = Math.max(0, Math.min(tabs.list.length - 1, to));
- if (to === from) return false;
- var before = new Map();
- tabs.list.forEach(function (t) {
- if (t._node) before.set(t, t._node.getBoundingClientRect().left);
- });
- tabs.list.splice(from, 1);
- tabs.list.splice(to, 0, tab);
- tabs.render();
- if (!reduced()) {
- tabs.list.forEach(function (t) {
- var n = t._node, b = before.get(t);
- if (!n || b == null) return;
- var d = b - n.getBoundingClientRect().left;
- if (d) {
- n.animate(
- [{ transform: "translateX(" + d + "px)" }, { transform: "none" }],
- { duration: 240, easing: "cubic-bezier(0.22, 1, 0.36, 1)" }
- );
- }
- });
- }
- if (tab._node) tab._node.scrollIntoView({ block: "nearest", inline: "nearest" });
- return true;
- },
-
- shift: function (dir, tab) {
- tab = tab || tabs.active;
- if (!tab) return;
- var i = tabs.list.indexOf(tab);
- if (i < 0) return;
- var j = i + dir;
- if (j < 0 || j >= tabs.list.length) return;
- tabs.reorder(tab, dir > 0 ? j + 1 : j);
- },
-
- render: function () {
- var el = tabs.el;
- if (!el) return;
- var animate = el._ready && !reduced();
- var seen = new Set();
- var prev = null;
- tabs.list.forEach(function (tab) {
- var node = tab._node;
- if (!node) {
- node = tab._node = buildTab(tab);
- if (animate) {
- node.classList.add("is-entering");
- node.addEventListener("animationend", onEnterEnd);
- }
- }
- syncTab(node, tab);
- seen.add(node);
- var ref = prev ? prev.nextSibling : el.firstChild;
- if (node !== ref) el.insertBefore(node, ref);
- prev = node;
- });
- Array.from(el.children).forEach(function (n) {
- if (seen.has(n) || n.classList.contains("is-leaving")) return;
- leave(n, animate);
- });
- el._ready = true;
- var act = tabs.active && tabs.active._node;
- if (act) act.scrollIntoView({ block: "nearest", inline: "nearest" });
- document.title = (tabs.active ? (tabs.active.dirty ? "● " : "") + tabs.active.name + " · " : "") + "AtheraStudio Code";
- }
- });
- })();