WebOrbiton
v1.5.0

AtheraStudio Code

1,648 lines · 71.3 KB
  1. (function () {
  2. "use strict";
  3. ​
  4. var A = window.Athera;
  5. var util = A.util;
  6. var fs = A.fs;
  7. ​
  8. var PREVIEWABLE = ["html", "htm", "xhtml", "php", "phtml", "svg"];
  9. var dataCache = new Map();
  10. var missing = new Set();
  11. var buildId = 0;
  12. ​
  13. var HELPER = "(function(){var B=__B__;" +
  14. "function send(m){m.__athera=B;try{parent.postMessage(m,'*')}catch(e){}}" +
  15. "document.addEventListener('click',function(e){var a=e.target.closest&&e.target.closest('a[href]');if(!a)return;" +
  16. "var h=a.getAttribute('href');if(!h||h.charAt(0)==='#'||/^(javascript|mailto|tel):/i.test(h))return;e.preventDefault();" +
  17. "if(/^([a-z]+:)?\\/\\//i.test(h)){window.open(h,'_blank','noopener');return}send({type:'nav',href:h})},true);" +
  18. "document.addEventListener('submit',function(e){var f=e.target;if(!f||f.tagName!=='FORM')return;var a=f.getAttribute('action')||'';" +
  19. "if(/^([a-z]+:)?\\/\\//i.test(a))return;e.preventDefault();var m=(f.getAttribute('method')||'GET').toUpperCase();var d=new FormData(f);" +
  20. "if(e.submitter&&e.submitter.name)d.append(e.submitter.name,e.submitter.value||'');var p=new URLSearchParams();" +
  21. "d.forEach(function(v,k){p.append(k,typeof v==='string'?v:(v&&v.name)||'')});send({type:'submit',action:a,method:m,data:p.toString()})},true);" +
  22. "var y=__Y__;if(y)addEventListener('load',function(){scrollTo(0,y)});" +
  23. "var t;addEventListener('scroll',function(){clearTimeout(t);t=setTimeout(function(){send({type:'scroll',y:scrollY})},120)},{passive:true});" +
  24. "if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',function(){send({type:'ready'})});else send({type:'ready'});" +
  25. "function seen(){var b=document.body;if(!b)return false;var L=b.querySelectorAll('*'),i,e,r,c,k;" +
  26. "for(i=0;i<L.length&&i<1500;i++){e=L[i];if(/^(SCRIPT|STYLE|LINK|META|NOSCRIPT|TEMPLATE|BR|HEAD|TITLE)$/.test(e.tagName))continue;" +
  27. "r=e.getBoundingClientRect();if(r.width<2||r.height<2)continue;" +
  28. "if(e.checkVisibility&&!e.checkVisibility({checkOpacity:true,checkVisibilityCSS:true,opacityProperty:true,visibilityProperty:true}))continue;" +
  29. "c=getComputedStyle(e);if(c.visibility==='hidden'||+c.opacity<0.05)continue;" +
  30. "if(/^(IMG|CANVAS|SVG|VIDEO|IFRAME|INPUT|TEXTAREA|SELECT|BUTTON|OBJECT|EMBED)$/i.test(e.tagName))return true;" +
  31. "for(k=e.firstChild;k;k=k.nextSibling)if(k.nodeType===3&&k.nodeValue.trim())return true;" +
  32. "if(c.backgroundImage!=='none'||(c.backgroundColor!=='rgba(0, 0, 0, 0)'&&c.backgroundColor!=='transparent'&&c.backgroundColor!=='rgb(255, 255, 255)'))return true}" +
  33. "return false}" +
  34. "var pd=0;function pt(){if(pd)return;pd=1;setTimeout(function(){requestAnimationFrame(function(){send({type:'painted',blank:!seen()})})},500)}" +
  35. "addEventListener('load',pt);setTimeout(pt,4000);" +
  36. "})();";
  37. ​
  38. ​
  39. function pageHook(B) {
  40. function send(m) {
  41. m.__athera = B;
  42. try { parent.postMessage(m, "*"); } catch (e) { }
  43. }
  44. ​
  45. var group = 0;
  46. var timers = {};
  47. var tallies = {};
  48. var orig = {};
  49. ​
  50. function clip(s, n) {
  51. s = String(s);
  52. return s.length > n ? s.slice(0, n) + "…" : s;
  53. }
  54. ​
  55. function describe(el) {
  56. var s = "<" + el.tagName.toLowerCase();
  57. if (el.id) s += " id=\"" + el.id + "\"";
  58. if (el.className && typeof el.className === "string") s += " class=\"" + el.className + "\"";
  59. return s + ">";
  60. }
  61. ​
  62. function fmt(v, depth, seen, top) {
  63. try {
  64. var t = typeof v;
  65. if (t === "string") return top ? v : JSON.stringify(clip(v, 200));
  66. if (t === "undefined" || v === null || t === "number" || t === "boolean") return String(v);
  67. if (t === "bigint") return v + "n";
  68. if (t === "symbol") return v.toString();
  69. if (t === "function") return "ƒ " + (v.name || "anonymous") + "()";
  70. if (v instanceof Error) return clip(v.stack || (v.name + ": " + v.message), 1500);
  71. if (v.nodeType === 1) return describe(v);
  72. if (v.nodeType) return "#" + (v.nodeName || "node");
  73. if (v === window) return "Window";
  74. if (seen.indexOf(v) >= 0) return "[Circular]";
  75. if (v instanceof Date) return isNaN(v) ? "Invalid Date" : v.toISOString();
  76. if (v instanceof RegExp) return String(v);
  77. if (typeof Promise !== "undefined" && v instanceof Promise) return "Promise {…}";
  78. if (depth > 2) return Array.isArray(v) ? "[…]" : "{…}";
  79. seen = seen.concat([v]);
  80. var out = [], n = 0, i;
  81. if (Array.isArray(v)) {
  82. for (i = 0; i < v.length && i < 30; i++) out.push(fmt(v[i], depth + 1, seen, false));
  83. if (v.length > 30) out.push("… " + (v.length - 30) + " more");
  84. return "[" + out.join(", ") + "]";
  85. }
  86. if (typeof Map !== "undefined" && v instanceof Map) {
  87. v.forEach(function (val, key) {
  88. if (n++ < 30) out.push(fmt(key, depth + 1, seen, false) + " => " + fmt(val, depth + 1, seen, false));
  89. });
  90. return "Map(" + v.size + ") {" + out.join(", ") + "}";
  91. }
  92. if (typeof Set !== "undefined" && v instanceof Set) {
  93. v.forEach(function (val) {
  94. if (n++ < 30) out.push(fmt(val, depth + 1, seen, false));
  95. });
  96. return "Set(" + v.size + ") {" + out.join(", ") + "}";
  97. }
  98. var keys = Object.keys(v);
  99. for (i = 0; i < keys.length && i < 30; i++) out.push(keys[i] + ": " + fmt(v[keys[i]], depth + 1, seen, false));
  100. if (keys.length > 30) out.push("… " + (keys.length - 30) + " more");
  101. var name = v.constructor && v.constructor.name;
  102. return (name && name !== "Object" ? name + " " : "") + "{" + out.join(", ") + "}";
  103. } catch (e) {
  104. return "[?]";
  105. }
  106. }
  107. ​
  108. function render(list) {
  109. var a = [].slice.call(list), first = a[0];
  110. if (typeof first === "string" && a.length > 1 && /%[sdifoOjc%]/.test(first)) {
  111. var i = 1;
  112. var head = first.replace(/%([sdifoOjc%])/g, function (m, c) {
  113. if (c === "%") return "%";
  114. if (i >= a.length) return m;
  115. var v = a[i++];
  116. if (c === "c") return "";
  117. if (c === "d") return String(Number(v));
  118. if (c === "i") return String(parseInt(v, 10));
  119. if (c === "f") return String(parseFloat(v));
  120. if (c === "s") return typeof v === "string" ? v : fmt(v, 1, [], false);
  121. return fmt(v, 0, [], false);
  122. });
  123. return [head].concat(a.slice(i).map(function (v) { return fmt(v, 0, [], true); })).join(" ");
  124. }
  125. return a.map(function (v) { return fmt(v, 0, [], true); }).join(" ");
  126. }
  127. ​
  128. function emit(level, list, extra) {
  129. var m = { type: "console", level: level, text: render(list), group: group, stack: clip(new Error().stack || "", 1500) };
  130. if (extra) for (var k in extra) m[k] = extra[k];
  131. send(m);
  132. }
  133. ​
  134. function key(l) {
  135. return l === undefined ? "default" : String(l);
  136. }
  137. ​
  138. ["log", "info", "debug", "warn", "error", "table", "dir"].forEach(function (name) {
  139. orig[name] = console[name];
  140. console[name] = function () {
  141. emit(name === "table" || name === "dir" ? "log" : name, arguments);
  142. return orig[name] && orig[name].apply(console, arguments);
  143. };
  144. });
  145. ​
  146. var oAssert = console.assert;
  147. console.assert = function (ok) {
  148. if (!ok) emit("error", [].slice.call(arguments, 1), { kind: "assert" });
  149. return oAssert && oAssert.apply(console, arguments);
  150. };
  151. ​
  152. var oClear = console.clear;
  153. console.clear = function () {
  154. send({ type: "console-clear" });
  155. return oClear && oClear.apply(console, arguments);
  156. };
  157. ​
  158. ["group", "groupCollapsed"].forEach(function (name) {
  159. var o = console[name];
  160. console[name] = function () {
  161. if (arguments.length) emit("log", arguments);
  162. group++;
  163. return o && o.apply(console, arguments);
  164. };
  165. });
  166. var oEnd = console.groupEnd;
  167. console.groupEnd = function () {
  168. if (group > 0) group--;
  169. return oEnd && oEnd.apply(console, arguments);
  170. };
  171. ​
  172. var oTime = console.time, oTimeEnd = console.timeEnd, oTimeLog = console.timeLog, oCount = console.count;
  173. console.time = function (l) {
  174. timers[key(l)] = performance.now();
  175. return oTime && oTime.apply(console, arguments);
  176. };
  177. console.timeLog = function (l) {
  178. var k = key(l);
  179. if (k in timers) emit("log", [k + ": " + (performance.now() - timers[k]).toFixed(2) + " ms"]);
  180. return oTimeLog && oTimeLog.apply(console, arguments);
  181. };
  182. console.timeEnd = function (l) {
  183. var k = key(l);
  184. if (k in timers) {
  185. emit("log", [k + ": " + (performance.now() - timers[k]).toFixed(2) + " ms"]);
  186. delete timers[k];
  187. }
  188. return oTimeEnd && oTimeEnd.apply(console, arguments);
  189. };
  190. console.count = function (l) {
  191. var k = key(l);
  192. tallies[k] = (tallies[k] || 0) + 1;
  193. emit("log", [k + ": " + tallies[k]]);
  194. return oCount && oCount.apply(console, arguments);
  195. };
  196. ​
  197. addEventListener("error", function (e) {
  198. var t = e.target;
  199. if (t && t !== window && t.nodeType === 1) {
  200. send({ type: "console", level: "error", kind: "resource", url: clip(t.currentSrc || t.src || t.href || t.tagName.toLowerCase(), 200), group: 0 });
  201. return;
  202. }
  203. send({
  204. type: "console", level: "error", kind: "exception", text: e.message || "", line: e.lineno || 0, col: e.colno || 0,
  205. file: e.filename || "", stack: clip((e.error && e.error.stack) || "", 1500), group: 0
  206. });
  207. }, true);
  208. ​
  209. addEventListener("unhandledrejection", function (e) {
  210. var r = e.reason;
  211. send({
  212. type: "console", level: "error", kind: "exception", text: "Promise: " + ((r && r.message) || fmt(r, 0, [], true)),
  213. line: 0, col: 0, file: "", stack: clip((r && r.stack) || "", 1500), group: 0
  214. });
  215. });
  216. ​
  217. if (window.fetch) {
  218. var oFetch = window.fetch;
  219. window.fetch = function (input, init) {
  220. var method = String((init && init.method) || (input && input.method) || "GET").toUpperCase();
  221. var url = clip(typeof input === "string" ? input : (input && input.url) || String(input), 200);
  222. return oFetch.apply(window, arguments).then(function (res) {
  223. if (!res.ok) send({ type: "console", level: "warn", kind: "http", method: method, url: url, status: res.status, group: 0 });
  224. return res;
  225. }, function (err) {
  226. send({ type: "console", level: "error", kind: "fetch", method: method, url: url, error: String((err && err.message) || err), group: 0 });
  227. throw err;
  228. });
  229. };
  230. }
  231. ​
  232. if (window.XMLHttpRequest) {
  233. var oOpen = XMLHttpRequest.prototype.open, oSend = XMLHttpRequest.prototype.send;
  234. XMLHttpRequest.prototype.open = function (method, url) {
  235. this.__athInfo = { method: String(method).toUpperCase(), url: clip(url, 200) };
  236. return oOpen.apply(this, arguments);
  237. };
  238. XMLHttpRequest.prototype.send = function () {
  239. var x = this, info = x.__athInfo, aborted = false;
  240. if (info) {
  241. x.addEventListener("abort", function () { aborted = true; });
  242. x.addEventListener("loadend", function () {
  243. if (aborted) return;
  244. if (x.status >= 400) send({ type: "console", level: "warn", kind: "http", method: info.method, url: info.url, status: x.status, group: 0 });
  245. else if (x.status === 0) send({ type: "console", level: "error", kind: "fetch", method: info.method, url: info.url, error: "Network error", group: 0 });
  246. });
  247. }
  248. return oSend.apply(this, arguments);
  249. };
  250. }
  251. ​
  252. var ai = (function () {
  253. var hoverStyle = null;
  254. var hovered = [];
  255. var picking = null;
  256. var STYLE_KEYS = ["display", "position", "top", "left", "width", "height", "margin", "padding", "color", "background-color",
  257. "font-family", "font-size", "font-weight", "line-height", "text-align", "overflow", "z-index", "opacity", "visibility",
  258. "flex-direction", "justify-content", "align-items", "gap", "grid-template-columns", "border", "border-radius", "box-shadow"];
  259. ​
  260. function esc(s) {
  261. return window.CSS && CSS.escape ? CSS.escape(s) : String(s).replace(/[^\w-]/g, "\\$&");
  262. }
  263. ​
  264. function selectorOf(el) {
  265. if (!el || el.nodeType !== 1) return "";
  266. if (el.id && document.querySelectorAll("#" + esc(el.id)).length === 1) return "#" + esc(el.id);
  267. var parts = [];
  268. while (el && el.nodeType === 1 && el !== document.documentElement && parts.length < 5) {
  269. if (el.id && document.querySelectorAll("#" + esc(el.id)).length === 1) { parts.unshift("#" + esc(el.id)); break; }
  270. var p = el.tagName.toLowerCase();
  271. var cls = [].slice.call(el.classList || []).filter(function (c) { return c.indexOf("ath-") !== 0; }).slice(0, 2);
  272. if (cls.length) p += "." + cls.map(esc).join(".");
  273. var parent = el.parentElement;
  274. if (parent) {
  275. var same = [].filter.call(parent.children, function (c) { return c.tagName === el.tagName; });
  276. if (same.length > 1) p += ":nth-of-type(" + (same.indexOf(el) + 1) + ")";
  277. }
  278. parts.unshift(p);
  279. el = parent;
  280. }
  281. return parts.join(" > ");
  282. }
  283. ​
  284. function all(selector) {
  285. try { return [].slice.call(document.querySelectorAll(selector)); } catch (e) { throw new Error("Invalid CSS selector: " + selector); }
  286. }
  287. ​
  288. function one(selector) {
  289. if (!selector) throw new Error("A CSS selector is required.");
  290. var list = all(selector);
  291. if (!list.length) throw new Error("No element matches " + selector);
  292. return list[0];
  293. }
  294. ​
  295. function rect(el) {
  296. var r = el.getBoundingClientRect();
  297. return { x: Math.round(r.left + scrollX), y: Math.round(r.top + scrollY), w: Math.round(r.width), h: Math.round(r.height) };
  298. }
  299. ​
  300. function shown(el) {
  301. if (!el.isConnected) return false;
  302. var r = el.getBoundingClientRect();
  303. if (r.width < 1 || r.height < 1) return false;
  304. if (el.checkVisibility && !el.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })) return false;
  305. var c = getComputedStyle(el);
  306. return c.visibility !== "hidden" && +c.opacity > 0.02;
  307. }
  308. ​
  309. function rgba(s) {
  310. var m = /rgba?\(([^)]+)\)/.exec(s || "");
  311. if (!m) return null;
  312. var p = m[1].split(/[\s,/]+/).filter(Boolean).map(parseFloat);
  313. return [p[0], p[1], p[2], p.length > 3 ? p[3] : 1];
  314. }
  315. ​
  316. function background(el) {
  317. while (el && el.nodeType === 1) {
  318. var c = getComputedStyle(el);
  319. if (c.backgroundImage && c.backgroundImage !== "none") return null;
  320. var bg = rgba(c.backgroundColor);
  321. if (bg && bg[3] > 0.95) return bg;
  322. el = el.parentElement;
  323. }
  324. return [255, 255, 255, 1];
  325. }
  326. ​
  327. function luminance(c) {
  328. var v = c.slice(0, 3).map(function (x) {
  329. x /= 255;
  330. return x <= 0.03928 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
  331. });
  332. return 0.2126 * v[0] + 0.7152 * v[1] + 0.0722 * v[2];
  333. }
  334. ​
  335. function contrast(el) {
  336. var fg = rgba(getComputedStyle(el).color);
  337. var bg = background(el);
  338. if (!fg || !bg) return null;
  339. var a = luminance(fg) + 0.05, b = luminance(bg) + 0.05;
  340. return Math.round((Math.max(a, b) / Math.min(a, b)) * 100) / 100;
  341. }
  342. ​
  343. function short(v, n) {
  344. v = String(v == null ? "" : v);
  345. if (/^data:/i.test(v)) return "[inline " + v.slice(5, v.indexOf(";") > 0 ? v.indexOf(";") : 20) + "]";
  346. return v.length > n ? v.slice(0, n) + "…" : v;
  347. }
  348. ​
  349. function textOf(el, n) {
  350. return short((el.innerText || el.textContent || "").replace(/\s+/g, " ").trim(), n || 80);
  351. }
  352. ​
  353. function attrsOf(el) {
  354. var out = {};
  355. [].forEach.call(el.attributes, function (a) {
  356. if (/^on/i.test(a.name) || a.name === "style" && a.value.length > 200) return;
  357. if (/^(id|class|href|src|alt|title|type|name|value|role|for|action|method|placeholder|lang|rel|target|width|height|style|tabindex)$/.test(a.name) || /^(aria|data)-/.test(a.name)) out[a.name] = short(a.value, 160);
  358. });
  359. return out;
  360. }
  361. ​
  362. function stylesOf(el) {
  363. var c = getComputedStyle(el);
  364. var out = {};
  365. STYLE_KEYS.forEach(function (k) { out[k] = c.getPropertyValue(k); });
  366. return out;
  367. }
  368. ​
  369. function describe(el, n) {
  370. var r = el.getBoundingClientRect();
  371. var W = document.documentElement.clientWidth;
  372. return {
  373. selector: selectorOf(el),
  374. tag: el.tagName.toLowerCase(),
  375. attributes: attrsOf(el),
  376. text: textOf(el, n || 160),
  377. box: rect(el),
  378. visible: shown(el),
  379. overflowsViewport: r.right > W + 1 || r.left < -1,
  380. contrast: contrast(el),
  381. styles: stylesOf(el)
  382. };
  383. }
  384. ​
  385. function external(href) {
  386. return /^([a-z][a-z0-9+.-]*:)?\/\//i.test(href || "") || /^(javascript|mailto|tel|data|blob):/i.test(href || "");
  387. }
  388. ​
  389. function line(el, depth) {
  390. var s = new Array(depth + 1).join(" ") + el.tagName.toLowerCase();
  391. if (el.id) s += "#" + el.id;
  392. var cls = [].slice.call(el.classList || []).slice(0, 3);
  393. if (cls.length) s += "." + cls.join(".");
  394. ["href", "src", "alt", "type", "name", "role", "aria-label", "action", "for"].forEach(function (k) {
  395. if (el.hasAttribute(k)) s += " " + k + "=\"" + short(el.getAttribute(k), 50) + "\"";
  396. });
  397. if (/^(H[1-6]|A|BUTTON|LABEL|P|LI|TITLE|SUMMARY|FIGCAPTION|TH|OPTION)$/.test(el.tagName)) {
  398. var t = textOf(el, 70);
  399. if (t) s += " \"" + t + "\"";
  400. }
  401. if (!shown(el)) s += " [hidden]";
  402. return s;
  403. }
  404. ​
  405. function outline(max) {
  406. var KEEP = /^(HEADER|NAV|MAIN|FOOTER|SECTION|ARTICLE|ASIDE|FORM|FIELDSET|H1|H2|H3|H4|H5|H6|A|BUTTON|IMG|PICTURE|VIDEO|IFRAME|INPUT|SELECT|TEXTAREA|LABEL|UL|OL|TABLE|DIALOG|DETAILS|FIGURE|P)$/;
  407. var out = [];
  408. var chars = 0;
  409. var limit = Math.max(1000, Math.min(20000, max || 6000));
  410. var head = document.querySelector("meta[name=viewport]");
  411. out.push("title \"" + short(document.title, 80) + "\" lang=\"" + (document.documentElement.getAttribute("lang") || "") + "\" viewport-meta=" + (head ? "\"" + head.getAttribute("content") + "\"" : "missing"));
  412. function walk(el, depth) {
  413. if (chars > limit || !el || el.nodeType !== 1) return;
  414. if (/^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE|svg|SVG|PATH|LINK|META)$/.test(el.tagName) || el.hasAttribute("data-ath-pick")) return;
  415. var keep = KEEP.test(el.tagName) || el.id || el.hasAttribute("role");
  416. var next = depth;
  417. if (keep) {
  418. var l = line(el, depth);
  419. out.push(l);
  420. chars += l.length + 1;
  421. next = depth + 1;
  422. if (/^(P|A|BUTTON|LABEL|H[1-6])$/.test(el.tagName)) return;
  423. }
  424. for (var c = el.firstElementChild; c; c = c.nextElementSibling) walk(c, next);
  425. }
  426. walk(document.body, 0);
  427. if (chars > limit) out.push("[outline cut]");
  428. return out.join("\n");
  429. }
  430. ​
  431. function labelled(el) {
  432. if (el.getAttribute("aria-label") || el.getAttribute("aria-labelledby") || el.getAttribute("title")) return true;
  433. if (el.id && document.querySelector("label[for=\"" + esc(el.id) + "\"]")) return true;
  434. return !!el.closest("label");
  435. }
  436. ​
  437. function layoutCheck() {
  438. var W = document.documentElement.clientWidth;
  439. var H = innerHeight;
  440. var issues = [];
  441. function add(type, severity, detail, el) {
  442. if (issues.filter(function (i) { return i.type === type; }).length >= 8) return;
  443. var item = { type: type, severity: severity, detail: detail };
  444. if (el) item.selector = selectorOf(el);
  445. issues.push(item);
  446. }
  447. var docW = Math.max(document.documentElement.scrollWidth, document.body ? document.body.scrollWidth : 0);
  448. if (docW > W + 1) {
  449. add("horizontal_overflow", "high", "page is " + docW + "px wide in a " + W + "px viewport");
  450. var els = document.body ? document.body.querySelectorAll("*") : [];
  451. for (var i = 0; i < els.length && i < 4000; i++) {
  452. var e = els[i];
  453. if (!shown(e)) continue;
  454. var r = e.getBoundingClientRect();
  455. var pr = e.parentElement ? e.parentElement.getBoundingClientRect() : { right: 0 };
  456. if (r.right > W + 1 && pr.right <= W + 1 && getComputedStyle(e).position !== "fixed") add("overflow_source", "high", "right edge at " + Math.round(r.right) + "px", e);
  457. }
  458. }
  459. if (!document.querySelector("meta[name=viewport]")) add("missing_viewport_meta", "high", "no <meta name=\"viewport\">");
  460. if (!document.documentElement.getAttribute("lang")) add("missing_lang", "medium", "<html> has no lang attribute");
  461. if (!document.title.trim()) add("missing_title", "medium", "empty <title>");
  462. var h1 = document.querySelectorAll("h1").length;
  463. if (h1 !== 1) add("h1_count", "medium", h1 + " h1 elements");
  464. var last = 0;
  465. [].forEach.call(document.querySelectorAll("h1,h2,h3,h4,h5,h6"), function (h) {
  466. var lvl = +h.tagName[1];
  467. if (last && lvl > last + 1) add("heading_skip", "low", "h" + last + " followed by h" + lvl, h);
  468. last = lvl;
  469. });
  470. [].forEach.call(document.querySelectorAll("img"), function (img) {
  471. if (!img.hasAttribute("alt")) add("img_no_alt", "medium", short(img.getAttribute("src") || "", 60), img);
  472. else if (!img.getAttribute("width") && !img.getAttribute("height") && shown(img) && !img.style.aspectRatio) add("img_no_size", "low", "no width/height (layout shift)", img);
  473. });
  474. [].forEach.call(document.querySelectorAll("a[href], button, [role=button]"), function (el) {
  475. if (!shown(el)) return;
  476. var name = (el.innerText || "").trim() || el.getAttribute("aria-label") || el.getAttribute("title") || (el.querySelector("img[alt]") ? el.querySelector("img[alt]").getAttribute("alt") : "");
  477. if (!name.trim()) add(el.tagName === "A" ? "empty_link" : "empty_button", "medium", "no accessible name", el);
  478. var r = el.getBoundingClientRect();
  479. var inline = el.tagName === "A" && el.closest("p, li, td, dd") && getComputedStyle(el).display === "inline";
  480. if (!inline && (r.width < 24 || r.height < 24)) add("small_tap_target", "medium", Math.round(r.width) + "x" + Math.round(r.height) + "px", el);
  481. });
  482. [].forEach.call(document.querySelectorAll("input, select, textarea"), function (el) {
  483. if (/^(hidden|submit|button|reset|image)$/i.test(el.type || "")) return;
  484. if (!labelled(el)) add("unlabelled_field", "medium", (el.name || el.type || el.tagName.toLowerCase()), el);
  485. });
  486. var checked = 0;
  487. var walker = document.body ? document.body.querySelectorAll("*") : [];
  488. for (var j = 0; j < walker.length && checked < 400; j++) {
  489. var t = walker[j];
  490. if (/^(SCRIPT|STYLE|NOSCRIPT)$/.test(t.tagName)) continue;
  491. var direct = false;
  492. for (var k = t.firstChild; k; k = k.nextSibling) if (k.nodeType === 3 && k.nodeValue.trim()) { direct = true; break; }
  493. if (!direct || !shown(t)) continue;
  494. checked++;
  495. var ratio = contrast(t);
  496. if (ratio == null) continue;
  497. var cs = getComputedStyle(t);
  498. var large = parseFloat(cs.fontSize) >= 24 || (parseFloat(cs.fontSize) >= 18.66 && +cs.fontWeight >= 700);
  499. if (ratio < (large ? 3 : 4.5)) add("low_contrast", "medium", "ratio " + ratio + " (" + cs.color + " on background)", t);
  500. }
  501. [].forEach.call(document.querySelectorAll("body *"), function (el) {
  502. if (issues.filter(function (i) { return i.type === "offscreen"; }).length >= 5) return;
  503. var c = getComputedStyle(el);
  504. if (c.position !== "absolute" && c.position !== "fixed") return;
  505. var r = el.getBoundingClientRect();
  506. if (r.width > 4 && r.height > 4 && r.right > 0 && r.left < 0 && shown(el)) add("offscreen", "low", "partly left of the viewport", el);
  507. });
  508. return { viewport: { w: W, h: H }, documentWidth: docW, issues: issues };
  509. }
  510. ​
  511. function setValue(el, value) {
  512. var proto = Object.getPrototypeOf(el);
  513. var desc = Object.getOwnPropertyDescriptor(proto, "value");
  514. if (desc && desc.set) desc.set.call(el, value);
  515. else el.value = value;
  516. el.dispatchEvent(new Event("input", { bubbles: true }));
  517. el.dispatchEvent(new Event("change", { bubbles: true }));
  518. }
  519. ​
  520. function clearHover() {
  521. hovered.forEach(function (el) { el.removeAttribute("data-ath-hover"); });
  522. hovered = [];
  523. }
  524. ​
  525. function buildHoverStyle() {
  526. if (hoverStyle) return hoverStyle.count;
  527. var rules = [];
  528. function scan(list, wrap) {
  529. [].forEach.call(list || [], function (r) {
  530. if (r.selectorText && r.selectorText.indexOf(":hover") >= 0) {
  531. rules.push(wrap(r.selectorText.replace(/:hover/g, "[data-ath-hover]") + "{" + r.style.cssText + "}"));
  532. } else if (r.cssRules && r.media) {
  533. scan(r.cssRules, function (inner) { return wrap("@media " + r.media.mediaText + "{" + inner + "}"); });
  534. }
  535. });
  536. }
  537. [].forEach.call(document.styleSheets, function (sheet) {
  538. try { scan(sheet.cssRules, function (x) { return x; }); } catch (e) { }
  539. });
  540. hoverStyle = document.createElement("style");
  541. hoverStyle.setAttribute("data-ath-pick", "");
  542. hoverStyle.textContent = rules.join("\n");
  543. hoverStyle.count = rules.length;
  544. (document.head || document.documentElement).appendChild(hoverStyle);
  545. return rules.length;
  546. }
  547. ​
  548. function screenshot(opts) {
  549. return new Promise(function (resolve, reject) {
  550. var W = document.documentElement.clientWidth;
  551. var full = !!opts.fullPage;
  552. var docH = Math.min(Math.max(document.documentElement.scrollHeight, innerHeight), 12000);
  553. var H = full ? docH : innerHeight;
  554. var clone = document.documentElement.cloneNode(true);
  555. var src = document.querySelectorAll("input, textarea, select");
  556. var dst = clone.querySelectorAll("input, textarea, select");
  557. for (var i = 0; i < src.length && i < dst.length; i++) {
  558. var s = src[i], d = dst[i];
  559. if (s.tagName === "TEXTAREA") d.textContent = s.value;
  560. else if (s.tagName === "SELECT") [].forEach.call(d.options, function (o, j) { if (s.options[j] && s.options[j].selected) o.setAttribute("selected", ""); else o.removeAttribute("selected"); });
  561. else if (/^(checkbox|radio)$/i.test(s.type)) { if (s.checked) d.setAttribute("checked", ""); else d.removeAttribute("checked"); }
  562. else d.setAttribute("value", s.value);
  563. }
  564. var cs = document.querySelectorAll("canvas");
  565. var cd = clone.querySelectorAll("canvas");
  566. for (var c = 0; c < cs.length && c < cd.length; c++) {
  567. try {
  568. var img = document.createElement("img");
  569. img.src = cs[c].toDataURL();
  570. img.setAttribute("style", "width:" + cs[c].offsetWidth + "px;height:" + cs[c].offsetHeight + "px");
  571. cd[c].parentNode.replaceChild(img, cd[c]);
  572. } catch (e) { }
  573. }
  574. [].forEach.call(clone.querySelectorAll("script, noscript, iframe, [data-ath-pick]:not(style)"), function (n) { n.parentNode.removeChild(n); });
  575. var xml = new XMLSerializer().serializeToString(clone);
  576. var svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"" + W + "\" height=\"" + H + "\"><foreignObject x=\"0\" y=\"" + (full ? 0 : -scrollY) + "\" width=\"" + W + "\" height=\"" + docH + "\">" + xml + "</foreignObject></svg>";
  577. var image = new Image();
  578. image.onload = function () {
  579. try {
  580. var scale = Math.min(1, (opts.maxWidth || 1024) / W);
  581. var canvas = document.createElement("canvas");
  582. canvas.width = Math.max(1, Math.round(W * scale));
  583. canvas.height = Math.max(1, Math.round(H * scale));
  584. var g = canvas.getContext("2d");
  585. var bg = getComputedStyle(document.body || document.documentElement).backgroundColor;
  586. g.fillStyle = !rgba(bg) || rgba(bg)[3] === 0 ? "#ffffff" : bg;
  587. g.fillRect(0, 0, canvas.width, canvas.height);
  588. g.drawImage(image, 0, 0, canvas.width, canvas.height);
  589. var url = canvas.toDataURL("image/png");
  590. var mime = "image/png";
  591. if (url.length > 1800000) { url = canvas.toDataURL("image/jpeg", 0.82); mime = "image/jpeg"; }
  592. resolve({ mime: mime, data: url.slice(url.indexOf(",") + 1), width: canvas.width, height: canvas.height, scale: Math.round(scale * 100) / 100 });
  593. } catch (e) {
  594. reject(new Error("Screenshot failed: " + e.message));
  595. }
  596. };
  597. image.onerror = function () { reject(new Error("Screenshot failed: the page could not be rendered.")); };
  598. image.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);
  599. });
  600. }
  601. ​
  602. function info(el) {
  603. var d = describe(el, 300);
  604. d.outerHTML = short(el.outerHTML.replace(/data:[^"')\s]{40,}/g, "[inline]"), 3000);
  605. d.classes = [].slice.call(el.classList || []);
  606. d.id = el.id || "";
  607. return d;
  608. }
  609. ​
  610. function pick() {
  611. if (picking) return { picking: true };
  612. var boxEl = document.createElement("div");
  613. boxEl.setAttribute("data-ath-pick", "");
  614. boxEl.style.cssText = "position:fixed;pointer-events:none;z-index:2147483647;border:2px solid #2563eb;background:rgba(37,99,235,.12);border-radius:3px;left:0;top:0;width:0;height:0";
  615. var tip = document.createElement("div");
  616. tip.setAttribute("data-ath-pick", "");
  617. tip.style.cssText = "position:fixed;pointer-events:none;z-index:2147483647;font:12px/1.4 system-ui,sans-serif;background:#1e293b;color:#fff;padding:2px 6px;border-radius:4px;max-width:80vw;white-space:nowrap;overflow:hidden;text-overflow:ellipsis";
  618. document.documentElement.appendChild(boxEl);
  619. document.documentElement.appendChild(tip);
  620. var target = null;
  621. function move(e) {
  622. var el = e.target;
  623. if (!el || el.nodeType !== 1 || el.hasAttribute("data-ath-pick")) return;
  624. target = el;
  625. var r = el.getBoundingClientRect();
  626. boxEl.style.left = r.left + "px";
  627. boxEl.style.top = r.top + "px";
  628. boxEl.style.width = r.width + "px";
  629. boxEl.style.height = r.height + "px";
  630. tip.textContent = selectorOf(el) + " " + Math.round(r.width) + "×" + Math.round(r.height);
  631. tip.style.left = Math.max(0, r.left) + "px";
  632. tip.style.top = (r.top > 24 ? r.top - 22 : r.bottom + 4) + "px";
  633. }
  634. function block(e) {
  635. e.preventDefault();
  636. e.stopPropagation();
  637. e.stopImmediatePropagation();
  638. }
  639. function click(e) {
  640. block(e);
  641. var el = e.target && e.target.nodeType === 1 ? e.target : target;
  642. stop();
  643. send({ type: "ai-picked", info: el ? info(el) : null });
  644. }
  645. function key(e) {
  646. if (e.key !== "Escape") return;
  647. block(e);
  648. stop();
  649. send({ type: "ai-picked", info: null });
  650. }
  651. function stop() {
  652. removeEventListener("mousemove", move, true);
  653. removeEventListener("click", click, true);
  654. removeEventListener("mousedown", block, true);
  655. removeEventListener("pointerdown", block, true);
  656. removeEventListener("mouseup", block, true);
  657. removeEventListener("keydown", key, true);
  658. if (boxEl.parentNode) boxEl.parentNode.removeChild(boxEl);
  659. if (tip.parentNode) tip.parentNode.removeChild(tip);
  660. picking = null;
  661. }
  662. addEventListener("mousemove", move, true);
  663. addEventListener("click", click, true);
  664. addEventListener("mousedown", block, true);
  665. addEventListener("pointerdown", block, true);
  666. addEventListener("mouseup", block, true);
  667. addEventListener("keydown", key, true);
  668. picking = { stop: stop };
  669. return { picking: true };
  670. }
  671. ​
  672. function act(action, a) {
  673. var el;
  674. switch (action) {
  675. case "state":
  676. return {
  677. title: document.title,
  678. lang: document.documentElement.getAttribute("lang") || "",
  679. viewport: { w: document.documentElement.clientWidth, h: innerHeight },
  680. scroll: { x: Math.round(scrollX), y: Math.round(scrollY), max: Math.max(0, document.documentElement.scrollHeight - innerHeight) },
  681. documentHeight: document.documentElement.scrollHeight,
  682. readyState: document.readyState,
  683. focused: document.activeElement && document.activeElement !== document.body ? selectorOf(document.activeElement) : "",
  684. hovered: hovered.length ? selectorOf(hovered[0]) : ""
  685. };
  686. case "outline":
  687. return outline(a.max);
  688. case "inspect":
  689. var list = all(a.selector);
  690. return { count: list.length, items: list.slice(0, Math.max(1, Math.min(10, a.max || 5))).map(function (x) { return describe(x); }) };
  691. case "layout_check":
  692. return layoutCheck();
  693. case "screenshot":
  694. return screenshot(a);
  695. case "scroll":
  696. if (a.selector) one(a.selector).scrollIntoView({ block: "center" });
  697. else scrollTo(0, Math.max(0, +a.y || 0));
  698. return { y: Math.round(scrollY) };
  699. case "click":
  700. el = one(a.selector);
  701. var link = el.closest("a[href]");
  702. if (link && external(link.getAttribute("href"))) throw new Error("Refused: the link leads outside the project (" + short(link.getAttribute("href"), 80) + ").");
  703. var form = el.closest("form");
  704. if (form && /^(submit|image)$/i.test(el.type || (el.tagName === "BUTTON" ? "submit" : "")) && external(form.getAttribute("action"))) throw new Error("Refused: the form is sent outside the project.");
  705. el.scrollIntoView({ block: "center" });
  706. el.click();
  707. return { clicked: selectorOf(el), tag: el.tagName.toLowerCase(), navigates: !!link || !!form };
  708. case "type":
  709. el = one(a.selector);
  710. el.focus();
  711. if (el.isContentEditable) {
  712. el.textContent = String(a.text == null ? "" : a.text);
  713. el.dispatchEvent(new Event("input", { bubbles: true }));
  714. } else if ("value" in el) {
  715. setValue(el, (a.append ? el.value : "") + String(a.text == null ? "" : a.text));
  716. } else {
  717. throw new Error("The element cannot receive text.");
  718. }
  719. return { typed: selectorOf(el), value: short(el.value != null ? el.value : el.textContent, 120) };
  720. case "select":
  721. el = one(a.selector);
  722. if (el.tagName !== "SELECT") throw new Error("The element is not a <select>.");
  723. var opt = [].find.call(el.options, function (o) { return o.value === String(a.value); }) || [].find.call(el.options, function (o) { return o.text.trim() === String(a.value).trim(); });
  724. if (!opt) throw new Error("No option with value or label " + a.value);
  725. setValue(el, opt.value);
  726. return { selected: opt.value, label: opt.text };
  727. case "hover":
  728. clearHover();
  729. if (!a.selector) return { hovered: "" };
  730. el = one(a.selector);
  731. var rules = buildHoverStyle();
  732. for (var n = el; n && n.nodeType === 1; n = n.parentElement) {
  733. n.setAttribute("data-ath-hover", "");
  734. hovered.push(n);
  735. }
  736. ["pointerover", "pointerenter", "mouseover", "mouseenter", "mousemove"].forEach(function (type) {
  737. el.dispatchEvent(new MouseEvent(type, { bubbles: type.indexOf("enter") < 0, cancelable: true }));
  738. });
  739. return { hovered: selectorOf(el), simulatedHoverRules: rules };
  740. case "focus":
  741. el = one(a.selector);
  742. el.focus();
  743. return { focused: selectorOf(el), active: document.activeElement === el };
  744. case "pick":
  745. return pick();
  746. case "pick_cancel":
  747. if (picking) picking.stop();
  748. return { picking: false };
  749. default:
  750. throw new Error("Unknown action " + action);
  751. }
  752. }
  753. ​
  754. return { act: act };
  755. })();
  756. ​
  757. addEventListener("message", function (e) {
  758. var d = e.data;
  759. if (e.source !== parent || !d || d.__athera !== B || d.type !== "ai") return;
  760. Promise.resolve().then(function () { return ai.act(String(d.action), d.args || {}); }).then(function (result) {
  761. send({ type: "ai-result", id: d.id, ok: true, result: result });
  762. }, function (err) {
  763. send({ type: "ai-result", id: d.id, ok: false, error: String((err && err.message) || err) });
  764. });
  765. });
  766. ​
  767. addEventListener("message", function (e) {
  768. var d = e.data;
  769. if (e.source !== parent || !d || d.__athera !== B || d.type !== "eval") return;
  770. try {
  771. var r = (0, eval)(d.code);
  772. send({ type: "console", level: "result", text: fmt(r, 0, [], false), group: 0 });
  773. } catch (err) {
  774. send({ type: "console", level: "error", kind: "eval", text: err && err.message ? (err.name || "Error") + ": " + err.message : String(err), group: 0 });
  775. }
  776. });
  777. }
  778. ​
  779. var FRAME = /(athera-src\/[^\s:()]+|[^\s()@]+):(\d+):(\d+)\)?\s*$/;
  780. var PHP_ERR = /<b>(Warning|Notice|Deprecated|Fatal error|Parse error|Strict Standards|Recoverable fatal error)<\/b>:\s+([\s\S]*?) in <b>([^<]+)<\/b> on line <b>(\d+)<\/b>/g;
  781. var PHP_LOG = /^PHP (Warning|Notice|Deprecated|Fatal error|Parse error|Strict Standards|Recoverable fatal error):\s+([\s\S]*?) in (\S+) on line (\d+)/;
  782. ​
  783. var DEVICES = [
  784. { group: "preview.device_mobile", items: [
  785. ["iPhone SE", 375, 667, "iphone", 2], ["iPhone 16", 393, 852, "iphone", 3], ["iPhone 16 Pro Max", 440, 956, "iphone", 3],
  786. ["Pixel 9", 412, 915, "android", 2.625, "Pixel 9"], ["Pixel 9 Pro", 412, 915, "android", 2.625, "Pixel 9 Pro"],
  787. ["Pixel 10", 412, 915, "android", 2.625, "Pixel 10"], ["Samsung Galaxy A55", 412, 892, "android", 2.625, "SM-A556B"]
  788. ] },
  789. { group: "preview.device_foldables", items: [
  790. ["Pixel 9 Pro Fold", 791, 820, "android", 2.625, "Pixel 9 Pro Fold"], ["Galaxy Z Fold 6", 773, 900, "android", 2.4, "SM-F956B"]
  791. ] },
  792. { group: "preview.device_tablets", items: [
  793. ["iPad Mini", 744, 1133, "ipad", 2], ["iPad Pro 13", 1032, 1376, "ipad", 2], ["Surface Pro 10", 912, 1368, "windows", 2]
  794. ] },
  795. { group: "preview.device_displays", items: [
  796. ["Nest Hub Max", 1280, 800, "hub", 1]
  797. ] }
  798. ];
  799. ​
  800. var CHROME = "Chrome/130.0.0.0";
  801. ​
  802. function profileOf(d) {
  803. if (!d) return null;
  804. var kind = d[3], model = d[5] || "";
  805. if (kind === "iphone") {
  806. return { ua: "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1",
  807. platform: "iPhone", vendor: "Apple Computer, Inc.", touch: 5, dpr: d[4], ch: false, mobile: true, os: "iOS" };
  808. }
  809. if (kind === "ipad") {
  810. return { ua: "Mozilla/5.0 (iPad; CPU OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1",
  811. platform: "iPad", vendor: "Apple Computer, Inc.", touch: 5, dpr: d[4], ch: false, mobile: false, os: "iOS" };
  812. }
  813. if (kind === "android") {
  814. return { ua: "Mozilla/5.0 (Linux; Android 15; " + model + ") AppleWebKit/537.36 (KHTML, like Gecko) " + CHROME + " Mobile Safari/537.36",
  815. platform: "Linux armv81", vendor: "Google Inc.", touch: 5, dpr: d[4], ch: true, mobile: true, os: "Android" };
  816. }
  817. if (kind === "windows") {
  818. return { ua: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " + CHROME + " Safari/537.36",
  819. platform: "Win32", vendor: "Google Inc.", touch: 10, dpr: d[4], ch: true, mobile: false, os: "Windows" };
  820. }
  821. return { ua: "Mozilla/5.0 (Linux; Android 12; Nest Hub Max) AppleWebKit/537.36 (KHTML, like Gecko) " + CHROME + " Safari/537.36 CrKey/1.56.500000",
  822. platform: "Linux armv8l", vendor: "Google Inc.", touch: 10, dpr: d[4], ch: true, mobile: false, os: "Android" };
  823. }
  824. ​
  825. function profileScript(p) {
  826. var json = JSON.stringify(p).replace(/</g, "\\u003c");
  827. return "(function(p){function d(o,k,v){try{Object.defineProperty(o,k,{get:function(){return v},configurable:true})}catch(e){}}" +
  828. "d(navigator,'userAgent',p.ua);d(navigator,'appVersion',p.ua.replace(/^Mozilla\\//,''));d(navigator,'platform',p.platform);" +
  829. "d(navigator,'vendor',p.vendor);d(navigator,'maxTouchPoints',p.touch);" +
  830. "d(navigator,'userAgentData',p.ch?{mobile:p.mobile,platform:p.os,brands:[{brand:'Chromium',version:'130'}],getHighEntropyValues:function(){return Promise.resolve({})}}:undefined);" +
  831. "d(window,'devicePixelRatio',p.dpr);if(p.touch&&!('ontouchstart' in window))d(window,'ontouchstart',null);" +
  832. "})(" + json + ");\n";
  833. }
  834. ​
  835. var deviceName = A.store.get("previewDevice", null);
  836. var override = null;
  837. var ready = { id: 0, ready: false };
  838. var rotated = !!A.store.get("previewRotated", false);
  839. var deviceBox = null;
  840. var deviceLabel = null;
  841. var deviceBtn = null;
  842. ​
  843. function findDevice(name) {
  844. for (var g = 0; g < DEVICES.length; g++) {
  845. for (var i = 0; i < DEVICES[g].items.length; i++) {
  846. if (DEVICES[g].items[i][0] === name) return DEVICES[g].items[i];
  847. }
  848. }
  849. return null;
  850. }
  851. ​
  852. function deviceSize() {
  853. if (override) return { w: override.w, h: override.h, name: override.name };
  854. var d = findDevice(deviceName);
  855. if (!d) return null;
  856. return rotated ? { w: d[2], h: d[1], name: d[0] } : { w: d[1], h: d[2], name: d[0] };
  857. }
  858. ​
  859. function fitDevice() {
  860. var size = deviceSize();
  861. if (!size || !deviceBox) return;
  862. var box = deviceBox.getBoundingClientRect();
  863. if (box.width < 40 || box.height < 40) return;
  864. var s = Math.min(1, (box.width - 24) / size.w, (box.height - 44) / size.h);
  865. s = Math.max(0.1, s);
  866. pv.frame.style.setProperty("--ath-device-scale", s.toFixed(4));
  867. deviceLabel.textContent = size.name + " · " + size.w + " × " + size.h + (s < 1 ? " · " + Math.round(s * 100) + "%" : "");
  868. }
  869. ​
  870. function applyDevice() {
  871. var size = deviceSize();
  872. deviceBox.classList.toggle("is-device", !!size);
  873. deviceLabel.hidden = !size;
  874. deviceBtn.classList.toggle("is-active", !!size);
  875. if (size) {
  876. pv.frame.style.width = size.w + "px";
  877. pv.frame.style.height = size.h + "px";
  878. fitDevice();
  879. } else {
  880. pv.frame.style.width = "";
  881. pv.frame.style.height = "";
  882. pv.frame.style.removeProperty("--ath-device-scale");
  883. }
  884. renderDeviceMenu();
  885. }
  886. ​
  887. function pickDevice(name) {
  888. deviceName = name;
  889. override = null;
  890. A.store.set("previewDevice", name);
  891. applyDevice();
  892. A.emit("preview-viewport", { by: "user", size: deviceSize() });
  893. if (pv.open) pv.build();
  894. }
  895. ​
  896. function renderDeviceMenu() {
  897. var menu = document.getElementById("device-menu");
  898. if (!menu) return;
  899. menu.innerHTML = "";
  900. ​
  901. var list = util.el("div", { class: "ath-device-list" });
  902. menu.appendChild(list);
  903. ​
  904. function item(label, active, size, onClick, icon, target, disabled) {
  905. var node = util.el("button", {
  906. type: "button",
  907. class: "orb-dropdown-item ath-device-item" + (active ? " is-current" : ""),
  908. role: "menuitemradio",
  909. "aria-checked": active ? "true" : "false",
  910. disabled: disabled ? true : null,
  911. html: (active ? A.icon("check") : icon ? A.icon(icon) : '<span class="ath-device-ph"></span>') +
  912. "<span>" + util.esc(label) + "</span>" + (size ? '<span class="ath-device-size">' + util.esc(size) + "</span>" : "")
  913. });
  914. node.addEventListener("click", onClick);
  915. (target || list).appendChild(node);
  916. }
  917. ​
  918. item(A.t("preview.device_default"), !deviceName, "", function () { pickDevice(null); });
  919. DEVICES.forEach(function (g) {
  920. list.appendChild(util.el("div", { class: "ath-accent-label" }, A.t(g.group)));
  921. g.items.forEach(function (d) {
  922. item(d[0], d[0] === deviceName, d[1] + " × " + d[2], function () { pickDevice(d[0]); });
  923. });
  924. });
  925. menu.appendChild(util.el("div", { class: "orb-dropdown-divider" }));
  926. item(A.t("preview.device_rotate"), false, "", function () {
  927. rotated = !rotated;
  928. A.store.set("previewRotated", rotated);
  929. applyDevice();
  930. A.emit("preview-viewport", { by: "user", size: deviceSize() });
  931. }, "redo", menu, !deviceName);
  932. }
  933. ​
  934. var RETRY_DELAYS = [2000, 5000, 10000];
  935. var READY_WAIT = 5000;
  936. var retry = { n: 0, timer: 0, wait: 0, ok: false, problem: false, expect: false, kind: "" };
  937. var lastFailure = null;
  938. ​
  939. function stopRetry() {
  940. clearTimeout(retry.timer);
  941. clearTimeout(retry.wait);
  942. retry.timer = 0;
  943. retry.wait = 0;
  944. }
  945. ​
  946. function isBlankHtml(html) {
  947. var h = String(html || "").replace(/<style[\s\S]*?<\/style>/gi, "");
  948. var text = h.replace(/<[^>]*>/g, "").replace(/&nbsp;|\s/g, "");
  949. return !text && !/<(img|canvas|svg|video|audio|iframe|input|object|embed|textarea|select|button|script)\b/i.test(h);
  950. }
  951. ​
  952. function scheduleRetry(kind, tab, text) {
  953. stopRetry();
  954. retry.kind = kind;
  955. if (retry.n >= RETRY_DELAYS.length) {
  956. showLoading(false);
  957. if (kind === "paint") A.console.add({ level: "warn", text: text, source: "js", group: 0 });
  958. if (kind !== "php" && kind !== "paint") {
  959. pv.frame.hidden = false;
  960. pv.frame.srcdoc = messagePage(A.t("preview.failed_title"), text + "\n\n" + A.t("preview.failed_hint"));
  961. }
  962. return;
  963. }
  964. var ms = RETRY_DELAYS[retry.n];
  965. showLoading(true, A.t("preview.retrying", { s: ms / 1000, n: retry.n + 1, total: RETRY_DELAYS.length }));
  966. retry.timer = setTimeout(function () {
  967. retry.timer = 0;
  968. showLoading(false);
  969. if (!pv.open || pv.target !== tab || (retry.ok && kind !== "paint")) return;
  970. retry.n++;
  971. if (kind === "php" && retry.n >= 2 && A.php) A.php.restart();
  972. pv.buildOnce();
  973. }, ms);
  974. }
  975. ​
  976. var extraErrors = [];
  977. var phpFound = [];
  978. var phpUsed = false;
  979. ​
  980. var pv = (A.preview = {
  981. open: false,
  982. target: null,
  983. scroll: {},
  984. routes: {},
  985. pathRoutes: {},
  986. errors: [],
  987. scripts: [],
  988. lastHtml: "",
  989. ​
  990. init: function (pane) {
  991. pv.pane = pane;
  992. pv.frame = pane.querySelector("iframe");
  993. pv.titleEl = pane.querySelector("[data-preview-title]");
  994. pv.statusEl = pane.querySelector("[data-preview-status]");
  995. pv.emptyEl = pane.querySelector("[data-preview-empty]");
  996. ​
  997. pv.loadingEl = util.el("div", { class: "ath-preview-loading", hidden: true }, [
  998. util.el("span", { class: "ath-spinner" }),
  999. util.el("span", {}, "")
  1000. ]);
  1001. deviceBox = pane.querySelector(".ath-preview-body");
  1002. deviceBox.appendChild(pv.loadingEl);
  1003. deviceLabel = util.el("div", { class: "ath-device-label", hidden: true });
  1004. deviceBox.appendChild(deviceLabel);
  1005. deviceBtn = pane.querySelector("[data-preview-device]");
  1006. if (!findDevice(deviceName)) deviceName = null;
  1007. applyDevice();
  1008. if (window.ResizeObserver) new ResizeObserver(fitDevice).observe(deviceBox);
  1009. A.on("lang", renderDeviceMenu);
  1010. A.console.init(pane.querySelector("[data-console]"), { jump: jumpTo, evaluate: evalInPage });
  1011. pane.querySelector("[data-preview-refresh]").addEventListener("click", function () {
  1012. dataCache.clear();
  1013. if (A.php) A.php.rescan();
  1014. if (pv.target && pv.routes[pv.target.id]) pv.routes[pv.target.id] = { query: pv.routes[pv.target.id].query || "" };
  1015. pv.build();
  1016. });
  1017. A.on("settings", function (keys) { if (pv.open && (keys.indexOf("phpRuntime") >= 0 || keys.indexOf("mysqlEmulation") >= 0)) pv.build(); });
  1018. pane.querySelector("[data-preview-window]").addEventListener("click", pv.openWindow);
  1019. pv.statusEl.addEventListener("click", function () { A.console.setOpen(true); });
  1020. ​
  1021. var later = util.debounce(function () { pv.build(); }, 350);
  1022. A.on("doc-change", function () { if (pv.open && pv.target && A.settings.get("livePreview")) later(); });
  1023. A.on("saved", function () { if (pv.open) later(); });
  1024. A.on("active-change", function (tab) {
  1025. if (tab && pv.canPreview(tab.name)) pv.target = tab;
  1026. if (pv.target && A.tabs.list.indexOf(pv.target) < 0) pv.target = null;
  1027. if (pv.open) pv.build();
  1028. });
  1029. A.on("workspace", function () { dataCache.clear(); });
  1030. A.on("lang", function () { if (pv.open) pv.build(); });
  1031. window.addEventListener("message", onMessage);
  1032. },
  1033. ​
  1034. userAgent: function () {
  1035. var prof = profileOf(findDevice(deviceName));
  1036. return prof ? prof.ua : "";
  1037. },
  1038. ​
  1039. canPreview: function (name) {
  1040. return PREVIEWABLE.indexOf(util.ext(name)) >= 0;
  1041. },
  1042. ​
  1043. setOpen: function (open) {
  1044. pv.open = open;
  1045. document.body.classList.toggle("ath-no-preview", !open);
  1046. A.store.set("preview", open);
  1047. if (open) {
  1048. var t = A.tabs.active;
  1049. if (t && pv.canPreview(t.name)) pv.target = t;
  1050. pv.build();
  1051. } else {
  1052. stopRetry();
  1053. showLoading(false);
  1054. pv.frame.removeAttribute("srcdoc");
  1055. pv.frame.hidden = true;
  1056. }
  1057. A.emit("preview-toggle", open);
  1058. },
  1059. ​
  1060. toggle: function () {
  1061. pv.setOpen(!pv.open);
  1062. },
  1063. ​
  1064. build: function () {
  1065. stopRetry();
  1066. retry.n = 0;
  1067. showLoading(false);
  1068. return pv.buildOnce();
  1069. },
  1070. ​
  1071. buildOnce: async function () {
  1072. var id = ++buildId;
  1073. retry.ok = false;
  1074. retry.problem = false;
  1075. clearTimeout(retry.wait);
  1076. var tab = pv.target;
  1077. if (tab && A.tabs.list.indexOf(tab) < 0) tab = pv.target = null;
  1078. if (!tab) {
  1079. stopRetry();
  1080. showLoading(false);
  1081. pv.errors = [];
  1082. pv.scripts = [];
  1083. A.console.reset();
  1084. A.console.setVisible(false);
  1085. renderStatus();
  1086. pv.titleEl.textContent = A.t("preview.title");
  1087. pv.emptyEl.hidden = false;
  1088. pv.frame.hidden = true;
  1089. pv.lastHtml = "";
  1090. return;
  1091. }
  1092. var html = null, problem = null;
  1093. try {
  1094. html = await render(tab);
  1095. } catch (e) {
  1096. problem = { kind: "error", text: (e && e.message) || String(e) };
  1097. html = messagePage(A.t("preview.failed_title"), problem.text);
  1098. }
  1099. if (id !== buildId || html == null) return;
  1100. if (!problem && lastFailure) problem = { kind: "php", text: lastFailure };
  1101. if (!problem && phpUsed && isBlankHtml(html)) problem = { kind: "blank", text: A.t("preview.blank") };
  1102. retry.problem = !!problem;
  1103. retry.expect = !problem && !isBlankHtml(html);
  1104. pv.errors = extraErrors.slice();
  1105. var gone = [];
  1106. missing.forEach(function (p) {
  1107. var text = A.t("preview.missing", { path: p });
  1108. pv.errors.push(text);
  1109. gone.push({ level: "error", text: text, source: "js", group: 0 });
  1110. });
  1111. renderStatus();
  1112. var route = pv.routes[tab.id];
  1113. pv.titleEl.textContent = tab.name + (phpUsed && route && route.query ? "?" + route.query : "");
  1114. if (phpUsed && A.php.version) pv.titleEl.setAttribute("data-badge", "PHP " + A.php.version.split(".").slice(0, 2).join("."));
  1115. else pv.titleEl.removeAttribute("data-badge");
  1116. pv.emptyEl.hidden = true;
  1117. pv.frame.hidden = false;
  1118. pv.lastHtml = html;
  1119. var doc = injectHelper(html, Math.round(pv.scroll[tab.id] || 0), id);
  1120. pv.scripts = scanScripts(doc);
  1121. A.console.reset();
  1122. A.console.setVisible(true);
  1123. A.console.addMany(phpFound.concat(gone));
  1124. if (retry.n > 0) {
  1125. pv.frame.hidden = true;
  1126. void pv.frame.offsetWidth;
  1127. pv.frame.hidden = false;
  1128. }
  1129. pv.frame.srcdoc = doc;
  1130. ready = { id: id, ready: false };
  1131. A.emit("preview-build", { id: id, target: tab.path != null ? tab.path : tab.name });
  1132. if (problem) {
  1133. scheduleRetry(problem.kind, tab, problem.text);
  1134. } else {
  1135. retry.wait = setTimeout(function () {
  1136. if (id === buildId && !retry.ok) scheduleRetry("load", tab, A.t("preview.not_ready"));
  1137. }, READY_WAIT);
  1138. }
  1139. },
  1140. ​
  1141. buildId: function () {
  1142. return buildId;
  1143. },
  1144. ​
  1145. status: function () {
  1146. return { id: ready.id, ready: ready.ready && ready.id === buildId, building: ready.id !== buildId, target: pv.target ? (pv.target.path != null ? pv.target.path : pv.target.name) : null, route: pv.target ? pv.routes[pv.target.id] || null : null, open: pv.open };
  1147. },
  1148. ​
  1149. missing: function () {
  1150. return Array.from(missing);
  1151. },
  1152. ​
  1153. post: function (msg) {
  1154. if (!pv.frame || pv.frame.hidden || !pv.frame.contentWindow) return false;
  1155. pv.frame.contentWindow.postMessage(Object.assign({}, msg, { __athera: buildId }), "*");
  1156. return true;
  1157. },
  1158. ​
  1159. frameSize: function () {
  1160. var size = deviceSize();
  1161. if (size) return { w: size.w, h: size.h, name: size.name, device: true };
  1162. var r = pv.frame ? pv.frame.getBoundingClientRect() : { width: 0, height: 0 };
  1163. return { w: Math.round(r.width), h: Math.round(r.height), name: "", device: false };
  1164. },
  1165. ​
  1166. setViewport: function (w, h, name) {
  1167. override = { w: Math.round(w), h: Math.round(h), name: name || "" };
  1168. applyDevice();
  1169. A.emit("preview-viewport", { by: "ai", size: deviceSize() });
  1170. return deviceSize();
  1171. },
  1172. ​
  1173. clearViewport: function () {
  1174. if (!override) return;
  1175. override = null;
  1176. applyDevice();
  1177. A.emit("preview-viewport", { by: "ai", size: deviceSize() });
  1178. },
  1179. ​
  1180. hasViewportOverride: function () {
  1181. return !!override;
  1182. },
  1183. ​
  1184. openRoute: async function (path, query, method, body) {
  1185. var route = { query: query || "", method: method || "GET", body: body || "" };
  1186. if (!pv.open) pv.setOpen(true);
  1187. var tab = A.tabs.byPath(path);
  1188. if (tab && tab === pv.target) {
  1189. pv.routes[tab.id] = route;
  1190. return pv.build();
  1191. }
  1192. pv.pathRoutes[path] = route;
  1193. tab = await A.tabs.openPath(path, { focusEditor: false });
  1194. if (tab && pv.target !== tab && pv.canPreview(tab.name)) {
  1195. pv.target = tab;
  1196. pv.build();
  1197. }
  1198. return tab;
  1199. },
  1200. ​
  1201. openWindow: function () {
  1202. if (!pv.lastHtml) return;
  1203. var url = URL.createObjectURL(new Blob([pv.lastHtml], { type: "text/html" }));
  1204. window.open(url, "_blank");
  1205. setTimeout(function () { URL.revokeObjectURL(url); }, 60000);
  1206. }
  1207. });
  1208. ​
  1209. function header(headers, name) {
  1210. var v = headers && headers[name];
  1211. return v ? [].concat(v)[0] : "";
  1212. }
  1213. ​
  1214. function scriptDir(tab) {
  1215. return tab.path != null ? util.dirname(tab.path) : "";
  1216. }
  1217. ​
  1218. function showLoading(on, text) {
  1219. pv.loadingEl.hidden = !on;
  1220. pv.loadingEl.lastChild.textContent = text || A.t("php.loading");
  1221. }
  1222. ​
  1223. function messagePage(title, text) {
  1224. return "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>body{font:14px/1.6 system-ui,sans-serif;margin:0;padding:32px;color:#0f172a}" +
  1225. "h1{font-size:18px;margin:0 0 8px}pre{white-space:pre-wrap;background:#f1f5f9;padding:12px;border-radius:8px;font-size:12.5px}</style></head><body>" +
  1226. "<h1>" + util.esc(title) + "</h1>" + (text ? "<pre>" + util.esc(text) + "</pre>" : "") + "</body></html>";
  1227. }
  1228. ​
  1229. function usesPhpRuntime(tab) {
  1230. return /^(php|phtml)$/.test(util.ext(tab.name)) && A.settings.get("phpRuntime");
  1231. }
  1232. ​
  1233. async function runPhp(tab, depth) {
  1234. if (tab.path != null && pv.pathRoutes[tab.path]) {
  1235. pv.routes[tab.id] = pv.pathRoutes[tab.path];
  1236. delete pv.pathRoutes[tab.path];
  1237. }
  1238. var route = pv.routes[tab.id] || {};
  1239. if (!A.php.isReady()) showLoading(true);
  1240. var res;
  1241. try {
  1242. res = await A.php.run(tab, route, function (done, total) {
  1243. showLoading(true, A.t("php.syncing", { done: done, total: total }));
  1244. });
  1245. } catch (e) {
  1246. showLoading(false);
  1247. lastFailure = e.message;
  1248. return messagePage(A.t("php.failed_title"), e.message);
  1249. }
  1250. showLoading(false);
  1251. if (route.method === "POST") pv.routes[tab.id] = { query: route.query || "" };
  1252. phpFound = phpDiagnostics(res);
  1253. phpFound.forEach(function (e) {
  1254. if (e.level === "error") extraErrors.push("PHP: " + e.text + (e.label ? " (" + e.label + ")" : ""));
  1255. });
  1256. var location = header(res.headers, "location");
  1257. if (res.status >= 300 && res.status < 400 && location) {
  1258. if (/^([a-z]+:)?\/\//i.test(location)) return messagePage(A.t("php.redirect_external", { url: location }), "");
  1259. if ((depth || 0) >= 5) return messagePage(A.t("php.redirect_loop"), location);
  1260. var moved = navigate(tab, location, "GET", "", true);
  1261. if (moved === "same") return runPhp(tab, (depth || 0) + 1);
  1262. return moved === "other" ? null : messagePage(A.t("php.redirect_missing", { url: location }), "");
  1263. }
  1264. var type = header(res.headers, "content-type");
  1265. if (type && !/html/i.test(type)) {
  1266. return "<!DOCTYPE html><html><head><meta charset=\"utf-8\"></head><body><pre style=\"white-space:pre-wrap;font:12.5px/1.5 monospace;margin:16px\">" +
  1267. util.esc(res.html) + "</pre></body></html>";
  1268. }
  1269. return res.html;
  1270. }
  1271. ​
  1272. function navigate(fromTab, href, method, body, internal) {
  1273. var clean = href.split("#")[0];
  1274. var qi = clean.indexOf("?");
  1275. var pathPart = qi >= 0 ? clean.slice(0, qi) : clean;
  1276. var query = qi >= 0 ? clean.slice(qi + 1) : "";
  1277. var target = pathPart ? util.resolve(scriptDir(fromTab), pathPart) : fromTab.path;
  1278. var route = { query: query, method: method || "GET", body: body || "" };
  1279. if (!pathPart || target === fromTab.path) {
  1280. pv.routes[fromTab.id] = route;
  1281. if (!internal) pv.build();
  1282. return "same";
  1283. }
  1284. if (!target || !pv.canPreview(target) || !fs.provider) return "none";
  1285. pv.pathRoutes[target] = route;
  1286. fs.provider.exists(target).then(function (ok) {
  1287. if (ok) A.tabs.openPath(target);
  1288. else A.ui.toast(A.t("preview.page_not_found", { path: target }), "warning");
  1289. });
  1290. return "other";
  1291. }
  1292. ​
  1293. async function render(tab) {
  1294. var src = A.tabs.textOf(tab);
  1295. var ext = util.ext(tab.name);
  1296. missing.clear();
  1297. lastFailure = null;
  1298. extraErrors = [];
  1299. phpFound = [];
  1300. phpUsed = false;
  1301. if (usesPhpRuntime(tab)) {
  1302. phpUsed = true;
  1303. src = await runPhp(tab, 0);
  1304. if (src == null) return null;
  1305. } else if (ext === "php" || ext === "phtml") {
  1306. src = stripPhp(src);
  1307. }
  1308. if (ext === "svg") return src;
  1309. var hasDoctype = /^\s*<!doctype/i.test(src);
  1310. var doc = new DOMParser().parseFromString(src, "text/html");
  1311. if (tab.path != null && fs.provider) {
  1312. try { await inlineAssets(doc, util.dirname(tab.path)); } catch (e) { console.warn(e); }
  1313. }
  1314. return (hasDoctype ? "<!DOCTYPE html>\n" : "") + doc.documentElement.outerHTML;
  1315. }
  1316. ​
  1317. function injectHelper(html, y, id) {
  1318. var prof = profileOf(findDevice(deviceName));
  1319. var tag = "<script>" + (prof ? profileScript(prof) : "") + HELPER.replace("__Y__", String(y)).replace("__B__", String(id)) +
  1320. "\n(" + pageHook.toString() + ")(" + id + ");\n//# sourceURL=athera-hook</script>";
  1321. var m = /<head(\s[^>]*)?>/i.exec(html);
  1322. if (m) return html.slice(0, m.index + m[0].length) + tag + html.slice(m.index + m[0].length);
  1323. return tag + html;
  1324. }
  1325. ​
  1326. function stripPhp(src) {
  1327. var vars = {};
  1328. var STR = /^\s*(["'])((?:\\.|(?!\1)[^\\])*)\1\s*;?\s*$/;
  1329. function unquote(s) { return s.replace(/\\(.)/g, "$1"); }
  1330. function echo(expr) {
  1331. var v = /^\s*(htmlspecialchars\s*\(\s*)?\$(\w+)\s*\)?\s*;?\s*$/.exec(expr);
  1332. if (v && Object.prototype.hasOwnProperty.call(vars, v[2])) return v[1] ? util.esc(vars[v[2]]) : vars[v[2]];
  1333. var s = STR.exec(expr);
  1334. return s ? unquote(s[2]) : "⟨php⟩";
  1335. }
  1336. return src.replace(/<\?(=|php\b)?([\s\S]*?)(\?>|$)/gi, function (all, kind, code) {
  1337. if (kind === "=") return echo(code);
  1338. code.replace(/\$(\w+)\s*=\s*(["'])((?:\\.|(?!\2)[^\\])*)\2\s*;/g, function (m, name, q, val) {
  1339. vars[name] = unquote(val);
  1340. });
  1341. var e = /^\s*echo\s+([\s\S]*?)\s*$/i.exec(code);
  1342. return e ? echo(e[1]) : "";
  1343. });
  1344. }
  1345. ​
  1346. async function readText(path) {
  1347. var live = A.tabs.contentOf(path);
  1348. if (live != null) return live;
  1349. try { return await fs.provider.readText(path); } catch (e) { missing.add(path); return null; }
  1350. }
  1351. ​
  1352. async function dataUrl(path) {
  1353. var live = A.tabs.contentOf(path);
  1354. if (live != null) return "data:" + fs.mime(path) + ";charset=utf-8," + encodeURIComponent(live);
  1355. var file;
  1356. try { file = await fs.provider.readFile(path); } catch (e) { missing.add(path); return null; }
  1357. var stamp = file.lastModified + ":" + file.size;
  1358. var hit = dataCache.get(path);
  1359. if (hit && hit.stamp === stamp) return hit.url;
  1360. var url = await new Promise(function (resolve) {
  1361. var r = new FileReader();
  1362. r.onload = function () { resolve(r.result); };
  1363. r.onerror = function () { resolve(null); };
  1364. r.readAsDataURL(new Blob([file], { type: fs.mime(path) }));
  1365. });
  1366. if (url) dataCache.set(path, { stamp: stamp, url: url });
  1367. return url;
  1368. }
  1369. ​
  1370. async function rewriteCss(css, baseDir) {
  1371. var re = /url\(\s*(['"]?)([^'")]+)\1\s*\)/gi, m, jobs = [];
  1372. while ((m = re.exec(css))) {
  1373. var p = util.resolve(baseDir, m[2]);
  1374. if (p && !/^data:/i.test(m[2].trim())) jobs.push({ text: m[0], path: p });
  1375. }
  1376. for (var j of jobs) {
  1377. var url = (await dataUrl(j.path)) || "data:,";
  1378. css = css.split(j.text).join('url("' + url + '")');
  1379. }
  1380. return css;
  1381. }
  1382. ​
  1383. async function rewriteSrcset(value, dir) {
  1384. var parts = value.split(",");
  1385. for (var i = 0; i < parts.length; i++) {
  1386. var bits = parts[i].trim().split(/\s+/);
  1387. var p = util.resolve(dir, bits[0]);
  1388. if (p) bits[0] = (await dataUrl(p)) || "data:,";
  1389. parts[i] = bits.join(" ");
  1390. }
  1391. return parts.join(", ");
  1392. }
  1393. ​
  1394. async function inlineAssets(doc, dir) {
  1395. for (var link of doc.querySelectorAll('link[rel~="stylesheet"][href]')) {
  1396. var cssPath = util.resolve(dir, link.getAttribute("href"));
  1397. if (!cssPath) continue;
  1398. var css = await readText(cssPath);
  1399. if (css == null) { link.removeAttribute("href"); continue; }
  1400. var style = doc.createElement("style");
  1401. if (link.media) style.media = link.media;
  1402. style.setAttribute("data-ath-href", link.getAttribute("href"));
  1403. style.textContent = await rewriteCss(css, util.dirname(cssPath));
  1404. link.replaceWith(style);
  1405. }
  1406. ​
  1407. for (var script of doc.querySelectorAll("script[src]")) {
  1408. var jsPath = util.resolve(dir, script.getAttribute("src"));
  1409. if (!jsPath) continue;
  1410. var js = await readText(jsPath);
  1411. if (js == null) { script.removeAttribute("src"); continue; }
  1412. var s = doc.createElement("script");
  1413. for (var attr of script.attributes) if (attr.name !== "src") s.setAttribute(attr.name, attr.value);
  1414. s.setAttribute("data-ath-src", script.getAttribute("src"));
  1415. s.setAttribute("data-ath-path", jsPath);
  1416. s.textContent = js.replace(/<\/script/gi, "<\\/script") + (isJsType(script.getAttribute("type")) ? "\n//# sourceURL=" + sourceName(jsPath) : "");
  1417. script.replaceWith(s);
  1418. }
  1419. ​
  1420. var mediaAttrs = [["img", "src"], ["source", "src"], ["video", "src"], ["video", "poster"], ["audio", "src"],
  1421. ["track", "src"], ["embed", "src"], ["input", "src"], ["object", "data"], ['link[rel~="icon"]', "href"]];
  1422. for (var pair of mediaAttrs) {
  1423. for (var node of doc.querySelectorAll(pair[0] + "[" + pair[1] + "]")) {
  1424. var p = util.resolve(dir, node.getAttribute(pair[1]));
  1425. if (!p) continue;
  1426. var url = await dataUrl(p);
  1427. if (url) node.setAttribute(pair[1], url);
  1428. else node.removeAttribute(pair[1]);
  1429. }
  1430. }
  1431. for (var n of doc.querySelectorAll("img[srcset], source[srcset]")) {
  1432. n.setAttribute("srcset", await rewriteSrcset(n.getAttribute("srcset"), dir));
  1433. }
  1434. for (var st of doc.querySelectorAll("style")) {
  1435. if (!st.hasAttribute("data-ath-href")) st.textContent = await rewriteCss(st.textContent, dir);
  1436. }
  1437. for (var el of doc.querySelectorAll("[style]")) {
  1438. var v = el.getAttribute("style");
  1439. if (/url\(/i.test(v)) el.setAttribute("style", await rewriteCss(v, dir));
  1440. }
  1441. }
  1442. ​
  1443. function onMessage(e) {
  1444. if (!pv.frame || e.source !== pv.frame.contentWindow || !e.data || e.data.__athera !== buildId) return;
  1445. var d = e.data;
  1446. if (d.type === "scroll" && pv.target) pv.scroll[pv.target.id] = d.y;
  1447. if (d.type === "ready") {
  1448. ready = { id: buildId, ready: true };
  1449. A.emit("preview-ready", { id: buildId });
  1450. }
  1451. if (d.type === "ai-result" || d.type === "ai-picked") A.emit("preview-ai", d);
  1452. if (d.type === "ready" && !retry.problem) {
  1453. retry.ok = true;
  1454. if (retry.kind !== "paint") {
  1455. stopRetry();
  1456. showLoading(false);
  1457. }
  1458. }
  1459. if (d.type === "painted" && !retry.problem && d.blank && retry.expect && pv.target) {
  1460. scheduleRetry("paint", pv.target, A.t("preview.blank_render"));
  1461. }
  1462. if (d.type === "console-clear") A.console.reset();
  1463. if (d.type === "console") {
  1464. var entry = toEntry(d);
  1465. if (entry.level === "error" && d.kind !== "eval") {
  1466. pv.errors.push(entry.text + (entry.label ? " (" + entry.label + ")" : ""));
  1467. renderStatus();
  1468. }
  1469. A.console.add(entry);
  1470. A.emit("preview-console", entry);
  1471. }
  1472. if (d.type === "nav" && pv.target) {
  1473. A.emit("preview-nav", { href: d.href, method: "GET" });
  1474. navigate(pv.target, d.href, "GET", "");
  1475. }
  1476. if (d.type === "submit" && pv.target) {
  1477. A.emit("preview-nav", { href: d.action, method: d.method });
  1478. if (d.method === "POST") navigate(pv.target, d.action, "POST", d.data);
  1479. else navigate(pv.target, d.action.split("?")[0] + "?" + d.data, "GET", "");
  1480. }
  1481. }
  1482. ​
  1483. function renderStatus() {
  1484. var n = pv.errors.length;
  1485. pv.statusEl.hidden = !n;
  1486. pv.statusEl.innerHTML = n ? A.icon("warning") + "<span>" + util.esc(A.tn("preview.problems", n)) + "</span>" : "";
  1487. pv.statusEl.title = pv.errors.join("\n");
  1488. }
  1489. ​
  1490. function isJsType(type) {
  1491. return !type || /^(module|(text|application)\/(x-)?(javascript|ecmascript))$/i.test(String(type).trim());
  1492. }
  1493. ​
  1494. function sourceName(path) {
  1495. return "athera-src/" + encodeURI(path).replace(/[()]/g, function (c) { return "%" + c.charCodeAt(0).toString(16).toUpperCase(); });
  1496. }
  1497. ​
  1498. function unattr(v) {
  1499. return v.replace(/&quot;/g, "\"").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&");
  1500. }
  1501. ​
  1502. function scanScripts(doc) {
  1503. var out = [], re = /<script\b[^>]*\bdata-ath-path="([^"]*)"[^>]*>/gi, m;
  1504. while ((m = re.exec(doc))) {
  1505. var start = m.index + m[0].length;
  1506. var stop = doc.indexOf("</script", start);
  1507. if (stop < 0) stop = doc.length;
  1508. var before = doc.slice(0, start);
  1509. var first = before.split("\n").length;
  1510. out.push({
  1511. path: unattr(m[1]),
  1512. start: first,
  1513. end: first + doc.slice(start, stop).split("\n").length - 1,
  1514. col0: start - (before.lastIndexOf("\n") + 1)
  1515. });
  1516. }
  1517. return out;
  1518. }
  1519. ​
  1520. function frameOf(stack) {
  1521. var lines = String(stack || "").split("\n");
  1522. for (var i = 0; i < lines.length; i++) {
  1523. if (lines[i].indexOf("athera-hook") >= 0) continue;
  1524. var m = FRAME.exec(lines[i]);
  1525. if (m) return { file: m[1], line: +m[2], col: +m[3] };
  1526. }
  1527. return null;
  1528. }
  1529. ​
  1530. function scriptAt(line) {
  1531. for (var i = 0; i < pv.scripts.length; i++) {
  1532. if (line >= pv.scripts[i].start && line <= pv.scripts[i].end) return pv.scripts[i];
  1533. }
  1534. return null;
  1535. }
  1536. ​
  1537. function mapScript(hit, path, line, col) {
  1538. var rel = hit ? line - hit.start + 1 : line;
  1539. if (rel < 1) rel = 1;
  1540. var c = col || 1;
  1541. if (hit && rel === 1) c = Math.max(1, c - hit.col0);
  1542. return { path: path, line: rel, col: c, label: util.basename(path) + ":" + rel };
  1543. }
  1544. ​
  1545. function locate(d) {
  1546. var f = frameOf(d.stack);
  1547. var file = f ? f.file : (d.file || "");
  1548. var line = f ? f.line : (d.line || 0);
  1549. var col = f ? f.col : (d.col || 0);
  1550. var named = /athera-src\/([^\s:()]+)/.exec(file);
  1551. if (named) {
  1552. var path = file;
  1553. try { path = decodeURIComponent(named[1]); } catch (e) { path = named[1]; }
  1554. var mine = pv.scripts.filter(function (s) { return s.path === path; });
  1555. var hit = null;
  1556. for (var i = 0; i < mine.length; i++) if (line >= mine[i].start && line <= mine[i].end) hit = mine[i];
  1557. return mapScript(hit, path, line, col);
  1558. }
  1559. if (!line) return null;
  1560. var inside = scriptAt(line);
  1561. if (inside) return mapScript(inside, inside.path, line, col);
  1562. return { label: A.t("console.page") + ":" + line };
  1563. }
  1564. ​
  1565. function toEntry(d) {
  1566. var text = d.text || "";
  1567. if (d.kind === "resource") text = A.t("console.resource_failed", { url: d.url });
  1568. else if (d.kind === "http") text = A.t("console.http_status", { method: d.method, url: d.url, status: d.status });
  1569. else if (d.kind === "fetch") text = A.t("console.fetch_failed", { method: d.method, url: d.url, error: d.error });
  1570. else if (d.kind === "assert") text = A.t("console.assert") + (text ? ": " + text : "");
  1571. var entry = { level: d.level || "log", text: text || A.t("preview.error"), source: "js", group: d.group || 0, kind: d.kind };
  1572. var where = d.level === "result" || d.kind === "eval" ? null : locate(d);
  1573. if (where) {
  1574. entry.label = where.label;
  1575. if (where.path) {
  1576. entry.path = where.path;
  1577. entry.line = where.line;
  1578. entry.col = where.col;
  1579. }
  1580. }
  1581. return entry;
  1582. }
  1583. ​
  1584. function decodeHtml(s) {
  1585. var box = document.createElement("textarea");
  1586. box.innerHTML = s.replace(/<[^>]*>/g, "");
  1587. return box.value.replace(/\s+$/, "");
  1588. }
  1589. ​
  1590. function phpLocation(file, line) {
  1591. var label = util.basename(file) + ":" + line;
  1592. if (file.indexOf("/www/") !== 0) return { label: label };
  1593. var path = file.slice(5);
  1594. if (path.indexOf("__untitled/") === 0) return { path: "", line: +line, col: 1, label: pv.target ? pv.target.name + ":" + line : label };
  1595. return { path: path, line: +line, col: 1, label: label };
  1596. }
  1597. ​
  1598. function phpEntry(kind, message, file, line) {
  1599. var where = phpLocation(file, line);
  1600. return {
  1601. level: /^(Warning|Notice|Deprecated|Strict Standards)$/.test(kind) ? "warn" : "error",
  1602. text: kind + ": " + message,
  1603. source: "php",
  1604. group: 0,
  1605. path: where.path,
  1606. line: where.line,
  1607. col: where.col,
  1608. label: where.label
  1609. };
  1610. }
  1611. ​
  1612. function phpDiagnostics(res) {
  1613. var out = [], m;
  1614. var html = String(res.html || "");
  1615. PHP_ERR.lastIndex = 0;
  1616. while ((m = PHP_ERR.exec(html)) && out.length < 100) out.push(phpEntry(m[1], decodeHtml(m[2]), decodeHtml(m[3]), m[4]));
  1617. String(res.errors || "").trim().split("\n").slice(0, 50).forEach(function (row) {
  1618. if (!row.trim()) return;
  1619. var g = PHP_LOG.exec(row);
  1620. if (g) out.push(phpEntry(g[1], g[2], g[3], g[4]));
  1621. else out.push({ level: "info", text: row, source: "php", group: 0 });
  1622. });
  1623. return out;
  1624. }
  1625. ​
  1626. async function jumpTo(path, line, col) {
  1627. var target = path;
  1628. if (path === "") {
  1629. if (!pv.target) return;
  1630. target = pv.target.path;
  1631. if (target == null) {
  1632. A.tabs.activate(pv.target);
  1633. requestAnimationFrame(function () { requestAnimationFrame(function () { A.editor.goTo(line, col); }); });
  1634. return;
  1635. }
  1636. }
  1637. var tab = await A.tabs.openPath(target);
  1638. if (!tab || tab.kind !== "text") return;
  1639. requestAnimationFrame(function () { requestAnimationFrame(function () { A.editor.goTo(line, col); }); });
  1640. }
  1641. ​
  1642. function evalInPage(code) {
  1643. if (!pv.frame || pv.frame.hidden || !pv.frame.contentWindow) return false;
  1644. pv.frame.contentWindow.postMessage({ __athera: buildId, type: "eval", code: code }, "*");
  1645. return true;
  1646. }
  1647. })();
  1648. ​