feat(structure): compact archive + tag pages + hero/featured, and fix site search
Deploy / build (push) Failing after 13m52s

Found a real bug while verifying the nav search: /pagefind/pagefind.js is an ES
module that defines no window.Pagefind, but Search.astro loaded it with a classic
<script src> and read window.Pagefind — so every query answered "Search is
unavailable." (confirmed live before the fix). Now a dynamic import; the specifier
must be a variable or Rollup resolves it at build time and the build fails.

Measured before/after in a real browser:

- archive /posts/ + /zh/posts/: 18,220px -> 3,788px (71 rows at 44px, grouped by
  year) with a client-side filter (title/tags/description text, category chips,
  14 tag chips, zero requests). Tested: "nginx" -> 6 rows, chip devops -> 28.
- tag pages for tags with >= 3 posts. Measured 235 distinct tags (an earlier brief
  claimed 74), 156 used exactly once — pages only where a topic exists: 40 tags ->
  80 pages, build 165 -> 245 pages. Pills link only when a page exists.
- homepage + ZH homepage: hero (288px) with the real scale claim, three CTAs, a
  fixed Featured 4 (scale -> automation -> observability -> a delivered result),
  Latest 10 -> 6. ZH hero had linked "关于我" to the English /about/.
- long code blocks collapse above 420px with an Expand button + gradient, copy
  button still copies the whole block (verified on the 1010px block).
- search is visible ("⌕ Search /" pill, "/" plus the existing Ctrl/Cmd+K) and the
  zero-result screen offers topic chips instead of a dead end.

Docs: project-state B3 entry, ops-runbook Pagefind gotcha.
This commit is contained in:
hoelee committed 2026-10-16 21:18:25 +08:00
1 parent 8619e48271
commit f4008d9e8b
15 files changed
+669 -60

No files matched your search

