WebOrbiton
v1.4.2

AtheraStudio Code

549 lines · 23.9 KB
  1. (function () {
  2. "use strict";
  3. ​
  4. var A = window.Athera;
  5. var util = A.util;
  6. var t = A.t;
  7. var DATA = A.snippetData;
  8. var FRAMEWORK = /^(orbitarium|tw:|bs:|shadcn:|water:|pico:|simple:|mvp:|sakura:)/;
  9. ​
  10. function enabled(list) {
  11. return A.settings.get("frameworkSnippets") ? list : list.filter(function (s) { return !FRAMEWORK.test(s.label); });
  12. }
  13. ​
  14. var TAG_PARTS = /^(OpenTag|SelfClosingTag|CloseTag|Attribute|AttributeName|AttributeValue|UnquotedAttributeValue|TagName|StartTag|StartCloseTag|EndTag|SelfCloseEndTag|MismatchedCloseTag|IncompleteCloseTag|Comment|DoctypeDecl|ProcessingInst)$/;
  15. var CTX_BY_TAG = {
  16. html: "html", head: "head", ul: "list", ol: "list", menu: "list", table: "table", thead: "table", tbody: "table",
  17. tfoot: "table", form: "form", select: "select", datalist: "select", script: "code", style: "code", textarea: "code", title: "code"
  18. };
  19. var VOID = ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr", "param", "keygen", "command"];
  20. var OPTIONAL_CLOSE = ["p", "li", "dt", "dd", "option", "optgroup", "tr", "td", "th", "thead", "tbody", "tfoot", "colgroup", "rt", "rp", "html", "head", "body"];
  21. var DEPRECATED = ["center", "font", "marquee", "big", "strike", "tt", "frame", "frameset", "blink", "acronym", "applet", "basefont", "dir"];
  22. ​
  23. function desc(item) {
  24. var lang = A.i18n.current();
  25. return item.d[lang && lang.code === "pl" ? 0 : 1];
  26. }
  27. ​
  28. function preview(template) {
  29. return function () {
  30. var pre = document.createElement("pre");
  31. pre.className = "ath-snippet-preview";
  32. pre.textContent = template
  33. .replace(/\$\{\d+:([^}]*)\}/g, "$1")
  34. .replace(/\$\{\d*\}/g, "")
  35. .replace(/\t/g, " ");
  36. return pre;
  37. };
  38. }
  39. ​
  40. function ranked(list, base) {
  41. return list.map(function (item, i) { return snippet(item, base - i / list.length); });
  42. }
  43. ​
  44. function snippet(item, boost) {
  45. return CM.snippetCompletion(item.body, {
  46. label: item.label,
  47. detail: desc(item),
  48. info: preview(item.body),
  49. type: "snippet",
  50. boost: boost || 0
  51. });
  52. }
  53. ​
  54. function isPhpDoc(state) {
  55. var lang = state.facet(CM.language);
  56. return !!lang && lang.name === "php";
  57. }
  58. ​
  59. function elementInfo(state, el) {
  60. var open = el.getChild("OpenTag") || el.getChild("SelfClosingTag");
  61. if (!open) return null;
  62. var nameNode = open.getChild("TagName");
  63. var attrs = {};
  64. open.getChildren("Attribute").forEach(function (a) {
  65. var an = a.getChild("AttributeName");
  66. var av = a.getChild("AttributeValue") || a.getChild("UnquotedAttributeValue");
  67. if (an) attrs[state.sliceDoc(an.from, an.to).toLowerCase()] = av ? state.sliceDoc(av.from, av.to).replace(/^["']|["']$/g, "") : "";
  68. });
  69. return {
  70. node: el,
  71. name: nameNode ? state.sliceDoc(nameNode.from, nameNode.to).toLowerCase() : "",
  72. attrs: attrs,
  73. open: open,
  74. nameTo: nameNode ? nameNode.to : open.from + 1,
  75. close: el.getChild("CloseTag")
  76. };
  77. }
  78. ​
  79. function htmlContext(state, pos) {
  80. var node = CM.syntaxTree(state).resolveInner(pos, -1);
  81. for (var n = node; n; n = n.parent) {
  82. if (TAG_PARTS.test(n.name) && pos < n.to && pos > n.from) return { ctx: "tag" };
  83. if (n.name === "Element") {
  84. var info = elementInfo(state, n);
  85. if (!info || pos < info.open.to) continue;
  86. if (info.close && pos >= info.close.to) continue;
  87. if (info.open.name === "SelfClosingTag" || VOID.indexOf(info.name) >= 0) continue;
  88. return { ctx: CTX_BY_TAG[info.name] || "body", element: info };
  89. }
  90. if (n.name === "Document") break;
  91. }
  92. var empty = /^\s*(<!doctype[^>]*>)?\s*$/i.test(state.doc.toString());
  93. return { ctx: empty ? "top" : "body" };
  94. }
  95. ​
  96. function elementIsEmpty(state, info) {
  97. var from = info.open.to;
  98. var to = info.close ? info.close.from : info.node.to;
  99. return !state.sliceDoc(from, to).trim();
  100. }
  101. ​
  102. function cssContext(state, pos) {
  103. for (var n = CM.syntaxTree(state).resolveInner(pos, -1); n; n = n.parent) {
  104. if (n.name === "Block" && pos > n.from) return "block";
  105. }
  106. return "top";
  107. }
  108. ​
  109. function htmlSource(ctx) {
  110. var word = ctx.matchBefore(/[\w:.@-]*/);
  111. var before = ctx.state.sliceDoc(Math.max(0, word.from - 2), word.from);
  112. if (/<\/?$/.test(before)) return null;
  113. if (!ctx.explicit && word.from === word.to) return null;
  114. var c = htmlContext(ctx.state, ctx.pos);
  115. if (c.ctx === "tag" || c.ctx === "code") return null;
  116. var options = ranked(enabled(DATA.html).filter(function (s) { return s.ctx.indexOf(c.ctx) >= 0; }), 20);
  117. if (isPhpDoc(ctx.state)) options = options.concat(ranked(DATA.phpInline, 15));
  118. if (c.ctx !== "top" && c.ctx !== "html" && c.ctx !== "head") {
  119. enabled(DATA.html).forEach(function (s) {
  120. if (s.ctx.indexOf(c.ctx) < 0 && s.ctx.indexOf("body") >= 0) options.push(snippet(s, -10));
  121. });
  122. }
  123. return options.length ? { from: word.from, options: options, validFor: /^[\w:.@-]*$/ } : null;
  124. }
  125. ​
  126. function cssSource(ctx) {
  127. var word = ctx.matchBefore(/[\w:.@-]*/);
  128. if (!ctx.explicit && word.from === word.to) return null;
  129. var c = cssContext(ctx.state, ctx.pos);
  130. var options = ranked(enabled(DATA.css).filter(function (s) { return s.ctx.indexOf(c) >= 0; }), 10);
  131. return { from: word.from, options: options, validFor: /^[\w:.@-]*$/ };
  132. }
  133. ​
  134. function jsSource(ctx) {
  135. var word = ctx.matchBefore(/[\w:]*/);
  136. if (!ctx.explicit && word.from === word.to) return null;
  137. var before = ctx.state.sliceDoc(Math.max(0, word.from - 1), word.from);
  138. if (before === ".") return null;
  139. var file = A.tabs && A.tabs.active ? A.tabs.active.name : "";
  140. var kind = util.ext(file);
  141. var options = ranked(DATA.js, 5);
  142. if (kind === "jsx" || kind === "tsx") options = options.concat(ranked(enabled(DATA.shadcn), 8));
  143. else if (kind === "ts") options = options.concat(ranked(enabled(DATA.shadcn).filter(function (s) { return s.label === "shadcn:cn"; }), 8));
  144. return { from: word.from, options: options, validFor: /^[\w:]*$/ };
  145. }
  146. ​
  147. var phpFunctionOptions = null;
  148. function phpFunctions() {
  149. if (!phpFunctionOptions) {
  150. phpFunctionOptions = DATA.phpFunctions.map(function (entry) {
  151. var i = entry.indexOf("|");
  152. var name = entry.slice(0, i), sig = entry.slice(i + 1);
  153. var bare = /^(echo|print|die|exit)$/.test(name);
  154. return CM.snippetCompletion(bare ? name + " ${}" : name + "(${})", { label: name, detail: sig.replace(/^[^(]*/, ""), info: sig, type: "function" });
  155. });
  156. }
  157. return phpFunctionOptions;
  158. }
  159. ​
  160. function phpSource(ctx) {
  161. var word = ctx.matchBefore(/\$?\w+(?::\w*)?|\$?\w*/);
  162. if (!ctx.explicit && word.from === word.to) return null;
  163. var text = ctx.state.sliceDoc(word.from, word.to);
  164. if (text.charAt(0) === "$") {
  165. var seen = {}, options = [];
  166. DATA.phpVariables.forEach(function (v) { seen[v] = 1; options.push({ label: v, type: "variable", boost: 5 }); });
  167. var re = /\$[A-Za-z_]\w*/g, m, doc = ctx.state.doc.toString();
  168. while ((m = re.exec(doc))) {
  169. if (seen[m[0]] || (m.index === word.from)) continue;
  170. seen[m[0]] = 1;
  171. options.push({ label: m[0], type: "variable" });
  172. }
  173. return { from: word.from, options: options, validFor: /^\$\w*$/ };
  174. }
  175. var list = phpFunctions()
  176. .concat(DATA.phpKeywords.map(function (k) { return { label: k, type: /^[A-Z_]+$/.test(k) ? "constant" : "keyword" }; }))
  177. .concat(ranked(DATA.php, 10));
  178. return { from: word.from, options: list, validFor: /^\w+(?::\w*)?$|^\w*$/ };
  179. }
  180. ​
  181. var JS_SCOPE = (function () {
  182. var names = ["window", "document", "console", "localStorage", "sessionStorage", "navigator", "location", "history", "JSON", "Math",
  183. "Date", "Array", "Object", "String", "Number", "Boolean", "Promise", "fetch", "setTimeout", "clearTimeout", "setInterval",
  184. "clearInterval", "requestAnimationFrame", "cancelAnimationFrame", "alert", "confirm", "prompt", "structuredClone", "URL",
  185. "URLSearchParams", "FormData", "Headers", "Request", "Response", "IntersectionObserver", "MutationObserver", "ResizeObserver",
  186. "Intl", "Map", "Set", "WeakMap", "WeakSet", "Symbol", "RegExp", "Error", "TypeError", "parseInt", "parseFloat", "isNaN",
  187. "isFinite", "encodeURIComponent", "decodeURIComponent", "CustomEvent", "Event", "Blob", "File", "FileReader", "crypto",
  188. "performance", "Image", "Audio", "AbortController", "BigInt", "Reflect", "Proxy", "screen", "matchMedia", "getComputedStyle",
  189. "queueMicrotask", "atob", "btoa", "TextEncoder", "TextDecoder", "Worker", "WebSocket", "EventSource", "Notification"];
  190. var scope = {};
  191. names.forEach(function (n) { if (n in window) scope[n] = window[n]; });
  192. return scope;
  193. })();
  194. ​
  195. function syntaxLint(view) {
  196. var state = view.state, out = [], lastLine = -1;
  197. var tree = CM.ensureSyntaxTree(state, state.doc.length, 300) || CM.syntaxTree(state);
  198. tree.iterate({
  199. enter: function (n) {
  200. if (!n.type.isError) return;
  201. var from = Math.min(n.from, state.doc.length);
  202. var line = state.doc.lineAt(from).number;
  203. if (line === lastLine || out.length >= 50) return;
  204. lastLine = line;
  205. var near = n.to > n.from ? state.sliceDoc(n.from, Math.min(n.to, n.from + 24)).split("\n")[0].trim() : "";
  206. var to = Math.max(n.to, Math.min(from + 1, state.doc.length));
  207. if (to === from && from > 0) from--;
  208. out.push({ from: from, to: to, severity: "error", source: "syntax", message: near ? t("lint.syntax_near", { text: near }) : t("lint.syntax") });
  209. }
  210. });
  211. return out;
  212. }
  213. ​
  214. function insertAction(label, pos, text) {
  215. return {
  216. name: label,
  217. apply: function (view) {
  218. view.dispatch({ changes: { from: pos, insert: text }, scrollIntoView: true });
  219. }
  220. };
  221. }
  222. ​
  223. function lineIndent(state, pos) {
  224. return /^\s*/.exec(state.doc.lineAt(pos).text)[0];
  225. }
  226. ​
  227. function htmlLint(view, strictClose) {
  228. var state = view.state, out = [];
  229. var tree = CM.ensureSyntaxTree(state, state.doc.length, 300) || CM.syntaxTree(state);
  230. var ids = {}, htmlEl = null, headEl = null, hasDoctype = false;
  231. var unit = CM.getIndentUnit ? CM.indentString(state, CM.getIndentUnit(state)) : " ";
  232. tree.iterate({
  233. enter: function (n) {
  234. if (n.name === "DoctypeDecl") hasDoctype = true;
  235. if (n.name === "MismatchedCloseTag") {
  236. out.push({ from: n.from, to: n.to, severity: "error", source: "html", message: t("lint.mismatched", { tag: state.sliceDoc(n.from, n.to) }) });
  237. return;
  238. }
  239. if (n.name !== "Element") return;
  240. var info = elementInfo(state, n.node);
  241. if (!info || !info.name) return;
  242. var tagFrom = info.open.from, tagTo = info.open.to;
  243. var seenAttrs = {};
  244. info.open.getChildren("Attribute").forEach(function (a) {
  245. var an = a.getChild("AttributeName");
  246. if (!an) return;
  247. var attr = state.sliceDoc(an.from, an.to).toLowerCase();
  248. if (seenAttrs[attr]) out.push({ from: a.from, to: a.to, severity: "warning", source: "html", message: t("lint.duplicate_attr", { name: attr }) });
  249. seenAttrs[attr] = true;
  250. });
  251. if (info.name === "html") htmlEl = info;
  252. if (info.name === "head") headEl = info;
  253. if (info.name === "img" && !("alt" in info.attrs)) {
  254. out.push({
  255. from: tagFrom, to: tagTo, severity: "warning", source: "html", message: t("lint.img_alt"),
  256. actions: [insertAction(t("lint.fix_alt"), info.nameTo, ' alt=""')]
  257. });
  258. }
  259. if (info.name === "a" && info.attrs.target === "_blank" && !/noopener|noreferrer/.test(info.attrs.rel || "")) {
  260. out.push({
  261. from: tagFrom, to: tagTo, severity: "info", source: "html", message: t("lint.blank_rel"),
  262. actions: [insertAction(t("lint.fix_rel"), info.nameTo, ' rel="noopener"')]
  263. });
  264. }
  265. if (DEPRECATED.indexOf(info.name) >= 0) {
  266. out.push({ from: tagFrom, to: tagTo, severity: "warning", source: "html", message: t("lint.deprecated", { tag: info.name }) });
  267. }
  268. if (info.attrs.id) {
  269. if (ids[info.attrs.id]) {
  270. out.push({ from: tagFrom, to: tagTo, severity: "warning", source: "html", message: t("lint.duplicate_id", { id: info.attrs.id }) });
  271. }
  272. ids[info.attrs.id] = true;
  273. }
  274. if (strictClose && !info.close && info.open.name === "OpenTag" && VOID.indexOf(info.name) < 0 && OPTIONAL_CLOSE.indexOf(info.name) < 0) {
  275. out.push({ from: tagFrom, to: tagTo, severity: "warning", source: "html", message: t("lint.unclosed", { tag: info.name }) });
  276. }
  277. }
  278. });
  279. if (htmlEl) {
  280. if (!hasDoctype && strictClose) {
  281. out.push({
  282. from: htmlEl.open.from, to: htmlEl.open.to, severity: "info", source: "html", message: t("lint.doctype"),
  283. actions: [insertAction(t("lint.fix_add"), htmlEl.open.from, "<!DOCTYPE html>\n")]
  284. });
  285. }
  286. if (!("lang" in htmlEl.attrs)) {
  287. var code = (A.i18n.current() || {}).code || "en";
  288. out.push({
  289. from: htmlEl.open.from, to: htmlEl.open.to, severity: "warning", source: "html", message: t("lint.lang"),
  290. actions: [insertAction(t("lint.fix_add"), htmlEl.nameTo, ' lang="' + code + '"')]
  291. });
  292. }
  293. }
  294. if (headEl) {
  295. var head = state.sliceDoc(headEl.open.to, headEl.close ? headEl.close.from : headEl.node.to);
  296. var at = headEl.open.to, pad = "\n" + lineIndent(state, headEl.open.from) + unit;
  297. var checks = [
  298. [/<meta[^>]+charset/i, "lint.charset", '<meta charset="UTF-8">'],
  299. [/<meta[^>]+name=["']?viewport/i, "lint.viewport", '<meta name="viewport" content="width=device-width, initial-scale=1.0">'],
  300. [/<title[\s>]/i, "lint.title", "<title></title>"]
  301. ];
  302. checks.forEach(function (c) {
  303. if (c[0].test(head)) return;
  304. out.push({
  305. from: headEl.open.from, to: headEl.open.to, severity: "warning", source: "html", message: t(c[1]),
  306. actions: [insertAction(t("lint.fix_add"), at, pad + c[2])]
  307. });
  308. });
  309. }
  310. return out;
  311. }
  312. ​
  313. var BRACKET_KINDS = ["js", "jsx", "ts", "tsx", "css"];
  314. ​
  315. function withBrackets(view, list) {
  316. var brackets = A.codetools.bracketDiagnostics(view.state);
  317. if (!brackets.length) return list;
  318. var doc = view.state.doc, end = doc.length;
  319. var lines = {};
  320. brackets.forEach(function (b) { lines[doc.lineAt(b.from).number] = true; });
  321. return list.filter(function (d) { return d.to < end && !lines[doc.lineAt(d.from).number]; }).concat(brackets);
  322. }
  323. ​
  324. function lintSource(kind) {
  325. return function (view) {
  326. if (!A.settings.get("lintHints")) return [];
  327. if (kind === "jsonc") return A.codetools.jsoncDiagnostics(view.state);
  328. var list = syntaxLint(view);
  329. if (BRACKET_KINDS.indexOf(kind) >= 0) list = withBrackets(view, list);
  330. if (kind === "html" || kind === "php") list = list.concat(htmlLint(view, kind === "html"));
  331. return list;
  332. };
  333. }
  334. ​
  335. var EMMET_SYNTAX = { html: "html", php: "html", svg: "xml", css: "css", scss: "scss", less: "less", jsx: "jsx", tsx: "jsx" };
  336. ​
  337. function emmet(syntax) {
  338. if (!syntax || !A.settings.get("emmet")) return [];
  339. return [
  340. CM.abbreviationTracker({
  341. syntax: syntax,
  342. mark: true,
  343. previewEnabled: true,
  344. markTagPairs: syntax === "html" || syntax === "xml",
  345. autoRenameTags: syntax === "html" || syntax === "xml",
  346. previewOpenTag: false
  347. }),
  348. CM.emmetConfig.of({ syntax: syntax }),
  349. CM.wrapWithAbbreviation("Mod-Alt-w")
  350. ];
  351. }
  352. ​
  353. function partnerName(state, nameNode) {
  354. var tag = nameNode.parent;
  355. if (!tag || (tag.name !== "OpenTag" && tag.name !== "CloseTag")) return null;
  356. var el = tag.parent;
  357. if (!el || el.name !== "Element") return null;
  358. var other = tag.name === "OpenTag" ? el.getChild("CloseTag") : el.getChild("OpenTag");
  359. var otherName = other && other.getChild("TagName");
  360. if (!otherName) return null;
  361. if (state.sliceDoc(otherName.from, otherName.to).toLowerCase() !== state.sliceDoc(nameNode.from, nameNode.to).toLowerCase()) return null;
  362. return otherName;
  363. }
  364. ​
  365. var setTagLink = CM.StateEffect.define();
  366. var tagLink = CM.StateField.define({
  367. create: function () { return null; },
  368. update: function (link, tr) {
  369. for (var e of tr.effects) if (e.is(setTagLink)) return e.value;
  370. if (!link) return null;
  371. if (tr.docChanged) {
  372. link = {
  373. a: { from: tr.changes.mapPos(link.a.from, -1), to: tr.changes.mapPos(link.a.to, 1) },
  374. b: { from: tr.changes.mapPos(link.b.from, -1), to: tr.changes.mapPos(link.b.to, 1) }
  375. };
  376. }
  377. var head = tr.state.selection.main.head;
  378. return head < link.a.from || head > link.a.to ? null : link;
  379. }
  380. });
  381. ​
  382. function tagNameAt(state, from, to) {
  383. var tree = CM.syntaxTree(state);
  384. var probes = [[from, 1], [from, -1], [to, -1]];
  385. for (var i = 0; i < probes.length; i++) {
  386. var n = tree.resolveInner(probes[i][0], probes[i][1]);
  387. if (n.name === "TagName" && from >= n.from && to <= n.to) return n;
  388. }
  389. return null;
  390. }
  391. ​
  392. function autoRenameTags() {
  393. return [tagLink, CM.EditorState.transactionFilter.of(function (tr) {
  394. if (!tr.docChanged || !(tr.isUserEvent("input") || tr.isUserEvent("delete")) || !A.settings.get("emmet")) return tr;
  395. var ranges = [];
  396. tr.changes.iterChanges(function (fromA, toA, fromB, toB, text) { ranges.push({ fromA: fromA, toA: toA, text: text.toString() }); });
  397. if (ranges.length !== 1) return tr;
  398. var ch = ranges[0], st = tr.startState;
  399. var a, b, link = st.field(tagLink, false);
  400. if (link && ch.fromA >= link.a.from && ch.toA <= link.a.to) {
  401. a = link.a;
  402. b = link.b;
  403. if (st.sliceDoc(a.from, a.to) !== st.sliceDoc(b.from, b.to)) return tr;
  404. } else {
  405. var node = tagNameAt(st, ch.fromA, ch.toA);
  406. var partner = node && partnerName(st, node);
  407. if (!partner) return tr;
  408. a = { from: node.from, to: node.to };
  409. b = { from: partner.from, to: partner.to };
  410. }
  411. var oldName = st.sliceDoc(a.from, a.to);
  412. var newName = oldName.slice(0, ch.fromA - a.from) + ch.text + oldName.slice(ch.toA - a.from);
  413. if (!/^[\w:.-]*$/.test(newName)) return tr;
  414. var na = { from: tr.changes.mapPos(a.from, -1), to: tr.changes.mapPos(a.to, 1) };
  415. var nb = { from: tr.changes.mapPos(b.from, -1), to: tr.changes.mapPos(b.to, 1) };
  416. var delta = newName.length - (nb.to - nb.from);
  417. var finalB = { from: nb.from, to: nb.from + newName.length };
  418. var finalA = nb.from < na.from ? { from: na.from + delta, to: na.to + delta } : na;
  419. return [tr, {
  420. changes: { from: nb.from, to: nb.to, insert: newName },
  421. effects: setTagLink.of({ a: finalA, b: finalB }),
  422. sequential: true
  423. }];
  424. })];
  425. }
  426. ​
  427. function smartSuggest() {
  428. return CM.EditorView.updateListener.of(function (u) {
  429. if (!u.docChanged || !A.settings.get("smartSuggest")) return;
  430. if (!u.transactions.some(function (tr) { return tr.isUserEvent("input"); })) return;
  431. var inserted = false;
  432. u.changes.iterChanges(function (fa, ta, fb, tb, text) { if (/\n/.test(text.toString())) inserted = true; });
  433. if (!inserted) return;
  434. var state = u.state, pos = state.selection.main.head;
  435. if (!state.selection.main.empty || state.doc.lineAt(pos).text.trim()) return;
  436. var data = state.languageDataAt("athera", pos)[0];
  437. if (!data) return;
  438. var open = false;
  439. if (data === "html") {
  440. var c = htmlContext(state, pos);
  441. open = c.element ? (c.ctx !== "body" || c.element.name === "body") && elementIsEmpty(state, c.element) : c.ctx === "top";
  442. } else if (data === "css") {
  443. var block = CM.syntaxTree(state).resolveInner(pos, -1);
  444. while (block && block.name !== "Block") block = block.parent;
  445. open = !!block && !state.sliceDoc(block.from + 1, block.to - 1).trim();
  446. }
  447. if (open) setTimeout(function () { CM.startCompletion(u.view); }, 0);
  448. });
  449. }
  450. ​
  451. var snippetLabels = {};
  452. DATA.html.concat(DATA.phpInline, DATA.css).forEach(function (s) { snippetLabels[s.label] = true; });
  453. ​
  454. function emmetSource(ctx) {
  455. var word = ctx.matchBefore(/[\w:.@-]+/);
  456. if (word && snippetLabels[word.text]) return null;
  457. return CM.emmetCompletionSource(ctx);
  458. }
  459. ​
  460. var languageData = [
  461. CM.htmlLanguage.data.of({ autocomplete: htmlSource, athera: "html" }),
  462. CM.htmlLanguage.data.of({ autocomplete: emmetSource }),
  463. CM.cssLanguage.data.of({ autocomplete: cssSource, athera: "css" }),
  464. CM.cssLanguage.data.of({ autocomplete: emmetSource }),
  465. CM.javascriptLanguage.data.of({ autocomplete: CM.ifNotIn(["String", "TemplateString", "LineComment", "BlockComment", "Comment"], jsSource) }),
  466. CM.javascriptLanguage.data.of({ autocomplete: CM.scopeCompletionSource(JS_SCOPE) }),
  467. CM.phpLanguage.data.of({ autocomplete: CM.ifNotIn(["String", "Comment", "LineComment", "BlockComment", "Heredoc", "Nowdoc"], phpSource) })
  468. ];
  469. ​
  470. var prettierLoad = null;
  471. function loadPrettier() {
  472. if (window.AtheraPrettier) return Promise.resolve(window.AtheraPrettier);
  473. if (!prettierLoad) {
  474. prettierLoad = new Promise(function (resolve, reject) {
  475. var s = document.createElement("script");
  476. s.src = A.asset("assets/vendor/prettier/prettier.bundle.js");
  477. s.onload = function () { resolve(window.AtheraPrettier); };
  478. s.onerror = function () { prettierLoad = null; reject(new Error(t("format.load_failed"))); };
  479. document.head.appendChild(s);
  480. });
  481. }
  482. return prettierLoad;
  483. }
  484. ​
  485. var PARSERS = {
  486. html: "html", htm: "html", xhtml: "html", vue: "vue", css: "css", scss: "scss", less: "less",
  487. js: "babel", mjs: "babel", cjs: "babel", jsx: "babel", ts: "babel-ts", mts: "babel-ts", tsx: "babel-ts",
  488. json: "json", jsonc: "json", webmanifest: "json", md: "markdown", markdown: "markdown", php: "php", phtml: "php"
  489. };
  490. ​
  491. A.intellisense = {
  492. htmlContext: htmlContext,
  493. ​
  494. base: function () {
  495. return [languageData, smartSuggest()];
  496. },
  497. ​
  498. forLanguage: function (id, ext) {
  499. var out = [emmet(EMMET_SYNTAX[ext] || EMMET_SYNTAX[id])];
  500. if (id === "html" || id === "php" || id === "svg") out.push(autoRenameTags());
  501. if (["html", "php", "css", "js", "jsx", "ts", "tsx", "svg", "jsonc"].indexOf(id) >= 0) {
  502. out.push(CM.linter(lintSource(id === "svg" ? "xml" : id), { delay: 600 }));
  503. }
  504. return out;
  505. },
  506. ​
  507. canFormat: function (name) {
  508. return !!PARSERS[util.ext(name)];
  509. },
  510. ​
  511. format: async function (view, name) {
  512. var parser = PARSERS[util.ext(name)];
  513. if (!parser) throw new Error(t("format.unsupported"));
  514. var P = await loadPrettier();
  515. var state = view.state, code = state.doc.toString();
  516. var cursor = state.selection.main.head;
  517. var res;
  518. try {
  519. res = await P.format(code, {
  520. parser: parser,
  521. plugins: P.plugins,
  522. cursorOffset: cursor,
  523. tabWidth: A.settings.get("tabSize"),
  524. useTabs: !A.settings.get("insertSpaces"),
  525. printWidth: 100,
  526. phpVersion: "8.3"
  527. });
  528. } catch (e) {
  529. var line = e.loc && e.loc.start ? e.loc.start.line : null;
  530. var msg = String(e.message || e).split("\n")[0].replace(/\s*\(\d+:\d+\)\s*$/, "");
  531. throw new Error(line ? t("format.error_line", { line: line, error: msg }) : t("format.error", { error: msg }));
  532. }
  533. if (view.state.doc.toString() !== code) return false;
  534. var out = res.formatted;
  535. if (out === code) return false;
  536. var start = 0, endA = code.length, endB = out.length;
  537. while (start < endA && start < endB && code.charCodeAt(start) === out.charCodeAt(start)) start++;
  538. while (endA > start && endB > start && code.charCodeAt(endA - 1) === out.charCodeAt(endB - 1)) { endA--; endB--; }
  539. view.dispatch({
  540. changes: { from: start, to: endA, insert: out.slice(start, endB) },
  541. selection: { anchor: Math.min(Math.max(0, res.cursorOffset), out.length) },
  542. userEvent: "format",
  543. scrollIntoView: true
  544. });
  545. return true;
  546. }
  547. };
  548. })();
  549. ​