migrated to react

This commit is contained in:
2026-03-27 22:15:50 +01:00
parent 11ac1e008f
commit 176f821598
24 changed files with 2281 additions and 888 deletions
@@ -0,0 +1,120 @@
import { useEffect, useRef } from 'react';
import { marked } from 'marked';
import hljs from 'highlight.js';
import katex from 'katex';
import 'katex/dist/katex.min.css';
interface Props {
content: string;
slug: string;
}
function renderMath(element: HTMLElement) {
const delimiters = [
{ left: '$$', right: '$$', display: true },
{ left: '$', right: '$', display: false },
{ left: '\\(', right: '\\)', display: false },
{ left: '\\[', right: '\\]', display: true },
];
const walk = (node: Node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
const el = node as HTMLElement;
if (el.tagName === 'CODE' || el.tagName === 'PRE') return;
for (const child of Array.from(el.childNodes)) walk(child);
} else if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent || '';
for (const { left, right, display } of delimiters) {
const idx = text.indexOf(left);
if (idx === -1) continue;
const end = text.indexOf(right, idx + left.length);
if (end === -1) continue;
const tex = text.slice(idx + left.length, end);
try {
const rendered = katex.renderToString(tex, { displayMode: display, throwOnError: false });
const span = document.createElement('span');
span.innerHTML = rendered;
const range = document.createRange();
range.setStart(node, idx);
range.setEnd(node, end + right.length);
range.deleteContents();
range.insertNode(span);
} catch { /* skip invalid tex */ }
return;
}
}
};
// Multiple passes to catch nested/sequential math
for (let i = 0; i < 3; i++) walk(element);
}
export default function PostContent({ content, slug }: Props) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!ref.current) return;
const html = marked.parse(content);
if (typeof html === 'string') {
ref.current.innerHTML = html;
} else {
html.then(h => { if (ref.current) ref.current.innerHTML = h; });
}
}, [content]);
useEffect(() => {
if (!ref.current) return;
// Wait a tick for innerHTML to settle
const timer = setTimeout(() => {
if (!ref.current) return;
renderMath(ref.current);
ref.current.querySelectorAll<HTMLElement>('pre code').forEach((block) => {
hljs.highlightElement(block);
});
}, 0);
return () => clearTimeout(timer);
}, [content]);
// Show edit button if admin
const isAdmin = typeof window !== 'undefined' && !!localStorage.getItem('admin_token');
return (
<>
<header className="mb-8 md:mb-12 border-b border-white/5 pb-8 md:pb-12">
<a
href="/"
className="text-blue hover:text-sky transition-colors mb-6 md:mb-8 inline-flex items-center gap-2 group text-sm md:text-base"
style={{ color: 'var(--blue)' }}
>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="md:w-5 md:h-5 transition-transform group-hover:-translate-x-1"><path d="m15 18-6-6 6-6"/></svg>
Back to list
</a>
<div className="flex flex-col md:flex-row md:justify-between md:items-start mt-2 md:mt-4 gap-4">
<h1 className="text-3xl md:text-5xl font-extrabold text-mauve">
{formatSlug(slug)}
</h1>
{isAdmin && (
<a
href={`/admin/editor?edit=${slug}`}
className="bg-surface0 hover:bg-surface1 text-blue px-3 py-1.5 md:px-4 md:py-2 rounded border border-surface1 transition-colors inline-flex items-center gap-2 text-sm md:text-base self-start"
style={{ color: 'var(--blue)' }}
>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="md:w-4 md:h-4"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg>
Edit
</a>
)}
</div>
</header>
<div className="prose max-w-none" ref={ref} />
</>
);
}
function formatSlug(slug: string) {
if (!slug) return '';
return slug
.split('-')
.map(w => w.charAt(0).toUpperCase() + w.slice(1))
.join(' ');
}
@@ -0,0 +1,44 @@
import { useState, useEffect } from 'react';
const THEMES = [
{ value: 'mocha', label: 'Mocha' },
{ value: 'macchiato', label: 'Macchiato' },
{ value: 'frappe', label: 'Frappe' },
{ value: 'latte', label: 'Latte' },
{ value: 'scaled-and-icy', label: 'Scaled and Icy' },
];
interface Props {
defaultTheme?: string;
}
export default function ThemeSwitcher({ defaultTheme = 'mocha' }: Props) {
const [theme, setTheme] = useState(() => {
if (typeof window !== 'undefined') {
return localStorage.getItem('user-theme') || defaultTheme;
}
return defaultTheme;
});
useEffect(() => {
document.documentElement.className = theme;
localStorage.setItem('user-theme', theme);
}, [theme]);
return (
<div className="relative inline-block text-left">
<select
value={theme}
onChange={(e) => setTheme(e.target.value)}
className="appearance-none bg-surface0/50 text-text border border-surface1 rounded-lg px-3 py-1.5 text-xs focus:outline-none focus:border-mauve transition-all cursor-pointer hover:bg-surface0 pr-8 shadow-sm"
>
{THEMES.map(t => (
<option key={t.value} value={t.value}>{t.label}</option>
))}
</select>
<div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-subtext0">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m6 9 6 6 6-9"/></svg>
</div>
</div>
);
}
@@ -0,0 +1,115 @@
import { useState, useEffect, useRef } from 'react';
import { getAssets, uploadAsset, deleteAsset as deleteAssetApi, ApiError } from '../../../lib/api';
import type { Asset } from '../../../lib/types';
interface Props {
mode?: 'manage' | 'select';
onSelect?: (asset: Asset) => void;
}
export default function AssetManager({ mode = 'manage', onSelect }: Props) {
const [assets, setAssets] = useState<Asset[]>([]);
const [alert, setAlert] = useState<{ msg: string; type: 'success' | 'error' } | null>(null);
const fileRef = useRef<HTMLInputElement>(null);
async function fetchAll() {
try {
setAssets(await getAssets());
} catch (e) {
console.error('Failed to fetch assets', e);
}
}
useEffect(() => { fetchAll(); }, []);
function showAlert(msg: string, type: 'success' | 'error') {
setAlert({ msg, type });
setTimeout(() => setAlert(null), 4000);
}
async function handleUpload(files: FileList) {
let ok = 0;
for (const file of Array.from(files)) {
try {
await uploadAsset(file);
ok++;
} catch { /* skip */ }
}
if (ok > 0) {
showAlert(`Successfully uploaded ${ok} file(s).`, 'success');
fetchAll();
}
}
async function handleDelete(name: string) {
if (!confirm(`Delete "${name}" permanently?`)) return;
try {
await deleteAssetApi(name);
showAlert('File deleted.', 'success');
fetchAll();
} catch (e) {
showAlert(e instanceof ApiError ? e.message : 'Failed to delete file.', 'error');
}
}
const isImage = (name: string) => /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(name);
return (
<div className="space-y-8">
{alert && (
<div className={`p-4 rounded-lg mb-6 text-sm ${
alert.type === 'success' ? 'bg-green/20 text-green border border-green/30' : 'bg-red/20 text-red border border-red/30'
}`}>
{alert.msg}
</div>
)}
{/* Upload Zone */}
<div
className="glass p-6 border-dashed border-2 border-surface1 hover:border-mauve transition-colors group relative cursor-pointer"
onClick={() => fileRef.current?.click()}
onDragOver={e => { e.preventDefault(); e.stopPropagation(); }}
onDrop={e => { e.preventDefault(); e.stopPropagation(); if (e.dataTransfer.files.length) handleUpload(e.dataTransfer.files); }}
>
<input ref={fileRef} type="file" multiple className="hidden" onChange={e => { if (e.target.files?.length) handleUpload(e.target.files); }} />
<div className="text-center py-4">
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" className="mx-auto mb-4 text-subtext0 group-hover:text-mauve transition-colors"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" x2="12" y1="3" y2="15"/></svg>
<p className="text-lg font-bold text-lavender">Click or drag to upload assets</p>
<p className="text-xs text-subtext0 mt-1">Any file type up to 50MB</p>
</div>
</div>
{/* Grid */}
{assets.length === 0 ? (
<div className="text-center py-20 text-subtext0">No assets uploaded yet.</div>
) : (
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4">
{assets.map(asset => (
<div key={asset.name} className="group relative aspect-square bg-crust rounded-xl overflow-hidden border border-white/5 transition-all hover:scale-105 shadow-lg flex flex-col">
<div className="flex-1 overflow-hidden bg-surface0/20 relative cursor-pointer">
{isImage(asset.name) ? (
<img src={asset.url} className="w-full h-full object-cover opacity-80 group-hover:opacity-100 transition-opacity" alt={asset.name} />
) : (
<div className="flex flex-col items-center justify-center h-full text-subtext0">
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="mb-2"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>
<span className="text-[8px] font-mono px-2 truncate w-full text-center">{asset.name.split('.').pop()?.toUpperCase()}</span>
</div>
)}
{/* Hover overlay */}
<div className="absolute inset-0 bg-crust/60 backdrop-blur-sm opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
{mode === 'select' && onSelect && (
<button onClick={() => onSelect(asset)} className="bg-mauve text-crust px-3 py-1 rounded-md text-xs font-bold">Insert</button>
)}
<button onClick={() => handleDelete(asset.name)} className="bg-red/80 hover:bg-red text-white p-1.5 rounded-md transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>
</button>
</div>
</div>
<div className="p-2 bg-crust text-[10px] truncate border-t border-white/5 text-subtext1">{asset.name}</div>
</div>
))}
</div>
)}
</div>
);
}
@@ -0,0 +1,117 @@
import { useState, useEffect } from 'react';
import { useAuth } from '../../../stores/auth';
import { getPosts, deletePost, ApiError } from '../../../lib/api';
import type { Post } from '../../../lib/types';
export default function Dashboard() {
const [posts, setPosts] = useState<Post[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const logout = useAuth(s => s.logout);
async function loadPosts() {
setLoading(true);
setError('');
try {
setPosts(await getPosts());
} catch (e) {
setError(e instanceof ApiError ? e.message : 'Failed to load posts.');
} finally {
setLoading(false);
}
}
useEffect(() => { loadPosts(); }, []);
async function handleDelete(slug: string) {
if (!confirm(`Are you sure you want to delete "${slug}"?`)) return;
try {
await deletePost(slug);
loadPosts();
} catch {
setError('Failed to delete post.');
}
}
function handleLogout() {
logout();
window.location.href = '/';
}
return (
<>
<div className="flex justify-end mb-4">
<button onClick={handleLogout} className="text-red hover:text-maroon transition-colors font-medium">
Logout
</button>
</div>
{/* Quick Links */}
<div className="grid md:grid-cols-3 gap-8 mb-12">
<QuickLink href="/admin/editor" icon="write" title="Write Post" desc="Create or edit markdown posts." color="mauve" hoverColor="pink" />
<QuickLink href="/admin/assets" icon="assets" title="Asset Library" desc="Manage images and uploads." color="teal" hoverColor="green" />
<QuickLink href="/admin/settings" icon="settings" title="Settings" desc="Site title and themes." color="blue" hoverColor="sky" />
</div>
{/* Posts List */}
<section>
<h2 className="text-2xl font-bold text-mauve mb-6 flex items-center gap-3">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>
Manage Posts
</h2>
<div className="space-y-4">
{loading && (
<div className="animate-pulse flex space-x-4 p-8 glass">
<div className="flex-1 space-y-4 py-1">
<div className="h-4 bg-surface1 rounded w-3/4" />
<div className="h-4 bg-surface1 rounded w-1/2" />
</div>
</div>
)}
{error && <div className="glass p-8 text-center text-red">{error}</div>}
{!loading && posts.length === 0 && !error && (
<div className="glass p-8 text-center text-subtext0">No posts yet.</div>
)}
{posts.map(post => (
<div key={post.slug} className="glass p-6 flex justify-between items-center group hover:bg-surface0/50 transition-colors">
<div>
<h3 className="font-bold text-lavender text-lg">{post.slug}</h3>
<p className="text-xs text-subtext0" style={{ color: 'var(--subtext0)' }}>/posts/{post.slug}</p>
</div>
<div className="flex gap-3">
<a href={`/admin/editor?edit=${post.slug}`} className="p-2 text-blue hover:bg-blue/10 rounded transition-colors" title="Edit">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg>
</a>
<button onClick={() => handleDelete(post.slug)} className="p-2 text-red hover:bg-red/10 rounded transition-colors" title="Delete">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg>
</button>
</div>
</div>
))}
</div>
</section>
</>
);
}
const ICONS: Record<string, JSX.Element> = {
write: <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 1 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>,
assets: <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>,
settings: <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>,
};
function QuickLink({ href, icon, title, desc, color, hoverColor }: { href: string; icon: string; title: string; desc: string; color: string; hoverColor: string }) {
return (
<a href={href} className="group">
<div className="bg-surface0/50 p-8 rounded-xl border border-white/5 transition-all hover:bg-surface0 hover:scale-[1.02] h-full flex flex-col items-center text-center gap-4">
<div className={`bg-${color}/20 p-4 rounded-full text-${color}`}>
{ICONS[icon]}
</div>
<div>
<h2 className={`text-xl font-bold text-lavender group-hover:text-${hoverColor} transition-colors`}>{title}</h2>
<p className="text-xs text-subtext0 mt-1">{desc}</p>
</div>
</div>
</a>
);
}
@@ -0,0 +1,321 @@
import { useState, useEffect, useRef } from 'react';
import { EditorView, keymap, placeholder as cmPlaceholder } from '@codemirror/view';
import { EditorState } from '@codemirror/state';
import { markdown, markdownLanguage } from '@codemirror/lang-markdown';
import { languages } from '@codemirror/language-data';
import { defaultKeymap, indentWithTab } from '@codemirror/commands';
import { getPost, savePost, deletePost, getAssets, ApiError } from '../../../lib/api';
import type { Asset } from '../../../lib/types';
import AssetManager from './AssetManager';
interface Props {
editSlug?: string;
}
// CodeMirror theme matching the Catppuccin narlblog style
const narlblogTheme = EditorView.theme({
'&': {
backgroundColor: 'var(--crust)',
color: 'var(--text)',
border: '1px solid var(--surface1)',
borderRadius: '0.75rem',
fontSize: '14px',
},
'.cm-content': {
fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace',
padding: '1rem',
caretColor: 'var(--text)',
},
'.cm-cursor': { borderLeftColor: 'var(--text)' },
'.cm-selectionBackground': { backgroundColor: 'var(--surface2) !important' },
'&.cm-focused .cm-selectionBackground': { backgroundColor: 'var(--surface2) !important' },
'.cm-activeLine': { backgroundColor: 'var(--surface0)' },
'.cm-gutters': {
backgroundColor: 'var(--mantle)',
color: 'var(--overlay0)',
border: 'none',
},
'.cm-activeLineGutter': { backgroundColor: 'var(--surface0)' },
}, { dark: true });
export default function Editor({ editSlug }: Props) {
const editorRef = useRef<HTMLDivElement>(null);
const viewRef = useRef<EditorView | null>(null);
const [slug, setSlug] = useState(editSlug || '');
const [summary, setSummary] = useState('');
const [originalSlug, setOriginalSlug] = useState(editSlug || '');
const [alert, setAlert] = useState<{ msg: string; type: 'success' | 'error' } | null>(null);
const [showModal, setShowModal] = useState(false);
const [showAutocomplete, setShowAutocomplete] = useState(false);
const [autocompleteAssets, setAutocompleteAssets] = useState<Asset[]>([]);
const [autocompletePos, setAutocompletePos] = useState({ top: 0, left: 0 });
function showAlertMsg(msg: string, type: 'success' | 'error') {
setAlert({ msg, type });
window.scrollTo({ top: 0, behavior: 'smooth' });
setTimeout(() => setAlert(null), 5000);
}
// Initialize CodeMirror 6
useEffect(() => {
if (!editorRef.current || viewRef.current) return;
const state = EditorState.create({
doc: '',
extensions: [
keymap.of([...defaultKeymap, indentWithTab]),
markdown({ base: markdownLanguage, codeLanguages: languages }),
EditorView.lineWrapping,
narlblogTheme,
cmPlaceholder('# Hello World\nWrite your markdown here...'),
EditorView.updateListener.of(update => {
if (!update.docChanged) return;
// Check for autocomplete trigger
const pos = update.state.selection.main.head;
const line = update.state.doc.lineAt(pos);
const textBefore = line.text.slice(0, pos - line.from);
const lastChar = textBefore.slice(-1);
if (lastChar === '/' || lastChar === '!') {
triggerAutocomplete(update.view);
} else if (lastChar === ' ' || textBefore.length === 0) {
setShowAutocomplete(false);
}
}),
],
});
const view = new EditorView({ state, parent: editorRef.current });
viewRef.current = view;
return () => { view.destroy(); viewRef.current = null; };
}, []);
// Load existing post for editing
useEffect(() => {
if (!editSlug) return;
getPost(editSlug).then(post => {
if (post.summary) setSummary(post.summary);
if (post.content && viewRef.current) {
viewRef.current.dispatch({
changes: { from: 0, to: viewRef.current.state.doc.length, insert: post.content },
});
}
}).catch(() => showAlertMsg('Failed to load post.', 'error'));
}, [editSlug]);
async function triggerAutocomplete(view: EditorView) {
try {
const assets = await getAssets();
setAutocompleteAssets(assets.slice(0, 8));
// Position near cursor
const pos = view.state.selection.main.head;
const coords = view.coordsAtPos(pos);
if (coords) {
const editorRect = editorRef.current?.getBoundingClientRect();
if (editorRect) {
setAutocompletePos({
top: coords.bottom - editorRect.top + 4,
left: coords.left - editorRect.left,
});
}
}
setShowAutocomplete(true);
} catch { /* ignore */ }
}
function insertAssetMarkdown(asset: Asset) {
const view = viewRef.current;
if (!view) return;
const isImage = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(asset.name);
const md = isImage ? `![${asset.name}](${asset.url})` : `[${asset.name}](${asset.url})`;
const pos = view.state.selection.main.head;
const line = view.state.doc.lineAt(pos);
const textBefore = line.text.slice(0, pos - line.from);
const triggerIdx = Math.max(textBefore.lastIndexOf('/'), textBefore.lastIndexOf('!'));
if (triggerIdx !== -1) {
const from = line.from + triggerIdx;
view.dispatch({ changes: { from, to: pos, insert: md } });
} else {
view.dispatch({ changes: { from: pos, insert: md } });
}
view.focus();
setShowAutocomplete(false);
}
function handleAssetSelect(asset: Asset) {
insertAssetMarkdown(asset);
setShowModal(false);
}
async function handleSave() {
const content = viewRef.current?.state.doc.toString() || '';
if (!slug || !content) {
showAlertMsg('Title and content are required.', 'error');
return;
}
try {
await savePost({
slug,
old_slug: originalSlug || null,
summary: summary || null,
content,
});
showAlertMsg('Post saved!', 'success');
setOriginalSlug(slug);
} catch (e) {
showAlertMsg(e instanceof ApiError ? `Error: ${e.message}` : 'Failed to connect to server.', 'error');
}
}
async function handleDelete() {
const target = originalSlug || slug;
if (!confirm(`Delete post "${target}" permanently?`)) return;
try {
await deletePost(target);
window.location.href = '/admin';
} catch {
showAlertMsg('Error deleting post.', 'error');
}
}
// Close autocomplete on outside click
useEffect(() => {
if (!showAutocomplete) return;
const handler = () => setShowAutocomplete(false);
window.addEventListener('click', handler);
return () => window.removeEventListener('click', handler);
}, [showAutocomplete]);
return (
<>
{alert && (
<div className={`p-4 rounded-lg mb-6 text-sm font-semibold text-center backdrop-blur-sm shadow-lg ${
alert.type === 'success' ? 'bg-green/15 border border-green/30' : 'bg-red/15 border border-red/30'
}`} style={{ color: 'var(--text)' }}>
{alert.msg}
</div>
)}
{/* Actions bar */}
<div className="flex flex-wrap gap-4 mb-6">
{originalSlug && (
<button onClick={handleDelete} className="text-red hover:bg-red/10 px-6 py-3 rounded-lg transition-colors font-bold border border-red/20">
Delete
</button>
)}
<button onClick={handleSave} className="bg-mauve text-crust font-bold py-3 px-8 rounded-lg hover:bg-pink transition-all transform hover:scale-105 whitespace-nowrap">
Save Post
</button>
{originalSlug && (
<a
href={`/posts/${originalSlug}`}
target="_blank"
rel="noreferrer"
className="bg-blue text-crust font-bold py-3 px-8 rounded-lg hover:bg-sky transition-all transform hover:scale-105 whitespace-nowrap inline-flex items-center justify-center gap-2"
>
<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"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
View Post
</a>
)}
</div>
<div className="space-y-6">
{/* Slug */}
<div>
<label className="block text-sm font-medium text-subtext1 mb-2">Post Title (URL identifier)</label>
<input
type="text"
value={slug}
onChange={e => setSlug(e.target.value)}
required
placeholder="my-awesome-post"
className="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors font-mono"
/>
</div>
{/* Summary */}
<div>
<label className="block text-sm font-medium text-subtext1 mb-2">Custom Summary (Optional)</label>
<textarea
value={summary}
onChange={e => setSummary(e.target.value)}
rows={2}
placeholder="A brief description of this post for the frontpage..."
className="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors resize-none"
/>
</div>
{/* Editor */}
<div className="relative">
<div className="flex flex-col md:flex-row justify-between items-start md:items-end mb-2 gap-2">
<label className="block text-sm font-medium text-subtext1 italic">Tip: Type '/' to browse your assets</label>
<button
type="button"
onClick={() => setShowModal(true)}
className="text-sm bg-surface0 hover:bg-surface1 text-lavender px-4 py-2 rounded border border-surface1 transition-colors inline-flex items-center gap-2"
>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>
Asset Library
</button>
</div>
<div ref={editorRef} className="min-h-[500px]" />
{/* Autocomplete dropdown */}
{showAutocomplete && autocompleteAssets.length > 0 && (
<div
className="absolute z-50 bg-mantle border border-surface1 rounded-lg shadow-2xl max-h-64 overflow-y-auto w-80"
style={{ top: autocompletePos.top, left: autocompletePos.left }}
onClick={e => e.stopPropagation()}
>
<div className="p-2 text-[10px] text-subtext0 uppercase border-b border-white/5 bg-crust/50">Assets Library</div>
<ul className="py-1">
{autocompleteAssets.map(asset => {
const img = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(asset.name);
return (
<li
key={asset.name}
onClick={() => insertAssetMarkdown(asset)}
className="px-4 py-2 hover:bg-mauve/20 cursor-pointer text-sm truncate text-subtext1 hover:text-mauve flex items-center gap-3 transition-colors"
>
<div className="w-6 h-6 flex-shrink-0 bg-surface0 rounded flex items-center justify-center overflow-hidden">
{img ? (
<img src={asset.url} className="w-full h-full object-cover" alt="" />
) : (
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/></svg>
)}
</div>
<span className="truncate">{asset.name}</span>
</li>
);
})}
</ul>
</div>
)}
</div>
</div>
{/* Asset Modal */}
{showModal && (
<div className="fixed inset-0 z-[100] bg-crust/80 backdrop-blur-sm flex items-center justify-center p-4 md:p-6">
<div className="glass w-full max-w-5xl max-h-[90vh] flex flex-col overflow-hidden">
<header className="p-4 md:p-6 border-b border-white/5 flex justify-between items-center bg-surface0/20">
<div>
<h2 className="text-xl md:text-2xl font-bold text-mauve">Asset Library</h2>
<p className="text-xs text-subtext0">Click 'Insert' to add an asset to your post.</p>
</div>
<button onClick={() => setShowModal(false)} className="p-2 text-subtext0 hover:text-red transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
</button>
</header>
<div className="p-4 md:p-6 overflow-y-auto flex-1 bg-base/50">
<AssetManager mode="select" onSelect={handleAssetSelect} />
</div>
</div>
</div>
)}
</>
);
}
@@ -0,0 +1,41 @@
import { useState } from 'react';
import { useAuth } from '../../../stores/auth';
export default function Login() {
const [value, setValue] = useState('');
const setToken = useAuth(s => s.setToken);
function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (value.trim()) {
setToken(value.trim());
window.location.href = '/admin';
}
}
return (
<div className="max-w-md mx-auto mt-20">
<div className="glass p-12">
<h1 className="text-3xl font-bold mb-6 text-mauve">Admin Login</h1>
<p className="text-subtext0 mb-8">Enter your admin token to access the dashboard.</p>
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label htmlFor="token" className="block text-sm font-medium text-subtext1 mb-2">Admin Token</label>
<input
type="password"
id="token"
required
value={value}
onChange={e => setValue(e.target.value)}
className="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors"
placeholder="••••••••••••"
/>
</div>
<button type="submit" className="w-full bg-mauve text-crust font-bold py-3 rounded-lg hover:bg-pink transition-colors">
Login
</button>
</form>
</div>
</div>
);
}
@@ -0,0 +1,115 @@
import { useState, useEffect } from 'react';
import { getConfig, updateConfig, ApiError } from '../../../lib/api';
import type { SiteConfig } from '../../../lib/types';
export default function Settings() {
const [config, setConfig] = useState<Partial<SiteConfig>>({});
const [alert, setAlert] = useState<{ msg: string; type: 'success' | 'error' } | null>(null);
useEffect(() => {
getConfig()
.then(setConfig)
.catch(() => showAlert('Failed to load settings from server.', 'error'));
}, []);
function showAlert(msg: string, type: 'success' | 'error') {
setAlert({ msg, type });
setTimeout(() => setAlert(null), 5000);
}
function update(key: keyof SiteConfig, value: string) {
setConfig(prev => ({ ...prev, [key]: value }));
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
try {
await updateConfig(config);
showAlert('Settings saved successfully! Refresh to see changes.', 'success');
} catch (e) {
showAlert(e instanceof ApiError ? `Error: ${e.message}` : 'Failed to save settings.', 'error');
}
}
return (
<form onSubmit={handleSubmit} className="space-y-8">
{alert && (
<div className={`p-4 rounded-lg mb-6 text-sm font-semibold text-center backdrop-blur-sm ${
alert.type === 'success'
? 'bg-green/15 text-green border border-green/30'
: 'bg-red/15 text-red border border-red/30'
}`}>
{alert.msg}
</div>
)}
<section className="space-y-6">
<h2 className="text-xl font-bold text-lavender border-l-4 border-lavender pl-4">General Identity</h2>
<div className="grid md:grid-cols-2 gap-6">
<Field label="Blog Title (Nav)" value={config.title || ''} onChange={v => update('title', v)} />
<Field label="Nav Subtitle" value={config.subtitle || ''} onChange={v => update('subtitle', v)} />
<Field label="Welcome Title (Frontpage)" value={config.welcome_title || ''} onChange={v => update('welcome_title', v)} />
<Field label="Welcome Subtitle" value={config.welcome_subtitle || ''} onChange={v => update('welcome_subtitle', v)} />
</div>
<div>
<Field label="Favicon URL" value={config.favicon || ''} onChange={v => update('favicon', v)} hint="URL to the icon shown in browser tabs." />
</div>
</section>
<section className="space-y-6">
<h2 className="text-xl font-bold text-blue border-l-4 border-blue pl-4">Appearance</h2>
<div>
<label className="block text-sm font-medium text-subtext1 mb-2">Color Theme (Catppuccin)</label>
<select
value={config.theme || 'mocha'}
onChange={e => update('theme', e.target.value)}
className="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors"
>
<option value="mocha">Mocha (Dark, High Contrast)</option>
<option value="macchiato">Macchiato (Dark, Medium Contrast)</option>
<option value="frappe">Frappe (Dark, Low Contrast)</option>
<option value="latte">Latte (Light Mode)</option>
<option value="scaled-and-icy">Scaled and Icy (Vibrant Light)</option>
</select>
<p className="text-[10px] text-subtext0 mt-1">Select a predefined Catppuccin color palette.</p>
</div>
<div>
<label className="block text-sm font-medium text-subtext1 mb-2">Custom CSS</label>
<textarea
value={config.custom_css || ''}
onChange={e => update('custom_css', e.target.value)}
rows={4}
className="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors font-mono text-xs"
placeholder="body { ... }"
/>
<p className="text-[10px] text-subtext0 mt-1">Inject custom CSS styles globally.</p>
</div>
</section>
<section className="space-y-6">
<h2 className="text-xl font-bold text-teal border-l-4 border-teal pl-4">Footer</h2>
<Field label="Footer Text" value={config.footer || ''} onChange={v => update('footer', v)} />
</section>
<button type="submit" className="w-full md:w-auto bg-mauve text-crust font-bold py-4 px-12 rounded-lg hover:bg-pink transition-all transform hover:scale-[1.02] active:scale-[0.98]">
Save Site Configuration
</button>
</form>
);
}
function Field({ label, value, onChange, hint }: { label: string; value: string; onChange: (v: string) => void; hint?: string }) {
return (
<div>
<label className="block text-sm font-medium text-subtext1 mb-2">{label}</label>
<input
type="text"
value={value}
onChange={e => onChange(e.target.value)}
required
className="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors"
/>
{hint && <p className="text-[10px] text-subtext0 mt-1">{hint}</p>}
</div>
);
}