docs.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /*
  2. AGI docs behaviour: theme, navigation drawer, code block tools, the
  3. "On this page" highlight and the search palette.
  4. */
  5. (function () {
  6. "use strict";
  7. var doc = document.documentElement;
  8. var body = document.body;
  9. var ROOT = body.getAttribute("data-root") || "";
  10. var isMac = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
  11. function $(sel, el) { return (el || document).querySelector(sel); }
  12. function $$(sel, el) { return Array.prototype.slice.call((el || document).querySelectorAll(sel)); }
  13. // ---------- toast ----------
  14. var toastEl = null, toastTimer = 0;
  15. function toast(msg) {
  16. if (!toastEl) {
  17. toastEl = document.createElement("div");
  18. toastEl.className = "toast";
  19. toastEl.setAttribute("role", "status");
  20. body.appendChild(toastEl);
  21. }
  22. toastEl.textContent = msg;
  23. toastEl.classList.add("show");
  24. clearTimeout(toastTimer);
  25. toastTimer = setTimeout(function () { toastEl.classList.remove("show"); }, 1600);
  26. }
  27. window.AGIDocs = { toast: toast };
  28. function copyText(text) {
  29. var done = function () { toast("Copied to the clipboard"); };
  30. if (navigator.clipboard && window.isSecureContext) {
  31. navigator.clipboard.writeText(text).then(done, function () { fallbackCopy(text); done(); });
  32. } else {
  33. fallbackCopy(text);
  34. done();
  35. }
  36. }
  37. function fallbackCopy(text) {
  38. var ta = document.createElement("textarea");
  39. ta.value = text;
  40. ta.style.position = "fixed";
  41. ta.style.opacity = "0";
  42. body.appendChild(ta);
  43. ta.select();
  44. try { document.execCommand("copy"); } catch (e) { /* nothing more to try */ }
  45. body.removeChild(ta);
  46. }
  47. window.AGIDocs.copy = copyText;
  48. // ---------- theme ----------
  49. var media = window.matchMedia("(prefers-color-scheme: dark)");
  50. function applyTheme(pref) {
  51. doc.setAttribute("data-theme-pref", pref);
  52. doc.setAttribute("data-theme", pref === "auto" ? (media.matches ? "dark" : "light") : pref);
  53. $$("[data-theme-set]").forEach(function (b) {
  54. b.setAttribute("aria-checked", b.getAttribute("data-theme-set") === pref ? "true" : "false");
  55. });
  56. document.dispatchEvent(new CustomEvent("agi-theme"));
  57. }
  58. applyTheme(doc.getAttribute("data-theme-pref") || "auto");
  59. media.addEventListener("change", function () {
  60. if (doc.getAttribute("data-theme-pref") === "auto") applyTheme("auto");
  61. });
  62. $$("[data-theme-set]").forEach(function (b) {
  63. b.addEventListener("click", function () {
  64. var pref = b.getAttribute("data-theme-set");
  65. try { localStorage.setItem("aroz-theme", pref); } catch (e) { /* private mode */ }
  66. applyTheme(pref);
  67. closePops();
  68. });
  69. });
  70. // ---------- pop menus ----------
  71. function closePops(except) {
  72. $$("[data-pop].open").forEach(function (p) {
  73. if (p !== except) {
  74. p.classList.remove("open");
  75. var b = p.querySelector("button");
  76. if (b) b.setAttribute("aria-expanded", "false");
  77. }
  78. });
  79. }
  80. $$("[data-pop]").forEach(function (p) {
  81. var btn = p.querySelector("button");
  82. btn.addEventListener("click", function (e) {
  83. e.stopPropagation();
  84. var open = !p.classList.contains("open");
  85. closePops(p);
  86. p.classList.toggle("open", open);
  87. btn.setAttribute("aria-expanded", open ? "true" : "false");
  88. });
  89. });
  90. document.addEventListener("click", function () { closePops(); });
  91. // ---------- header and drawer ----------
  92. var top = $("#top");
  93. if (top && doc.classList.contains("kind-home")) {
  94. var onScroll = function () { top.classList.toggle("scrolled", window.scrollY > 8); };
  95. window.addEventListener("scroll", onScroll, { passive: true });
  96. onScroll();
  97. }
  98. var sideBtn = $(".side-btn");
  99. function setSide(open) {
  100. doc.classList.toggle("side-open", open);
  101. if (sideBtn) sideBtn.setAttribute("aria-expanded", open ? "true" : "false");
  102. }
  103. if (sideBtn) sideBtn.addEventListener("click", function () { setSide(!doc.classList.contains("side-open")); });
  104. $$("[data-side-close]").forEach(function (el) { el.addEventListener("click", function () { setSide(false); }); });
  105. var current = $(".side a[aria-current]");
  106. if (current) current.scrollIntoView({ block: "center" });
  107. $$("[data-kbd]").forEach(function (k) { k.textContent = isMac ? "⌘K" : "Ctrl K"; });
  108. $$("[data-copy]").forEach(function (b) {
  109. b.addEventListener("click", function () { copyText(b.getAttribute("data-copy")); });
  110. });
  111. // ---------- code blocks ----------
  112. function encodeCode(code) {
  113. var b = btoa(unescape(encodeURIComponent(code)));
  114. return b.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
  115. }
  116. window.AGIDocs.encodeCode = encodeCode;
  117. var playIcon = '<svg class="i" viewBox="0 0 24 24" aria-hidden="true" fill="currentColor"><path d="M8 5.6v12.8c0 .8.9 1.3 1.6.9l10.2-6.4c.6-.4.6-1.3 0-1.7L9.6 4.8C8.9 4.3 8 4.8 8 5.6z"/></svg>';
  118. var copyIcon = '<svg class="i" viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="11" height="11" rx="2.5"/><path d="M5.5 15H5a1.5 1.5 0 0 1-1.5-1.5V5A1.5 1.5 0 0 1 5 3.5h8.5A1.5 1.5 0 0 1 15 5v.5"/></svg>';
  119. $$("pre > code").forEach(function (code) {
  120. var pre = code.parentNode;
  121. if (pre.closest(".pg")) return;
  122. var m = /language-(\w+)/.exec(code.className);
  123. var lang = m ? m[1] : "";
  124. var src = code.textContent;
  125. if (window.AGIHL && lang) code.innerHTML = window.AGIHL.highlight(src, lang);
  126. var box = document.createElement("div");
  127. box.className = "code-box";
  128. pre.parentNode.insertBefore(box, pre);
  129. box.appendChild(pre);
  130. var tools = document.createElement("div");
  131. tools.className = "code-tools";
  132. var isJS = lang === "javascript" || lang === "js";
  133. if (isJS) {
  134. var run = document.createElement("a");
  135. run.className = "run";
  136. run.href = ROOT + "playground.html#code=" + encodeCode(src);
  137. run.innerHTML = playIcon + "<span>Run</span>";
  138. run.title = "Open this code in the playground";
  139. tools.appendChild(run);
  140. }
  141. var cp = document.createElement("button");
  142. cp.type = "button";
  143. cp.innerHTML = copyIcon + "<span>Copy</span>";
  144. cp.addEventListener("click", function () { copyText(src); });
  145. tools.appendChild(cp);
  146. box.appendChild(tools);
  147. });
  148. $$(".prose table").forEach(function (t) {
  149. if (t.parentNode.classList.contains("table-wrap")) return;
  150. var w = document.createElement("div");
  151. w.className = "table-wrap";
  152. t.parentNode.insertBefore(w, t);
  153. w.appendChild(t);
  154. });
  155. // ---------- "On this page" ----------
  156. var tocLinks = $$("[data-toc]");
  157. if (tocLinks.length && "IntersectionObserver" in window) {
  158. var targets = tocLinks.map(function (a) { return document.getElementById(a.getAttribute("data-toc")); }).filter(Boolean);
  159. var visible = {};
  160. var setOn = function (id) {
  161. tocLinks.forEach(function (a) { a.classList.toggle("on", a.getAttribute("data-toc") === id); });
  162. var on = $(".toc a.on");
  163. var box = $(".toc");
  164. if (on && box) {
  165. var r = on.getBoundingClientRect(), br = box.getBoundingClientRect();
  166. if (r.top < br.top + 40 || r.bottom > br.bottom - 40) box.scrollTop += r.top - br.top - br.height / 2;
  167. }
  168. };
  169. var io = new IntersectionObserver(function (entries) {
  170. entries.forEach(function (e) { visible[e.target.id] = e.isIntersecting; });
  171. for (var i = 0; i < targets.length; i++) {
  172. if (visible[targets[i].id]) { setOn(targets[i].id); return; }
  173. }
  174. }, { rootMargin: "-64px 0px -60% 0px" });
  175. targets.forEach(function (t) { io.observe(t); });
  176. }
  177. // Briefly outline the function card a link pointed to.
  178. function flashTarget() {
  179. var id = decodeURIComponent(location.hash.slice(1));
  180. if (!id) return;
  181. var el = document.getElementById(id);
  182. if (!el) return;
  183. var card = el.classList.contains("fn") ? el : el.closest(".fn");
  184. if (!card) return;
  185. card.classList.add("flash");
  186. setTimeout(function () { card.classList.remove("flash"); }, 1400);
  187. }
  188. window.addEventListener("hashchange", flashTarget);
  189. flashTarget();
  190. // ---------- search ----------
  191. var search = $("#search"), q = $("#search-q"), res = $("#search-res");
  192. var index = null, loading = false, hits = [], sel = 0, lastFocus = null;
  193. if (res) res.setAttribute("data-empty", "Type to search functions, libraries and guides.");
  194. function loadIndex() {
  195. if (index || loading) return;
  196. loading = true;
  197. fetch(ROOT + "search.json?v=" + body.getAttribute("data-ver"))
  198. .then(function (r) { return r.json(); })
  199. .then(function (data) { index = data; loading = false; runSearch(); })
  200. .catch(function () {
  201. loading = false;
  202. res.setAttribute("data-empty", "The search index could not be loaded.");
  203. });
  204. }
  205. function openSearch() {
  206. if (!search) return;
  207. lastFocus = document.activeElement;
  208. search.hidden = false;
  209. body.classList.add("noscroll");
  210. q.value = "";
  211. runSearch();
  212. loadIndex();
  213. setTimeout(function () { q.focus(); }, 0);
  214. }
  215. function closeSearch() {
  216. if (!search || search.hidden) return;
  217. search.hidden = true;
  218. body.classList.remove("noscroll");
  219. if (lastFocus && lastFocus.focus) lastFocus.focus();
  220. }
  221. window.AGIDocs.openSearch = openSearch;
  222. function score(e, terms, whole) {
  223. var t = e.t.toLowerCase();
  224. var short = t.slice(t.lastIndexOf(".") + 1);
  225. var s = 0;
  226. if (t === whole || short === whole) s = 100;
  227. else if (t.indexOf(whole) === 0 || short.indexOf(whole) === 0) s = 80;
  228. else if (t.indexOf(whole) >= 0) s = 60;
  229. else {
  230. var hay = (t + " " + e.s + " " + (e.d || "")).toLowerCase();
  231. for (var i = 0; i < terms.length; i++) {
  232. if (hay.indexOf(terms[i]) < 0) return 0;
  233. }
  234. s = t.indexOf(terms[0]) >= 0 ? 35 : 15;
  235. }
  236. if (e.k === "page") s += 6;
  237. if (e.k === "fn") s += 3;
  238. return s - t.length / 100;
  239. }
  240. function mark(text, whole) {
  241. var i = text.toLowerCase().indexOf(whole);
  242. var E = window.AGIHL ? window.AGIHL.escape : function (x) { return x; };
  243. if (!whole || i < 0) return E(text);
  244. return E(text.slice(0, i)) + "<mark>" + E(text.slice(i, i + whole.length)) + "</mark>" + E(text.slice(i + whole.length));
  245. }
  246. function runSearch() {
  247. if (!res) return;
  248. var whole = q.value.trim().toLowerCase();
  249. hits = [];
  250. if (whole && index) {
  251. var terms = whole.split(/\s+/);
  252. index.forEach(function (e) {
  253. var sc = score(e, terms, whole);
  254. if (sc > 0) hits.push({ e: e, s: sc });
  255. });
  256. hits.sort(function (a, b) { return b.s - a.s; });
  257. hits = hits.slice(0, 40);
  258. }
  259. if (whole && index && !hits.length) res.setAttribute("data-empty", "Nothing matches “" + q.value.trim() + "”.");
  260. else if (!index && whole) res.setAttribute("data-empty", "Loading the index…");
  261. else res.setAttribute("data-empty", "Type to search functions, libraries and guides.");
  262. sel = 0;
  263. res.innerHTML = hits.map(function (h, i) {
  264. var e = h.e;
  265. var k = e.k === "fn" ? "fn" : e.k === "section" ? "#" : "doc";
  266. var label = e.k === "fn" ? "f" : e.k === "section" ? "#" : "¶";
  267. return '<li role="option"><a href="' + ROOT + e.u + '" data-i="' + i + '" aria-selected="' + (i === 0) + '">' +
  268. '<span class="k ' + k + '">' + label + "</span>" +
  269. '<span class="t' + (e.k === "fn" ? " mono" : "") + '">' + mark(e.t, whole) + "</span>" +
  270. '<span class="s">' + mark(e.s + (e.d ? " · " + e.d : ""), "") + "</span></a></li>";
  271. }).join("");
  272. }
  273. function move(d) {
  274. var items = $$("a", res);
  275. if (!items.length) return;
  276. sel = (sel + d + items.length) % items.length;
  277. items.forEach(function (a, i) { a.setAttribute("aria-selected", i === sel ? "true" : "false"); });
  278. items[sel].scrollIntoView({ block: "nearest" });
  279. }
  280. if (search) {
  281. q.addEventListener("input", runSearch);
  282. q.addEventListener("keydown", function (e) {
  283. if (e.key === "ArrowDown") { e.preventDefault(); move(1); }
  284. else if (e.key === "ArrowUp") { e.preventDefault(); move(-1); }
  285. else if (e.key === "Enter") {
  286. var a = $$("a", res)[sel];
  287. if (a) { e.preventDefault(); closeSearch(); location.href = a.href; }
  288. }
  289. });
  290. search.addEventListener("click", function (e) {
  291. if (e.target === search) closeSearch();
  292. var a = e.target.closest && e.target.closest("a");
  293. if (a) closeSearch();
  294. });
  295. $$("[data-search-open]").forEach(function (b) {
  296. b.addEventListener("click", function (e) { e.stopPropagation(); openSearch(); });
  297. });
  298. }
  299. document.addEventListener("keydown", function (e) {
  300. var typing = /INPUT|TEXTAREA|SELECT/.test((e.target && e.target.tagName) || "") || (e.target && e.target.isContentEditable);
  301. if ((e.ctrlKey || e.metaKey) && (e.key === "k" || e.key === "K")) {
  302. e.preventDefault();
  303. if (search && search.hidden) openSearch(); else closeSearch();
  304. } else if (e.key === "/" && !typing && search && search.hidden) {
  305. e.preventDefault();
  306. openSearch();
  307. } else if (e.key === "Escape") {
  308. closeSearch();
  309. closePops();
  310. setSide(false);
  311. }
  312. });
  313. })();