Dough Git

commit

Updates

commit
f1a8d31ebb09c4d331090992026797cbb8fec92d
author
Clove Twilight <[email protected]>
date
2026-11-10 21:08

diff --git a/src/lib/components/Header.svelte b/src/lib/components/Header.svelte
index 45108e0..ec5939c 100644
--- a/src/lib/components/Header.svelte
+++ b/src/lib/components/Header.svelte
@@ -8,6 +8,7 @@
 	import IcKey from '~icons/ic/outline-key';
 	import Hamburger from '#lib/components/Hamburger.svelte';
 	import NowPlaying from '#lib/components/NowPlaying.svelte';
+	import SearchPalette from '#lib/components/SearchPalette.svelte';
 	import SiGithub from '~icons/simple-icons/github';
 	import SiDiscord from '~icons/simple-icons/discord';
 	import '#lib/styles/header.css';
@@ -38,6 +39,7 @@
 		<a href="/blog" title="Blog"
 			><IcArticle class="nav-icon" /><span class="nav-label">Blog</span></a
 		>
+		<SearchPalette />
 		<Hamburger />
 	</nav>
 	<NowPlaying />
diff --git a/src/lib/components/SearchPalette.svelte b/src/lib/components/SearchPalette.svelte
new file mode 100644
index 0000000..2e4ae68
--- /dev/null
+++ b/src/lib/components/SearchPalette.svelte
@@ -0,0 +1,181 @@
+<!-- src/lib/components/SearchPalette.svelte
+     DASL-1.2 — (c) Clove Twilight
+-->
+
+<script lang="ts">
+	import IcSearch from '~icons/ic/outline-search';
+	import '#lib/styles/search.css';
+	import { KIND_LABEL, loadIndex, search, type SearchItem } from '#lib/scripts/search.ts';
+
+	let dialog: HTMLDialogElement | undefined = $state();
+	let input: HTMLInputElement | undefined = $state();
+	let list: HTMLUListElement | undefined = $state();
+
+	let items = $state<SearchItem[]>([]);
+	let query = $state('');
+	let activeIndex = $state(0);
+	let loadError = $state('');
+	let loading = $state(false);
+
+	const results = $derived(search(items, query));
+	const activeId = $derived(results.length ? `search-result-${activeIndex}` : undefined);
+
+	// Mac shows ⌘K, everything else Ctrl K
+	let shortcut = $state('Ctrl K');
+
+	$effect(() => {
+		if (/Mac|iPhone|iPad/.test(navigator.platform)) shortcut = '⌘K';
+	});
+
+	// A new query starts back at the top result
+	$effect(() => {
+		void query;
+		activeIndex = 0;
+	});
+
+	async function open() {
+		if (!dialog || dialog.open) return;
+
+		query = '';
+		dialog.showModal();
+		input?.focus();
+
+		if (items.length) return;
+
+		loading = true;
+		loadError = '';
+
+		try {
+			items = await loadIndex();
+		} catch {
+			loadError = 'Search is unavailable right now, try again in a moment.';
+		} finally {
+			loading = false;
+		}
+	}
+
+	function close() {
+		dialog?.close();
+	}
+
+	function isExternal(url: string): boolean {
+		return /^(https?:|mailto:)/.test(url);
+	}
+
+	function moveTo(index: number) {
+		if (!results.length) return;
+
+		activeIndex = (index + results.length) % results.length;
+
+		list?.querySelector(`#search-result-${activeIndex}`)?.scrollIntoView({ block: 'nearest' });
+	}
+
+	// Ctrl+K / ⌘K anywhere on the site toggles the palette
+	function onWindowKeydown(event: KeyboardEvent) {
+		if (event.key.toLowerCase() !== 'k' || !(event.ctrlKey || event.metaKey)) return;
+
+		event.preventDefault();
+
+		if (dialog?.open) close();
+		else open();
+	}
+
+	function onInputKeydown(event: KeyboardEvent) {
+		if (event.key === 'ArrowDown') {
+			event.preventDefault();
+			moveTo(activeIndex + 1);
+		} else if (event.key === 'ArrowUp') {
+			event.preventDefault();
+			moveTo(activeIndex - 1);
+		} else if (event.key === 'Enter' && results.length) {
+			event.preventDefault();
+
+			// Results are real links, so clicking one lets SvelteKit (or the browser) navigate
+			list?.querySelector<HTMLAnchorElement>(`#search-result-${activeIndex}`)?.click();
+		}
+	}
+
+	// A click on the dimmed area outside the box lands on the dialog itself
+	function onDialogClick(event: MouseEvent) {
+		if (event.target === dialog) close();
+	}
+</script>
+
+<svelte:window onkeydown={onWindowKeydown} />
+
+<button class="search-trigger" type="button" aria-label="Search the site" onclick={open}>
+	<IcSearch class="nav-icon" />
+	<kbd class="search-shortcut" aria-hidden="true">{shortcut}</kbd>
+</button>
+
+<dialog class="search-dialog" bind:this={dialog} onclick={onDialogClick} aria-label="Search">
+	<div class="search-box">
+		<div class="search-field">
+			<IcSearch class="search-field-icon" aria-hidden="true" />
+			<input
+				bind:this={input}
+				bind:value={query}
+				onkeydown={onInputKeydown}
+				type="search"
+				placeholder="Search pages, posts, projects…"
+				autocomplete="off"
+				spellcheck="false"
+				role="combobox"
+				aria-expanded={results.length > 0}
+				aria-controls="search-results"
+				aria-activedescendant={activeId}
+				aria-autocomplete="list"
+			/>
+			<kbd class="search-esc" aria-hidden="true">Esc</kbd>
+		</div>
+
+		{#if loading}
+			<p class="search-note">Loading…</p>
+		{:else if loadError}
+			<p class="search-note">{loadError}</p>
+		{:else if !results.length}
+			<p class="search-note">Nothing matches “{query}”.</p>
+		{/if}
+
+		<ul class="search-results" id="search-results" role="listbox" bind:this={list}>
+			{#each results as item, i (item.kind + item.url)}
+				<li role="presentation">
+					<!-- eslint-disable svelte/no-navigation-without-resolve -- urls come from the build-time index -->
+					<a
+						id="search-result-{i}"
+						class="search-result"
+						class:active={i === activeIndex}
+						href={item.url}
+						role="option"
+						aria-selected={i === activeIndex}
+						target={isExternal(item.url) && !item.url.startsWith('mailto:') ? '_blank' : undefined}
+						rel={isExternal(item.url) ? 'noopener noreferrer' : undefined}
+						tabindex="-1"
+						onclick={close}
+						onpointermove={() => (activeIndex = i)}
+					>
+						<span class="search-kind" data-kind={item.kind}>{KIND_LABEL[item.kind]}</span>
+						<span class="search-text">
+							<span class="search-title">{item.title}</span>
+							{#if item.parent}
+								<span class="search-sub">in {item.parent}</span>
+							{:else if item.description}
+								<span class="search-sub">{item.description}</span>
+							{/if}
+						</span>
+						{#if isExternal(item.url)}
+							<span class="search-external" aria-hidden="true">↗</span>
+						{/if}
+					</a>
+					<!-- eslint-enable svelte/no-navigation-without-resolve -->
+				</li>
+			{/each}
+		</ul>
+
+		<p class="search-help" aria-hidden="true">
+			<span><kbd>↑</kbd><kbd>↓</kbd> move</span>
+			<span><kbd>Enter</kbd> open</span>
+			<span><kbd>Esc</kbd> close</span>
+		</p>
+	</div>
+</dialog>
diff --git a/src/lib/scripts/headingAnchors.ts b/src/lib/scripts/headingAnchors.ts
index 25d5ee6..914b914 100644
--- a/src/lib/scripts/headingAnchors.ts
+++ b/src/lib/scripts/headingAnchors.ts
@@ -5,15 +5,7 @@
 import { mount, unmount } from 'svelte';
 import IcLink from '~icons/ic/outline-link';
 
-// "Update: I Think I Kinda Fell…" → "update-i-think-i-kinda-fell"
-function slugify(text: string): string {
-	return text
-		.toLowerCase()
-		.normalize('NFKD')
-		.replace(/[\u0300-\u036f]/g, '')
-		.replace(/[^a-z0-9]+/g, '-')
-		.replace(/^-+|-+$/g, '');
-}
+import { slugify } from '#lib/scripts/slugify.ts';
 
 // Gives each h2/h3 in a post an id and a hover link to it, so sections can be shared
 export function headingAnchors(container: HTMLElement) {
diff --git a/src/lib/scripts/search.ts b/src/lib/scripts/search.ts
new file mode 100644
index 0000000..8e8ada4
--- /dev/null
+++ b/src/lib/scripts/search.ts
@@ -0,0 +1,131 @@
+/* src/lib/scripts/search.ts
+ * DASL-1.2 — (c) Clove Twilight
+ */
+
+// Ctrl+K site search: the index shape (built by routes/search.json) and the
+// scoring that ranks it as you type
+
+export type SearchKind = 'page' | 'post' | 'section' | 'project' | 'link';
+
+export interface SearchItem {
+	kind: SearchKind;
+	title: string;
+	url: string;
+	description?: string;
+	// Page or post a section belongs to
+	parent?: string;
+	keywords?: string[];
+}
+
+export const KIND_LABEL: Record<SearchKind, string> = {
+	page: 'Page',
+	post: 'Post',
+	section: 'Section',
+	project: 'Project',
+	link: 'Link'
+};
+
+// Small nudge so whole pages beat sections that match equally well
+const KIND_BONUS: Record<SearchKind, number> = {
+	page: 6,
+	post: 4,
+	project: 3,
+	link: 2,
+	section: 0
+};
+
+const MAX_RESULTS = 30;
+
+let index: Promise<SearchItem[]> | undefined;
+
+// Fetched on first open, then kept for the whole visit
+export function loadIndex(): Promise<SearchItem[]> {
+	index ??= fetch('/search.json')
+		.then((res) => {
+			if (!res.ok) throw new Error(`Search index failed (${res.status})`);
+			return res.json() as Promise<SearchItem[]>;
+		})
+		.catch((err) => {
+			index = undefined;
+			throw err;
+		});
+	return index;
+}
+
+// Lowercase and drop accents, so "cafe" finds "Café"
+function normalise(text: string): string {
+	return text
+		.toLowerCase()
+		.normalize('NFKD')
+		.replace(/[\u0300-\u036f]/g, '');
+}
+
+// Letters of the term appear in order, e.g. "npdn" in "npm to deno"
+function isSubsequence(term: string, text: string): boolean {
+	let position = 0;
+
+	for (const letter of text) {
+		if (letter === term[position]) position += 1;
+		if (position === term.length) return true;
+	}
+
+	return false;
+}
+
+function scoreText(text: string, term: string, allowFuzzy: boolean): number {
+	if (text === term) return 100;
+	if (text.startsWith(term)) return 80;
+
+	const at = text.indexOf(term);
+
+	// Start of a word beats the middle of one
+	if (at > 0 && /[^a-z0-9]/.test(text[at - 1])) return 60;
+	if (at > 0) return 40;
+	if (allowFuzzy && term.length >= 2 && isSubsequence(term, text)) return 15;
+
+	return 0;
+}
+
+function scoreItem(item: SearchItem, terms: string[]): number {
+	const title = normalise(item.title);
+	const keywords = normalise((item.keywords ?? []).join(' '));
+	const parent = normalise(item.parent ?? '');
+	const description = normalise(item.description ?? '');
+
+	let total = 0;
+
+	for (const term of terms) {
+		const best = Math.max(
+			scoreText(title, term, true),
+			scoreText(keywords, term, false) * 0.6,
+			scoreText(parent, term, false) * 0.5,
+			scoreText(description, term, false) * 0.4
+		);
+
+		// Every word typed has to match somewhere
+		if (best === 0) return 0;
+
+		total += best;
+	}
+
+	return total + KIND_BONUS[item.kind];
+}
+
+// With nothing typed, list every page so the palette doubles as a menu
+export function search(items: SearchItem[], query: string): SearchItem[] {
+	const terms = normalise(query).split(/\s+/).filter(Boolean);
+
+	if (!terms.length) {
+		return items.filter((item) => item.kind === 'page');
+	}
+
+	return items
+		.map((item) => ({
+			item,
+			score: scoreItem(item, terms)
+		}))
+		.filter((result) => result.score > 0)
+		.sort((a, b) => b.score - a.score)
+		.slice(0, MAX_RESULTS)
+		.map((result) => result.item);
+}
diff --git a/src/lib/scripts/slugify.ts b/src/lib/scripts/slugify.ts
new file mode 100644
index 0000000..746cb25
--- /dev/null
+++ b/src/lib/scripts/slugify.ts
@@ -0,0 +1,13 @@
+/* src/lib/scripts/slugify.ts
+ * DASL-1.2 — (c) Clove Twilight
+ */
+
+// "Update: I Think I Kinda Fell…" → "update-i-think-i-kinda-fell"
+export function slugify(text: string): string {
+	return text
+		.toLowerCase()
+		.normalize('NFKD')
+		.replace(/[\u0300-\u036f]/g, '')
+		.replace(/[^a-z0-9]+/g, '-')
+		.replace(/^-+|-+$/g, '');
+}
diff --git a/src/lib/styles/search.css b/src/lib/styles/search.css
new file mode 100644
index 0000000..8e67153
--- /dev/null
+++ b/src/lib/styles/search.css
@@ -0,0 +1,224 @@
+/* src/lib/styles/search.css
+ * DASL-1.2 — (c) Clove Twilight
+ */
+
+/* Header button */
+
+.search-trigger {
+	display: inline-flex;
+	gap: 0.5rem;
+	align-items: center;
+	height: 2.25rem;
+	padding: 0 0.6rem;
+	border: 1px solid var(--line);
+	border-radius: 0.6rem;
+	background: var(--raised);
+	color: var(--muted);
+	font: inherit;
+	font-size: 0.9rem;
+	cursor: pointer;
+}
+
+.search-trigger:hover {
+	border-color: var(--accent);
+	color: var(--text);
+}
+
+.search-trigger:focus-visible {
+	outline: 2px solid var(--accent);
+	outline-offset: 2px;
+}
+
+.search-dialog kbd,
+.search-trigger kbd {
+	padding: 0.05rem 0.35rem;
+	border: 1px solid var(--line);
+	border-radius: 0.3rem;
+	font-family: inherit;
+	font-size: 0.75rem;
+	line-height: 1.4;
+}
+
+/* Touch screens have no keyboard shortcut to show */
+@media (max-width: 52rem), (pointer: coarse) {
+	.search-shortcut {
+		display: none;
+	}
+
+	.search-trigger {
+		justify-content: center;
+		width: 2.25rem;
+		padding: 0;
+	}
+}
+
+/* Palette */
+
+.search-dialog {
+	width: min(38rem, calc(100% - 2rem));
+	max-height: min(32rem, calc(100% - 6rem));
+	margin: 12vh auto auto;
+	padding: 0;
+	border: 1px solid var(--line);
+	border-radius: 0.9rem;
+	background: var(--bg);
+	color: var(--text);
+	/* Lives inside header nav, so undo its smaller text */
+	font-size: 1rem;
+	box-shadow: 0 1.5rem 4rem rgb(0 0 0 / 60%);
+}
+
+.search-dialog::backdrop {
+	background: rgb(0 0 0 / 55%);
+	backdrop-filter: blur(2px);
+}
+
+.search-dialog[open] {
+	animation: search-in 0.15s ease-out;
+}
+
+@keyframes search-in {
+	from {
+		opacity: 0;
+		transform: translateY(-0.5rem);
+	}
+}
+
+@media (prefers-reduced-motion: reduce) {
+	.search-dialog[open] {
+		animation: none;
+	}
+}
+
+.search-box {
+	display: flex;
+	flex-direction: column;
+	max-height: inherit;
+}
+
+.search-field {
+	display: flex;
+	gap: 0.6rem;
+	align-items: center;
+	padding: 0.85rem 1rem;
+	border-bottom: 1px solid var(--line);
+}
+
+.search-field-icon {
+	width: 1.2rem;
+	height: 1.2rem;
+	flex-shrink: 0;
+	color: var(--muted);
+}
+
+.search-field input {
+	flex: 1;
+	min-width: 0;
+	border: 0;
+	outline: 0;
+	background: none;
+	color: var(--text);
+	font: inherit;
+	font-size: 1.05rem;
+}
+
+.search-field input::-webkit-search-cancel-button {
+	display: none;
+}
+
+.search-esc {
+	color: var(--muted);
+}
+
+.search-note {
+	margin: 0;
+	padding: 1.25rem 1rem;
+	color: var(--muted);
+	text-align: center;
+}
+
+.search-results {
+	flex: 1;
+	margin: 0;
+	padding: 0.4rem;
+	overflow-y: auto;
+	list-style: none;
+}
+
+.search-results:empty {
+	display: none;
+}
+
+.search-result {
+	display: flex;
+	gap: 0.75rem;
+	align-items: center;
+	padding: 0.55rem 0.7rem;
+	border-radius: 0.55rem;
+	color: var(--text);
+	font-size: inherit;
+	text-decoration: none;
+}
+
+.search-result.active {
+	background: var(--accent-dim);
+	color: #fff;
+}
+
+.search-kind {
+	flex-shrink: 0;
+	width: 4.2rem;
+	color: var(--muted);
+	font-size: 0.72rem;
+	letter-spacing: 0.04em;
+	text-transform: uppercase;
+}
+
+.search-result.active .search-kind {
+	color: var(--accent);
+}
+
+.search-text {
+	display: flex;
+	flex: 1;
+	flex-direction: column;
+	min-width: 0;
+}
+
+.search-title,
+.search-sub {
+	overflow: hidden;
+	text-overflow: ellipsis;
+	white-space: nowrap;
+}
+
+.search-sub {
+	color: var(--muted);
+	font-size: 0.82rem;
+}
+
+.search-external {
+	color: var(--muted);
+}
+
+.search-help {
+	display: flex;
+	gap: 1rem;
+	justify-content: flex-end;
+	margin: 0;
+	padding: 0.55rem 1rem;
+	border-top: 1px solid var(--line);
+	color: var(--muted);
+	font-size: 0.78rem;
+}
+
+.search-help kbd {
+	margin-right: 0.2rem;
+}
+
+@media (pointer: coarse) {
+	.search-help,
+	.search-esc {
+		display: none;
+	}
+}
diff --git a/src/routes/projects/+page.svelte b/src/routes/projects/+page.svelte
deleted file mode 100644
index d9be566..0000000
--- a/src/routes/projects/+page.svelte
+++ /dev/null
@@ -1,135 +0,0 @@
-<!-- src/routes/projects/+page.svelte
-     DASL-1.2 — (c) Clove Twilight
--->
-
-<script lang="ts">
-	import Meta from '#lib/components/Meta.svelte';
-	import '#lib/styles/projects.css';
-	import { apiBase, authUrl, githubUrl, mediaBase } from '#lib';
-
-	type Project = {
-		title: string;
-		bio: string;
-		href?: string;
-		img?: string;
-		closed?: boolean;
-		deprecated?: boolean;
-		live?: string;
-	};
-
-	type Group = { heading: string; projects: Project[] };
-
-	const IMG_BASE = mediaBase + '/';
-
-	const GROUPS: Group[] = [
-		{
-			heading: 'Personal Projects',
-			projects: [
-				{
-					title: 'Doughmination Auth',
-					bio: 'A public auth server, which is my auth for all my projects',
-					href: githubUrl + '/auth-server',
-					live: authUrl,
-					img: 'favicons/favicon.png'
-				},
-				{
-					title: 'Doughmination API',
-					bio: "My personal API, which I don't mind people hooking into",
-					href: githubUrl + '/api',
-					live: apiBase,
-					img: 'favicons/favicon.png'
-				},
-				{
-					title: 'Doughmination Mail',
-					bio: 'My personal inbox',
-					href: githubUrl + '/email',
-					img: 'favicons/favicon.png'
-				}
-			]
-		},
-		{
-			heading: 'WLW Devs',
-			projects: [
-				{
-					title: 'GayBot',
-					href: 'https://github.com/WLWDevs/GayBot',
-					img: 'img/projects/gaybot.png',
-					bio: 'A Discord bot for LGBTQIA+ servers: keyword emoji reactions, identity profiles, lookups and a few fun extras.'
-				}
-			]
-		},
-		{
-			heading: 'Depreciated Works',
-			projects: [
-				{
-					title: 'Ghostwire',
-					img: 'img/projects/ghostwire.png',
-					bio: 'The former security bot and brains behind everything major in Girls.',
-					closed: true,
-					deprecated: true
-				},
-				{
-					title: 'BanSync',
-					img: 'img/projects/bansync.png',
-					bio: 'Syncs bans from Girls to our partner servers.',
-					deprecated: true
-				}
-			]
-		}
-	];
-</script>
-
-<Meta
-	title="Projects"
-	description="The projects Clove Twilight builds and contributes to, from personal tools to Discord bots."
-/>
-
-<svelte:head>
-	<link rel="preconnect" href={mediaBase} crossorigin="" />
-</svelte:head>
-
-<section class="hero">
-	<div class="wrap">
-		<p class="eyebrow">Coding</p>
-		<h1>Projects</h1>
-		<p class="subtitle">Things I build and help run, click a card to see it's source</p>
-	</div>
-</section>
-
-<section class="wrap project-groups">
-	{#each GROUPS as group (group.heading)}
-		<h2 class="project-heading">{group.heading}</h2>
-		<ul class="project-grid">
-			{#each group.projects as p (p.title)}
-				<li class="project-card" class:deprecated={p.deprecated}>
-					<svelte:element
-						this={p.href ? 'a' : 'div'}
-						class="project-main"
-						href={p.href}
-						target={p.href ? '_blank' : undefined}
-						rel={p.href ? 'noopener noreferrer' : undefined}
-					>
-						<img src={IMG_BASE + p.img} alt="" width="56" height="56" loading="lazy" />
-						<div class="project-body">
-							<div class="project-head">
-								<span class="project-title">{p.title}</span>
-								<span class="project-status" class:closed={p.closed}>
-									{p.closed ? 'Closed Source' : 'Open Source'}
-								</span>
-								{#if p.deprecated}
-									<span class="project-status deprecated">Deprecated</span>
-								{/if}
-							</div>
-							<p class="project-bio">{p.bio}</p>
-						</div>
-					</svelte:element>
-					{#if p.live}
-						<a class="project-live" href={p.live} target="_blank" rel="noopener noreferrer"
-							>View live ↗</a
-						>
-					{/if}
-				</li>
-			{/each}
-		</ul>
-	{/each}
-</section>
diff --git a/src/routes/search.json/+server.ts b/src/routes/search.json/+server.ts
new file mode 100644
index 0000000..9f173f1
--- /dev/null
+++ b/src/routes/search.json/+server.ts
@@ -0,0 +1,215 @@
+// src/routes/search.json/+server.ts
+// DASL-1.2 — (c) Clove Twilight
+
+import {
+	blueskyUrl,
+	contactEmail,
+	discordInvite,
+	githubUrl,
+	linkedinUrl,
+	twitchUrl,
+	twitterUrl,
+	youtubeUrl
+} from '#lib';
+import type { PostMeta } from '#lib/scripts/blog.ts';
+import { PROJECT_GROUPS } from '#lib/scripts/projects.ts';
+import type { SearchItem } from '#lib/scripts/search.ts';
+import { slugify } from '#lib/scripts/slugify.ts';
+
+// Built once at build time into a static search.json, read by the Ctrl+K palette
+export const prerender = true;
+
+// Every page's source, so new pages are searchable without touching this file
+const sources = import.meta.glob<string>('../**/+page.svelte', {
+	eager: true,
+	query: '?raw',
+	import: 'default'
+});
+
+const posts = import.meta.glob<PostMeta>('../blog/*/+page.svelte', {
+	eager: true,
+	import: 'metadata'
+});
+
+const ENTITIES: Record<string, string> = {
+	'&apos;': "'",
+	'&#39;': "'",
+	'&quot;': '"',
+	'&amp;': '&',
+	'&lt;': '<',
+	'&gt;': '>',
+	'&nbsp;': ' '
+};
+
+function decode(text: string): string {
+	return text.replace(/&[#a-z0-9]+;/gi, (entity) => ENTITIES[entity] ?? entity).trim();
+}
+
+// "../blog/arch-btw/+page.svelte" → "/blog/arch-btw"
+function routePath(file: string): string {
+	return file.replace(/^\.\.|\/\+page\.svelte$/g, '') || '/';
+}
+
+// title="…" or title='…' inside the page's <Meta … /> tag
+function metaAttribute(source: string, name: string): string | undefined {
+	const tag = /<Meta\b[\s\S]*?\/>/.exec(source)?.[0] ?? '';
+	const match = new RegExp(`\\b${name}=(?:"([^"]*)"|'([^']*)')`).exec(tag);
+	const value = match?.[1] ?? match?.[2];
+
+	return value ? decode(value) : undefined;
+}
+
+// Plain-text headings only; ones built from {expressions} are skipped
+function headings(source: string, levels: string): string[] {
+	const pattern = new RegExp(`<h([${levels}])\\b[^>]*>([^<{]+)</h\\1>`, 'g');
+
+	return [...source.matchAll(pattern)].map((match) => decode(match[2])).filter(Boolean);
+}
+
+function pageItems(): SearchItem[] {
+	const items: SearchItem[] = [];
+
+	for (const [file, source] of Object.entries(sources)) {
+		const path = routePath(file);
+
+		// Admin is private, [params] routes have no single page, posts are added below
+		if (path.startsWith('/admin') || path.includes('[')) continue;
+		if (file in posts) continue;
+
+		const title = metaAttribute(source, 'title') ?? headings(source, '1')[0] ?? path;
+
+		items.push({
+			kind: 'page',
+			title,
+			url: path,
+			description: metaAttribute(source, 'description'),
+			keywords: headings(source, '123').filter((heading) => heading !== title)
+		});
+	}
+
+	// Home first, then A to Z
+	return items.sort((a, b) => {
+		if (a.url === '/') return -1;
+		if (b.url === '/') return 1;
+
+		return a.title.localeCompare(b.title);
+	});
+}
+
+// Each post, plus its h2/h3 sections linked straight to their anchors
+function postItems(): SearchItem[] {
+	const items: SearchItem[] = [];
+
+	const sorted = Object.entries(posts).sort(([, a], [, b]) => b.date.localeCompare(a.date));
+
+	for (const [file, meta] of sorted) {
+		const url = routePath(file);
+
+		items.push({
+			kind: 'post',
+			title: meta.title,
+			url,
+			description: meta.excerpt,
+			keywords: meta.tags
+		});
+
+		// A content warning hides the post until the reader continues, so its anchors don't exist yet
+		if (meta.warning) continue;
+
+		const usedIds = new Set<string>();
+
+		for (const heading of headings(sources[file] ?? '', '23')) {
+			// Same -2, -3 suffixes as headingAnchors.ts gives repeated headings
+			const baseId = slugify(heading) || 'section';
+			let uniqueId = baseId;
+			let suffix = 2;
+
+			while (usedIds.has(uniqueId)) {
+				uniqueId = `${baseId}-${suffix}`;
+				suffix += 1;
+			}
+
+			usedIds.add(uniqueId);
+
+			items.push({
+				kind: 'section',
+				title: heading,
+				url: `${url}#${uniqueId}`,
+				parent: meta.title,
+				keywords: meta.tags
+			});
+		}
+	}
+
+	return items;
+}
+
+function projectItems(): SearchItem[] {
+	return PROJECT_GROUPS.flatMap((group) =>
+		group.projects.map((project) => ({
+			kind: 'project' as const,
+			title: project.title,
+			url: project.href ?? project.live ?? '/projects',
+			description: project.bio,
+			parent: group.heading
+		}))
+	);
+}
+
+const LINKS: SearchItem[] = [
+	{
+		kind: 'link',
+		title: 'GitHub',
+		url: githubUrl
+	},
+	{
+		kind: 'link',
+		title: 'Discord server',
+		url: discordInvite,
+		keywords: ['invite', 'join']
+	},
+	{
+		kind: 'link',
+		title: 'Email',
+		url: `mailto:${contactEmail}`,
+		description: contactEmail,
+		keywords: ['contact', 'mail']
+	},
+	{
+		kind: 'link',
+		title: 'Bluesky',
+		url: blueskyUrl
+	},
+	{
+		kind: 'link',
+		title: 'X / Twitter',
+		url: twitterUrl
+	},
+	{
+		kind: 'link',
+		title: 'LinkedIn',
+		url: linkedinUrl
+	},
+	{
+		kind: 'link',
+		title: 'Twitch',
+		url: twitchUrl,
+		keywords: ['stream']
+	},
+	{
+		kind: 'link',
+		title: 'YouTube',
+		url: youtubeUrl,
+		keywords: ['video']
+	}
+];
+
+export function GET() {
+	const items = [...pageItems(), ...postItems(), ...projectItems(), ...LINKS];
+
+	return new Response(JSON.stringify(items), {
+		headers: {
+			'Content-Type': 'application/json'
+		}
+	});
+}