site: the docs can be searched, in each language (WeltAn_X on X)
WeltAn_X on X: "文档站建议加入搜索功能". A search button in the docs' nav (in the contents bar under 900px), / or Cmd/Ctrl+K, opens a dialog that finds in the browser: docs-search.js, loaded on first use, reads /search/<lang>.json once (en, zh, ja; search-index.mjs builds them from the pages, by section, with the nav's name for each page). Nothing typed leaves the page; no third-party host. Every term must be found; a heading counts most, then the page's title, then the text; three sections a page at most. Arrows or Ctrl+N/P, Enter (this page's section closes the dialog and jumps), Escape gives focus back. A 120ms fade in, no movement, nothing under reduced motion; the site's card colour, no accent. search.test.mjs fails while a committed index differs from what search-index.mjs builds, or misses a page, as llms-full's does. search.browser.mjs (not *.test.mjs, so CI's node --test leaves it out) drives it in real browsers. Found on the way: ja's nav made the page 2px too wide at 320px (on main too); .btn.small takes less padding under 360px. Run at this head, on mica: - node --test site/*.test.mjs: 126/126. - node site/search.browser.mjs: 48/48 (Chromium and WebKit, light and dark, 1280/900/390/320px, en/zh/ja): nothing loads with the page, one button shows, no sideways scroll, opening doesn't move the page, the Download source section is in the top three, Enter to this page and to another, / and Ctrl/Cmd+K, the scrim, no page errors. Screenshots looked at in both themes and at 320px. Broken by hand: a stale ja index makes search.test red; close() without giving focus back makes the browser test red.
This commit is contained in:
@@ -0,0 +1,192 @@
|
||||
// The docs' search: docs.js loads this on the first open (the search
|
||||
// button, / or Cmd/Ctrl+K). It reads /search/<lang>.json (search-index.mjs
|
||||
// builds it from the pages) once, and finds in the browser alone; nothing
|
||||
// typed leaves the page. find and snippet are plain functions, which
|
||||
// search.test.mjs runs in Node.
|
||||
(() => {
|
||||
// a word in the docs is matched as typed, any case; Chinese and Japanese
|
||||
// have no spaces between words, so a term is a run of text, not a word
|
||||
const fold = (s) => s.toLowerCase();
|
||||
const terms = (q) => [...new Set(fold(q).split(/\s+/).filter(Boolean))];
|
||||
|
||||
// find returns the sections every term of q is in, the best first: a
|
||||
// term in a section's heading counts most, then in its page's title,
|
||||
// then in its text; a page gives at most `per` sections.
|
||||
function find(index, q, limit = 40, per = 3) {
|
||||
const ts = terms(q);
|
||||
if (!ts.length) return [];
|
||||
const whole = fold(q.trim());
|
||||
const hits = [];
|
||||
for (const [path, title, sections] of index) {
|
||||
const ft = fold(title);
|
||||
for (const [id, head, body] of sections) {
|
||||
const fh = fold(head), fb = fold(body);
|
||||
let score = 0, all = true;
|
||||
for (const t of ts) {
|
||||
const inHead = fh.includes(t), inTitle = ft.includes(t), inBody = fb.includes(t);
|
||||
if (!inHead && !inTitle && !inBody) { all = false; break; }
|
||||
score += (inHead ? 8 : 0) + (inTitle ? 5 : 0) + (inBody ? 1 + Math.min(3, count(fb, t) - 1) * 0.25 : 0);
|
||||
}
|
||||
if (!all) continue;
|
||||
if (fh.includes(whole)) score += 6;
|
||||
if (ft.includes(whole)) score += id ? 3 : 8; // the page itself, at its top
|
||||
if (fh.startsWith(ts[0]) || ft.startsWith(ts[0])) score += 2;
|
||||
hits.push({ path, title, id, head, body, score });
|
||||
}
|
||||
}
|
||||
hits.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
|
||||
const perPage = new Map(), out = [];
|
||||
for (const h of hits) {
|
||||
const n = perPage.get(h.path) || 0;
|
||||
if (n >= per) continue;
|
||||
perPage.set(h.path, n + 1);
|
||||
out.push(h);
|
||||
if (out.length >= limit) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function count(s, t) {
|
||||
let n = 0;
|
||||
for (let i = s.indexOf(t); i >= 0 && n < 8; i = s.indexOf(t, i + t.length)) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
// snippet is the stretch of text around the first term found, as
|
||||
// [before-or-between, match, …] pieces: odd ones are what was typed
|
||||
function snippet(text, q, width = 150) {
|
||||
const ts = terms(q), ft = fold(text);
|
||||
let at = -1;
|
||||
for (const t of ts) { const i = ft.indexOf(t); if (i >= 0 && (at < 0 || i < at)) at = i; }
|
||||
let from = 0;
|
||||
if (at > 40) from = at - 40;
|
||||
let s = text.slice(from, from + width);
|
||||
if (from > 0) s = "…" + s.replace(/^\S{0,12}\s/, "");
|
||||
if (from + width < text.length) s += "…";
|
||||
if (!ts.length) return [s];
|
||||
const re = new RegExp(ts.sort((a, b) => b.length - a.length).map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"), "gi");
|
||||
return s.split(new RegExp("(" + re.source + ")", "gi"));
|
||||
}
|
||||
|
||||
const api = { find, snippet };
|
||||
if (typeof module === "object" && module.exports) { module.exports = api; return; }
|
||||
window.docsSearchFind = api;
|
||||
|
||||
// the dialog
|
||||
const lang = (document.documentElement.lang || "en").slice(0, 2);
|
||||
const L = {
|
||||
en: { search: "Search", ph: "Search the docs", none: "Nothing found for “{q}”", fail: "The search couldn't load. Check your connection and try again." },
|
||||
zh: { search: "搜索", ph: "搜索文档", none: "没有找到与“{q}”相关的内容", fail: "搜索没能加载,请检查网络后重试。" },
|
||||
ja: { search: "検索", ph: "ドキュメントを検索", none: "「{q}」に一致する内容はありません", fail: "検索を読み込めませんでした。接続を確かめて、もう一度お試しください。" },
|
||||
}[lang] || null;
|
||||
const words = L || { search: "Search", ph: "Search the docs", none: "Nothing found for “{q}”", fail: "The search couldn't load." };
|
||||
const file = "/search/" + (L ? lang : "en") + ".json";
|
||||
|
||||
let index = null, loading = null;
|
||||
const load = () => loading || (loading = fetch(file).then((r) => { if (!r.ok) throw new Error(r.status); return r.json(); })
|
||||
.then((d) => (index = d), (e) => { loading = null; throw e; }));
|
||||
|
||||
const el = (tag, cls, txt) => { const e = document.createElement(tag); if (cls) e.className = cls; if (txt) e.textContent = txt; return e; };
|
||||
const box = el("div", "sx");
|
||||
box.hidden = true;
|
||||
box.innerHTML = '<div class="sx-scrim"></div><div class="sx-panel" role="dialog" aria-modal="true"><div class="sx-top"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" aria-hidden="true"><circle cx="7" cy="7" r="4.75"/><path d="M10.5 10.5 14 14"/></svg><input type="search" autocomplete="off" spellcheck="false" enterkeyhint="go" role="combobox" aria-autocomplete="list" aria-expanded="false" aria-controls="sx-list"><kbd>Esc</kbd></div><div class="sx-list" id="sx-list" role="listbox"></div></div>';
|
||||
const panel = box.querySelector(".sx-panel"), input = box.querySelector("input"), list = box.querySelector(".sx-list");
|
||||
panel.setAttribute("aria-label", words.search);
|
||||
input.placeholder = words.ph;
|
||||
input.setAttribute("aria-label", words.ph);
|
||||
document.body.append(box);
|
||||
|
||||
let items = [], cur = -1, back = null, gen = 0;
|
||||
const pick = (i, keep) => {
|
||||
items.forEach((a, j) => a.setAttribute("aria-selected", String(j === i)));
|
||||
cur = i;
|
||||
if (i >= 0) {
|
||||
input.setAttribute("aria-activedescendant", items[i].id);
|
||||
// the list scrolls itself, never the page
|
||||
if (!keep) {
|
||||
const a = items[i], top = a.offsetTop, bottom = top + a.offsetHeight;
|
||||
if (top < list.scrollTop) list.scrollTop = top - 6;
|
||||
else if (bottom > list.scrollTop + list.clientHeight) list.scrollTop = bottom - list.clientHeight + 6;
|
||||
}
|
||||
} else input.removeAttribute("aria-activedescendant");
|
||||
};
|
||||
const draw = () => {
|
||||
const q = input.value.trim();
|
||||
list.textContent = "";
|
||||
items = [];
|
||||
cur = -1;
|
||||
input.removeAttribute("aria-activedescendant");
|
||||
box.classList.toggle("has", !!q);
|
||||
if (!q) { input.setAttribute("aria-expanded", "false"); return; }
|
||||
if (!index) {
|
||||
const g = ++gen;
|
||||
load().then(() => { if (g === gen && !box.hidden) draw(); }, () => { if (g === gen) { list.textContent = ""; list.append(el("p", "sx-none", words.fail)); } });
|
||||
return;
|
||||
}
|
||||
const hits = find(index, q);
|
||||
input.setAttribute("aria-expanded", String(hits.length > 0));
|
||||
if (!hits.length) { list.append(el("p", "sx-none", words.none.replace("{q}", q))); return; }
|
||||
hits.forEach((h, i) => {
|
||||
const a = el("a", "sx-item");
|
||||
a.href = h.path + (h.id ? "#" + h.id : "");
|
||||
a.id = "sx-" + i;
|
||||
a.setAttribute("role", "option");
|
||||
a.tabIndex = -1;
|
||||
const where = el("span", "sx-where");
|
||||
where.append(el("span", "sx-page", h.title));
|
||||
if (h.head) where.append(el("span", "sx-sep", "›"), el("span", "sx-head", h.head));
|
||||
a.append(where);
|
||||
const sn = el("span", "sx-snip");
|
||||
snippet(h.body || h.head || h.title, q).forEach((part, j) => sn.append(j % 2 ? el("mark", "", part) : part));
|
||||
a.append(sn);
|
||||
a.addEventListener("mousemove", () => { if (cur !== i) pick(i, true); });
|
||||
a.addEventListener("click", (e) => { if (!e.metaKey && !e.ctrlKey && !e.shiftKey) go(a, e); });
|
||||
list.append(a);
|
||||
items.push(a);
|
||||
});
|
||||
list.scrollTop = 0;
|
||||
pick(0, true);
|
||||
};
|
||||
const go = (a, e) => {
|
||||
const u = new URL(a.href);
|
||||
if (u.pathname === location.pathname.replace(/\.html$/, "")) {
|
||||
// this page: jump to the section, the dialog out of the way first
|
||||
e && e.preventDefault();
|
||||
close(false);
|
||||
if (u.hash) location.hash = u.hash; else scrollTo(0, 0);
|
||||
return;
|
||||
}
|
||||
if (!e) location.href = a.href;
|
||||
};
|
||||
input.addEventListener("input", draw);
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.isComposing || e.keyCode === 229) return; // an IME choosing its words
|
||||
if (e.key === "ArrowDown" || (e.key === "n" && e.ctrlKey)) { e.preventDefault(); if (items.length) pick((cur + 1) % items.length); }
|
||||
else if (e.key === "ArrowUp" || (e.key === "p" && e.ctrlKey)) { e.preventDefault(); if (items.length) pick((cur - 1 + items.length) % items.length); }
|
||||
else if (e.key === "Enter") { e.preventDefault(); if (items[cur]) go(items[cur]); }
|
||||
else if (e.key === "Escape") { e.preventDefault(); close(true); }
|
||||
});
|
||||
box.querySelector(".sx-scrim").addEventListener("click", () => close(true));
|
||||
// Tab stays in the dialog: the field is all there is to focus
|
||||
panel.addEventListener("keydown", (e) => { if (e.key === "Tab") { e.preventDefault(); input.focus(); } });
|
||||
|
||||
function open(from) {
|
||||
if (!box.hidden) { input.focus(); input.select(); return; }
|
||||
back = from || document.activeElement;
|
||||
box.hidden = false;
|
||||
// a short fade: it opens many times, and comes from nowhere on the page
|
||||
requestAnimationFrame(() => box.classList.add("in"));
|
||||
input.focus();
|
||||
input.select();
|
||||
load().catch(() => {});
|
||||
if (input.value.trim()) draw();
|
||||
}
|
||||
function close(refocus) {
|
||||
if (box.hidden) return;
|
||||
box.hidden = true;
|
||||
box.classList.remove("in");
|
||||
if (refocus && back && back.focus) back.focus();
|
||||
}
|
||||
// back to a page left from the dialog: the page, not the dialog
|
||||
addEventListener("pageshow", (e) => { if (e.persisted) close(false); });
|
||||
window.docsSearch = { open, close, load };
|
||||
})();
|
||||
+40
-2
@@ -101,6 +101,8 @@ nav .links a.toc-only { display: none; }
|
||||
.toc .secs a { color: var(--ink3); font-size: 13px; }
|
||||
.toc .secs a.on { color: var(--ink); font-weight: 560; background: color-mix(in srgb, var(--ink) 8%, transparent); }
|
||||
.toc-bar, .toc-scrim { display: none; }
|
||||
.icon-btn.search.in-bar { width: 32px; height: 32px; border: 0; margin-right: -7px; }
|
||||
@media (max-width: 900px) { .icon-btn.search.in-nav { display: none; } }
|
||||
|
||||
/* language menu, as on the home page */
|
||||
.langs { position: relative; flex: none; }
|
||||
@@ -243,10 +245,11 @@ footer a:hover { color: var(--ink); }
|
||||
.doc { grid-template-columns: 1fr; gap: 0; padding-top: 32px; }
|
||||
/* on a phone the contents are a menu under a bar that names the section being read */
|
||||
.toc-bar { display: block; position: sticky; top: 61px; z-index: 9; background: color-mix(in srgb, var(--bg) 86%, transparent); backdrop-filter: saturate(1.4) blur(14px); -webkit-backdrop-filter: saturate(1.4) blur(14px); border-bottom: 1px solid var(--line); }
|
||||
.toc-bar button { display: flex; align-items: center; gap: 10px; width: 100%; height: 46px; padding: 0; border: 0; background: none; color: var(--ink); font: inherit; font-size: 14.5px; text-align: left; cursor: pointer; }
|
||||
.toc-bar .wrap { display: flex; align-items: center; gap: 12px; }
|
||||
.toc-bar button:not(.search) { flex: 1; min-width: 0; display: flex; align-items: center; gap: 10px; width: 100%; height: 46px; padding: 0; border: 0; background: none; color: var(--ink); font: inherit; font-size: 14.5px; text-align: left; cursor: pointer; }
|
||||
.toc-bar .k { flex: none; font-size: 11.5px; letter-spacing: .08em; text-transform: uppercase; color: var(--ink3); padding-right: 10px; border-right: 1px solid var(--line); line-height: 1.2; }
|
||||
.toc-bar .t { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 560; }
|
||||
.toc-bar svg { flex: none; width: 16px; height: 16px; color: var(--ink3); transition: transform .2s; }
|
||||
.toc-bar button:not(.search) svg { flex: none; width: 16px; height: 16px; color: var(--ink3); transition: transform .2s; }
|
||||
.toc-bar button[aria-expanded="true"] svg { transform: rotate(180deg); }
|
||||
.toc { display: none; position: fixed; top: 115px; left: 24px; right: 24px; z-index: 12; margin: 0; max-height: calc(100vh - 135px); max-height: calc(100dvh - 135px); padding: 12px 8px; background: var(--card); border: 1px solid var(--line); border-radius: 14px; box-shadow: var(--shadow); font-size: 15px; }
|
||||
.toc.open { display: block; }
|
||||
@@ -275,3 +278,38 @@ footer a:hover { color: var(--ink); }
|
||||
nav .links + .langs { margin-left: 0; }
|
||||
nav a.icon-btn[href*="discord"], nav a.icon-btn[href*="github.com"] { display: none; }
|
||||
}
|
||||
/* 320px holds Japanese's longer Download too */
|
||||
@media (max-width: 360px) {
|
||||
.btn.small { padding: 0 10px; }
|
||||
}
|
||||
|
||||
/* search: a dialog over the page, opened by the nav's button, / or Cmd/Ctrl+K.
|
||||
It opens many times, so it only fades in, briefly, and closes at once. */
|
||||
.sx { position: fixed; inset: 0; z-index: 50; display: flex; justify-content: center; align-items: flex-start; padding: max(12vh, 64px) 16px 16px; padding-top: max(12vh, calc(64px + env(safe-area-inset-top, 0px))); opacity: 0; }
|
||||
.sx.in { opacity: 1; transition: opacity .12s cubic-bezier(.23, 1, .32, 1); }
|
||||
.sx[hidden] { display: none; }
|
||||
.sx-scrim { position: absolute; inset: 0; background: rgba(0,0,0,.28); }
|
||||
.sx-panel { position: relative; width: min(640px, 100%); max-height: min(560px, 100%); display: flex; flex-direction: column; background: var(--card); border: 1px solid var(--line); border-radius: 14px; box-shadow: var(--shadow); overflow: hidden; }
|
||||
.sx-top { flex: none; display: flex; align-items: center; gap: 10px; padding: 0 14px; height: 52px; }
|
||||
.sx.has .sx-top { border-bottom: 1px solid var(--line); }
|
||||
.sx-top svg { flex: none; width: 17px; height: 17px; color: var(--ink3); }
|
||||
.sx-top input { flex: 1; min-width: 0; height: 100%; border: 0; outline: 0; background: none; color: var(--ink); font: inherit; font-size: 16px; -webkit-appearance: none; appearance: none; }
|
||||
.sx-top input::placeholder { color: var(--ink3); }
|
||||
.sx-top input::-webkit-search-cancel-button { display: none; }
|
||||
.sx-top kbd { flex: none; font-size: 11.5px; color: var(--ink3); border: 1px solid var(--line); border-radius: 5px; padding: 1px 6px; }
|
||||
.sx-list { overflow-y: auto; overscroll-behavior: contain; padding: 6px; }
|
||||
.sx-list:empty { display: none; }
|
||||
.sx-item { display: block; padding: 9px 12px; border-radius: 9px; text-decoration: none; color: var(--ink2); }
|
||||
.sx-item[aria-selected="true"] { background: var(--bg2); }
|
||||
.sx-where { display: flex; align-items: baseline; gap: 6px; min-width: 0; font-size: 14.5px; font-weight: 560; color: var(--ink); white-space: nowrap; overflow: hidden; }
|
||||
.sx-page { flex: none; max-width: 60%; overflow: hidden; text-overflow: ellipsis; }
|
||||
.sx-sep { flex: none; color: var(--ink3); font-weight: 400; }
|
||||
.sx-head { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
||||
.sx-snip { display: block; margin-top: 2px; font-size: 13.5px; line-height: 1.5; color: var(--ink2); overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
|
||||
.sx-snip mark { background: color-mix(in srgb, var(--ink) 12%, transparent); color: var(--ink); border-radius: 3px; padding: 0 1px; }
|
||||
.sx-none { margin: 0; padding: 14px 12px; font-size: 14px; color: var(--ink3); }
|
||||
@media (max-width: 600px) {
|
||||
.sx { padding-top: calc(12px + env(safe-area-inset-top, 0px)); padding-left: 12px; padding-right: 12px; }
|
||||
.sx-top kbd { display: none; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .sx.in { transition-duration: .08s; } }
|
||||
|
||||
+48
-8
@@ -1,14 +1,14 @@
|
||||
// The docs' contents, language menu and reading position, shared by every
|
||||
// language. Each page's aside.toc lists its own sections; this adds the other
|
||||
// The docs' contents, language menu, search and reading position, shared by
|
||||
// every language. Each page's aside.toc lists its own sections; this adds the other
|
||||
// pages around them, follows the reading position, and on a phone turns the
|
||||
// list into a menu under a bar that names the section being read.
|
||||
(() => {
|
||||
const lang = (document.documentElement.lang || "en").slice(0, 2);
|
||||
const L = {
|
||||
en: { docs: "Docs", contents: "Contents" },
|
||||
zh: { docs: "文档", contents: "目录" },
|
||||
ja: { docs: "ドキュメント", contents: "目次" },
|
||||
}[lang] || { docs: "Docs", contents: "Contents" };
|
||||
en: { docs: "Docs", contents: "Contents", search: "Search" },
|
||||
zh: { docs: "文档", contents: "目录", search: "搜索" },
|
||||
ja: { docs: "ドキュメント", contents: "目次", search: "検索" },
|
||||
}[lang] || { docs: "Docs", contents: "Contents", search: "Search" };
|
||||
const clean = (p) => p.replace(/\.html$/, "").replace(/\/+$/, "") || "/";
|
||||
const el = (tag, cls, text) => {
|
||||
const e = document.createElement(tag);
|
||||
@@ -28,9 +28,47 @@
|
||||
a.addEventListener("click", () => { document.cookie = "lang=" + a.hreflang + "; path=/; max-age=31536000; samesite=lax"; });
|
||||
});
|
||||
document.addEventListener("click", (e) => { if (!langBtn.parentNode.contains(e.target)) langOpen(false); });
|
||||
document.addEventListener("keydown", (e) => { if (e.key === "Escape" && !langs.hidden) { langOpen(false); langBtn.focus(); } });
|
||||
document.addEventListener("keydown", (e) => { if (e.key === "Escape" && !e.defaultPrevented && !langs.hidden) { langOpen(false); langBtn.focus(); } });
|
||||
}
|
||||
|
||||
// search: docs-search.js (the dialog and the finding) and the index load
|
||||
// the first time it is wanted, a pointer over the button already starting
|
||||
// them; / or Cmd/Ctrl+K opens it from anywhere but a field
|
||||
const mac = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
|
||||
let engine = null;
|
||||
const want = () => engine || (engine = new Promise((ok, no) => {
|
||||
const s = document.createElement("script");
|
||||
s.src = "/docs-search.js";
|
||||
s.onload = () => (window.docsSearch ? ok(window.docsSearch) : no(new Error("docs-search")));
|
||||
s.onerror = () => { engine = null; no(new Error("docs-search")); };
|
||||
document.head.append(s);
|
||||
}));
|
||||
const warm = () => want().then((d) => d.load()).catch(() => {});
|
||||
const openSearch = (from) => want().then((d) => d.open(from)).catch(() => {});
|
||||
const searchBtn = (cls) => {
|
||||
const b = el("button", "icon-btn search" + (cls ? " " + cls : ""));
|
||||
b.type = "button";
|
||||
b.setAttribute("aria-label", L.search);
|
||||
b.title = L.search + " (" + (mac ? "⌘K" : "Ctrl+K") + ")";
|
||||
b.setAttribute("aria-haspopup", "dialog");
|
||||
b.innerHTML = '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" aria-hidden="true"><circle cx="7" cy="7" r="4.75"/><path d="M10.5 10.5 14 14"/></svg>';
|
||||
b.addEventListener("click", () => openSearch(b));
|
||||
b.addEventListener("pointerenter", warm, { once: true });
|
||||
b.addEventListener("focus", warm, { once: true });
|
||||
return b;
|
||||
};
|
||||
const navLangs = document.querySelector("body > nav .langs");
|
||||
if (navLangs) navLangs.before(searchBtn("in-nav"));
|
||||
document.addEventListener("keydown", (e) => {
|
||||
if (e.defaultPrevented || e.isComposing) return;
|
||||
const k = e.key.toLowerCase();
|
||||
const typing = e.target.closest && e.target.closest("input, textarea, select, [contenteditable]:not([contenteditable=false])");
|
||||
if ((k === "k" && (mac ? e.metaKey : e.ctrlKey) && !e.altKey && !e.shiftKey) || (e.key === "/" && !typing && !e.metaKey && !e.ctrlKey && !e.altKey)) {
|
||||
e.preventDefault();
|
||||
openSearch(document.activeElement);
|
||||
}
|
||||
});
|
||||
|
||||
// contents: every docs page, this one's sections under it
|
||||
const toc = document.querySelector("aside.toc");
|
||||
if (!toc) return;
|
||||
@@ -70,6 +108,8 @@
|
||||
label.textContent = title;
|
||||
const scrim = el("div", "toc-scrim");
|
||||
scrim.hidden = true;
|
||||
// a phone's nav has no room for another button; its bar does
|
||||
bar.querySelector(".wrap").append(searchBtn("in-bar"));
|
||||
document.querySelector("body > nav").after(bar);
|
||||
document.body.append(scrim);
|
||||
|
||||
@@ -82,7 +122,7 @@
|
||||
btn.addEventListener("click", () => show(!toc.classList.contains("open")));
|
||||
scrim.addEventListener("click", () => show(false));
|
||||
toc.addEventListener("click", (e) => { if (e.target.closest("a")) show(false); });
|
||||
document.addEventListener("keydown", (e) => { if (e.key === "Escape" && toc.classList.contains("open")) { show(false); btn.focus(); } });
|
||||
document.addEventListener("keydown", (e) => { if (e.key === "Escape" && !e.defaultPrevented && toc.classList.contains("open")) { show(false); btn.focus(); } });
|
||||
matchMedia("(min-width: 901px)").addEventListener("change", (m) => { if (m.matches) show(false); });
|
||||
|
||||
// scroll the list itself, never the page, to keep the current section shown
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,78 @@
|
||||
// search-index.mjs builds public/search/<lang>.json, what the docs' search
|
||||
// (public/docs-search.js) looks through: each docs page in that language,
|
||||
// its title and its sections, as plain text. Run `node search-index.mjs`
|
||||
// after changing a docs page; a test fails while a committed index differs
|
||||
// from what this builds.
|
||||
import { readFile, readdir, writeFile } from "node:fs/promises";
|
||||
|
||||
const pub = new URL("./public/", import.meta.url);
|
||||
export const LANGS = { en: "docs/", zh: "docs/zh/", ja: "docs/ja/" };
|
||||
|
||||
const ENT = { amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'", nbsp: " ", rarr: "→", larr: "←", hellip: "…", mdash: "—", ndash: "–", middot: "·" };
|
||||
const unent = (s) => s.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (m, e) => {
|
||||
if (e[0] === "#") return String.fromCodePoint(e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10));
|
||||
return ENT[e] ?? m;
|
||||
});
|
||||
// text is a fragment of HTML as one line of plain text; a step's bold
|
||||
// first words (ol.steps) keep a space from the words after them
|
||||
const text = (h) => unent(h.replace(/(<li[^>]*>\s*<b>[\s\S]*?<\/b>)/g, "$1 ").replace(/<br\s*\/?>/g, " ").replace(/<\/(p|li|h[1-6]|tr|td|th|pre|div)>/g, " ").replace(/<[^>]+>/g, "")).replace(/\s+/g, " ").trim();
|
||||
|
||||
// page reads one docs page: its title (the contents' name for it, else the
|
||||
// h1) and its sections, each the
|
||||
// id of its h2 ("" for what comes before the first), the h2's words and
|
||||
// the text under it. An h3 stays in its h2's section.
|
||||
const GENERIC = new Set(["On this page", "本页内容", "このページ"]);
|
||||
export function page(html, path) {
|
||||
const m = html.match(/<article>([\s\S]*?)<\/article>/);
|
||||
if (!m) return null;
|
||||
const a = m[1]
|
||||
.replace(/<p class="eyebrow"[\s\S]*?<\/p>/g, "")
|
||||
.replace(/<button[\s\S]*?<\/button>/g, "")
|
||||
.replace(/<span class="lang">[\s\S]*?<\/span>/g, "")
|
||||
.replace(/<script[\s\S]*?<\/script>/g, "")
|
||||
.replace(/<style[\s\S]*?<\/style>/g, "");
|
||||
// the page's short name: the nav's link to it (what the contents list),
|
||||
// else its contents' heading, else its h1
|
||||
const h1 = a.match(/<h1[^>]*>([\s\S]*?)<\/h1>/);
|
||||
const links = (html.match(/<div class="links">([\s\S]*?)<\/div>/) || [])[1] || "";
|
||||
const link = path && [...links.matchAll(/<a\b([^>]*)>([\s\S]*?)<\/a>/g)].find((m) => m[1].includes(`href="${path}"`));
|
||||
const short = html.match(/<aside class="toc">\s*<p>([\s\S]*?)<\/p>/);
|
||||
const title = link ? text(link[2]) : short && !GENERIC.has(text(short[1])) ? text(short[1]) : h1 ? text(h1[1]) : "";
|
||||
const parts = a.split(/(?=<h2\b)/);
|
||||
const sections = [];
|
||||
for (const [i, p] of parts.entries()) {
|
||||
let id = "", head = "", body = p;
|
||||
if (i > 0 || /^<h2\b/.test(p)) {
|
||||
const h = p.match(/^<h2([^>]*)>([\s\S]*?)<\/h2>/);
|
||||
if (!h) continue;
|
||||
id = (h[1].match(/\bid="([^"]+)"/) || [])[1] || "";
|
||||
head = text(h[2]);
|
||||
body = p.slice(h[0].length);
|
||||
} else body = body.replace(/<h1[^>]*>[\s\S]*?<\/h1>/, "");
|
||||
const t = text(body);
|
||||
if (!head && !t) continue;
|
||||
sections.push([id, head, t]);
|
||||
}
|
||||
return { title, sections };
|
||||
}
|
||||
|
||||
// build returns each language's index, by language: [[path, title,
|
||||
// [[id, heading, text], …]], …], the pages in name order.
|
||||
export async function build() {
|
||||
const out = {};
|
||||
for (const [lang, dir] of Object.entries(LANGS)) {
|
||||
const files = (await readdir(new URL(dir, pub))).filter((f) => f.endsWith(".html") && f !== "contributors.html").sort();
|
||||
const pages = [];
|
||||
for (const f of files) {
|
||||
const path = "/" + dir + f.slice(0, -5);
|
||||
const p = page(await readFile(new URL(dir + f, pub), "utf8"), path);
|
||||
if (p && p.title) pages.push([path, p.title, p.sections]);
|
||||
}
|
||||
out[lang] = JSON.stringify(pages) + "\n";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
for (const [lang, json] of Object.entries(await build())) await writeFile(new URL(`search/${lang}.json`, pub), json);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// The docs' search in real browsers: Chromium and WebKit, each docs
|
||||
// language, wide to 320px, light and dark. Not a *.test.mjs, so CI's
|
||||
// `node --test site/*.test.mjs` (no browsers there) leaves it out; run it by
|
||||
// hand where Playwright is on NODE_PATH:
|
||||
// node site/search.browser.mjs [screenshot-dir]
|
||||
import { createServer } from "node:http";
|
||||
import { readFile, mkdir } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
const { chromium, webkit } = createRequire(import.meta.url)("playwright");
|
||||
const pub = new URL("./public/", import.meta.url);
|
||||
const shots = process.argv[2];
|
||||
if (shots) await mkdir(shots, { recursive: true });
|
||||
|
||||
const types = { html: "text/html; charset=utf-8", js: "text/javascript", css: "text/css", json: "application/json", svg: "image/svg+xml", png: "image/png", txt: "text/plain" };
|
||||
let served = [];
|
||||
const server = createServer(async (req, res) => {
|
||||
let p = decodeURIComponent(new URL(req.url, "http://x").pathname).replace(/^\/+/, "");
|
||||
served.push("/" + p);
|
||||
if (!/\.\w+$/.test(p)) p += ".html";
|
||||
try {
|
||||
const body = await readFile(new URL(p, pub));
|
||||
res.writeHead(200, { "content-type": types[p.split(".").pop()] || "application/octet-stream" });
|
||||
res.end(body);
|
||||
} catch {
|
||||
res.writeHead(404);
|
||||
res.end();
|
||||
}
|
||||
});
|
||||
await new Promise((ok) => server.listen(0, "127.0.0.1", ok));
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
|
||||
const langs = {
|
||||
en: { dir: "/docs/", q: "download source mirror", none: "Nothing found for “zzqqxx”", ph: "Search the docs" },
|
||||
zh: { dir: "/docs/zh/", q: "下载源 镜像", none: "没有找到与“zzqqxx”相关的内容", ph: "搜索文档" },
|
||||
ja: { dir: "/docs/ja/", q: "ダウンロード元 ミラー", none: "「zzqqxx」に一致する内容はありません", ph: "ドキュメントを検索" },
|
||||
};
|
||||
let fails = 0, runs = 0;
|
||||
|
||||
for (const [ename, engine] of [["chromium", chromium], ["webkit", webkit]]) {
|
||||
const browser = await engine.launch();
|
||||
for (const scheme of ["light", "dark"]) {
|
||||
for (const width of [1280, 900, 390, 320]) {
|
||||
for (const [lang, L] of Object.entries(langs)) {
|
||||
const name = `${ename} ${scheme} ${width} ${lang}`;
|
||||
runs++;
|
||||
const ctx = await browser.newContext({ viewport: { width, height: 800 }, colorScheme: scheme, reducedMotion: width === 390 ? "reduce" : "no-preference" });
|
||||
const page = await ctx.newPage();
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(String(e)));
|
||||
page.on("console", (m) => { if (m.type() === "error") errors.push(m.text()); });
|
||||
try {
|
||||
served = [];
|
||||
await page.goto(base + L.dir + "mirrors", { waitUntil: "load" });
|
||||
// nothing of the search loads until it is wanted
|
||||
assert.ok(!served.some((p) => p.startsWith("/search/") || p === "/docs-search.js"), "the search loaded with the page");
|
||||
|
||||
// one search button shows: the nav's when wide, the contents bar's on a phone
|
||||
const vis = await page.$$eval("button.search", (bs) => bs.filter((b) => b.offsetParent).map((b) => b.className));
|
||||
assert.deepEqual(vis, [width > 900 ? "icon-btn search in-nav" : "icon-btn search in-bar"], "visible search buttons");
|
||||
const btn = page.locator("button.search:visible");
|
||||
const box = await btn.boundingBox();
|
||||
assert.ok(box.x >= 0 && box.x + box.width <= width, `button off screen: ${JSON.stringify(box)}`);
|
||||
const sideways = () => page.evaluate(() => document.documentElement.scrollWidth - innerWidth);
|
||||
assert.ok((await sideways()) <= 0, "the page scrolls sideways");
|
||||
|
||||
// a pointer over the button starts the loading (the mouse, not
|
||||
// the locator: Playwright's scrolling into view moves the page
|
||||
// under a sticky bar, which no reader does)
|
||||
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
|
||||
await page.waitForFunction(() => window.docsSearch, null, { timeout: 5000 });
|
||||
|
||||
// scrolled down a little, then opened by the button: the page stays put
|
||||
await page.evaluate(() => scrollTo({ top: 600, behavior: "instant" }));
|
||||
const y0 = await page.evaluate(() => scrollY);
|
||||
assert.equal(y0, 600);
|
||||
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
|
||||
const input = page.locator(".sx-panel input");
|
||||
await input.waitFor({ state: "visible" });
|
||||
assert.equal(await input.evaluate((i) => i === document.activeElement), true, "the field has the focus");
|
||||
assert.equal(await input.getAttribute("placeholder"), L.ph);
|
||||
assert.equal(await page.locator(".sx-item").count(), 0, "nothing listed before typing");
|
||||
|
||||
await input.fill(L.q);
|
||||
await page.locator(".sx-item").first().waitFor();
|
||||
const first = await page.locator(".sx-item").first().getAttribute("href");
|
||||
const top3 = await page.locator(".sx-item").evaluateAll((as) => as.slice(0, 3).map((a) => a.getAttribute("href")));
|
||||
assert.ok(top3.includes(L.dir + "mirrors#settings"), `top results: ${top3}`);
|
||||
assert.ok((await page.locator(".sx-item mark").count()) > 0, "no marked words");
|
||||
assert.equal(await page.locator('.sx-item[aria-selected="true"]').getAttribute("href"), first, "the first result is picked");
|
||||
await page.keyboard.press("ArrowDown");
|
||||
assert.equal(await page.locator('.sx-item[aria-selected="true"]').getAttribute("id"), "sx-1", "ArrowDown picks the next");
|
||||
await page.keyboard.press("ArrowUp");
|
||||
const panel = await page.locator(".sx-panel").boundingBox();
|
||||
assert.ok(panel.x >= 8 && panel.x + panel.width <= width - 8, `panel out of the screen: ${JSON.stringify(panel)}`);
|
||||
assert.ok(panel.y + panel.height <= 800, "panel taller than the screen");
|
||||
assert.equal(await page.evaluate(() => scrollY), y0, "opening and typing scrolled the page");
|
||||
assert.ok((await sideways()) <= 0, "the page scrolls sideways with the dialog");
|
||||
// it is shown, faded in all the way
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector(".sx")).opacity === "1", null, { timeout: 2000 });
|
||||
if (shots) await page.screenshot({ path: `${shots}/${ename}-${scheme}-${width}-${lang}.png` });
|
||||
|
||||
// the panel is the card's colour, which the theme sets
|
||||
const bg = await page.locator(".sx-panel").evaluate((p) => getComputedStyle(p).backgroundColor);
|
||||
assert.equal(bg, scheme === "dark" ? "rgb(22, 22, 24)" : "rgb(255, 255, 255)");
|
||||
|
||||
await input.fill("zzqqxx");
|
||||
await page.locator(".sx-none").waitFor();
|
||||
assert.equal(await page.locator(".sx-none").textContent(), L.none);
|
||||
|
||||
// Escape closes it and gives the focus back to the button
|
||||
await page.keyboard.press("Escape");
|
||||
assert.equal(await page.locator(".sx").isHidden(), true, "Escape left it open");
|
||||
assert.equal(await btn.evaluate((b) => b === document.activeElement), true, "focus not back on the button");
|
||||
|
||||
// / and Cmd/Ctrl+K open it; / typed in the field is a character
|
||||
await page.locator("article h1").click();
|
||||
await page.keyboard.press("/");
|
||||
await input.waitFor({ state: "visible" });
|
||||
assert.equal(await input.inputValue(), "zzqqxx", "the field keeps what was typed, selected");
|
||||
await page.keyboard.type("a/b");
|
||||
assert.equal(await input.inputValue(), "a/b");
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.press("ControlOrMeta+k");
|
||||
await input.waitFor({ state: "visible" });
|
||||
|
||||
// a click on the scrim closes it
|
||||
await page.mouse.click(4, 790);
|
||||
assert.equal(await page.locator(".sx").isHidden(), true, "the scrim's click left it open");
|
||||
|
||||
// Enter on a section of this page goes to it, dialog closed
|
||||
await page.keyboard.press("ControlOrMeta+k");
|
||||
await input.fill(L.q);
|
||||
await page.locator(`.sx-item[href="${L.dir}mirrors#settings"]`).waitFor();
|
||||
const i = await page.locator(".sx-item").evaluateAll((as, h) => as.findIndex((a) => a.getAttribute("href") === h), L.dir + "mirrors#settings");
|
||||
for (let k = 0; k < i; k++) await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.waitForFunction(() => location.hash === "#settings");
|
||||
assert.equal(await page.locator(".sx").isHidden(), true);
|
||||
const top = await page.locator("#settings").evaluate((h) => h.getBoundingClientRect().top);
|
||||
assert.ok(top >= 0 && top < 300, `#settings at ${top}`);
|
||||
|
||||
// Enter on another page goes there
|
||||
await page.keyboard.press("ControlOrMeta+k");
|
||||
await input.fill(lang === "en" ? "update proxy" : lang === "zh" ? "代理" : "プロキシ");
|
||||
await page.locator(".sx-item").first().waitFor();
|
||||
const other = await page.locator('.sx-item[aria-selected="true"]').getAttribute("href");
|
||||
if (!other.startsWith(L.dir + "mirrors")) {
|
||||
await Promise.all([page.waitForURL((u) => u.pathname === other.split("#")[0]), page.keyboard.press("Enter")]);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("ok ", name);
|
||||
} catch (e) {
|
||||
fails++;
|
||||
console.log("FAIL", name, e.message.split("\n").slice(0, 6).join("\n "));
|
||||
if (shots) await page.screenshot({ path: `${shots}/FAIL-${ename}-${scheme}-${width}-${lang}.png` }).catch(() => {});
|
||||
}
|
||||
await ctx.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
await browser.close();
|
||||
}
|
||||
server.close();
|
||||
console.log(`${runs - fails}/${runs} ok`);
|
||||
process.exit(fails ? 1 : 0);
|
||||
@@ -0,0 +1,79 @@
|
||||
// The docs' search: the committed indexes are what search-index.mjs builds,
|
||||
// every docs page in every language is in its language's index, and the
|
||||
// finding in public/docs-search.js ranks and cuts as its comments say.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile, readdir } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { LANGS, build, page } from "./search-index.mjs";
|
||||
|
||||
const pub = new URL("./public/", import.meta.url);
|
||||
const { find, snippet } = createRequire(import.meta.url)("./public/docs-search.js");
|
||||
|
||||
test("search: each committed index is current and holds every docs page", async () => {
|
||||
const built = await build();
|
||||
for (const [lang, dir] of Object.entries(LANGS)) {
|
||||
const have = await readFile(new URL(`search/${lang}.json`, pub), "utf8");
|
||||
assert.equal(have, built[lang], `public/search/${lang}.json is stale: run \`node search-index.mjs\` in site/`);
|
||||
const idx = JSON.parse(have);
|
||||
const paths = new Set(idx.map((p) => p[0]));
|
||||
const files = (await readdir(new URL(dir, pub))).filter((f) => f.endsWith(".html") && f !== "contributors.html");
|
||||
for (const f of files) assert.ok(paths.has("/" + dir + f.slice(0, -5)), `${lang} index misses ${dir}${f}`);
|
||||
const src = new Map();
|
||||
for (const f of files) src.set("/" + dir + f.slice(0, -5), await readFile(new URL(dir + f, pub), "utf8"));
|
||||
for (const [path, title, secs] of idx) {
|
||||
assert.ok(title, `${path} has no title`);
|
||||
assert.ok(secs.length, `${path} has no sections`);
|
||||
for (const [id, head, body] of secs) {
|
||||
// a tag left in the text is one the page writes as text (<…),
|
||||
// an HTML sample in a code block, never the page's own markup
|
||||
for (const [, tag] of (head + " " + body).matchAll(/<(\/?[a-z][\w-]*)/gi)) assert.ok(src.get(path).includes("<" + tag), `${path}#${id} keeps the page's <${tag}>`);
|
||||
if (head) assert.ok(id, `${path}: section "${head}" has no id to link to`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("search: the new Download source section is found in each language", async () => {
|
||||
const q = { en: "download source mirror", zh: "下载源 镜像", ja: "ダウンロード元 ミラー" };
|
||||
for (const lang of Object.keys(LANGS)) {
|
||||
const idx = JSON.parse(await readFile(new URL(`search/${lang}.json`, pub), "utf8"));
|
||||
const hits = find(idx, q[lang]);
|
||||
assert.ok(hits.slice(0, 3).some((h) => h.path.endsWith("/mirrors") && h.id === "settings"), `${lang}: ${JSON.stringify(hits.slice(0, 3).map((h) => h.path + "#" + h.id))}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("search: page reads sections, not the page's chrome", () => {
|
||||
const named = '<nav><div class="links"><a href="/docs/x">Other</a><a class="toc-only" href="/docs/mirrors">Mirrors & proxies</a></div></nav><aside class="toc">\n <p>On this page</p></aside><article><h1>Mirrors in China: faster</h1></article>';
|
||||
assert.equal(page(named, "/docs/mirrors").title, "Mirrors & proxies", "the nav's name for the page");
|
||||
assert.equal(page(named, "/docs/y").title, "Mirrors in China: faster", "the h1 when the nav has no link and the contents' heading is generic");
|
||||
assert.equal(page(named.replace("On this page", "Mirrors"), "/docs/y").title, "Mirrors", "the contents' heading");
|
||||
const p = page('<nav>Nav words</nav><article><p class="eyebrow">Docs</p><h1>Mirrors & more</h1><p>Intro <code>x</code>.</p><button>Copy</button><h2 id="a">First</h2><p>One</p><h3>Sub</h3><ol class="steps"><li><b>Open</b>Settings</li></ol><h2 id="b">Second</h2><p>Two</p></article>');
|
||||
assert.deepEqual(p, { title: "Mirrors & more", sections: [["", "", "Intro x."], ["a", "First", "One Sub Open Settings"], ["b", "Second", "Two"]] });
|
||||
});
|
||||
|
||||
test("search: find needs every term, ranks headings first and caps each page", () => {
|
||||
const idx = [
|
||||
["/docs/a", "Alpha", [["", "", "mirror text here, a mirror"], ["s1", "Mirror settings", "how to set it"], ["s2", "Other", "mirror once"], ["s3", "More", "mirror again"]]],
|
||||
["/docs/b", "Beta mirror", [["", "", "nothing else"], ["x", "Proxy", "a proxy and a mirror"]]],
|
||||
["/docs/c", "镜像", [["", "", "下载源可以设成镜像"]]],
|
||||
];
|
||||
const hits = find(idx, "mirror");
|
||||
assert.equal(hits[0].path + "#" + hits[0].id, "/docs/a#s1", "a heading match comes first");
|
||||
assert.ok(hits.filter((h) => h.path === "/docs/a").length <= 3, "at most three sections a page");
|
||||
assert.deepEqual(find(idx, "MIRROR proxy").map((h) => h.path + "#" + h.id), ["/docs/b#x"], "every term, any case");
|
||||
assert.deepEqual(find(idx, "下载源 镜像").map((h) => h.path), ["/docs/c"], "Chinese terms match inside text");
|
||||
assert.deepEqual(find(idx, " "), []);
|
||||
assert.deepEqual(find(idx, "nowhere"), []);
|
||||
assert.equal(find(idx, "a", 2).length, 2, "the limit holds");
|
||||
});
|
||||
|
||||
test("search: snippet marks the terms around the first one found", () => {
|
||||
const long = "x ".repeat(100) + "the Download source row holds a mirror address " + "y ".repeat(100);
|
||||
const parts = snippet(long, "mirror download");
|
||||
assert.ok(parts[0].startsWith("…"), "cut text starts with an ellipsis");
|
||||
assert.ok(parts.at(-1).endsWith("…"));
|
||||
assert.deepEqual(parts.filter((_, i) => i % 2), ["Download", "mirror"]);
|
||||
assert.deepEqual(snippet("a.b (c)", "(c)"), ["a.b ", "(c)", ""], "regex characters are literal");
|
||||
assert.deepEqual(snippet("short", ""), ["short"]);
|
||||
});
|
||||
Reference in New Issue
Block a user