layout redesign

This commit is contained in:
2026-05-09 10:40:58 +02:00
parent 828bdce906
commit 9c913adacd
8 changed files with 712 additions and 229 deletions
+263
View File
@@ -0,0 +1,263 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { getPosts } from '../../lib/api';
interface Post {
slug: string;
date: string;
title?: string;
excerpt?: string;
tags: string[];
draft: boolean;
reading_time: number;
}
function formatSlug(slug: string) {
if (!slug) return '';
return slug
.split('-')
.map(w => w.charAt(0).toUpperCase() + w.slice(1))
.join(' ');
}
function formatDate(date: string) {
return new Date(date).toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
});
}
export default function Search() {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState('');
const [posts, setPosts] = useState<Post[] | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [activeIdx, setActiveIdx] = useState(0);
const inputRef = useRef<HTMLInputElement>(null);
const listRef = useRef<HTMLUListElement>(null);
// Global Cmd/Ctrl+K + Esc listener
useEffect(() => {
function onKey(e: KeyboardEvent) {
const isMac = navigator.platform.toLowerCase().includes('mac');
const mod = isMac ? e.metaKey : e.ctrlKey;
if (mod && e.key.toLowerCase() === 'k') {
e.preventDefault();
setOpen(o => !o);
} else if (e.key === 'Escape' && open) {
setOpen(false);
}
}
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [open]);
// Lazy fetch posts on first open
useEffect(() => {
if (!open || posts !== null || loading) return;
setLoading(true);
getPosts()
.then(p => setPosts(p as Post[]))
.catch(e => setError(e instanceof Error ? e.message : 'Failed to load'))
.finally(() => setLoading(false));
}, [open, posts, loading]);
// Focus input on open
useEffect(() => {
if (open) {
setQuery('');
setActiveIdx(0);
requestAnimationFrame(() => inputRef.current?.focus());
}
}, [open]);
// Lock body scroll when open
useEffect(() => {
if (!open) return;
const prev = document.body.style.overflow;
document.body.style.overflow = 'hidden';
return () => { document.body.style.overflow = prev; };
}, [open]);
const results = useMemo(() => {
if (!posts) return [];
const q = query.trim().toLowerCase();
if (!q) return posts;
return posts.filter(p => {
const hay = `${p.title || formatSlug(p.slug)} ${p.excerpt || ''} ${p.tags?.join(' ') || ''}`.toLowerCase();
return hay.includes(q);
});
}, [posts, query]);
// Reset active index when results change
useEffect(() => {
setActiveIdx(0);
}, [query, posts]);
function navigate(slug: string) {
window.location.href = `/posts/${encodeURIComponent(slug)}`;
}
function onInputKey(e: React.KeyboardEvent<HTMLInputElement>) {
if (e.key === 'ArrowDown') {
e.preventDefault();
setActiveIdx(i => Math.min(i + 1, Math.max(0, results.length - 1)));
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setActiveIdx(i => Math.max(i - 1, 0));
} else if (e.key === 'Enter' && results[activeIdx]) {
e.preventDefault();
navigate(results[activeIdx].slug);
}
}
// Scroll active result into view
useEffect(() => {
if (!open || !listRef.current) return;
const el = listRef.current.children[activeIdx] as HTMLElement | undefined;
el?.scrollIntoView({ block: 'nearest' });
}, [activeIdx, open]);
return (
<>
<button
type="button"
onClick={() => setOpen(true)}
aria-label="Search posts (Ctrl+K)"
title="Search (Ctrl+K)"
className="text-subtext0 hover:text-text transition-colors flex items-center gap-2 px-2 py-1 rounded-md hover:bg-surface0/60"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</svg>
<kbd className="hidden md:inline-flex items-center gap-0.5 text-[10px] font-mono text-subtext0 px-1.5 py-0.5 rounded border border-surface1 bg-surface0/60">
<span></span><span>K</span>
</kbd>
</button>
{open && (
<div
className="fixed inset-0 z-[200] flex items-start justify-center pt-[10vh] md:pt-[15vh] px-4"
role="dialog"
aria-modal="true"
aria-label="Search posts"
onClick={() => setOpen(false)}
>
<div
className="absolute inset-0 bg-crust/70 backdrop-blur-md"
aria-hidden="true"
/>
<div
className="relative w-full max-w-xl bg-mantle border border-surface1 rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[70vh] animate-in fade-in slide-in-from-top-4 duration-200"
onClick={e => e.stopPropagation()}
>
<div className="flex items-center gap-3 px-4 py-3 border-b border-surface1">
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="text-subtext0 shrink-0"
aria-hidden="true"
>
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</svg>
<input
ref={inputRef}
type="search"
value={query}
onChange={e => setQuery(e.target.value)}
onKeyDown={onInputKey}
placeholder="Search posts…"
aria-label="Search query"
className="flex-1 bg-transparent outline-none text-base text-text placeholder:text-subtext0"
/>
<kbd className="text-[10px] font-mono text-subtext0 px-1.5 py-0.5 rounded border border-surface1 bg-surface0/60">
Esc
</kbd>
</div>
<div className="flex-1 overflow-y-auto">
{loading && (
<div className="px-4 py-8 text-center text-sm text-subtext0">Loading</div>
)}
{error && (
<div className="px-4 py-8 text-center text-sm text-red">{error}</div>
)}
{!loading && !error && posts && results.length === 0 && (
<div className="px-4 py-8 text-center text-sm text-subtext0">
{query ? 'No posts match.' : 'No posts.'}
</div>
)}
{!loading && !error && results.length > 0 && (
<ul ref={listRef} className="py-1">
{results.map((p, i) => {
const title = p.title || formatSlug(p.slug);
const active = i === activeIdx;
return (
<li
key={p.slug}
onMouseEnter={() => setActiveIdx(i)}
onClick={() => navigate(p.slug)}
className={`px-4 py-3 cursor-pointer border-l-2 transition-colors ${
active
? 'bg-surface0 border-mauve'
: 'border-transparent hover:bg-surface0/60'
}`}
>
<div className="flex items-baseline justify-between gap-3">
<div className={`font-medium truncate ${active ? 'text-mauve' : 'text-lavender'}`}>
{title}
</div>
<time className="text-[10px] text-subtext0 shrink-0" dateTime={p.date}>
{formatDate(p.date)}
</time>
</div>
{p.excerpt && (
<div className="text-xs text-subtext1 line-clamp-1 mt-0.5">{p.excerpt}</div>
)}
</li>
);
})}
</ul>
)}
</div>
<div className="flex items-center justify-between px-4 py-2 border-t border-surface1 text-[10px] text-subtext0 bg-crust/40">
<div className="flex items-center gap-3">
<span className="flex items-center gap-1">
<kbd className="font-mono px-1 rounded border border-surface1 bg-surface0/60"></kbd>
navigate
</span>
<span className="flex items-center gap-1">
<kbd className="font-mono px-1 rounded border border-surface1 bg-surface0/60"></kbd>
open
</span>
</div>
<span>{results.length} {results.length === 1 ? 'result' : 'results'}</span>
</div>
</div>
</div>
)}
</>
);
}