+238
View File
@@ -0,0 +1,238 @@
---
import type { CollectionEntry } from 'astro:content';
import { tagCounts, tagHref } from '../lib/tags';
interface Props {
posts: CollectionEntry<'posts'>[];
lang?: 'en' | 'zh';
/** Filter bar + chips. Off on tag/collection pages, where the set is already narrow. */
chrome?: boolean;
}
const { posts, lang = 'en', chrome = true } = Astro.props;
const isZh = lang === 'zh';
const counts = tagCounts(posts);
const years = [...new Set(posts.map((p) => p.data.pubDate.getUTCFullYear()))].sort((a, b) => b - a);
const categories = [...new Set(posts.map((p) => p.data.category))]
.map((c) => ({ name: c, n: posts.filter((p) => p.data.category === c).length }))
.sort((a, b) => b.n - a.n);
// Only tags that have their own page become chips — a chip that leads nowhere is the
// same trap the old non-clickable pills were.
const chips = [...counts.entries()]
.filter(([, n]) => n >= 3)
.sort((a, b) => b[1] - a[1])
.slice(0, 14)
.map(([t, n]) => ({ tag: t, n }));
const shortDate = (d: Date) =>
`${String(d.getUTCMonth() + 1).padStart(2, '0')}-${String(d.getUTCDate()).padStart(2, '0')}`;
const yearOf = (d: Date) => d.getUTCFullYear();
const labels = isZh
? { filter: '按标题或标签筛选…', all: '全部', empty: '没有匹配的文章。', search: '全文搜索', count: '篇' }
: { filter: 'Filter by title or tag…', all: 'All', empty: 'No posts match.', search: 'Full-text search', count: 'posts' };
---
{chrome && (
<>
<div class="archive-bar">
<input
type="search"
id="archive-q"
class="archive-input"
placeholder={labels.filter}
autocomplete="off"
aria-label={labels.filter}
/>
<button class="archive-overlay-btn" id="archive-search" type="button">⌕ {labels.search}</button>
</div>
<div class="archive-chips" role="group" aria-label={isZh ? '按分类筛选' : 'Filter by category'}>
<button class="chip is-active" data-cat="" type="button">{labels.all} <span>{posts.length}</span></button>
{categories.map((c) => (
<button class="chip" data-cat={c.name} type="button">{c.name} <span>{c.n}</span></button>
))}
</div>
<div class="archive-chips archive-tags" role="group" aria-label={isZh ? '按标签筛选' : 'Filter by tag'}>
{chips.map((c) => (
<a class="chip tag-chip" href={tagHref(c.tag, lang)}>{c.tag} <span>{c.n}</span></a>
))}
</div>
</>
)}
{!chrome && <p class="archive-meta">{posts.length} {labels.count}</p>}
<ol class="archive" id="archive-list">
{years.map((y) => (
<li class="archive-year-block" data-year={y}>
<h2 class="archive-year">{y}</h2>
<ol class="archive-rows">
{posts.filter((p) => yearOf(p.data.pubDate) === y).map((p) => (
<li
class="archive-row"
data-cat={p.data.category}
data-tags={p.data.tags.join(' ')}
data-q={`${p.data.title} ${p.data.tags.join(' ')} ${p.data.description}`.toLowerCase()}
>
<time datetime={p.data.pubDate.toISOString()}>{shortDate(p.data.pubDate)}</time>
<a class="archive-title" href={`/posts/${p.slug}/`}>{p.data.title}</a>
<a class="archive-cat" href={`${isZh ? '/zh' : ''}/categories/${p.data.category}/`}>{p.data.category}</a>
</li>
))}
</ol>
</li>
))}
</ol>
<p class="archive-empty" id="archive-empty" hidden>{labels.empty}</p>
<style>
.archive-bar {
display: flex;
gap: 0.6rem;
align-items: center;
margin: 1.25rem 0 0.9rem;
flex-wrap: wrap;
}
.archive-input {
flex: 1 1 16rem;
min-width: 12rem;
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
color: var(--ink);
font: inherit;
font-size: 0.95rem;
padding: 0.6rem 0.8rem;
}
.archive-input:focus { outline: none; border-color: var(--brand); }
.archive-overlay-btn {
font: inherit;
font-size: 0.9rem;
color: var(--muted);
background: none;
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 0.6rem 0.8rem;
cursor: pointer;
white-space: nowrap;
}
.archive-overlay-btn:hover { color: var(--brand); border-color: var(--brand); }
.archive-chips { display: flex; flex-wrap: wrap; gap: 0.4rem; margin-bottom: 0.5rem; }
.archive-tags { margin-bottom: 1.1rem; }
.chip {
font: inherit;
font-size: 0.78rem;
color: var(--muted);
background: var(--surface);
border: 1px solid var(--border);
border-radius: 999px;
padding: 0.22rem 0.6rem;
cursor: pointer;
text-decoration: none;
white-space: nowrap;
}
.chip span { opacity: 0.55; margin-left: 0.15rem; }
.chip:hover { color: var(--brand); border-color: var(--brand); }
.chip.is-active { color: var(--ink); border-color: var(--brand); }
.archive { list-style: none; padding: 0; margin: 0; }
.archive-year {
font-size: 0.8rem;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--faint);
margin: 1.4rem 0 0.4rem;
padding-bottom: 0.3rem;
border-bottom: 1px solid var(--border);
}
.archive-rows { list-style: none; padding: 0; margin: 0; }
.archive-row {
display: flex;
align-items: center;
gap: 0.8rem;
min-height: 44px;
border-bottom: 1px solid color-mix(in srgb, var(--border) 45%, transparent);
}
.archive-row time {
flex: 0 0 3.2rem;
font-family: var(--font-mono);
font-size: 0.8rem;
color: var(--faint);
}
.archive-title {
flex: 1 1 auto;
color: var(--ink);
text-decoration: none;
font-size: 0.95rem;
line-height: 1.35;
}
.archive-title:hover { color: var(--brand); }
.archive-cat {
flex: 0 0 auto;
font-size: 0.72rem;
color: var(--muted);
text-decoration: none;
border: 1px solid var(--border);
border-radius: 999px;
padding: 0.1em 0.55em;
}
.archive-cat:hover { color: var(--brand); border-color: var(--brand); }
.archive-empty { color: var(--muted); margin-top: 1.5rem; }
[hidden] { display: none !important; }
@media (max-width: 600px) {
.archive-row { flex-wrap: wrap; gap: 0.3rem 0.6rem; padding: 0.4rem 0; }
.archive-title { flex: 1 1 100%; order: 2; }
.archive-row time { flex: 0 0 auto; order: 1; }
.archive-cat { order: 1; }
}
</style>
<script>
// Client-side filter over an already-rendered list: zero network requests, works
// with the browser's own Ctrl+F, and keeps the archive one static page.
const q = document.getElementById('archive-q') as HTMLInputElement | null;
const list = document.getElementById('archive-list');
const empty = document.getElementById('archive-empty');
const chips = Array.from(document.querySelectorAll('.chip[data-cat]'));
const overlayBtn = document.getElementById('archive-search');
let activeCat = '';
overlayBtn?.addEventListener('click', () => {
document.getElementById('search-toggle')?.click();
});
function apply() {
const term = (q?.value ?? '').trim().toLowerCase();
const terms = term ? term.split(/\s+/) : [];
let shown = 0;
document.querySelectorAll('.archive-row').forEach((row) => {
const el = row as HTMLElement;
const cat = el.dataset.cat ?? '';
const hay = el.dataset.q ?? '';
const okCat = !activeCat || cat === activeCat;
const okTerm = terms.every((t) => hay.includes(t));
const ok = okCat && okTerm;
el.hidden = !ok;
if (ok) shown++;
});
document.querySelectorAll('.archive-year-block').forEach((block) => {
const el = block as HTMLElement;
const any = Array.from(el.querySelectorAll('.archive-row')).some((r) => !(r as HTMLElement).hidden);
el.hidden = !any;
});
if (empty) empty.hidden = shown !== 0;
}
q?.addEventListener('input', apply);
chips.forEach((chip) => {
chip.addEventListener('click', () => {
activeCat = (chip as HTMLElement).dataset.cat ?? '';
chips.forEach((c) => c.classList.toggle('is-active', c === chip));
apply();
});
});
</script>
+11 -1
View File
@@ -1,5 +1,8 @@
---
import type { CollectionEntry } from 'astro:content';
import { getCollection } from 'astro:content';
import { postLang } from '../lib/lang';
import { tagCounts, tagLink } from '../lib/tags';
interface Props {
posts: CollectionEntry<'posts'>[];
@@ -24,6 +27,10 @@ const catHref = (cat: string) => `/${isZh ? 'zh/categories' : 'categories'}/${ca
const og = (post: CollectionEntry<'posts'>) => post.data.ogImage || '/og-default.png';
// Tag pills only link when the tag has its own page (>= TAG_MIN_POSTS in this language).
const counts = tagCounts((await getCollection('posts', ({ data }) => !data.draft))
.filter((p) => postLang(p.slug) === lang));
// The row thumbnail is displayed at ~398 CSS px wide, so the list used to pull a
// 1200x630 PNG (~45 KB) per row for a 398px slot. Serve 400w/800w WebP derived from
// the same art instead (5.8 KB / 16.1 KB — see scripts/optimize-images.py).
@@ -64,7 +71,10 @@ const thumb = (post: CollectionEntry<'posts'>, w: 400 | 800) =>
)}
<span class="sep">·</span>
<a class="tag" href={catHref(post.data.category)}>{post.data.category}</a>
{post.data.tags.map((t) => <span class="tag">{t}</span>)}
{post.data.tags.map((t) => {
const href = tagLink(t, counts, lang);
return href ? <a class="tag" href={href}>{t}</a> : <span class="tag">{t}</span>;
})}
</div>
<p>{post.data.description}</p>
</div>
+44 -15
View File
@@ -11,6 +11,13 @@ const placeholder =
lang === 'zh' ? '搜索文章…' : 'Search posts…';
const noResults =
lang === 'zh' ? '没有匹配的结果。' : 'No results.';
// Empty-search state: a dead end helps nobody. Offer the topic entry points that
// actually exist (tag pages are generated for tags with >= 3 posts).
const popular = ['docker', 'self-hosting', 'nginx', 'monitoring', 'automation'];
const popularHref = (t: string) => (lang === 'zh' ? `/zh/tags/${t}/` : `/tags/${t}/`);
const tryLabel = lang === 'zh' ? '试试这些主题:' : 'Try a topic:';
const archiveLabel = lang === 'zh' ? '浏览全部文章' : 'Browse all posts';
const archiveHref = lang === 'zh' ? '/zh/posts/' : '/posts/';
---
<div class="search-overlay" id="search-overlay" hidden>
@@ -28,6 +35,16 @@ const noResults =
</div>
<div class="search-results" id="search-results"></div>
</div>
<!-- Dead-end screen for a search with no hits: real links, rendered at build time. -->
<template id="search-empty-tpl">
<p class="excerpt" data-role="message">{noResults}</p>
<p class="excerpt" data-role="try">{tryLabel}</p>
<p class="search-empty-chips">
{popular.map((t) => <a class="chip" href={popularHref(t)}>{t}</a>)}
<a class="chip" href={archiveHref}>{archiveLabel}</a>
</p>
</template>
</div>
<style>
@@ -88,6 +105,17 @@ const noResults =
.search-result:hover { color: var(--brand); }
.search-result h3 { margin: 0 0 0.2rem; font-size: 1.05rem; }
.search-result .excerpt { color: var(--muted); font-size: 0.88rem; margin: 0; }
.search-empty-chips { display: flex; flex-wrap: wrap; gap: 0.4rem; margin-top: 0.5rem; }
.search-empty .chip {
color: var(--muted);
background: var(--surface);
border: 1px solid var(--border);
border-radius: 999px;
padding: 0.22rem 0.6rem;
font-size: 0.78rem;
text-decoration: none;
}
.search-empty .chip:hover { color: var(--brand); border-color: var(--brand); }
.search-result mark {
background: color-mix(in srgb, var(--brand) 25%, transparent);
color: var(--ink);
@@ -140,17 +168,17 @@ const noResults =
async function loadPagefind() {
if (pagefind) return pagefind;
// Pagefind's UI/JS is copied into /pagefind/ post-build. Load it via a
// script tag (not a dynamic import) so Vite leaves the URL untouched.
await new Promise<void>((resolve, reject) => {
const s = document.createElement('script');
s.src = '/pagefind/pagefind.js';
s.onload = () => resolve();
s.onerror = () => reject(new Error('pagefind load failed'));
document.head.appendChild(s);
});
const w = window as unknown as { Pagefind?: Pagefind };
pagefind = w.Pagefind;
// /pagefind/pagefind.js is copied into the build post-build. It is an **ES module**
// (`export { search, debouncedSearch, … }`) and defines NO window global, so loading
// it with a classic <script src> leaves window.Pagefind undefined and every search
// answered "Search is unavailable." — which is what happened between the search
// shipping and this fix. Import it as a module instead; @vite-ignore keeps Vite from
// trying to resolve a path that only exists in dist/.
// The specifier must be a VARIABLE: Rollup resolves a literal dynamic-import path
// at build time (and @vite-ignore does not stop it), which breaks the build because
// /pagefind/ only exists in dist/ after the index is generated.
const url = '/pagefind/pagefind.js';
pagefind = (await import(/* @vite-ignore */ url)) as unknown as Pagefind;
return pagefind;
}
@@ -169,10 +197,11 @@ const noResults =
const res = await search;
results.innerHTML = '';
if (!res.results.length) {
const empty = document.createElement('p');
empty.className = 'excerpt';
empty.textContent = 'No results.';
results.appendChild(empty);
// Clone the build-time template: the links cannot drift from the pages that
// actually exist (tag pages are only generated for tags with >= 3 posts).
results.innerHTML = '';
const tpl = document.getElementById('search-empty-tpl') as HTMLTemplateElement | null;
if (tpl) results.appendChild(tpl.content.cloneNode(true));
return;
}
for (const r of res.results.slice(0, 12)) {