WebOrbiton
v1.5.0

AtheraStudio Code

662 lines · 30.7 KB
  1. (function () {
  2. "use strict";
  3. ​
  4. var A = window.Athera;
  5. var util = A.util;
  6. var t = CM.tags;
  7. ​
  8. var LANGS = {
  9. html: { label: "HTML", make: function () { return CM.html({ autoCloseTags: true }); } },
  10. php: { label: "PHP", make: function () { return CM.php(); } },
  11. css: { label: "CSS", make: function () { return CM.css(); } },
  12. js: { label: "JavaScript", make: function () { return CM.javascript(); } },
  13. jsx: { label: "JavaScript JSX", make: function () { return CM.javascript({ jsx: true }); } },
  14. ts: { label: "TypeScript", make: function () { return CM.javascript({ typescript: true }); } },
  15. tsx: { label: "TypeScript JSX", make: function () { return CM.javascript({ typescript: true, jsx: true }); } },
  16. json: { label: "JSON", make: function () { return [CM.json(), CM.linter(CM.jsonParseLinter())]; } },
  17. jsonc: { label: "JSON with Comments", make: function () { return CM.javascript(); } },
  18. md: { label: "Markdown", make: function () { return CM.markdown(); } },
  19. svg: { label: "SVG", make: function () { return CM.html(); } },
  20. text: { label: null, make: function () { return []; } }
  21. };
  22. var EXT_LANG = {
  23. html: "html", htm: "html", xhtml: "html", svg: "svg", xml: "html",
  24. php: "php", phtml: "php",
  25. css: "css", scss: "css", less: "css",
  26. js: "js", mjs: "js", cjs: "js", jsx: "jsx", ts: "ts", mts: "ts", tsx: "tsx",
  27. json: "json", jsonc: "jsonc", webmanifest: "json",
  28. md: "md", markdown: "md"
  29. };
  30. ​
  31. function langId(name) {
  32. return EXT_LANG[util.ext(name)] || "text";
  33. }
  34. ​
  35. var highlight = CM.HighlightStyle.define([
  36. { tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.definitionKeyword, t.moduleKeyword, t.modifier, t.self], color: "var(--ath-syn-keyword)" },
  37. { tag: [t.string, t.special(t.string), t.attributeValue, t.character], color: "var(--ath-syn-string)" },
  38. { tag: [t.number, t.bool, t.null, t.atom, t.unit], color: "var(--ath-syn-number)" },
  39. { tag: [t.comment, t.lineComment, t.blockComment, t.docComment], color: "var(--ath-syn-comment)", fontStyle: "italic" },
  40. { tag: [t.tagName, t.standard(t.tagName)], color: "var(--ath-syn-tag)" },
  41. { tag: t.attributeName, color: "var(--ath-syn-attr)" },
  42. { tag: [t.propertyName, t.definition(t.propertyName)], color: "var(--ath-syn-property)" },
  43. { tag: [t.function(t.variableName), t.function(t.propertyName), t.macroName], color: "var(--ath-syn-function)" },
  44. { tag: [t.typeName, t.className, t.namespace], color: "var(--ath-syn-type)" },
  45. { tag: [t.definition(t.variableName), t.special(t.variableName)], color: "var(--ath-syn-variable)" },
  46. { tag: [t.operator, t.punctuation, t.separator, t.bracket, t.angleBracket, t.derefOperator], color: "var(--ath-syn-punct)" },
  47. { tag: [t.meta, t.processingInstruction, t.documentMeta], color: "var(--ath-syn-meta)" },
  48. { tag: t.regexp, color: "var(--ath-syn-regexp)" },
  49. { tag: [t.color, t.constant(t.name), t.labelName], color: "var(--ath-syn-number)" },
  50. { tag: t.heading, fontWeight: "700", color: "var(--ath-syn-keyword)" },
  51. { tag: t.strong, fontWeight: "700" },
  52. { tag: t.emphasis, fontStyle: "italic" },
  53. { tag: t.link, color: "var(--ath-syn-function)", textDecoration: "underline" },
  54. { tag: t.url, color: "var(--ath-syn-string)" },
  55. { tag: t.invalid, color: "var(--orb-danger)" }
  56. ]);
  57. ​
  58. var theme = CM.EditorView.theme({
  59. "&": { height: "100%", backgroundColor: "var(--ath-editor-bg)", color: "var(--orb-text)", fontSize: "var(--ath-font-size)" },
  60. "&.cm-focused": { outline: "none" },
  61. ".cm-scroller": { fontFamily: "var(--ath-font-code)", lineHeight: "var(--ath-line-height, 1.65)" },
  62. ".cm-content": { caretColor: "var(--orb-primary)", padding: "10px 0 40vh" },
  63. ".cm-cursor, .cm-dropCursor": { borderLeftColor: "var(--orb-primary)", borderLeftWidth: "2px" },
  64. "&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":
  65. { backgroundColor: "var(--ath-selection) !important" },
  66. ".cm-activeLine": { backgroundColor: "var(--ath-active-line)" },
  67. ".cm-gutters": { backgroundColor: "var(--ath-editor-bg)", color: "var(--orb-text-subtle)", border: "none", paddingLeft: "6px" },
  68. ".cm-activeLineGutter": { backgroundColor: "transparent", color: "var(--orb-text)" },
  69. ".cm-lineNumbers .cm-gutterElement": { padding: "0 10px 0 6px", minWidth: "36px" },
  70. ".cm-foldGutter .cm-gutterElement": { color: "var(--orb-text-subtle)", cursor: "pointer", padding: "0 4px" },
  71. ".cm-foldPlaceholder": { backgroundColor: "var(--orb-primary-dim)", border: "1px solid var(--orb-primary-border)", color: "var(--orb-primary-text)", borderRadius: "4px", padding: "0 6px" },
  72. ".cm-matchingBracket, &.cm-focused .cm-matchingBracket": { backgroundColor: "var(--orb-primary-dim-strong)", outline: "1px solid var(--orb-primary-border)", color: "inherit" },
  73. ".cm-nonmatchingBracket": { color: "var(--orb-danger)" },
  74. ".cm-selectionMatch": { backgroundColor: "var(--ath-selection-match)" },
  75. ".cm-searchMatch": { backgroundColor: "color-mix(in srgb, var(--orb-warning) 30%, transparent)", outline: "1px solid color-mix(in srgb, var(--orb-warning) 60%, transparent)" },
  76. ".cm-searchMatch.cm-searchMatch-selected": { backgroundColor: "color-mix(in srgb, var(--orb-warning) 55%, transparent)" },
  77. ".cm-tooltip": { backgroundColor: "var(--orb-surface)", color: "var(--orb-text)", border: "1px solid var(--orb-border)", borderRadius: "10px", boxShadow: "var(--orb-shadow-lg)", overflow: "hidden" },
  78. ".cm-tooltip-autocomplete > ul": { fontFamily: "var(--ath-font-code)", fontSize: "13px", maxHeight: "18em" },
  79. ".cm-tooltip-autocomplete > ul > li": { padding: "3px 10px 3px 6px", lineHeight: "1.5" },
  80. ".cm-tooltip-autocomplete > ul > li[aria-selected]": { backgroundColor: "var(--orb-primary-dim-strong)", color: "var(--orb-text)" },
  81. ".cm-completionIcon": { opacity: "0.75", width: "1.2em", paddingRight: "8px" },
  82. ".cm-completionDetail": { color: "var(--orb-text-muted)", fontStyle: "normal", marginLeft: "10px" },
  83. ".cm-completionMatchedText": { color: "var(--orb-primary-text)", textDecoration: "none", fontWeight: "700" },
  84. ".cm-completionInfo": { padding: "8px 12px", maxWidth: "380px", fontFamily: "var(--orb-font-sans)", fontSize: "13px" },
  85. ".cm-panels": { backgroundColor: "var(--orb-surface-alt)", color: "var(--orb-text)" },
  86. ".cm-panels.cm-panels-bottom": { borderTop: "1px solid var(--orb-border)" },
  87. ".cm-panels.cm-panels-top": { borderBottom: "1px solid var(--orb-border)" },
  88. ".cm-search": { fontFamily: "var(--orb-font-sans)", fontSize: "13px", padding: "8px 12px" },
  89. ".cm-search input, .cm-search button, .cm-search label": { fontSize: "13px" },
  90. ".cm-textfield": { backgroundColor: "var(--orb-bg)", border: "1px solid var(--orb-border-strong)", borderRadius: "6px", color: "var(--orb-text)", padding: "3px 8px" },
  91. ".cm-button": { backgroundImage: "none", backgroundColor: "var(--orb-surface)", border: "1px solid var(--orb-border-strong)", borderRadius: "6px", color: "var(--orb-text)", padding: "3px 10px" },
  92. ".cm-diagnostic": { fontFamily: "var(--orb-font-sans)", fontSize: "13px", padding: "6px 10px" },
  93. ".cm-diagnostic-error": { borderLeft: "3px solid var(--orb-danger)" },
  94. ".cm-diagnostic-warning": { borderLeft: "3px solid var(--orb-warning)" },
  95. ".cm-lintRange-error": { backgroundImage: "none", textDecoration: "underline wavy var(--orb-danger)", textUnderlineOffset: "3px" },
  96. ".cm-lintRange-warning": { backgroundImage: "none", textDecoration: "underline wavy var(--orb-warning)", textUnderlineOffset: "3px" },
  97. ".cm-lintRange-info": { backgroundImage: "none", textDecoration: "underline dotted var(--orb-info)", textUnderlineOffset: "3px" },
  98. ".cm-diagnostic-info": { borderLeft: "3px solid var(--orb-info)" },
  99. ".cm-diagnosticAction": { backgroundColor: "var(--orb-primary)", color: "var(--orb-primary-ink)", border: "0", borderRadius: "6px", padding: "2px 10px", marginLeft: "10px", font: "inherit", fontWeight: "600", cursor: "pointer" },
  100. ".cm-panel.cm-panel-lint ul [aria-selected]": { backgroundColor: "var(--orb-primary-dim-strong)", color: "var(--orb-text)" },
  101. ".cm-panel.cm-panel-lint ul": { fontFamily: "var(--orb-font-sans)", fontSize: "13px" },
  102. ".emmet-tracker": { textDecoration: "underline 1px dotted var(--orb-primary)", textUnderlineOffset: "3px" },
  103. ".emmet-preview": { fontSize: "12px", padding: "6px 10px", fontFamily: "var(--ath-font-code)" },
  104. ".emmet-preview .cm-editor": { backgroundColor: "transparent" },
  105. ".emmet-preview_error": { color: "var(--orb-danger)" },
  106. ".emmet-wrap-with-abbreviation__content": { backgroundColor: "var(--orb-surface)", border: "1px solid var(--orb-border-strong)", borderTop: "0", boxShadow: "var(--orb-shadow-lg)", padding: "8px" },
  107. ".emmet-wrap-with-abbreviation__content input": { backgroundColor: "var(--orb-bg)", color: "var(--orb-text)", border: "1px solid var(--orb-border-strong)", borderRadius: "6px", padding: "6px 10px", font: "inherit", outline: "none" },
  108. ".cm-completionIcon-snippet::after": { content: "'⧉'" },
  109. ".cm-tooltip.cm-completionInfo": { padding: "10px 12px" }
  110. });
  111. ​
  112. function createMultilineSearchPanel(view) {
  113. var dom = util.el("div", { class: "ath-cm-search-panel" });
  114. var search = util.el("textarea", {
  115. class: "orb-input ath-cm-search-field",
  116. rows: "1",
  117. "main-field": "",
  118. "aria-label": A.t("search.editor_find"),
  119. placeholder: A.t("search.editor_find"),
  120. spellcheck: "false"
  121. });
  122. var replace = util.el("textarea", {
  123. class: "orb-input ath-cm-search-field",
  124. rows: "1",
  125. "aria-label": A.t("search.editor_replace"),
  126. placeholder: A.t("search.editor_replace"),
  127. spellcheck: "false"
  128. });
  129. var replaceRow = util.el("div", { class: "ath-cm-search-replace", hidden: true });
  130. var caseSensitive = false, wholeWord = false, regexp = false;
  131. var options = [];
  132. ​
  133. function refreshQuery() {
  134. view.dispatch({
  135. effects: CM.setSearchQuery.of(new CM.SearchQuery({
  136. search: search.value,
  137. replace: replace.value,
  138. caseSensitive: caseSensitive,
  139. wholeWord: wholeWord,
  140. regexp: regexp
  141. }))
  142. });
  143. }
  144. ​
  145. function action(label, title, run, className) {
  146. var button = util.el("button", {
  147. type: "button",
  148. class: className || "ath-cm-search-button",
  149. title: title,
  150. "aria-label": title
  151. }, label);
  152. button.addEventListener("click", run);
  153. return button;
  154. }
  155. ​
  156. function resizeField(field) {
  157. field.style.height = "auto";
  158. field.style.height = Math.min(field.scrollHeight, 84) + "px";
  159. }
  160. ​
  161. function option(label, title, key) {
  162. var button = action(label, title, function () {
  163. if (key === "caseSensitive") caseSensitive = !caseSensitive;
  164. else if (key === "wholeWord") wholeWord = !wholeWord;
  165. else regexp = !regexp;
  166. button.setAttribute("aria-pressed", button.getAttribute("aria-pressed") !== "true" ? "true" : "false");
  167. refreshQuery();
  168. }, "ath-cm-search-button ath-cm-search-option");
  169. button.setAttribute("aria-pressed", "false");
  170. options.push({ key: key, button: button });
  171. return button;
  172. }
  173. ​
  174. var controls = util.el("div", { class: "ath-cm-search-controls" }, [
  175. option("Aa", A.t("search.case"), "caseSensitive"),
  176. option("ab", A.t("search.word"), "wholeWord"),
  177. option(".*", A.t("search.regex"), "regexp"),
  178. action("↕", A.t("search.toggle_replace"), function () {
  179. replaceRow.hidden = !replaceRow.hidden;
  180. }),
  181. action("‹", A.t("search.editor_previous"), function () { CM.findPrevious(view); }),
  182. action("›", A.t("search.editor_next"), function () { CM.findNext(view); }),
  183. action("×", A.t("search.editor_close"), function () { CM.closeSearchPanel(view); })
  184. ]);
  185. var searchRow = util.el("div", { class: "ath-cm-search-row" }, [search, controls]);
  186. replaceRow.appendChild(replace);
  187. replaceRow.appendChild(action(A.t("search.replace_one"), A.t("search.replace_one"), function () { CM.replaceNext(view); }));
  188. replaceRow.appendChild(action(A.t("search.replace_all"), A.t("search.replace_all"), function () { CM.replaceAll(view); }));
  189. dom.appendChild(searchRow);
  190. dom.appendChild(replaceRow);
  191. ​
  192. search.addEventListener("input", function () {
  193. resizeField(search);
  194. refreshQuery();
  195. });
  196. replace.addEventListener("input", function () {
  197. resizeField(replace);
  198. refreshQuery();
  199. });
  200. [search, replace].forEach(function (field) {
  201. field.addEventListener("keydown", function (event) {
  202. if (event.key === "Escape") {
  203. event.preventDefault();
  204. CM.closeSearchPanel(view);
  205. } else if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) {
  206. event.preventDefault();
  207. if (event.shiftKey) CM.findPrevious(view);
  208. else CM.findNext(view);
  209. }
  210. });
  211. });
  212. ​
  213. function updateFromState() {
  214. var query = CM.getSearchQuery(view.state);
  215. if (!query) return;
  216. if (search.value !== query.search) search.value = query.search;
  217. if (replace.value !== query.replace) replace.value = query.replace;
  218. resizeField(search);
  219. resizeField(replace);
  220. caseSensitive = query.caseSensitive;
  221. wholeWord = query.wholeWord;
  222. regexp = query.regexp;
  223. options.forEach(function (item) {
  224. var enabled = item.key === "caseSensitive" ? caseSensitive : item.key === "wholeWord" ? wholeWord : regexp;
  225. item.button.setAttribute("aria-pressed", enabled ? "true" : "false");
  226. });
  227. }
  228. ​
  229. updateFromState();
  230. return { dom: dom, top: true, update: updateFromState };
  231. }
  232. ​
  233. var langComp = new CM.Compartment();
  234. var optComp = new CM.Compartment();
  235. var phraseComp = new CM.Compartment();
  236. var S = A.settings;
  237. ​
  238. var langCache = {};
  239. function langExt(name) {
  240. var id = langId(name), ext = util.ext(name);
  241. var swatches = S.get("colorSwatches") && A.colors.supports(id);
  242. var key = id + ":" + ext + ":" + S.get("emmet") + ":" + (swatches ? "c" : "");
  243. if (!langCache[key]) {
  244. langCache[key] = [LANGS[id].make(), A.intellisense.forLanguage(id, ext)];
  245. if (swatches) langCache[key].push(A.colors.extension(id));
  246. }
  247. return langCache[key];
  248. }
  249. ​
  250. var lastCounts = "";
  251. function countDiagnostics(state) {
  252. var c = { error: 0, warning: 0, info: 0 };
  253. CM.forEachDiagnostic(state, function (d) { c[d.severity] = (c[d.severity] || 0) + 1; });
  254. return c;
  255. }
  256. ​
  257. function onUpdate(u) {
  258. if (u.docChanged) A.emit("doc-change", u.state);
  259. if (u.docChanged || u.selectionSet) A.emit("cursor", u.state);
  260. var c = countDiagnostics(u.state), key = c.error + ":" + c.warning + ":" + c.info;
  261. if (key !== lastCounts) {
  262. lastCounts = key;
  263. A.emit("diagnostics", c);
  264. }
  265. }
  266. ​
  267. var minimapExt = CM.ViewPlugin.fromClass(class {
  268. constructor(view) {
  269. this.view = view;
  270. this.host = view.dom.parentElement;
  271. this.el = document.createElement("div");
  272. this.el.className = "ath-minimap";
  273. this.el.tabIndex = 0;
  274. this.el.setAttribute("role", "scrollbar");
  275. this.el.setAttribute("aria-orientation", "vertical");
  276. this.el.setAttribute("aria-label", A.t("settings.minimap"));
  277. if (!view.contentDOM.id) view.contentDOM.id = "ath-editor-content";
  278. this.el.setAttribute("aria-controls", view.contentDOM.id);
  279. this.canvas = document.createElement("canvas");
  280. this.viewport = document.createElement("div");
  281. this.viewport.className = "ath-minimap-viewport";
  282. this.markers = document.createElement("div");
  283. this.markers.className = "ath-minimap-markers";
  284. this.el.appendChild(this.canvas);
  285. this.el.appendChild(this.viewport);
  286. this.el.appendChild(this.markers);
  287. this.host.classList.add("has-minimap");
  288. this.host.appendChild(this.el);
  289. this.dragOffset = 0;
  290. this.renderFrame = 0;
  291. this.documentDirty = true;
  292. this.selectionDirty = true;
  293. this.onScroll = this.renderViewport.bind(this);
  294. this.onResize = function () { this.scheduleRender(true, true); }.bind(this);
  295. this.onPointerDown = this.pointerDown.bind(this);
  296. this.onPointerMove = this.pointerMove.bind(this);
  297. this.onPointerEnd = this.pointerEnd.bind(this);
  298. this.onKeyDown = this.keyDown.bind(this);
  299. view.scrollDOM.addEventListener("scroll", this.onScroll, { passive: true });
  300. this.el.addEventListener("pointerdown", this.onPointerDown);
  301. this.el.addEventListener("pointermove", this.onPointerMove);
  302. this.el.addEventListener("pointerup", this.onPointerEnd);
  303. this.el.addEventListener("pointercancel", this.onPointerEnd);
  304. this.el.addEventListener("keydown", this.onKeyDown);
  305. this.resizeObserver = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(this.onResize);
  306. if (this.resizeObserver) {
  307. this.resizeObserver.observe(view.scrollDOM);
  308. this.resizeObserver.observe(this.el);
  309. }
  310. else window.addEventListener("resize", this.onResize);
  311. this.scheduleRender();
  312. }
  313. ​
  314. update(update) {
  315. var documentChanged = update.docChanged || update.geometryChanged;
  316. if (documentChanged || update.selectionSet) this.scheduleRender(documentChanged, documentChanged || update.selectionSet);
  317. }
  318. ​
  319. scheduleRender(documentChanged, selectionChanged) {
  320. if (documentChanged) this.documentDirty = true;
  321. if (selectionChanged) this.selectionDirty = true;
  322. if (this.renderFrame) return;
  323. this.renderFrame = requestAnimationFrame(function () {
  324. this.renderFrame = 0;
  325. var rect = this.canvas.getBoundingClientRect();
  326. if (!rect.width || !rect.height) return;
  327. var contentHeight = this.view.contentHeight;
  328. if (this.documentDirty) {
  329. this.renderDocument(rect, contentHeight);
  330. this.documentDirty = false;
  331. }
  332. if (this.selectionDirty) {
  333. this.renderSelection(rect, contentHeight);
  334. this.selectionDirty = false;
  335. }
  336. this.renderViewport();
  337. }.bind(this));
  338. }
  339. ​
  340. destroy() {
  341. if (this.renderFrame) cancelAnimationFrame(this.renderFrame);
  342. this.view.scrollDOM.removeEventListener("scroll", this.onScroll);
  343. this.el.removeEventListener("pointerdown", this.onPointerDown);
  344. this.el.removeEventListener("pointermove", this.onPointerMove);
  345. this.el.removeEventListener("pointerup", this.onPointerEnd);
  346. this.el.removeEventListener("pointercancel", this.onPointerEnd);
  347. this.el.removeEventListener("keydown", this.onKeyDown);
  348. if (this.resizeObserver) this.resizeObserver.disconnect();
  349. else window.removeEventListener("resize", this.onResize);
  350. this.el.remove();
  351. this.host.classList.remove("has-minimap");
  352. }
  353. ​
  354. renderDocument(rect, contentHeight) {
  355. var dpr = window.devicePixelRatio || 1;
  356. var width = Math.round(rect.width * dpr), height = Math.round(rect.height * dpr);
  357. if (this.canvas.width !== width || this.canvas.height !== height) {
  358. this.canvas.width = width;
  359. this.canvas.height = height;
  360. }
  361. var ctx = this.canvas.getContext("2d");
  362. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  363. ctx.clearRect(0, 0, rect.width, rect.height);
  364. if (!contentHeight) return;
  365. var sampleHeight = 1;
  366. var codeColor = getComputedStyle(this.el).getPropertyValue("--ath-minimap-code").trim();
  367. var codeFont = getComputedStyle(this.view.contentDOM).fontFamily;
  368. var lastFrom = -1, lastMapY = -1;
  369. for (var y = 0; y < rect.height; y += sampleHeight) {
  370. var block = this.view.lineBlockAtHeight((y + sampleHeight / 2) / rect.height * contentHeight);
  371. if (block.from === lastFrom) continue;
  372. lastFrom = block.from;
  373. var mapY = Math.max(0, Math.min(rect.height - 1, Math.round(block.top / contentHeight * rect.height)));
  374. if (mapY === lastMapY) continue;
  375. lastMapY = mapY;
  376. var text = this.view.state.doc.lineAt(block.from).text;
  377. if (!text.trim()) continue;
  378. var indent = (text.match(/^\s*/) || [""])[0].length;
  379. var x = 10 + Math.min(24, indent * 1.25);
  380. var lineHeight = block.height / contentHeight * rect.height;
  381. var fontSize = Math.max(0.65, Math.min(3, lineHeight * 0.72));
  382. ctx.fillStyle = codeColor;
  383. ctx.globalAlpha = text.trimStart().charAt(0) === "<" ? 0.78 : 1;
  384. ctx.font = fontSize + "px " + codeFont;
  385. ctx.textBaseline = "top";
  386. ctx.fillText(text.slice(0, 500), x, mapY, rect.width - x - 8);
  387. }
  388. }
  389. ​
  390. renderSelection(rect, contentHeight) {
  391. this.markers.replaceChildren();
  392. if (!contentHeight) return;
  393. var view = this.view;
  394. var scale = rect.height / contentHeight;
  395. var selection = view.state.selection;
  396. selection.ranges.forEach(function (range) {
  397. if (range.empty) return;
  398. var from = view.lineBlockAt(range.from);
  399. var to = view.lineBlockAt(range.to);
  400. var top = Math.max(0, Math.min(from.top, to.top));
  401. var bottom = Math.min(contentHeight, Math.max(from.top + from.height, to.top + to.height));
  402. if (bottom > top) {
  403. var marker = document.createElement("div");
  404. marker.className = "ath-minimap-selection";
  405. marker.style.top = top * scale + "px";
  406. marker.style.height = Math.max(0.75, (bottom - top) * scale) + "px";
  407. this.markers.appendChild(marker);
  408. }
  409. }, this);
  410. var cursor = selection.main;
  411. var cursorBlock = view.lineBlockAt(cursor.head);
  412. var cursorY = Math.max(0, Math.min(contentHeight, cursorBlock.top + cursorBlock.height / 2)) * scale;
  413. var caret = document.createElement("div");
  414. caret.className = "ath-minimap-cursor";
  415. caret.style.top = Math.max(0, Math.min(rect.height - 1, cursorY - 0.5)) + "px";
  416. this.markers.appendChild(caret);
  417. }
  418. ​
  419. renderViewport() {
  420. var rect = this.canvas.getBoundingClientRect();
  421. if (!rect.width || !rect.height) return;
  422. var scroll = this.view.scrollDOM;
  423. var contentHeight = this.view.contentHeight;
  424. var maxScroll = Math.max(0, contentHeight - scroll.clientHeight);
  425. var top = maxScroll ? scroll.scrollTop / contentHeight * rect.height : 0;
  426. var visible = maxScroll ? scroll.clientHeight / contentHeight * rect.height : rect.height;
  427. this.viewport.hidden = maxScroll <= 1;
  428. this.viewport.style.top = Math.min(top, rect.height - visible) + "px";
  429. this.viewport.style.height = Math.min(visible, rect.height) + "px";
  430. this.el.setAttribute("aria-valuemin", "0");
  431. this.el.setAttribute("aria-valuemax", "100");
  432. this.el.setAttribute("aria-valuenow", String(maxScroll ? Math.round(scroll.scrollTop / maxScroll * 100) : 0));
  433. }
  434. ​
  435. scrollFromPointer(event, behavior) {
  436. var rect = this.canvas.getBoundingClientRect();
  437. var scroll = this.view.scrollDOM;
  438. var contentHeight = this.view.contentHeight;
  439. var maxScroll = Math.max(0, contentHeight - scroll.clientHeight);
  440. if (!maxScroll) return;
  441. var visible = scroll.clientHeight / contentHeight * rect.height;
  442. var mapTop = Math.max(0, Math.min(rect.height - visible, event.clientY - rect.top - this.dragOffset));
  443. this.view.scrollDOM.scrollTo({ top: mapTop / rect.height * contentHeight, behavior: behavior });
  444. }
  445. ​
  446. pointerDown(event) {
  447. if (event.button !== 0) return;
  448. event.preventDefault();
  449. this.el.focus();
  450. this.el.setPointerCapture(event.pointerId);
  451. var viewportRect = this.viewport.getBoundingClientRect();
  452. this.dragOffset = event.clientY >= viewportRect.top && event.clientY <= viewportRect.bottom
  453. ? event.clientY - viewportRect.top
  454. : viewportRect.height / 2;
  455. this.el.classList.add("is-dragging");
  456. this.scrollFromPointer(event, "smooth");
  457. }
  458. ​
  459. pointerMove(event) {
  460. if (this.el.hasPointerCapture(event.pointerId)) this.scrollFromPointer(event, "instant");
  461. }
  462. ​
  463. pointerEnd() {
  464. this.el.classList.remove("is-dragging");
  465. }
  466. ​
  467. keyDown(event) {
  468. var scroll = this.view.scrollDOM, step = 40;
  469. if (event.key === "ArrowUp") scroll.scrollTop -= step;
  470. else if (event.key === "ArrowDown") scroll.scrollTop += step;
  471. else if (event.key === "PageUp") scroll.scrollTop -= scroll.clientHeight;
  472. else if (event.key === "PageDown") scroll.scrollTop += scroll.clientHeight;
  473. else if (event.key === "Home") scroll.scrollTop = 0;
  474. else if (event.key === "End") scroll.scrollTop = scroll.scrollHeight;
  475. else return;
  476. event.preventDefault();
  477. }
  478. });
  479. ​
  480. var baseExtensions = [
  481. CM.highlightSpecialChars(),
  482. CM.history(),
  483. CM.drawSelection(),
  484. CM.dropCursor(),
  485. CM.EditorState.allowMultipleSelections.of(true),
  486. CM.indentOnInput(),
  487. CM.syntaxHighlighting(highlight),
  488. CM.bracketMatching(),
  489. CM.rectangularSelection(),
  490. CM.crosshairCursor(),
  491. CM.lintGutter(),
  492. CM.search({ top: true, createPanel: createMultilineSearchPanel }),
  493. A.intellisense.base(),
  494. CM.Prec.highest(CM.keymap.of([{ key: "Tab", run: CM.acceptCompletion }])),
  495. CM.keymap.of([].concat(
  496. CM.closeBracketsKeymap, CM.defaultKeymap, CM.searchKeymap, CM.historyKeymap,
  497. CM.foldKeymap, CM.completionKeymap, CM.lintKeymap, [CM.indentWithTab]
  498. )),
  499. theme,
  500. CM.EditorView.domEventHandlers({
  501. drop: function (e, view) { return !!A.images && A.images.onDrop(e, view); },
  502. paste: function (e, view) { return !!A.images && A.images.onPaste(e, view); }
  503. }),
  504. CM.EditorView.updateListener.of(onUpdate)
  505. ];
  506. ​
  507. function optExt() {
  508. var o = S.all();
  509. var ext = [
  510. CM.EditorState.tabSize.of(o.tabSize),
  511. CM.indentUnit.of(o.insertSpaces ? " ".repeat(o.tabSize) : " "),
  512. CM.autocompletion({ activateOnTyping: o.autocomplete, icons: true })
  513. ];
  514. if (o.lineNumbers) ext.push(CM.lineNumbers(), CM.highlightActiveLineGutter());
  515. if (o.fold) ext.push(CM.foldGutter({ openText: "⌄", closedText: "›" }));
  516. if (o.activeLine) ext.push(CM.highlightActiveLine());
  517. if (o.closeBrackets) ext.push(CM.closeBrackets());
  518. if (o.matchHighlight) ext.push(CM.highlightSelectionMatches());
  519. if (o.wrap) ext.push(CM.EditorView.lineWrapping);
  520. if (o.minimap) ext.push(minimapExt);
  521. return ext;
  522. }
  523. ​
  524. function phraseExt() {
  525. return CM.EditorState.phrases.of(A.i18n.phrases());
  526. }
  527. ​
  528. var editor = (A.editor = {
  529. view: null,
  530. langId: langId,
  531. ​
  532. langLabel: function (name) {
  533. return LANGS[langId(name)].label || A.t("status.plain_text");
  534. },
  535. ​
  536. init: function (parent) {
  537. editor.view = new CM.EditorView({ state: editor.createState("", "untitled.txt"), parent: parent });
  538. A.on("lang", function () {
  539. editor.view.dispatch({ effects: phraseComp.reconfigure(phraseExt()) });
  540. });
  541. A.on("settings", function (keys) {
  542. var effects = [optComp.reconfigure(optExt())];
  543. if ((keys.indexOf("emmet") >= 0 || keys.indexOf("colorSwatches") >= 0) && A.tabs && A.tabs.active) effects.push(langComp.reconfigure(langExt(A.tabs.active.name)));
  544. editor.view.dispatch({ effects: effects });
  545. if (keys.indexOf("lintHints") >= 0) CM.forceLinting(editor.view);
  546. if (keys.some(function (k) { return /font|lineHeight/i.test(k); })) editor.view.requestMeasure();
  547. });
  548. if (document.fonts) {
  549. document.fonts.addEventListener("loadingdone", function () { editor.view.requestMeasure(); });
  550. }
  551. },
  552. ​
  553. createState: function (doc, name) {
  554. return CM.EditorState.create({
  555. doc: doc,
  556. extensions: [
  557. A.aiGhost ? A.aiGhost.extension() : [],
  558. A.links ? A.links.extension() : [],
  559. baseExtensions,
  560. optComp.of(optExt()),
  561. phraseComp.of(phraseExt()),
  562. langComp.of(langExt(name))
  563. ]
  564. });
  565. },
  566. ​
  567. setLanguage: function (state, name) {
  568. return state.update({ effects: langComp.reconfigure(langExt(name)) }).state;
  569. },
  570. ​
  571. syncState: function (state, name) {
  572. var effects = [optComp.reconfigure(optExt()), phraseComp.reconfigure(phraseExt())];
  573. if (name) effects.push(langComp.reconfigure(langExt(name)));
  574. return state.update({ effects: effects }).state;
  575. },
  576. ​
  577. diagnostics: function () {
  578. return countDiagnostics(editor.view.state);
  579. },
  580. ​
  581. toggleWrap: function () {
  582. S.set("wrap", !S.get("wrap"));
  583. return S.get("wrap");
  584. },
  585. ​
  586. zoom: function (delta) {
  587. S.set("fontSize", delta === 0 ? S.defaults.fontSize : Math.max(10, Math.min(28, S.get("fontSize") + delta)));
  588. },
  589. ​
  590. focus: function () {
  591. if (editor.view) editor.view.focus();
  592. },
  593. ​
  594. openSearch: function () {
  595. CM.openSearchPanel(editor.view);
  596. },
  597. ​
  598. run: function (command) {
  599. editor.view.focus();
  600. return command(editor.view);
  601. },
  602. ​
  603. goTo: function (line, col) {
  604. var view = editor.view, doc = view.state.doc;
  605. var l = doc.line(Math.max(1, Math.min(doc.lines, line)));
  606. var pos = Math.min(l.from + Math.max(0, (col || 1) - 1), l.to);
  607. view.dispatch({ selection: { anchor: pos }, effects: CM.EditorView.scrollIntoView(pos, { y: "center" }) });
  608. view.focus();
  609. },
  610. ​
  611. select: function (line, col, length) {
  612. var view = editor.view, doc = view.state.doc;
  613. var l = doc.line(Math.max(1, Math.min(doc.lines, line)));
  614. var from = Math.min(l.from + Math.max(0, (col || 1) - 1), l.to);
  615. var to = Math.min(from + (length || 0), doc.length);
  616. view.dispatch({ selection: { anchor: from, head: to }, effects: CM.EditorView.scrollIntoView(from, { y: "center" }) });
  617. view.focus();
  618. },
  619. ​
  620. selectOccurrences: function () {
  621. var view = editor.view, r = view.state.selection.main;
  622. if (r.empty) {
  623. var w = view.state.wordAt(r.head);
  624. if (!w) return false;
  625. view.dispatch({ selection: { anchor: w.from, head: w.to } });
  626. }
  627. view.focus();
  628. return CM.selectSelectionMatches(view);
  629. },
  630. ​
  631. copy: async function (cut) {
  632. var view = editor.view, st = view.state;
  633. var ranges = st.selection.ranges.filter(function (r) { return !r.empty; });
  634. var text, changes;
  635. if (ranges.length) {
  636. text = ranges.map(function (r) { return st.sliceDoc(r.from, r.to); }).join(st.lineBreak);
  637. changes = ranges.map(function (r) { return { from: r.from, to: r.to }; });
  638. } else {
  639. var line = st.doc.lineAt(st.selection.main.head);
  640. text = line.text + st.lineBreak;
  641. changes = { from: line.from, to: Math.min(line.to + 1, st.doc.length) };
  642. }
  643. await A.ui.copyText(text);
  644. if (cut) view.dispatch({ changes: changes, userEvent: "delete.cut" });
  645. view.focus();
  646. },
  647. ​
  648. paste: async function () {
  649. var view = editor.view;
  650. var text = await navigator.clipboard.readText();
  651. view.dispatch(view.state.replaceSelection(text), { userEvent: "input.paste", scrollIntoView: true });
  652. view.focus();
  653. },
  654. ​
  655. simulateKey: function (key, code, mods) {
  656. var ev = new KeyboardEvent("keydown", Object.assign({ key: key, code: code, bubbles: true, cancelable: true }, mods || {}));
  657. editor.view.focus();
  658. editor.view.contentDOM.dispatchEvent(ev);
  659. }
  660. });
  661. })();
  662. ​