diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 8633b271..ce9cc331 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -11,6 +11,15 @@ on: - "docs/**" - "scripts/**" - ".github/workflows/pages.yml" + pull_request: + paths: + - "Reports/**" + - "Posts/**" + - "Contributors/**" + - "assets/**" + - "docs/**" + - "scripts/**" + - ".github/workflows/pages.yml" workflow_dispatch: inputs: runner: @@ -23,11 +32,9 @@ on: permissions: contents: read - pages: write - id-token: write concurrency: - group: pages + group: ${{ github.event_name == 'pull_request' && format('pages-pr-{0}', github.event.pull_request.number) || 'pages' }} cancel-in-progress: false jobs: @@ -36,7 +43,8 @@ jobs: # 手动 workflow_dispatch 时可在 inputs.runner 选择 ubuntu-latest 作为兜底。 # 注意:runs-on 匹配的是 runner 的 label 而非 name;这里只用 "self-hosted" # 通用 label 命中我们挂载到本仓库的 self-hosted runner。 - runs-on: ${{ inputs.runner == 'ubuntu-latest' && 'ubuntu-latest' || 'self-hosted' }} + # Run unmerged pull request code on an isolated GitHub-hosted runner. + runs-on: ${{ (github.event_name == 'pull_request' || inputs.runner == 'ubuntu-latest') && 'ubuntu-latest' || 'self-hosted' }} steps: - name: Checkout uses: actions/checkout@v4 @@ -58,6 +66,13 @@ jobs: fi gtar --version | head -n 1 + - name: Install WebP encoder (Ubuntu) + if: runner.environment == 'github-hosted' + run: sudo apt-get update && sudo apt-get install -y webp + + - name: Check WebP encoder + run: cwebp -version + - name: Setup Node uses: actions/setup-node@v4 with: @@ -70,29 +85,24 @@ jobs: - name: Install build deps run: npm ci --prefix scripts - - name: Build search & metadata index - run: node scripts/build-index.js + - name: Build static site + run: npm run build --prefix scripts - - name: Assemble _site - run: | - set -euo pipefail - rm -rf _site - mkdir -p _site - cp -R docs/. _site/ - cp -R assets _site/assets - cp -R Reports Posts Contributors _site/ - touch _site/.nojekyll - # do not ship raw npm install metadata - rm -rf _site/data/.git || true - ls -la _site | head -40 + - name: Verify generated pages and search + run: npm test --prefix scripts - name: Upload Pages artifact + if: github.event_name != 'pull_request' uses: actions/upload-pages-artifact@v3 with: path: _site deploy: + if: github.event_name != 'pull_request' needs: build + permissions: + pages: write + id-token: write runs-on: ${{ inputs.runner == 'ubuntu-latest' && 'ubuntu-latest' || 'self-hosted' }} environment: name: github-pages diff --git a/README.md b/README.md index dee70dc2..9dbf0d2f 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,10 @@ 我们也提供了[网页版本](https://swiftolddriver.github.io/iOS-Weekly/)供大家浏览。 +维护网页时,在仓库根目录运行 `npm ci --prefix scripts` 和 `npm run build:dev --prefix scripts`,然后打开 `http://localhost:8080/`。网页构建需要 Node.js 20 和 `cwebp`(macOS 可用 `brew install webp`,Ubuntu 可用 `sudo apt-get install webp`)。`npm run build --prefix scripts` 生成 `_site/`,`npm test --prefix scripts` 检查生成的链接和搜索。 + +周报模板标题下的 `` 会让该期跳过网页构建,包括首页、归档、搜索和正文页面。发布前移除标记,合入后网页随下一次 GitHub Pages 部署更新。 + ## [WWDC 内参](https://swiftolddriver.github.io/WWDC-InternalReference/) **WWDC 内参** 系列是由「老司机技术」牵头组织的精品原创内容系列。已经做了几年了,口碑一直不错。得益于组建的审核团队和不断优化的创作流程,大家创作的内容都已经超越了视频本身的内容,非常有学习和参考意义。 diff --git a/Report template.md b/Report template.md index 3c1cf0a3..4e662db6 100644 --- a/Report template.md +++ b/Report template.md @@ -1,5 +1,7 @@ # 老司机 iOS 周报 #319 | 2026-01-06 + + ![ios-weekly](https://github.com/SwiftOldDriver/iOS-Weekly/blob/master/assets/weekly-header/302.jpg?raw=true) 老司机 iOS 周报,只为你呈现有价值的信息。 diff --git a/Reports/2026/#384-2026.11.23.md b/Reports/2026/#384-2026.11.23.md index 459bf005..bbef5b76 100644 --- a/Reports/2026/#384-2026.11.23.md +++ b/Reports/2026/#384-2026.11.23.md @@ -1,5 +1,7 @@ # 老司机 iOS 周报 #384 | 2026-11-23 + + ![ios-weekly](https://github.com/SwiftOldDriver/iOS-Weekly/blob/master/assets/weekly-header/384.png?raw=true) 老司机 iOS 周报,只为你呈现有价值的信息。 diff --git a/docs/app.js b/docs/app.js index d28799f4..8688cbb7 100644 --- a/docs/app.js +++ b/docs/app.js @@ -1,639 +1,328 @@ -/** - * iOS Weekly site SPA - * - hash-based router - * - lazy-loaded full-text search via MiniSearch - * - markdown rendering via marked - * - reuses assets/page.css by wrapping content in
- */ - -import { marked } from "./vendor/marked.esm.js"; -import { tokenizeCJK } from "./vendor/tokenize.mjs"; - -const VIEW = document.getElementById("app-view"); -const SEARCH_INPUT = document.getElementById("app-search-input"); -const SEARCH_PANEL = document.getElementById("app-search-panel"); -const NAV_LINKS = document.querySelectorAll(".app-nav a[data-route]"); -const REPO_BASE = "https://github.com/SwiftOldDriver/iOS-Weekly/blob/master/"; -const REPO_IMAGE_BASES = [ - REPO_BASE, - "https://github.com/SwiftOldDriver/iOS-Weekly/raw/master/", - "https://raw.githubusercontent.com/SwiftOldDriver/iOS-Weekly/master/", -]; +import { buildPreviewSearch, highlightPattern } from "./search-core.mjs"; + +const SITE_ROOT = new URL("./", import.meta.url); +const QUICK_LIMIT = 8; +const LABELS = { report: "周报", post: "文章", contributor: "贡献者" }; +const input = document.querySelector("#app-search-input"); +const form = input?.form; +const panel = document.querySelector("#app-search-panel"); +const status = document.querySelector("#app-search-status"); +const more = document.querySelector("#app-search-more"); + +let previewPromise; +let worker; +let nextRequest = 0; +const requests = new Map(); + +function loadPreview() { + previewPromise ??= fetch(new URL("data/search-preview.json", SITE_ROOT)) + .then((response) => { + if (!response.ok) throw new Error(`Search preview: ${response.status}`); + return response.json(); + }) + .then(buildPreviewSearch) + .catch((error) => { + previewPromise = undefined; + throw error; + }); + return previewPromise; +} -marked.setOptions({ gfm: true, breaks: false }); +function makeWorker() { + const instance = new Worker(new URL("search-worker.js", SITE_ROOT), { type: "module" }); + instance.addEventListener("message", ({ data }) => { + const request = requests.get(data.scope); + if (request?.id !== data.id) return; + requests.delete(data.scope); + request.resolve(data.failed ? null : data); + }); + const onError = () => { + instance.terminate(); + if (worker !== instance) return; + worker = undefined; + for (const request of requests.values()) request.resolve(null); + requests.clear(); + }; + instance.addEventListener("error", onError); + instance.addEventListener("messageerror", onError); + return instance; +} -marked.use({ - walkTokens(token) { - if (token.type !== "image") return; +function cancelSearch(scope) { + const request = requests.get(scope); + if (!request) return; + requests.delete(scope); + request.resolve(null); + worker?.postMessage({ scope, id: ++nextRequest }); +} - const { href } = token; - // Legacy reports use a relative path from before the year directories. - if (href.startsWith("../assets/")) { - token.href = href.slice("../".length); - return; +function requestFullSearch(scope, query, limit) { + cancelSearch(scope); + return new Promise((resolve) => { + try { + worker ??= makeWorker(); + const id = ++nextRequest; + requests.set(scope, { id, resolve }); + worker.postMessage({ scope, id, query, limit }); + } catch { + requests.delete(scope); + resolve(null); } - - // Pages already ships these images under its own assets directory. - const base = REPO_IMAGE_BASES.find((base) => href.startsWith(`${base}assets/`)); - if (base) token.href = href.slice(base.length).replace(/\?raw=true$/, ""); - }, - renderer: { - // page.css uses .content to apply colored accents to headings. - heading(text, level) { - return `${text}\n`; - }, - }, -}); - -const state = { - index: null, // full index.json - byId: new Map(), // id -> entry - byType: { report: [], post: [], contributor: [] }, - yearGroups: [], // [{ year, items: [] }] - docCache: new Map(), // path -> rendered html - miniSearch: null, - searchLoading: null, // in-flight promise -}; - -const router = createRouter([ - { path: /^\/?$/, render: renderHome, name: "home" }, - { path: /^\/reports\/?$/, render: renderReports, name: "/reports" }, - { path: /^\/posts\/?$/, render: renderPosts, name: "/posts" }, - { path: /^\/contributors\/?$/, render: renderContributors, name: "/contributors" }, - { path: /^\/d\/(.+)$/, render: (m) => renderDetail(decodeURIComponent(m[1])) }, -]); - -bootstrap(); - -async function bootstrap() { - try { - const res = await fetch("data/index.json", { cache: "default" }); - if (!res.ok) throw new Error(`index.json HTTP ${res.status}`); - const data = await res.json(); - ingest(data); - window.addEventListener("hashchange", router.handle); - router.handle(); - installSearchHandlers(); - installShortcuts(); - } catch (err) { - VIEW.innerHTML = `
索引加载失败:${escapeHtml(err.message)}
`; - console.error(err); - } + }); } -function ingest(data) { - state.index = data; - for (const item of data.items) { - state.byId.set(item.id, item); - if (state.byType[item.type]) state.byType[item.type].push(item); +async function search(scope, query, limit, onPreview) { + let finished = false; + const preview = loadPreview().then((run) => { + if (finished) return null; + const result = run(query, limit); + onPreview(result); + return result; + }).catch(() => null); + const full = await requestFullSearch(scope, query, limit); + if (full) { + finished = true; + return { ...full, mode: "full" }; } - state.byType.report.sort((a, b) => (b.issue || 0) - (a.issue || 0)); - state.byType.post.sort((a, b) => (b.date || "").localeCompare(a.date || "")); - - const years = new Map(); - for (const r of state.byType.report) { - const y = r.year || "其他"; - if (!years.has(y)) years.set(y, []); - years.get(y).push(r); - } - state.yearGroups = [...years.entries()] - .map(([year, items]) => ({ year, items })) - .sort((a, b) => (b.year || 0) - (a.year || 0)); + const fallback = await preview; + return fallback ? { ...fallback, mode: "preview" } : { total: 0, results: [], mode: "failed" }; } -/* ===================================================================== - * Router - * ===================================================================== */ -function createRouter(routes) { - function parseHash() { - const h = location.hash || "#/"; - return h.replace(/^#/, ""); +function resultLink(result, query) { + const link = makeElement("a", "app-search__result"); + link.href = new URL(result.href, SITE_ROOT); + const head = makeElement("span", "app-search__result-head"); + const badge = makeElement("span", `app-badge app-badge--${result.type}`, LABELS[result.type]); + const title = makeElement("span", "app-search__result-title"); + const issue = result.type === "report" && result.id.match(/^r-(\d+)-/); + const label = issue ? `第 ${Number(issue[1])} 期` : result.title; + appendHighlight(title, label, query, result.matchedTerms); + head.append(badge, title); + if (result.date) { + const date = makeElement("time", "app-search__result-date", result.date); + date.dateTime = result.date; + head.append(date); } - async function handle() { - const path = parseHash(); - for (const r of routes) { - const m = path.match(r.path); - if (m) { - highlightNav(r.name); - VIEW.innerHTML = `
载入中…
`; - try { - await r.render(m); - VIEW.scrollTop = 0; - document.getElementById("main").focus({ preventScroll: true }); - window.scrollTo({ top: 0, behavior: "instant" in window ? "instant" : "auto" }); - } catch (err) { - console.error(err); - VIEW.innerHTML = `
加载失败:${escapeHtml(err.message)}
`; - } - return; - } - } - VIEW.innerHTML = `
页面不存在 — 回到首页
`; + link.append(head); + if (result.snippet) { + const snippet = makeElement("span", "app-search__result-snippet"); + appendHighlight(snippet, result.snippet, query, result.matchedTerms); + link.append(snippet); } - return { handle }; + return link; } -function highlightNav(name) { - NAV_LINKS.forEach((a) => { - a.classList.toggle("is-active", a.dataset.route === name); - }); +function makeElement(tag, className, text) { + const element = document.createElement(tag); + if (className) element.className = className; + if (text) element.textContent = text; + return element; } -/* ===================================================================== - * Views - * ===================================================================== */ -function renderHome() { - const reports = state.byType.report.slice(0, 8); - const posts = state.byType.post; - const contributors = state.byType.contributor.slice(0, 8); - const stats = state.index.stats || {}; - - const html = ` -
-

iOS 开发者的精品周报检索站

-

收录 ${stats.reports || 0} 期老司机 iOS 周报、${stats.posts || 0} 篇精品文章与 ${stats.contributors || 0} 位贡献者,支持全文搜索(按 / 快速聚焦)。

-
-
${stats.reports || 0} Reports
-
${stats.posts || 0} Posts
-
${stats.contributors || 0} Contributors
- ${stats.builtAt ? `
${stats.builtAt.slice(0, 10)} 索引更新
` : ""} -
-
- -
-
-

最近周报

- 全部 Reports → -
-
- ${reports.map(cardReport).join("")} -
-
- -
-
-

WWDC 内参

- 查看 WWDC 内参 → -
-
-

WWDC 内参 系列是由「老司机技术」牵头组织的精品原创内容系列。已经做了几年了,口碑一直不错。得益于组建的审核团队和不断优化的创作流程,大家创作的内容都已经超越了视频本身的内容,非常有学习和参考意义。

-
双审核机制:一位审核从专业性角度看内容是否正确,另外一位审核从读者角度看知识是否正确引导。
-

仓库已脱敏开源,覆盖 WWDC 21 – 24 历年内参。

- -
-
- -
-
-

精品文章

- 全部 Posts → -
-
- ${posts.map(cardPost).join("")} -
-
- -
-
-

部分贡献者

- 全部 Contributors → -
-
- ${contributors.map(cardContributor).join("")} -
-
- `; - VIEW.innerHTML = html; -} - -function renderReports() { - const html = ` -
-
-

Reports(${state.byType.report.length} 期)

-
- ${state.yearGroups.map(renderYearGroup).join("")} -
- `; - VIEW.innerHTML = html; - - VIEW.querySelectorAll(".app-year__head").forEach((btn) => { - btn.addEventListener("click", () => { - const yr = btn.closest(".app-year"); - yr.dataset.collapsed = yr.dataset.collapsed === "true" ? "false" : "true"; - }); - }); -} - -function renderYearGroup(group) { - const collapsed = group.year < (state.yearGroups[0]?.year || 0) - 1; - return ` -
- - -
- `; +function appendHighlight(element, text, query, terms) { + const pattern = highlightPattern(query, terms, "giu"); + let offset = 0; + if (pattern) { + for (const match of text.matchAll(pattern)) { + element.append(text.slice(offset, match.index), makeElement("mark", "", match[0])); + offset = match.index + match[0].length; + } + } + element.append(text.slice(offset)); } -function renderPosts() { - const html = ` -
-
-

Posts(${state.byType.post.length} 篇)

-
-
- ${state.byType.post.map(cardPost).join("")} -
-
- `; - VIEW.innerHTML = html; +function cleanQuery(value) { + return Array.from((value ?? "").trim()).slice(0, 120).join(""); } -function renderContributors() { - const html = ` -
-
-

Contributors(${state.byType.contributor.length} 位)

-
-
- ${state.byType.contributor.map(cardContributor).join("")} -
-
- `; - VIEW.innerHTML = html; +function resultMessage({ total, mode }) { + if (mode === "failed") return "搜索加载失败,请稍后重试。"; + if (mode === "preview") return `全文搜索暂不可用。标题和栏目匹配 ${total} 条。`; + return total ? `找到 ${total} 条结果` : "没有找到匹配结果"; } -async function renderDetail(id) { - const item = state.byId.get(id); - if (!item) { - VIEW.innerHTML = `
未找到内容 — 回到首页
`; - return; - } - - const head = ` -
- 返回${typeLabel(item.type)}列表 -
- ${typeLabel(item.type)} - ${item.date ? `${escapeHtml(item.date)}` : ""} - ${item.path ? `在 GitHub 查看源文件 ↗` : ""} -
-
${renderDetailBody(item)}
-
- `; - VIEW.innerHTML = head; - - const body = document.getElementById("app-detail-body"); - try { - const html = await fetchAndRender(item); - body.innerHTML = `
${html}
`; - applyExternalLinks(body); - applyInternalAnchors(body); - } catch (err) { - body.innerHTML = `
内容加载失败:${escapeHtml(err.message)}
`; +function installQuickSearch() { + let revision = 0; + let timer; + let options = []; + let active = -1; + let composing = false; + let composingEnter = false; + const count = makeElement("span", "app-search__count"); + const all = makeElement("a", "app-search__all", "查看全部"); + more.replaceChildren(count, all); + + function showMore(message, query) { + status.textContent = message; + count.textContent = message; + const resultsUrl = new URL("search/", SITE_ROOT); + resultsUrl.searchParams.set("q", query); + all.href = resultsUrl; + more.hidden = false; } -} -function renderDetailBody(item) { - if (item.type === "contributor" && item.body) { - try { - return `
${marked.parse(item.body)}
`; - } catch { - // fall through to fetch path + function setActive(index, scroll = true) { + active = index; + for (const [position, option] of options.entries()) { + const selected = position === index; + option.classList.toggle("is-active", selected); + option.setAttribute("aria-selected", String(selected)); + } + const option = options[active]; + if (option) { + input.setAttribute("aria-activedescendant", option.id); + if (scroll) option.scrollIntoView({ block: "nearest" }); + } else { + input.removeAttribute("aria-activedescendant"); } } - return `
载入正文…
`; -} - -async function fetchAndRender(item) { - if (state.docCache.has(item.id)) return state.docCache.get(item.id); - if (item.type === "contributor" && item.body) { - const html = marked.parse(item.body); - state.docCache.set(item.id, html); - return html; + function renderOptions(results, query) { + const selected = options[active]?.href; + options = results.map((result, index) => { + const option = resultLink(result, query); + option.id = `app-search-option-${index}`; + option.tabIndex = -1; + option.setAttribute("role", "option"); + return option; + }); + panel.replaceChildren(...options); + panel.hidden = !options.length; + input.setAttribute("aria-expanded", String(options.length > 0)); + setActive(options.findIndex((option) => option.href === selected), false); } - const url = item.url || encodePath(item.path); - const res = await fetch(url, { cache: "default" }); - if (!res.ok) throw new Error(`HTTP ${res.status}`); - const md = await res.text(); - const html = marked.parse(md); - state.docCache.set(item.id, html); - if (state.docCache.size > 12) { - const firstKey = state.docCache.keys().next().value; - state.docCache.delete(firstKey); + function dismiss() { + revision++; + clearTimeout(timer); + cancelSearch("popup"); + renderOptions([], ""); + more.hidden = true; + status.textContent = ""; } - return html; -} - -/* ===================================================================== - * Cards - * ===================================================================== */ -function cardReport(it) { - return ` - -
- 周报 - #${it.issue ?? "—"} - · - ${escapeHtml(it.date || "")} -
-

${escapeHtml(reportShortTitle(it))}

-

${escapeHtml(it.excerpt || "")}

-
- `; -} - -function cardPost(it) { - return ` - -
- 文章 - ${it.date ? `${escapeHtml(it.date)}` : ""} -
-

${escapeHtml(it.title)}

-

${escapeHtml(it.excerpt || "")}

-
- `; -} - -function cardContributor(it) { - const avatar = it.avatar || "assets/ios-weekly-avatar-new.png"; - return ` - - -

${escapeHtml(it.title)}

-

${escapeHtml(it.excerpt || "")}

-
- `; -} -/* ===================================================================== - * Search - * ===================================================================== */ -function installSearchHandlers() { - let activeIdx = -1; - let lastResults = []; - const debounced = debounce(runSearch, 120); + function schedule() { + dismiss(); + const query = cleanQuery(input.value); + if (!query || composing || document.activeElement !== input) return; + const current = revision; + showMore("正在搜索…", query); + timer = setTimeout(async () => { + const result = await search("popup", query, QUICK_LIMIT, (preview) => { + if (current !== revision) return; + renderOptions(preview.results, query); + showMore(`标题和栏目匹配 ${preview.total} 条,正在搜索全文…`, query); + }); + if (current !== revision) return; + renderOptions(result.results, query); + showMore(resultMessage(result), query); + }, 120); + } - SEARCH_INPUT.addEventListener("focus", () => { - ensureSearchLoaded(); - if (SEARCH_INPUT.value.trim()) showPanel(); + input.addEventListener("focus", schedule); + input.addEventListener("input", (event) => { + if (!event.isComposing && !composing) schedule(); + }); + input.addEventListener("compositionstart", () => { + composing = true; + dismiss(); }); - SEARCH_INPUT.addEventListener("input", () => { - debounced(SEARCH_INPUT.value); + input.addEventListener("compositionend", () => { + composing = false; + schedule(); }); - SEARCH_INPUT.addEventListener("keydown", (e) => { - if (e.key === "Escape") { - SEARCH_INPUT.blur(); - hidePanel(); + input.addEventListener("keydown", (event) => { + if (composing || event.isComposing || event.keyCode === 229) { + if (event.key === "Enter") { + composingEnter = true; + setTimeout(() => { composingEnter = false; }, 0); + } return; } - if (!lastResults.length) return; - if (e.key === "ArrowDown") { - e.preventDefault(); - activeIdx = (activeIdx + 1) % lastResults.length; - updateActive(); - } else if (e.key === "ArrowUp") { - e.preventDefault(); - activeIdx = (activeIdx - 1 + lastResults.length) % lastResults.length; - updateActive(); - } else if (e.key === "Enter") { - e.preventDefault(); - const pick = lastResults[Math.max(0, activeIdx)]; - if (pick) { - location.hash = `#/d/${encodeURIComponent(pick.id)}`; - SEARCH_INPUT.value = ""; - hidePanel(); - SEARCH_INPUT.blur(); - } + if (event.key === "Escape" && !more.hidden) { + event.preventDefault(); + dismiss(); + } else if (options.length && (event.key === "ArrowDown" || event.key === "ArrowUp")) { + event.preventDefault(); + const next = event.key === "ArrowDown" ? active + 1 : active < 0 ? options.length - 1 : active - 1; + setActive((next + options.length) % options.length); + } else if (event.key === "Enter" && options[active]) { + event.preventDefault(); + const href = options[active].href; + dismiss(); + window.location.assign(href); } }); - - document.addEventListener("click", (e) => { - if (!e.target.closest(".app-search")) hidePanel(); - }); - - function updateActive() { - SEARCH_PANEL.querySelectorAll(".app-search__result").forEach((el, i) => { - el.classList.toggle("is-active", i === activeIdx); - if (i === activeIdx) el.scrollIntoView({ block: "nearest" }); - }); - } - - async function runSearch(query) { - const q = query.trim(); - if (!q) { - lastResults = []; - activeIdx = -1; - hidePanel(); - return; - } - showPanel(`
搜索中…
`); - const results = await search(q); - lastResults = results; - activeIdx = results.length ? 0 : -1; - if (!results.length) { - showPanel(`
没有匹配结果。
`); + form.addEventListener("submit", (event) => { + const query = cleanQuery(input.value); + if (composing || composingEnter || !query) { + event.preventDefault(); return; } - showPanel(results.map((r, i) => renderResult(r, i === 0, q)).join("")); - } - - function showPanel(content) { - if (typeof content === "string") SEARCH_PANEL.innerHTML = content; - SEARCH_PANEL.hidden = false; - SEARCH_INPUT.setAttribute("aria-expanded", "true"); - } - function hidePanel() { - SEARCH_PANEL.hidden = true; - SEARCH_INPUT.setAttribute("aria-expanded", "false"); + input.value = query; + dismiss(); + }); + form.addEventListener("focusout", (event) => { + if (!form.contains(event.relatedTarget)) dismiss(); + }); + document.addEventListener("pointerdown", (event) => { + if (!form.contains(event.target) && !more.hidden) dismiss(); + }); + for (const container of [panel, more]) { + container.addEventListener("mousedown", (event) => { + // Keep focus on the combobox until a pointer selection is activated. + if (event.button === 0 && event.target.closest("a[href]")) event.preventDefault(); + }); + container.addEventListener("click", (event) => { + const link = event.target.closest("a[href]"); + if (!link || event.defaultPrevented) return; + if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) { + setTimeout(dismiss, 0); + return; + } + event.preventDefault(); + const href = link.href; + dismiss(); + window.location.assign(href); + }); } + window.addEventListener("pagehide", dismiss); + document.addEventListener("keydown", (event) => { + if (event.key !== "/" || event.isComposing || event.altKey || event.ctrlKey || event.metaKey) return; + if (event.target.closest?.("input, textarea, select, [contenteditable]:not([contenteditable='false'])")) return; + event.preventDefault(); + input.focus(); + input.select(); + }); } -function renderResult(r, active, query) { - const item = state.byId.get(r.id); - if (!item) return ""; - const snippet = makeSnippet(item, query); - return ` - -
- ${typeLabel(item.type)} - ${escapeHtml(item.title)} - ${item.date ? `· ${escapeHtml(item.date)}` : ""} -
-
${snippet}
-
- `; -} - -function makeSnippet(item, query) { - const haystack = [item.excerpt || "", item.body || "", (item.sections || []).map((s) => `${s.heading || ""} ${s.summary || ""}`).join(" ")].join(" "); - const tokens = query.split(/\s+/).filter(Boolean).map((t) => t.toLowerCase()); - if (!haystack || !tokens.length) return escapeHtml((item.excerpt || "").slice(0, 120)); - const lower = haystack.toLowerCase(); - let pos = -1; - for (const t of tokens) { - const p = lower.indexOf(t); - if (p >= 0 && (pos < 0 || p < pos)) pos = p; - } - if (pos < 0) return escapeHtml(haystack.slice(0, 120)); - const start = Math.max(0, pos - 30); - const end = Math.min(haystack.length, pos + 100); - let frag = haystack.slice(start, end); - if (start > 0) frag = "…" + frag; - if (end < haystack.length) frag += "…"; - let html = escapeHtml(frag); - for (const t of tokens) { - const re = new RegExp(escapeRegex(t), "gi"); - html = html.replace(re, (m) => `${m}`); +async function showSearchPage() { + const list = document.querySelector("#app-search-results"); + const message = document.querySelector("#app-search-results-status"); + if (!list || !message) return; + const query = cleanQuery(new URLSearchParams(window.location.search).get("q")); + if (!query) { + message.textContent = "输入期号、关键词或技术标识符开始搜索。"; + return; } - return html; -} + if (input) input.value = query; -async function ensureSearchLoaded() { - if (state.miniSearch) return state.miniSearch; - if (state.searchLoading) return state.searchLoading; - state.searchLoading = (async () => { - const [{ default: MiniSearch }, raw] = await Promise.all([ - import("./vendor/minisearch.esm.js"), - fetch("data/search.json", { cache: "default" }).then((r) => { - if (!r.ok) throw new Error(`search.json HTTP ${r.status}`); - return r.json(); - }), - ]); - state.miniSearch = MiniSearch.loadJS(raw, { - idField: "id", - fields: ["title", "sections", "body"], - storeFields: ["id", "title", "type", "date"], - tokenize: tokenizeCJK, - searchOptions: { - prefix: true, - fuzzy: 0.15, - boost: { title: 3, sections: 2 }, - combineWith: "AND", - }, + function update(results, text) { + const rows = results.map((result) => { + const row = document.createElement("li"); + row.append(resultLink(result, query)); + return row; }); - return state.miniSearch; - })().catch((err) => { - console.error("search load failed", err); - state.searchLoading = null; - throw err; - }); - return state.searchLoading; -} - -async function search(query) { - try { - const ms = await ensureSearchLoaded(); - return ms.search(query).slice(0, 30); - } catch { - return fallbackSearch(query); + list.replaceChildren(...rows); + message.textContent = `“${query}”:${text}`; } -} - -function fallbackSearch(query) { - const q = query.toLowerCase(); - const tokens = q.split(/\s+/).filter(Boolean); - if (!tokens.length) return []; - return state.index.items - .map((it) => { - const hay = `${it.title}\n${it.excerpt || ""}\n${(it.sections || []).map((s) => s.heading || "").join("\n")}`.toLowerCase(); - const score = tokens.reduce((s, t) => s + (hay.includes(t) ? 1 : 0), 0); - return { id: it.id, score }; - }) - .filter((r) => r.score > 0) - .sort((a, b) => b.score - a.score) - .slice(0, 30); -} - -function installShortcuts() { - document.addEventListener("keydown", (e) => { - if (e.key === "/" && !isTypingTarget(e.target)) { - e.preventDefault(); - SEARCH_INPUT.focus(); - SEARCH_INPUT.select(); - } - }); -} - -/* ===================================================================== - * Helpers - * ===================================================================== */ -function reportShortTitle(it) { - const t = it.title || ""; - return t.replace(/^老司机[^#]*#\d+\s*\|?\s*/, "").trim() || t; -} - -function typeLabel(type) { - return { report: "周报", post: "文章", contributor: "贡献者" }[type] || type; -} -function backHref(item) { - return { report: "#/reports", post: "#/posts", contributor: "#/contributors" }[item.type] || "#/"; -} - -function encodePath(p) { - return p.split("/").map((s) => encodeURIComponent(s)).join("/"); -} - -function applyExternalLinks(root) { - root.querySelectorAll("a[href]").forEach((a) => { - const href = a.getAttribute("href") || ""; - if (/^https?:\/\//i.test(href)) { - a.target = "_blank"; - a.rel = "noopener noreferrer"; - } - }); -} - -function applyInternalAnchors(root) { - /* Collapse first H1 in body since we already show the title in meta? Keep H1 for visual continuity. */ - root.querySelectorAll("img[src]").forEach((img) => { - img.loading = "lazy"; - img.referrerPolicy = "no-referrer"; + update([], "正在搜索…"); + const result = await search("page", query, undefined, (preview) => { + update(preview.results, `标题和栏目匹配 ${preview.total} 条,正在搜索全文…`); }); + update(result.results, resultMessage(result)); } -function debounce(fn, ms) { - let t; - return function (...args) { - clearTimeout(t); - t = setTimeout(() => fn.apply(this, args), ms); - }; -} - -function isTypingTarget(t) { - if (!t) return false; - const tag = t.tagName; - return tag === "INPUT" || tag === "TEXTAREA" || t.isContentEditable; -} - -function escapeHtml(s) { - return String(s ?? "") - .replace(/&/g, "&") - .replace(//g, ">") - .replace(/"/g, """) - .replace(/'/g, "'"); -} -function escapeAttr(s) { return escapeHtml(s); } -function escapeRegex(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } +if (form && panel && status && more) installQuickSearch(); +showSearchPage(); diff --git a/docs/index.html b/docs/index.html index f32d5a4e..26c08957 100644 --- a/docs/index.html +++ b/docs/index.html @@ -3,70 +3,74 @@ - - - 老司机 iOS 周报 - - - - - - + + + + {{TITLE}} + {{PAGE_META}} + + + {{ARTICLE_CSS}} + - + 跳到主要内容 - -