v1.4.2
AtheraStudio Code
- (function () {
- "use strict";
-
- var A = window.Athera;
- var util = A.util;
- var t = A.t;
- var DATA = A.snippetData;
- var FRAMEWORK = /^(orbitarium|tw:|bs:|shadcn:|water:|pico:|simple:|mvp:|sakura:)/;
-
- function enabled(list) {
- return A.settings.get("frameworkSnippets") ? list : list.filter(function (s) { return !FRAMEWORK.test(s.label); });
- }
-
- var TAG_PARTS = /^(OpenTag|SelfClosingTag|CloseTag|Attribute|AttributeName|AttributeValue|UnquotedAttributeValue|TagName|StartTag|StartCloseTag|EndTag|SelfCloseEndTag|MismatchedCloseTag|IncompleteCloseTag|Comment|DoctypeDecl|ProcessingInst)$/;
- var CTX_BY_TAG = {
- html: "html", head: "head", ul: "list", ol: "list", menu: "list", table: "table", thead: "table", tbody: "table",
- tfoot: "table", form: "form", select: "select", datalist: "select", script: "code", style: "code", textarea: "code", title: "code"
- };
- var VOID = ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr", "param", "keygen", "command"];
- var OPTIONAL_CLOSE = ["p", "li", "dt", "dd", "option", "optgroup", "tr", "td", "th", "thead", "tbody", "tfoot", "colgroup", "rt", "rp", "html", "head", "body"];
- var DEPRECATED = ["center", "font", "marquee", "big", "strike", "tt", "frame", "frameset", "blink", "acronym", "applet", "basefont", "dir"];
-
- function desc(item) {
- var lang = A.i18n.current();
- return item.d[lang && lang.code === "pl" ? 0 : 1];
- }
-
- function preview(template) {
- return function () {
- var pre = document.createElement("pre");
- pre.className = "ath-snippet-preview";
- pre.textContent = template
- .replace(/\$\{\d+:([^}]*)\}/g, "$1")
- .replace(/\$\{\d*\}/g, "")
- .replace(/\t/g, " ");
- return pre;
- };
- }
-
- function ranked(list, base) {
- return list.map(function (item, i) { return snippet(item, base - i / list.length); });
- }
-
- function snippet(item, boost) {
- return CM.snippetCompletion(item.body, {
- label: item.label,
- detail: desc(item),
- info: preview(item.body),
- type: "snippet",
- boost: boost || 0
- });
- }
-
- function isPhpDoc(state) {
- var lang = state.facet(CM.language);
- return !!lang && lang.name === "php";
- }
-
- function elementInfo(state, el) {
- var open = el.getChild("OpenTag") || el.getChild("SelfClosingTag");
- if (!open) return null;
- var nameNode = open.getChild("TagName");
- var attrs = {};
- open.getChildren("Attribute").forEach(function (a) {
- var an = a.getChild("AttributeName");
- var av = a.getChild("AttributeValue") || a.getChild("UnquotedAttributeValue");
- if (an) attrs[state.sliceDoc(an.from, an.to).toLowerCase()] = av ? state.sliceDoc(av.from, av.to).replace(/^["']|["']$/g, "") : "";
- });
- return {
- node: el,
- name: nameNode ? state.sliceDoc(nameNode.from, nameNode.to).toLowerCase() : "",
- attrs: attrs,
- open: open,
- nameTo: nameNode ? nameNode.to : open.from + 1,
- close: el.getChild("CloseTag")
- };
- }
-
- function htmlContext(state, pos) {
- var node = CM.syntaxTree(state).resolveInner(pos, -1);
- for (var n = node; n; n = n.parent) {
- if (TAG_PARTS.test(n.name) && pos < n.to && pos > n.from) return { ctx: "tag" };
- if (n.name === "Element") {
- var info = elementInfo(state, n);
- if (!info || pos < info.open.to) continue;
- if (info.close && pos >= info.close.to) continue;
- if (info.open.name === "SelfClosingTag" || VOID.indexOf(info.name) >= 0) continue;
- return { ctx: CTX_BY_TAG[info.name] || "body", element: info };
- }
- if (n.name === "Document") break;
- }
- var empty = /^\s*(<!doctype[^>]*>)?\s*$/i.test(state.doc.toString());
- return { ctx: empty ? "top" : "body" };
- }
-
- function elementIsEmpty(state, info) {
- var from = info.open.to;
- var to = info.close ? info.close.from : info.node.to;
- return !state.sliceDoc(from, to).trim();
- }
-
- function cssContext(state, pos) {
- for (var n = CM.syntaxTree(state).resolveInner(pos, -1); n; n = n.parent) {
- if (n.name === "Block" && pos > n.from) return "block";
- }
- return "top";
- }
-
- function htmlSource(ctx) {
- var word = ctx.matchBefore(/[\w:.@-]*/);
- var before = ctx.state.sliceDoc(Math.max(0, word.from - 2), word.from);
- if (/<\/?$/.test(before)) return null;
- if (!ctx.explicit && word.from === word.to) return null;
- var c = htmlContext(ctx.state, ctx.pos);
- if (c.ctx === "tag" || c.ctx === "code") return null;
- var options = ranked(enabled(DATA.html).filter(function (s) { return s.ctx.indexOf(c.ctx) >= 0; }), 20);
- if (isPhpDoc(ctx.state)) options = options.concat(ranked(DATA.phpInline, 15));
- if (c.ctx !== "top" && c.ctx !== "html" && c.ctx !== "head") {
- enabled(DATA.html).forEach(function (s) {
- if (s.ctx.indexOf(c.ctx) < 0 && s.ctx.indexOf("body") >= 0) options.push(snippet(s, -10));
- });
- }
- return options.length ? { from: word.from, options: options, validFor: /^[\w:.@-]*$/ } : null;
- }
-
- function cssSource(ctx) {
- var word = ctx.matchBefore(/[\w:.@-]*/);
- if (!ctx.explicit && word.from === word.to) return null;
- var c = cssContext(ctx.state, ctx.pos);
- var options = ranked(enabled(DATA.css).filter(function (s) { return s.ctx.indexOf(c) >= 0; }), 10);
- return { from: word.from, options: options, validFor: /^[\w:.@-]*$/ };
- }
-
- function jsSource(ctx) {
- var word = ctx.matchBefore(/[\w:]*/);
- if (!ctx.explicit && word.from === word.to) return null;
- var before = ctx.state.sliceDoc(Math.max(0, word.from - 1), word.from);
- if (before === ".") return null;
- var file = A.tabs && A.tabs.active ? A.tabs.active.name : "";
- var kind = util.ext(file);
- var options = ranked(DATA.js, 5);
- if (kind === "jsx" || kind === "tsx") options = options.concat(ranked(enabled(DATA.shadcn), 8));
- else if (kind === "ts") options = options.concat(ranked(enabled(DATA.shadcn).filter(function (s) { return s.label === "shadcn:cn"; }), 8));
- return { from: word.from, options: options, validFor: /^[\w:]*$/ };
- }
-
- var phpFunctionOptions = null;
- function phpFunctions() {
- if (!phpFunctionOptions) {
- phpFunctionOptions = DATA.phpFunctions.map(function (entry) {
- var i = entry.indexOf("|");
- var name = entry.slice(0, i), sig = entry.slice(i + 1);
- var bare = /^(echo|print|die|exit)$/.test(name);
- return CM.snippetCompletion(bare ? name + " ${}" : name + "(${})", { label: name, detail: sig.replace(/^[^(]*/, ""), info: sig, type: "function" });
- });
- }
- return phpFunctionOptions;
- }
-
- function phpSource(ctx) {
- var word = ctx.matchBefore(/\$?\w+(?::\w*)?|\$?\w*/);
- if (!ctx.explicit && word.from === word.to) return null;
- var text = ctx.state.sliceDoc(word.from, word.to);
- if (text.charAt(0) === "$") {
- var seen = {}, options = [];
- DATA.phpVariables.forEach(function (v) { seen[v] = 1; options.push({ label: v, type: "variable", boost: 5 }); });
- var re = /\$[A-Za-z_]\w*/g, m, doc = ctx.state.doc.toString();
- while ((m = re.exec(doc))) {
- if (seen[m[0]] || (m.index === word.from)) continue;
- seen[m[0]] = 1;
- options.push({ label: m[0], type: "variable" });
- }
- return { from: word.from, options: options, validFor: /^\$\w*$/ };
- }
- var list = phpFunctions()
- .concat(DATA.phpKeywords.map(function (k) { return { label: k, type: /^[A-Z_]+$/.test(k) ? "constant" : "keyword" }; }))
- .concat(ranked(DATA.php, 10));
- return { from: word.from, options: list, validFor: /^\w+(?::\w*)?$|^\w*$/ };
- }
-
- var JS_SCOPE = (function () {
- var names = ["window", "document", "console", "localStorage", "sessionStorage", "navigator", "location", "history", "JSON", "Math",
- "Date", "Array", "Object", "String", "Number", "Boolean", "Promise", "fetch", "setTimeout", "clearTimeout", "setInterval",
- "clearInterval", "requestAnimationFrame", "cancelAnimationFrame", "alert", "confirm", "prompt", "structuredClone", "URL",
- "URLSearchParams", "FormData", "Headers", "Request", "Response", "IntersectionObserver", "MutationObserver", "ResizeObserver",
- "Intl", "Map", "Set", "WeakMap", "WeakSet", "Symbol", "RegExp", "Error", "TypeError", "parseInt", "parseFloat", "isNaN",
- "isFinite", "encodeURIComponent", "decodeURIComponent", "CustomEvent", "Event", "Blob", "File", "FileReader", "crypto",
- "performance", "Image", "Audio", "AbortController", "BigInt", "Reflect", "Proxy", "screen", "matchMedia", "getComputedStyle",
- "queueMicrotask", "atob", "btoa", "TextEncoder", "TextDecoder", "Worker", "WebSocket", "EventSource", "Notification"];
- var scope = {};
- names.forEach(function (n) { if (n in window) scope[n] = window[n]; });
- return scope;
- })();
-
- function syntaxLint(view) {
- var state = view.state, out = [], lastLine = -1;
- var tree = CM.ensureSyntaxTree(state, state.doc.length, 300) || CM.syntaxTree(state);
- tree.iterate({
- enter: function (n) {
- if (!n.type.isError) return;
- var from = Math.min(n.from, state.doc.length);
- var line = state.doc.lineAt(from).number;
- if (line === lastLine || out.length >= 50) return;
- lastLine = line;
- var near = n.to > n.from ? state.sliceDoc(n.from, Math.min(n.to, n.from + 24)).split("\n")[0].trim() : "";
- var to = Math.max(n.to, Math.min(from + 1, state.doc.length));
- if (to === from && from > 0) from--;
- out.push({ from: from, to: to, severity: "error", source: "syntax", message: near ? t("lint.syntax_near", { text: near }) : t("lint.syntax") });
- }
- });
- return out;
- }
-
- function insertAction(label, pos, text) {
- return {
- name: label,
- apply: function (view) {
- view.dispatch({ changes: { from: pos, insert: text }, scrollIntoView: true });
- }
- };
- }
-
- function lineIndent(state, pos) {
- return /^\s*/.exec(state.doc.lineAt(pos).text)[0];
- }
-
- function htmlLint(view, strictClose) {
- var state = view.state, out = [];
- var tree = CM.ensureSyntaxTree(state, state.doc.length, 300) || CM.syntaxTree(state);
- var ids = {}, htmlEl = null, headEl = null, hasDoctype = false;
- var unit = CM.getIndentUnit ? CM.indentString(state, CM.getIndentUnit(state)) : " ";
- tree.iterate({
- enter: function (n) {
- if (n.name === "DoctypeDecl") hasDoctype = true;
- if (n.name === "MismatchedCloseTag") {
- out.push({ from: n.from, to: n.to, severity: "error", source: "html", message: t("lint.mismatched", { tag: state.sliceDoc(n.from, n.to) }) });
- return;
- }
- if (n.name !== "Element") return;
- var info = elementInfo(state, n.node);
- if (!info || !info.name) return;
- var tagFrom = info.open.from, tagTo = info.open.to;
- var seenAttrs = {};
- info.open.getChildren("Attribute").forEach(function (a) {
- var an = a.getChild("AttributeName");
- if (!an) return;
- var attr = state.sliceDoc(an.from, an.to).toLowerCase();
- if (seenAttrs[attr]) out.push({ from: a.from, to: a.to, severity: "warning", source: "html", message: t("lint.duplicate_attr", { name: attr }) });
- seenAttrs[attr] = true;
- });
- if (info.name === "html") htmlEl = info;
- if (info.name === "head") headEl = info;
- if (info.name === "img" && !("alt" in info.attrs)) {
- out.push({
- from: tagFrom, to: tagTo, severity: "warning", source: "html", message: t("lint.img_alt"),
- actions: [insertAction(t("lint.fix_alt"), info.nameTo, ' alt=""')]
- });
- }
- if (info.name === "a" && info.attrs.target === "_blank" && !/noopener|noreferrer/.test(info.attrs.rel || "")) {
- out.push({
- from: tagFrom, to: tagTo, severity: "info", source: "html", message: t("lint.blank_rel"),
- actions: [insertAction(t("lint.fix_rel"), info.nameTo, ' rel="noopener"')]
- });
- }
- if (DEPRECATED.indexOf(info.name) >= 0) {
- out.push({ from: tagFrom, to: tagTo, severity: "warning", source: "html", message: t("lint.deprecated", { tag: info.name }) });
- }
- if (info.attrs.id) {
- if (ids[info.attrs.id]) {
- out.push({ from: tagFrom, to: tagTo, severity: "warning", source: "html", message: t("lint.duplicate_id", { id: info.attrs.id }) });
- }
- ids[info.attrs.id] = true;
- }
- if (strictClose && !info.close && info.open.name === "OpenTag" && VOID.indexOf(info.name) < 0 && OPTIONAL_CLOSE.indexOf(info.name) < 0) {
- out.push({ from: tagFrom, to: tagTo, severity: "warning", source: "html", message: t("lint.unclosed", { tag: info.name }) });
- }
- }
- });
- if (htmlEl) {
- if (!hasDoctype && strictClose) {
- out.push({
- from: htmlEl.open.from, to: htmlEl.open.to, severity: "info", source: "html", message: t("lint.doctype"),
- actions: [insertAction(t("lint.fix_add"), htmlEl.open.from, "<!DOCTYPE html>\n")]
- });
- }
- if (!("lang" in htmlEl.attrs)) {
- var code = (A.i18n.current() || {}).code || "en";
- out.push({
- from: htmlEl.open.from, to: htmlEl.open.to, severity: "warning", source: "html", message: t("lint.lang"),
- actions: [insertAction(t("lint.fix_add"), htmlEl.nameTo, ' lang="' + code + '"')]
- });
- }
- }
- if (headEl) {
- var head = state.sliceDoc(headEl.open.to, headEl.close ? headEl.close.from : headEl.node.to);
- var at = headEl.open.to, pad = "\n" + lineIndent(state, headEl.open.from) + unit;
- var checks = [
- [/<meta[^>]+charset/i, "lint.charset", '<meta charset="UTF-8">'],
- [/<meta[^>]+name=["']?viewport/i, "lint.viewport", '<meta name="viewport" content="width=device-width, initial-scale=1.0">'],
- [/<title[\s>]/i, "lint.title", "<title></title>"]
- ];
- checks.forEach(function (c) {
- if (c[0].test(head)) return;
- out.push({
- from: headEl.open.from, to: headEl.open.to, severity: "warning", source: "html", message: t(c[1]),
- actions: [insertAction(t("lint.fix_add"), at, pad + c[2])]
- });
- });
- }
- return out;
- }
-
- var BRACKET_KINDS = ["js", "jsx", "ts", "tsx", "css"];
-
- function withBrackets(view, list) {
- var brackets = A.codetools.bracketDiagnostics(view.state);
- if (!brackets.length) return list;
- var doc = view.state.doc, end = doc.length;
- var lines = {};
- brackets.forEach(function (b) { lines[doc.lineAt(b.from).number] = true; });
- return list.filter(function (d) { return d.to < end && !lines[doc.lineAt(d.from).number]; }).concat(brackets);
- }
-
- function lintSource(kind) {
- return function (view) {
- if (!A.settings.get("lintHints")) return [];
- if (kind === "jsonc") return A.codetools.jsoncDiagnostics(view.state);
- var list = syntaxLint(view);
- if (BRACKET_KINDS.indexOf(kind) >= 0) list = withBrackets(view, list);
- if (kind === "html" || kind === "php") list = list.concat(htmlLint(view, kind === "html"));
- return list;
- };
- }
-
- var EMMET_SYNTAX = { html: "html", php: "html", svg: "xml", css: "css", scss: "scss", less: "less", jsx: "jsx", tsx: "jsx" };
-
- function emmet(syntax) {
- if (!syntax || !A.settings.get("emmet")) return [];
- return [
- CM.abbreviationTracker({
- syntax: syntax,
- mark: true,
- previewEnabled: true,
- markTagPairs: syntax === "html" || syntax === "xml",
- autoRenameTags: syntax === "html" || syntax === "xml",
- previewOpenTag: false
- }),
- CM.emmetConfig.of({ syntax: syntax }),
- CM.wrapWithAbbreviation("Mod-Alt-w")
- ];
- }
-
- function partnerName(state, nameNode) {
- var tag = nameNode.parent;
- if (!tag || (tag.name !== "OpenTag" && tag.name !== "CloseTag")) return null;
- var el = tag.parent;
- if (!el || el.name !== "Element") return null;
- var other = tag.name === "OpenTag" ? el.getChild("CloseTag") : el.getChild("OpenTag");
- var otherName = other && other.getChild("TagName");
- if (!otherName) return null;
- if (state.sliceDoc(otherName.from, otherName.to).toLowerCase() !== state.sliceDoc(nameNode.from, nameNode.to).toLowerCase()) return null;
- return otherName;
- }
-
- var setTagLink = CM.StateEffect.define();
- var tagLink = CM.StateField.define({
- create: function () { return null; },
- update: function (link, tr) {
- for (var e of tr.effects) if (e.is(setTagLink)) return e.value;
- if (!link) return null;
- if (tr.docChanged) {
- link = {
- a: { from: tr.changes.mapPos(link.a.from, -1), to: tr.changes.mapPos(link.a.to, 1) },
- b: { from: tr.changes.mapPos(link.b.from, -1), to: tr.changes.mapPos(link.b.to, 1) }
- };
- }
- var head = tr.state.selection.main.head;
- return head < link.a.from || head > link.a.to ? null : link;
- }
- });
-
- function tagNameAt(state, from, to) {
- var tree = CM.syntaxTree(state);
- var probes = [[from, 1], [from, -1], [to, -1]];
- for (var i = 0; i < probes.length; i++) {
- var n = tree.resolveInner(probes[i][0], probes[i][1]);
- if (n.name === "TagName" && from >= n.from && to <= n.to) return n;
- }
- return null;
- }
-
- function autoRenameTags() {
- return [tagLink, CM.EditorState.transactionFilter.of(function (tr) {
- if (!tr.docChanged || !(tr.isUserEvent("input") || tr.isUserEvent("delete")) || !A.settings.get("emmet")) return tr;
- var ranges = [];
- tr.changes.iterChanges(function (fromA, toA, fromB, toB, text) { ranges.push({ fromA: fromA, toA: toA, text: text.toString() }); });
- if (ranges.length !== 1) return tr;
- var ch = ranges[0], st = tr.startState;
- var a, b, link = st.field(tagLink, false);
- if (link && ch.fromA >= link.a.from && ch.toA <= link.a.to) {
- a = link.a;
- b = link.b;
- if (st.sliceDoc(a.from, a.to) !== st.sliceDoc(b.from, b.to)) return tr;
- } else {
- var node = tagNameAt(st, ch.fromA, ch.toA);
- var partner = node && partnerName(st, node);
- if (!partner) return tr;
- a = { from: node.from, to: node.to };
- b = { from: partner.from, to: partner.to };
- }
- var oldName = st.sliceDoc(a.from, a.to);
- var newName = oldName.slice(0, ch.fromA - a.from) + ch.text + oldName.slice(ch.toA - a.from);
- if (!/^[\w:.-]*$/.test(newName)) return tr;
- var na = { from: tr.changes.mapPos(a.from, -1), to: tr.changes.mapPos(a.to, 1) };
- var nb = { from: tr.changes.mapPos(b.from, -1), to: tr.changes.mapPos(b.to, 1) };
- var delta = newName.length - (nb.to - nb.from);
- var finalB = { from: nb.from, to: nb.from + newName.length };
- var finalA = nb.from < na.from ? { from: na.from + delta, to: na.to + delta } : na;
- return [tr, {
- changes: { from: nb.from, to: nb.to, insert: newName },
- effects: setTagLink.of({ a: finalA, b: finalB }),
- sequential: true
- }];
- })];
- }
-
- function smartSuggest() {
- return CM.EditorView.updateListener.of(function (u) {
- if (!u.docChanged || !A.settings.get("smartSuggest")) return;
- if (!u.transactions.some(function (tr) { return tr.isUserEvent("input"); })) return;
- var inserted = false;
- u.changes.iterChanges(function (fa, ta, fb, tb, text) { if (/\n/.test(text.toString())) inserted = true; });
- if (!inserted) return;
- var state = u.state, pos = state.selection.main.head;
- if (!state.selection.main.empty || state.doc.lineAt(pos).text.trim()) return;
- var data = state.languageDataAt("athera", pos)[0];
- if (!data) return;
- var open = false;
- if (data === "html") {
- var c = htmlContext(state, pos);
- open = c.element ? (c.ctx !== "body" || c.element.name === "body") && elementIsEmpty(state, c.element) : c.ctx === "top";
- } else if (data === "css") {
- var block = CM.syntaxTree(state).resolveInner(pos, -1);
- while (block && block.name !== "Block") block = block.parent;
- open = !!block && !state.sliceDoc(block.from + 1, block.to - 1).trim();
- }
- if (open) setTimeout(function () { CM.startCompletion(u.view); }, 0);
- });
- }
-
- var snippetLabels = {};
- DATA.html.concat(DATA.phpInline, DATA.css).forEach(function (s) { snippetLabels[s.label] = true; });
-
- function emmetSource(ctx) {
- var word = ctx.matchBefore(/[\w:.@-]+/);
- if (word && snippetLabels[word.text]) return null;
- return CM.emmetCompletionSource(ctx);
- }
-
- var languageData = [
- CM.htmlLanguage.data.of({ autocomplete: htmlSource, athera: "html" }),
- CM.htmlLanguage.data.of({ autocomplete: emmetSource }),
- CM.cssLanguage.data.of({ autocomplete: cssSource, athera: "css" }),
- CM.cssLanguage.data.of({ autocomplete: emmetSource }),
- CM.javascriptLanguage.data.of({ autocomplete: CM.ifNotIn(["String", "TemplateString", "LineComment", "BlockComment", "Comment"], jsSource) }),
- CM.javascriptLanguage.data.of({ autocomplete: CM.scopeCompletionSource(JS_SCOPE) }),
- CM.phpLanguage.data.of({ autocomplete: CM.ifNotIn(["String", "Comment", "LineComment", "BlockComment", "Heredoc", "Nowdoc"], phpSource) })
- ];
-
- var prettierLoad = null;
- function loadPrettier() {
- if (window.AtheraPrettier) return Promise.resolve(window.AtheraPrettier);
- if (!prettierLoad) {
- prettierLoad = new Promise(function (resolve, reject) {
- var s = document.createElement("script");
- s.src = A.asset("assets/vendor/prettier/prettier.bundle.js");
- s.onload = function () { resolve(window.AtheraPrettier); };
- s.onerror = function () { prettierLoad = null; reject(new Error(t("format.load_failed"))); };
- document.head.appendChild(s);
- });
- }
- return prettierLoad;
- }
-
- var PARSERS = {
- html: "html", htm: "html", xhtml: "html", vue: "vue", css: "css", scss: "scss", less: "less",
- js: "babel", mjs: "babel", cjs: "babel", jsx: "babel", ts: "babel-ts", mts: "babel-ts", tsx: "babel-ts",
- json: "json", jsonc: "json", webmanifest: "json", md: "markdown", markdown: "markdown", php: "php", phtml: "php"
- };
-
- A.intellisense = {
- htmlContext: htmlContext,
-
- base: function () {
- return [languageData, smartSuggest()];
- },
-
- forLanguage: function (id, ext) {
- var out = [emmet(EMMET_SYNTAX[ext] || EMMET_SYNTAX[id])];
- if (id === "html" || id === "php" || id === "svg") out.push(autoRenameTags());
- if (["html", "php", "css", "js", "jsx", "ts", "tsx", "svg", "jsonc"].indexOf(id) >= 0) {
- out.push(CM.linter(lintSource(id === "svg" ? "xml" : id), { delay: 600 }));
- }
- return out;
- },
-
- canFormat: function (name) {
- return !!PARSERS[util.ext(name)];
- },
-
- format: async function (view, name) {
- var parser = PARSERS[util.ext(name)];
- if (!parser) throw new Error(t("format.unsupported"));
- var P = await loadPrettier();
- var state = view.state, code = state.doc.toString();
- var cursor = state.selection.main.head;
- var res;
- try {
- res = await P.format(code, {
- parser: parser,
- plugins: P.plugins,
- cursorOffset: cursor,
- tabWidth: A.settings.get("tabSize"),
- useTabs: !A.settings.get("insertSpaces"),
- printWidth: 100,
- phpVersion: "8.3"
- });
- } catch (e) {
- var line = e.loc && e.loc.start ? e.loc.start.line : null;
- var msg = String(e.message || e).split("\n")[0].replace(/\s*\(\d+:\d+\)\s*$/, "");
- throw new Error(line ? t("format.error_line", { line: line, error: msg }) : t("format.error", { error: msg }));
- }
- if (view.state.doc.toString() !== code) return false;
- var out = res.formatted;
- if (out === code) return false;
- var start = 0, endA = code.length, endB = out.length;
- while (start < endA && start < endB && code.charCodeAt(start) === out.charCodeAt(start)) start++;
- while (endA > start && endB > start && code.charCodeAt(endA - 1) === out.charCodeAt(endB - 1)) { endA--; endB--; }
- view.dispatch({
- changes: { from: start, to: endA, insert: out.slice(start, endB) },
- selection: { anchor: Math.min(Math.max(0, res.cursorOffset), out.length) },
- userEvent: "format",
- scrollIntoView: true
- });
- return true;
- }
- };
- })();
-