WebOrbiton
v1.5.0

AtheraStudio Code

334 lines · 11.5 KB
  1. (function () {
  2. "use strict";
  3. ​
  4. var A = window.Athera;
  5. var util = A.util;
  6. var t = function (k, p) { return A.t(k, p); };
  7. ​
  8. var LINE_MAX = 5000;
  9. var INDEX = ["index.html", "index.php", "index.htm"];
  10. ​
  11. var PATTERNS = [
  12. { re: /\b(?:href|src|action|formaction|poster|data-src|data-href|xlink:href)\s*=\s*(["'])([^"'\n]*)\1/gi, group: 2 },
  13. { re: /\bsrcset\s*=\s*(["'])([^"'\n]*)\1/gi, group: 2, srcset: true },
  14. { re: /\burl\(\s*(["']?)([^"')\s]+)\1\s*\)/gi, group: 2 },
  15. { re: /@import\s+(["'])([^"'\n]+)\1/gi, group: 2 },
  16. { re: /\b(?:include|require)(?:_once)?\s*\(?\s*(__DIR__\s*\.\s*)?(["'])([^"'\n]+)\2/gi, group: 3, php: true },
  17. { re: /\bfrom\s*(["'])(\.{0,2}\/[^"'\n]+)\1/g, group: 2 },
  18. { re: /\bimport\s*\(?\s*(["'])(\.{0,2}\/[^"'\n]+)\1/g, group: 2 },
  19. { re: /\]\(([^()\s]+)\)/g, group: 1 },
  20. { re: /\b(?:https?:\/\/|mailto:)[^\s"'<>()\[\]{}`\\]+/gi, group: 0, bare: true }
  21. ];
  22. ​
  23. function find(state, pos) {
  24. var line = state.doc.lineAt(pos);
  25. if (line.length > LINE_MAX) return null;
  26. var text = line.text, off = pos - line.from;
  27. for (var i = 0; i < PATTERNS.length; i++) {
  28. var p = PATTERNS[i];
  29. p.re.lastIndex = 0;
  30. var m;
  31. while ((m = p.re.exec(text))) {
  32. if (!m[0]) { p.re.lastIndex++; continue; }
  33. var value = m[p.group];
  34. if (value == null) continue;
  35. if (p.bare) value = value.replace(/[.,;:!?]+$/, "");
  36. var start = p.group === 0 ? m.index : m.index + m[0].lastIndexOf(value);
  37. var end = start + value.length;
  38. if (off < start || off > end || !value) continue;
  39. if (p.srcset) {
  40. var seg = segmentAt(value, off - start);
  41. if (!seg) continue;
  42. start += seg.start;
  43. end = start + seg.text.length;
  44. value = seg.text;
  45. }
  46. return { from: line.from + start, to: line.from + end, value: value, phpDir: !!(p.php && m[1]) };
  47. }
  48. }
  49. return null;
  50. }
  51. ​
  52. function segmentAt(value, at) {
  53. var re = /[^\s,][^\s,]*/g, m;
  54. while ((m = re.exec(value))) {
  55. if (at >= m.index && at <= m.index + m[0].length && !/^\d+(\.\d+)?[wx]$/.test(m[0])) return { start: m.index, text: m[0] };
  56. }
  57. return null;
  58. }
  59. ​
  60. function classify(link) {
  61. var v = String(link.value || "").trim();
  62. if (!v || /[<>{}$`]|\?>|\{\{/.test(v) || /^(javascript|data|blob|about|vbscript):/i.test(v)) return null;
  63. if (/^\/\//.test(v)) return { type: "url", url: "https:" + v };
  64. if (/^https?:\/\//i.test(v)) return { type: "url", url: v };
  65. if (/^(mailto|tel):/i.test(v)) return { type: "url", url: v };
  66. if (/^[a-z][a-z0-9+.\-]*:/i.test(v)) return null;
  67. if (v.charAt(0) === "#") {
  68. var id = v.slice(1);
  69. try { id = decodeURIComponent(id); } catch (e) { }
  70. return id ? { type: "anchor", id: id } : null;
  71. }
  72. var hash = "";
  73. var h = v.indexOf("#");
  74. if (h >= 0) {
  75. hash = v.slice(h + 1);
  76. try { hash = decodeURIComponent(hash); } catch (e) { }
  77. }
  78. if (link.phpDir) v = v.replace(/^\/+/, "");
  79. return { type: "file", ref: v, hash: hash };
  80. }
  81. ​
  82. function at(state, pos) {
  83. var link = find(state, pos);
  84. if (!link) return null;
  85. var target = classify(link);
  86. return target ? Object.assign(link, target) : null;
  87. }
  88. ​
  89. function hostLabel(url) {
  90. if (/^mailto:/i.test(url)) return url.slice(7).split("?")[0];
  91. if (/^tel:/i.test(url)) return url.slice(4);
  92. try { return new URL(url).hostname; } catch (e) { return url; }
  93. }
  94. ​
  95. async function openUrl(url) {
  96. var body = util.el("div", { class: "ath-link-confirm" }, [
  97. util.el("div", { class: "ath-link-host" }, hostLabel(url)),
  98. util.el("div", { class: "ath-link-full" }, url)
  99. ]);
  100. var yes = await A.ui.dialog({
  101. title: t("links.url_title"),
  102. size: "sm",
  103. body: body,
  104. actions: [
  105. { label: t("links.no"), value: false, kind: "secondary" },
  106. { label: t("links.yes"), value: true, kind: "primary" }
  107. ]
  108. });
  109. if (yes !== true) return;
  110. if (window.atheraDesktop && typeof window.atheraDesktop.openExternal === "function") return window.atheraDesktop.openExternal(url);
  111. window.open(url, "_blank", "noopener,noreferrer");
  112. }
  113. ​
  114. function jumpToId(id) {
  115. var view = A.editor.view;
  116. var text = view.state.doc.toString();
  117. var esc = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  118. var m = new RegExp("\\b(?:id|name)\\s*=\\s*([\"']?)" + esc + "\\1(?=[\\s>/])", "i").exec(text);
  119. if (!m) {
  120. A.ui.toast(t("links.anchor_missing", { id: id }), "warning");
  121. return false;
  122. }
  123. var pos = m.index + m[0].lastIndexOf(id);
  124. view.dispatch({ selection: { anchor: pos, head: pos + id.length }, scrollIntoView: true });
  125. A.editor.focus();
  126. return true;
  127. }
  128. ​
  129. async function kindOf(path) {
  130. var p = A.fs.provider;
  131. try { await p.readFile(path); return "file"; } catch (e) { }
  132. try { return (await p.exists(path)) ? "dir" : null; } catch (e) { return null; }
  133. }
  134. ​
  135. async function missingDir(path) {
  136. var dir = util.dirname(path), top = "";
  137. while (dir && !(await A.fs.provider.exists(dir))) {
  138. top = dir;
  139. dir = util.dirname(dir);
  140. }
  141. return top;
  142. }
  143. ​
  144. async function openPath(path, hash) {
  145. var tab = await A.tabs.openPath(path);
  146. if (tab && hash && tab.kind === "text") setTimeout(function () { jumpToId(hash); }, 30);
  147. return tab;
  148. }
  149. ​
  150. async function createAndOpen(path, hash) {
  151. if (A.fs.isBinary(path)) {
  152. A.ui.toast(t("links.missing", { path: path }), "warning");
  153. return;
  154. }
  155. var dir = await missingDir(path);
  156. var body = util.el("div", {}, [
  157. util.el("p", { class: "ath-dialog-text" }, t("links.create_text", { path: path })),
  158. dir ? util.el("p", { class: "ath-dialog-text ath-link-dirs" }, t("links.create_dirs", { dir: dir })) : null
  159. ]);
  160. var go = await A.ui.dialog({
  161. title: t("links.create_title"),
  162. size: "sm",
  163. body: body,
  164. actions: [
  165. { label: A.t("common.cancel"), value: false, kind: "secondary" },
  166. { label: t("links.create"), value: true, kind: "primary" }
  167. ]
  168. });
  169. if (go !== true) return;
  170. try {
  171. await A.fs.provider.createFile(path, A.templates ? A.templates.forFile(path) : "");
  172. } catch (e) {
  173. A.ui.toast(e.message, "danger");
  174. return;
  175. }
  176. if (A.explorer) {
  177. await A.explorer.refresh();
  178. A.explorer.reveal(path).catch(function () { });
  179. }
  180. A.ui.toast(t("links.created", { path: path }), "success");
  181. await openPath(path, hash);
  182. }
  183. ​
  184. async function openFile(target, tab) {
  185. if (!A.fs.provider || !tab || tab.path == null) {
  186. A.ui.toast(t("links.no_folder"), "info");
  187. return;
  188. }
  189. var base = util.dirname(tab.path);
  190. var path = target.ref === "/" ? "" : util.resolve(base, target.ref);
  191. if (path == null) return;
  192. var kind = path ? await kindOf(path) : "dir";
  193. if (kind === "file") return openPath(path, target.hash);
  194. if (!kind && /\/$/.test(target.ref.split(/[?#]/)[0])) kind = "dir";
  195. var candidates = [];
  196. if (kind === "dir") candidates = INDEX.map(function (n) { return util.join(path, n); });
  197. else if (!util.ext(path)) candidates = [path + ".html", path + ".php", util.join(path, "index.html"), util.join(path, "index.php")];
  198. for (var i = 0; i < candidates.length; i++) {
  199. if ((await kindOf(candidates[i])) === "file") return openPath(candidates[i], target.hash);
  200. }
  201. var create = path;
  202. if (kind === "dir") create = util.join(path, /\.php$/i.test(tab.path) ? "index.php" : "index.html");
  203. else if (!util.ext(path)) create = path + (/\.php$/i.test(tab.path) ? ".php" : ".html");
  204. return createAndOpen(create, target.hash);
  205. }
  206. ​
  207. async function follow(view, pos) {
  208. var link = at(view.state, pos);
  209. if (!link) return false;
  210. var tab = A.tabs.active;
  211. if (link.type === "url") await openUrl(link.url);
  212. else if (link.type === "anchor") jumpToId(link.id);
  213. else await openFile(link, tab);
  214. return true;
  215. }
  216. ​
  217. function run(promise) {
  218. Promise.resolve(promise).catch(function (e) {
  219. console.error(e);
  220. A.ui.toast(e && e.message ? e.message : String(e), "danger");
  221. });
  222. }
  223. ​
  224. var setHover = CM.StateEffect.define();
  225. ​
  226. var hoverField = CM.StateField.define({
  227. create: function () { return CM.Decoration.none; },
  228. update: function (deco, tr) {
  229. deco = deco.map(tr.changes);
  230. tr.effects.forEach(function (e) {
  231. if (!e.is(setHover)) return;
  232. deco = e.value
  233. ? CM.Decoration.set([CM.Decoration.mark({ class: "ath-link-hover", attributes: { title: e.value.title } }).range(e.value.from, e.value.to)])
  234. : CM.Decoration.none;
  235. });
  236. return deco;
  237. },
  238. provide: function (f) { return CM.EditorView.decorations.from(f); }
  239. });
  240. ​
  241. function isMod(e) {
  242. return (e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey;
  243. }
  244. ​
  245. var hoverPlugin = CM.ViewPlugin.fromClass(class {
  246. constructor(view) {
  247. var self = this;
  248. this.view = view;
  249. this.last = null;
  250. this.inside = false;
  251. this.x = 0;
  252. this.y = 0;
  253. this.mod = false;
  254. this.onMove = function (e) {
  255. self.inside = true;
  256. self.x = e.clientX;
  257. self.y = e.clientY;
  258. self.mod = isMod(e);
  259. self.check();
  260. };
  261. this.onLeave = function () {
  262. self.inside = false;
  263. self.mod = false;
  264. self.set(null);
  265. };
  266. this.onKey = function (e) {
  267. var m = isMod(e);
  268. if (m === self.mod) return;
  269. self.mod = m;
  270. if (self.inside) self.check();
  271. };
  272. view.dom.addEventListener("mousemove", this.onMove);
  273. view.dom.addEventListener("mouseleave", this.onLeave);
  274. window.addEventListener("keydown", this.onKey, true);
  275. window.addEventListener("keyup", this.onKey, true);
  276. window.addEventListener("blur", this.onLeave);
  277. }
  278. update(u) {
  279. if (u.docChanged && this.last) this.set(null);
  280. }
  281. check() {
  282. if (!this.mod) return this.set(null);
  283. var pos = this.view.posAtCoords({ x: this.x, y: this.y });
  284. var link = pos == null ? null : at(this.view.state, pos);
  285. this.set(link ? { from: link.from, to: link.to, title: t(link.type === "url" ? "links.hover_url" : "links.hover_file") } : null);
  286. }
  287. set(r) {
  288. var a = this.last;
  289. if ((!r && !a) || (r && a && r.from === a.from && r.to === a.to)) return;
  290. this.last = r;
  291. var view = this.view;
  292. Promise.resolve().then(function () { view.dispatch({ effects: setHover.of(r) }); });
  293. }
  294. destroy() {
  295. this.view.dom.removeEventListener("mousemove", this.onMove);
  296. this.view.dom.removeEventListener("mouseleave", this.onLeave);
  297. window.removeEventListener("keydown", this.onKey, true);
  298. window.removeEventListener("keyup", this.onKey, true);
  299. window.removeEventListener("blur", this.onLeave);
  300. }
  301. });
  302. ​
  303. var clickHandler = CM.Prec.highest(CM.EditorView.domEventHandlers({
  304. mousedown: function (e, view) {
  305. if (e.button !== 0 || !isMod(e)) return false;
  306. var pos = view.posAtCoords({ x: e.clientX, y: e.clientY });
  307. if (pos == null || !at(view.state, pos)) return false;
  308. e.preventDefault();
  309. run(follow(view, pos));
  310. return true;
  311. }
  312. }));
  313. ​
  314. A.links = {
  315. at: at,
  316. follow: follow,
  317. run: run,
  318. extension: function () {
  319. return [hoverField, hoverPlugin, clickHandler];
  320. },
  321. atCursor: function () {
  322. var view = A.editor.view;
  323. return view ? at(view.state, view.state.selection.main.head) : null;
  324. },
  325. followCursor: function () {
  326. var view = A.editor.view;
  327. if (!view) return;
  328. var pos = view.state.selection.main.head;
  329. if (!at(view.state, pos)) return A.ui.toast(t("links.none"), "info");
  330. run(follow(view, pos));
  331. }
  332. };
  333. })();
  334. ​