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

View File

@@ -2,12 +2,13 @@
import { defineConfig } from 'astro/config'; import { defineConfig } from 'astro/config';
import tailwindcss from '@tailwindcss/vite'; import tailwindcss from '@tailwindcss/vite';
import react from '@astrojs/react';
import node from '@astrojs/node'; import node from '@astrojs/node';
// https://astro.build/config // https://astro.build/config
export default defineConfig({ export default defineConfig({
output: 'server', output: 'server',
integrations: [react()],
security: { security: {
checkOrigin: false checkOrigin: false
}, },

File diff suppressed because it is too large Load Diff

View File

@@ -13,12 +13,28 @@
}, },
"dependencies": { "dependencies": {
"@astrojs/node": "^10.0.3", "@astrojs/node": "^10.0.3",
"@astrojs/react": "^5.0.2",
"@codemirror/autocomplete": "^6.20.1",
"@codemirror/commands": "^6.10.3",
"@codemirror/lang-markdown": "^6.5.0",
"@codemirror/language-data": "^6.5.2",
"@codemirror/state": "^6.6.0",
"@codemirror/view": "^6.40.0",
"@tailwindcss/vite": "^4.2.2", "@tailwindcss/vite": "^4.2.2",
"astro": "^6.0.8", "astro": "^6.0.8",
"codemirror": "^6.0.2",
"highlight.js": "^11.11.1",
"katex": "^0.16.44",
"marked": "^17.0.5", "marked": "^17.0.5",
"tailwindcss": "^4.2.2" "react": "^19.2.4",
"react-dom": "^19.2.4",
"tailwindcss": "^4.2.2",
"zustand": "^5.0.12"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^25.5.0" "@types/katex": "^0.16.8",
"@types/node": "^25.5.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3"
} }
} }

View File

@@ -1,178 +0,0 @@
---
interface Props {
mode?: 'select' | 'manage';
}
const { mode = 'manage' } = Astro.props;
---
<div class="space-y-8">
<div id="asset-alert" class="hidden p-4 rounded-lg mb-6 text-sm"></div>
<!-- Upload Zone -->
<div class="glass p-6 border-dashed border-2 border-surface1 hover:border-mauve transition-colors group relative">
<input type="file" id="zone-file-upload" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer" multiple />
<div class="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" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="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 class="text-lg font-bold text-lavender">Click or drag to upload assets</p>
<p class="text-xs text-subtext0 mt-1">Any file type up to 50MB</p>
</div>
</div>
<!-- Assets Grid -->
<div id="manager-assets-grid" class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4">
<!-- Assets injected here -->
</div>
<div id="manager-assets-empty" class="hidden text-center py-20 text-subtext0">
No assets uploaded yet.
</div>
</div>
<script is:inline define:vars={{ mode }}>
const token = localStorage.getItem('admin_token');
const grid = document.getElementById('manager-assets-grid');
const empty = document.getElementById('manager-assets-empty');
const fileInput = document.getElementById('zone-file-upload');
const alertEl = document.getElementById('asset-alert');
let allAssets = [];
async function fetchAssets() {
try {
const res = await fetch('/api/uploads', {
headers: { 'Authorization': `Bearer ${token}` }
});
if (res.ok) {
allAssets = await res.json();
renderAssets();
}
} catch (e) {
console.error("Failed to fetch assets", e);
}
}
function showLocalAlert(msg, type) {
if (!alertEl) return;
alertEl.textContent = msg;
alertEl.className = `p-4 rounded-lg mb-6 text-sm ${type === 'success' ? 'bg-green/20 text-green border border-green/30' : 'bg-red/20 text-red border border-red/30'}`;
alertEl.classList.remove('hidden');
setTimeout(() => alertEl.classList.add('hidden'), 4000);
}
async function uploadFiles(files) {
let successCount = 0;
for (const file of files) {
const formData = new FormData();
formData.append('file', file);
try {
const res = await fetch('/api/upload', {
method: 'POST',
headers: { 'Authorization': `Bearer ${token}` },
body: formData
});
if (res.ok) successCount++;
} catch (e) {}
}
if (successCount > 0) {
showLocalAlert(`Successfully uploaded ${successCount} file(s).`, 'success');
fetchAssets();
}
}
async function deleteAsset(filename) {
if (!confirm(`Delete "${filename}" permanently?`)) return;
try {
const res = await fetch(`/api/uploads/${encodeURIComponent(filename)}`, {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${token}` }
});
if (res.ok) {
showLocalAlert('File deleted.', 'success');
fetchAssets();
} else {
showLocalAlert('Failed to delete file.', 'error');
}
} catch (e) {
showLocalAlert('Connection error.', 'error');
}
}
function renderAssets() {
if (!grid || !empty) return;
grid.innerHTML = '';
if (allAssets.length === 0) {
empty.classList.remove('hidden');
return;
}
empty.classList.add('hidden');
allAssets.forEach(asset => {
const div = document.createElement('div');
div.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";
const isImage = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(asset.name);
// Preview Container
const preview = document.createElement('div');
preview.className = "flex-1 overflow-hidden bg-surface0/20 relative cursor-pointer";
if (isImage) {
const img = document.createElement('img');
img.src = asset.url;
img.className = "w-full h-full object-cover opacity-80 group-hover:opacity-100 transition-opacity";
preview.appendChild(img);
} else {
preview.className += " flex flex-col items-center justify-center text-subtext0";
preview.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="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 class="text-[8px] font-mono px-2 truncate w-full text-center">${asset.name.split('.').pop().toUpperCase()}</span>
`;
}
// Action Overlays
const actions = document.createElement('div');
actions.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";
if (mode === 'select') {
const selectBtn = document.createElement('button');
selectBtn.className = "bg-mauve text-crust px-3 py-1 rounded-md text-xs font-bold";
selectBtn.textContent = "Insert";
selectBtn.onclick = () => {
document.dispatchEvent(new CustomEvent('asset-selected', { detail: asset }));
};
actions.appendChild(selectBtn);
}
const deleteBtn = document.createElement('button');
deleteBtn.className = "bg-red/80 hover:bg-red text-white p-1.5 rounded-md transition-colors";
deleteBtn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="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>';
deleteBtn.onclick = (e) => {
e.stopPropagation();
deleteAsset(asset.name);
};
actions.appendChild(deleteBtn);
preview.appendChild(actions);
// Label
const label = document.createElement('div');
label.className = "p-2 bg-crust text-[10px] truncate border-t border-white/5 text-subtext1";
label.textContent = asset.name;
div.appendChild(preview);
div.appendChild(label);
grid.appendChild(div);
});
}
fileInput?.addEventListener('change', (e) => {
if (e.target.files.length > 0) uploadFiles(e.target.files);
});
// Initialize
fetchAssets();
// Re-fetch on global upload events if needed
document.addEventListener('assets-updated', fetchAssets);
</script>

View File

@@ -1,41 +0,0 @@
---
const { defaultTheme } = Astro.props;
---
<div class="relative inline-block text-left">
<select
id="user-theme-switcher"
class="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"
>
<option value="mocha">Mocha</option>
<option value="macchiato">Macchiato</option>
<option value="frappe">Frappe</option>
<option value="latte">Latte</option>
<option value="scaled-and-icy">Scaled and Icy</option>
</select>
<div class="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" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-9"/></svg>
</div>
</div>
<script is:inline define:vars={{ defaultTheme }}>
const initTheme = () => {
const switcher = document.getElementById('user-theme-switcher');
if (switcher) {
const savedTheme = localStorage.getItem('user-theme') || defaultTheme;
switcher.value = savedTheme;
document.documentElement.className = savedTheme;
switcher.addEventListener('change', (e) => {
const newTheme = e.target.value;
localStorage.setItem('user-theme', newTheme);
document.documentElement.className = newTheme;
});
}
};
// Initialize immediately
initTheme();
// Re-initialize after Astro view transitions or navigation
document.addEventListener('astro:after-swap', initTheme);
</script>

View File

@@ -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(' ');
}

View File

@@ -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>
);
}

View File

@@ -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>
);
}

View File

@@ -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>
);
}

View File

@@ -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>
)}
</>
);
}

View File

@@ -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>
);
}

View File

@@ -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>
);
}

View File

@@ -9,12 +9,6 @@ const { title } = Astro.props;
--- ---
<Layout title={title}> <Layout title={title}>
<!-- CodeMirror Assets -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css">
<script is:inline src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script>
<script is:inline src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/markdown/markdown.min.js"></script>
<script is:inline src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/keymap/vim.min.js"></script>
<div class="glass p-6 md:p-12 mb-12" id="admin-content" style="display: none;"> <div class="glass p-6 md:p-12 mb-12" id="admin-content" style="display: none;">
<header class="mb-8 md:mb-12 border-b border-white/5 pb-8 md:pb-12 flex flex-col md:flex-row justify-between items-start md:items-center gap-4"> <header class="mb-8 md:mb-12 border-b border-white/5 pb-8 md:pb-12 flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
<div> <div>
@@ -44,7 +38,6 @@ const { title } = Astro.props;
const content = document.getElementById('admin-content'); const content = document.getElementById('admin-content');
if (content) content.style.display = 'block'; if (content) content.style.display = 'block';
// Smart Back Link
const backLink = document.getElementById('back-link'); const backLink = document.getElementById('back-link');
if (backLink && document.referrer && document.referrer.includes(window.location.host) && !document.referrer.includes('/admin/login')) { if (backLink && document.referrer && document.referrer.includes(window.location.host) && !document.referrer.includes('/admin/login')) {
backLink.addEventListener('click', (ev) => { backLink.addEventListener('click', (ev) => {
@@ -52,9 +45,6 @@ const { title } = Astro.props;
window.history.back(); window.history.back();
}); });
} }
// Dispatch custom event for child components to know token is ready
document.dispatchEvent(new CustomEvent('admin-auth-ready', { detail: { token } }));
} }
</script> </script>
</Layout> </Layout>

View File

@@ -1,6 +1,6 @@
--- ---
import '../styles/global.css'; import '../styles/global.css';
import ThemeSwitcher from '../components/ThemeSwitcher.astro'; import ThemeSwitcher from '../components/react/ThemeSwitcher';
interface Props { interface Props {
title: string; title: string;
@@ -40,8 +40,6 @@ try {
<title>{title} | {siteConfig.title}</title> <title>{title} | {siteConfig.title}</title>
{siteConfig.custom_css && <style set:html={siteConfig.custom_css} />} {siteConfig.custom_css && <style set:html={siteConfig.custom_css} />}
<script is:inline define:vars={{ defaultTheme: siteConfig.theme }}> <script is:inline define:vars={{ defaultTheme: siteConfig.theme }}>
// Prevention of FOUC (Flash of Unstyled Content)
// Immediately apply theme before rendering
const savedTheme = localStorage.getItem('user-theme') || defaultTheme; const savedTheme = localStorage.getItem('user-theme') || defaultTheme;
document.documentElement.className = savedTheme; document.documentElement.className = savedTheme;
</script> </script>
@@ -65,7 +63,7 @@ try {
<div class="flex gap-3 md:gap-4 items-center text-sm md:text-base w-full md:w-auto justify-center md:justify-end"> <div class="flex gap-3 md:gap-4 items-center text-sm md:text-base w-full md:w-auto justify-center md:justify-end">
<a href="/" class="text-subtext0 hover:text-text transition-colors">Home</a> <a href="/" class="text-subtext0 hover:text-text transition-colors">Home</a>
<a href="/admin" class="text-subtext0 hover:text-mauve transition-colors">Admin</a> <a href="/admin" class="text-subtext0 hover:text-mauve transition-colors">Admin</a>
<ThemeSwitcher defaultTheme={siteConfig.theme} /> <ThemeSwitcher client:load defaultTheme={siteConfig.theme} />
</div> </div>
</header> </header>
</nav> </nav>

61
frontend/src/lib/api.ts Normal file
View File

@@ -0,0 +1,61 @@
import type { Post, SiteConfig, Asset } from './types';
function getToken(): string | null {
if (typeof window === 'undefined') return null;
return localStorage.getItem('admin_token');
}
async function apiFetch<T>(path: string, options: RequestInit = {}): Promise<T> {
const headers: Record<string, string> = {
...(options.headers as Record<string, string> || {}),
};
const token = getToken();
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
if (!(options.body instanceof FormData)) {
headers['Content-Type'] = headers['Content-Type'] || 'application/json';
}
const res = await fetch(`/api${path}`, { ...options, headers });
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new ApiError(res.status, body.error || res.statusText);
}
const text = await res.text();
return text ? JSON.parse(text) : (undefined as T);
}
export class ApiError extends Error {
constructor(public status: number, message: string) {
super(message);
this.name = 'ApiError';
}
}
// Posts
export const getPosts = () => apiFetch<Post[]>('/posts');
export const getPost = (slug: string) => apiFetch<Post>(`/posts/${encodeURIComponent(slug)}`);
export const savePost = (data: { slug: string; old_slug?: string | null; summary?: string | null; content: string }) =>
apiFetch<Post>('/posts', { method: 'POST', body: JSON.stringify(data) });
export const deletePost = (slug: string) =>
apiFetch<void>(`/posts/${encodeURIComponent(slug)}`, { method: 'DELETE' });
// Config
export const getConfig = () => apiFetch<SiteConfig>('/config');
export const updateConfig = (data: Partial<SiteConfig>) =>
apiFetch<SiteConfig>('/config', { method: 'POST', body: JSON.stringify(data) });
// Assets
export const getAssets = () => apiFetch<Asset[]>('/uploads');
export const uploadAsset = (file: File) => {
const form = new FormData();
form.append('file', file);
return apiFetch<Asset>('/upload', { method: 'POST', body: form });
};
export const deleteAsset = (name: string) =>
apiFetch<void>(`/uploads/${encodeURIComponent(name)}`, { method: 'DELETE' });

22
frontend/src/lib/types.ts Normal file
View File

@@ -0,0 +1,22 @@
export interface Post {
slug: string;
content: string;
summary?: string;
excerpt?: string;
}
export interface SiteConfig {
title: string;
subtitle: string;
welcome_title: string;
welcome_subtitle: string;
footer: string;
favicon: string;
theme: string;
custom_css: string;
}
export interface Asset {
name: string;
url: string;
}

View File

@@ -1,10 +1,9 @@
--- ---
import AdminLayout from '../../layouts/AdminLayout.astro'; import AdminLayout from '../../layouts/AdminLayout.astro';
import AssetManager from '../../components/AssetManager.astro'; import AssetManager from '../../components/react/admin/AssetManager';
--- ---
<AdminLayout title="Asset Library"> <AdminLayout title="Asset Library">
<p slot="header-subtitle" class="mt-2 text-sm md:text-base" style="color: var(--text) !important;">Manage your uploaded images and files.</p> <p slot="header-subtitle" class="mt-2 text-sm md:text-base" style="color: var(--text) !important;">Manage your uploaded images and files.</p>
<AssetManager client:load mode="manage" />
<AssetManager mode="manage" />
</AdminLayout> </AdminLayout>

View File

@@ -1,291 +1,11 @@
--- ---
import AdminLayout from '../../layouts/AdminLayout.astro'; import AdminLayout from '../../layouts/AdminLayout.astro';
import AssetManager from '../../components/AssetManager.astro'; import Editor from '../../components/react/admin/Editor';
const editSlug = Astro.url.searchParams.get('edit') || undefined;
--- ---
<AdminLayout title="Write Post"> <AdminLayout title="Write Post">
<p slot="header-subtitle" id="post-status" class="mt-2 text-sm md:text-base" style="color: var(--text) !important;">Create/Edit post.</p> <p slot="header-subtitle" class="mt-2 text-sm md:text-base" style="color: var(--text) !important;">Create/Edit post.</p>
<Editor client:load editSlug={editSlug} />
<div slot="header-actions" class="flex gap-4 w-full">
<button id="delete-btn" class="hidden text-red hover:bg-red/10 px-6 py-3 rounded-lg transition-colors font-bold border border-red/20 w-full md:w-auto">
Delete
</button>
<button
id="save-btn"
class="bg-mauve text-crust font-bold py-3 px-8 rounded-lg hover:bg-pink transition-all transform hover:scale-105 w-full md:w-auto whitespace-nowrap"
>
Save Post
</button>
<a
id="view-post-btn"
href="#"
target="_blank"
class="hidden bg-blue text-crust font-bold py-3 px-8 rounded-lg hover:bg-sky transition-all transform hover:scale-105 w-full md:w-auto whitespace-nowrap 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" stroke-width="2" stroke-linecap="round" stroke-linejoin="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 id="alert" class="hidden p-4 rounded-lg mb-6"></div>
<div class="space-y-6">
<div>
<label for="slug" class="block text-sm font-medium text-subtext1 mb-2">Post Title (URL identifier)</label>
<input
type="text"
id="slug"
required
placeholder="my-awesome-post"
class="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>
<div>
<label for="summary" class="block text-sm font-medium text-subtext1 mb-2">Custom Summary (Optional)</label>
<textarea
id="summary"
rows="2"
placeholder="A brief description of this post for the frontpage..."
class="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"
></textarea>
</div>
<div class="relative">
<div class="flex flex-col md:flex-row justify-between items-start md:items-end mb-2 gap-2">
<label for="content" class="block text-sm font-medium text-subtext1 italic">Tip: Type '/' to browse your assets</label>
<button
id="open-library-btn"
class="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" stroke-width="2" stroke-linecap="round" stroke-linejoin="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>
<textarea
id="content"
required
rows="25"
placeholder="# Hello World&#10;Write your markdown here..."
class="w-full bg-crust border border-surface1 rounded-lg px-4 py-4 text-text focus:outline-none focus:border-mauve transition-colors font-mono resize-y leading-relaxed"
></textarea>
<!-- Autocomplete Dropdown -->
<div id="autocomplete" class="hidden absolute z-50 bg-mantle border border-surface1 rounded-lg shadow-2xl max-h-64 overflow-y-auto w-80">
<div class="p-2 text-[10px] text-subtext0 uppercase border-b border-white/5 bg-crust/50">Assets Library</div>
<ul id="autocomplete-list" class="py-1">
<!-- Items injected here -->
</ul>
</div>
</div>
</div>
<!-- Assets Modal -->
<div id="assets-modal" class="hidden fixed inset-0 z-[100] bg-crust/80 backdrop-blur-sm flex items-center justify-center p-4 md:p-6">
<div class="glass w-full max-w-5xl max-h-[90vh] flex flex-col overflow-hidden">
<header class="p-4 md:p-6 border-b border-white/5 flex justify-between items-center bg-surface0/20">
<div>
<h2 class="text-xl md:text-2xl font-bold text-mauve">Asset Library</h2>
<p class="text-xs text-subtext0">Click 'Insert' to add an asset to your post.</p>
</div>
<button id="close-modal" class="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" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
</button>
</header>
<div class="p-4 md:p-6 overflow-y-auto flex-1 bg-base/50">
<AssetManager mode="select" />
</div>
</div>
</div>
<script>
import { showAlert } from '../../components/ui/Alert';
document.addEventListener('admin-auth-ready', (e: any) => {
const token = e.detail.token;
const slugInput = document.getElementById('slug') as HTMLInputElement;
const summaryInput = document.getElementById('summary') as HTMLTextAreaElement;
const contentInput = document.getElementById('content') as HTMLTextAreaElement;
const saveBtn = document.getElementById('save-btn');
const delBtn = document.getElementById('delete-btn');
const viewPostBtn = document.getElementById('view-post-btn') as HTMLAnchorElement;
const openLibraryBtn = document.getElementById('open-library-btn');
const assetsModal = document.getElementById('assets-modal');
const closeModal = document.getElementById('close-modal');
const autocomplete = document.getElementById('autocomplete');
const autocompleteList = document.getElementById('autocomplete-list');
let originalSlug = "";
// @ts-ignore
const editor = CodeMirror.fromTextArea(contentInput, {
mode: 'markdown',
theme: 'narlblog',
lineWrapping: true,
keyMap: window.innerWidth > 768 ? 'vim' : 'default',
extraKeys: {"Enter": "newlineAndIndentContinueMarkdownList"}
});
openLibraryBtn?.addEventListener('click', () => {
assetsModal?.classList.remove('hidden');
});
closeModal?.addEventListener('click', () => {
assetsModal?.classList.add('hidden');
});
// Listen for asset selection from the component
document.addEventListener('asset-selected', (ev: any) => {
const asset = ev.detail;
insertMarkdown(asset.name, asset.url);
assetsModal?.classList.add('hidden');
});
function insertMarkdown(name: string, url: string) {
const isImage = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(name);
const markdown = isImage ? `![${name}](${url})` : `[${name}](${url})`;
const doc = editor.getDoc();
const cursor = doc.getCursor();
doc.replaceRange(markdown, cursor);
editor.focus();
}
// Autocomplete Logic
editor.on('inputRead', async (cm: any, change: any) => {
if (change.text && change.text.length === 1 && (change.text[0] === '/' || change.text[0] === '!')) {
const res = await fetch('/api/uploads', {
headers: { 'Authorization': `Bearer ${token}` }
});
if (res.ok) {
const allAssets = await res.json();
showAutocomplete(allAssets);
}
} else if (change.text && change.text[0] === ' ') {
hideAutocomplete();
}
});
function showAutocomplete(assets: any[]) {
if (!autocomplete || !autocompleteList) return;
const cursor = editor.cursorCoords(true, 'local');
autocomplete.classList.remove('hidden');
autocomplete.style.top = `${cursor.bottom + 10}px`;
autocomplete.style.left = `${cursor.left}px`;
autocompleteList.innerHTML = '';
assets.slice(0, 8).forEach(asset => {
const li = document.createElement('li');
li.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";
const isImage = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(asset.name);
li.innerHTML = `
<div class="w-6 h-6 flex-shrink-0 bg-surface0 rounded flex items-center justify-center overflow-hidden">
${isImage ? `<img src="${asset.url}" class="w-full h-full object-cover">` : `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="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 class="truncate">${asset.name}</span>
`;
li.addEventListener('click', () => {
const doc = editor.getDoc();
const cursor = doc.getCursor();
const line = doc.getLine(cursor.line);
const triggerIndex = Math.max(line.lastIndexOf('/'), line.lastIndexOf('!'));
if (triggerIndex !== -1) {
doc.replaceRange('', {line: cursor.line, ch: triggerIndex}, cursor);
}
insertMarkdown(asset.name, asset.url);
hideAutocomplete();
});
autocompleteList.appendChild(li);
});
}
function hideAutocomplete() {
autocomplete?.classList.add('hidden');
}
window.addEventListener('click', (ev) => {
if (!autocomplete?.contains(ev.target as Node)) {
hideAutocomplete();
}
});
saveBtn?.addEventListener('click', async () => {
const payload = {
slug: slugInput.value,
old_slug: originalSlug || null,
summary: summaryInput.value || null,
content: editor.getValue()
};
if (!payload.slug || !payload.content) {
showAlert('Title and content are required.', 'error');
return;
}
try {
const res = await fetch('/api/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(payload)
});
if (res.ok) {
showAlert('Post saved!', 'success');
originalSlug = payload.slug;
if (viewPostBtn) {
viewPostBtn.href = `/posts/${payload.slug}`;
viewPostBtn.classList.remove('hidden');
viewPostBtn.classList.add('inline-flex');
}
} else {
const err = await res.json();
showAlert(`Error: ${err.error}`, 'error');
}
} catch (err) {
showAlert('Failed to connect to server.', 'error');
}
});
delBtn?.addEventListener('click', async () => {
const slugToDelete = originalSlug || slugInput.value;
if (confirm(`Delete post "${slugToDelete}" permanently?`)) {
try {
const res = await fetch(`/api/posts/${encodeURIComponent(slugToDelete)}`, {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${token}` }
});
if (res.ok) window.location.href = '/admin';
else showAlert('Error deleting post.', 'error');
} catch (e) {
showAlert('Connection error.', 'error');
}
}
});
const urlParams = new URLSearchParams(window.location.search);
const editSlug = urlParams.get('edit');
if (editSlug) {
slugInput.value = editSlug;
originalSlug = editSlug;
delBtn?.classList.remove('hidden');
if (viewPostBtn) {
viewPostBtn.href = `/posts/${editSlug}`;
viewPostBtn.classList.remove('hidden');
viewPostBtn.classList.add('inline-flex');
}
fetch(`/api/posts/${encodeURIComponent(editSlug)}`)
.then(res => res.json())
.then(data => {
if (data.summary) summaryInput.value = data.summary;
if (data.content) editor.setValue(data.content);
})
.catch(() => showAlert('Failed to load post.', 'error'));
}
});
</script>
</AdminLayout> </AdminLayout>

View File

@@ -1,136 +1,8 @@
--- ---
import AdminLayout from '../../layouts/AdminLayout.astro'; import AdminLayout from '../../layouts/AdminLayout.astro';
import Dashboard from '../../components/react/admin/Dashboard';
--- ---
<AdminLayout title="Admin Dashboard"> <AdminLayout title="Admin Dashboard">
<button slot="header-actions" id="logout-btn" class="text-red hover:text-maroon transition-colors font-medium"> <Dashboard client:load />
Logout
</button>
<div class="grid md:grid-cols-3 gap-8 mb-12">
<a href="/admin/editor" class="group">
<div class="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 class="bg-mauve/20 p-4 rounded-full text-mauve">
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="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>
</div>
<div>
<h2 class="text-xl font-bold text-lavender group-hover:text-mauve transition-colors">Write Post</h2>
<p class="text-xs text-subtext0 mt-1">Create or edit markdown posts.</p>
</div>
</div>
</a>
<a href="/admin/assets" class="group">
<div class="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 class="bg-teal/20 p-4 rounded-full text-teal">
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="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>
</div>
<div>
<h2 class="text-xl font-bold text-teal group-hover:text-green transition-colors">Asset Library</h2>
<p class="text-xs text-subtext0 mt-1">Manage images and uploads.</p>
</div>
</div>
</a>
<a href="/admin/settings" class="group">
<div class="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 class="bg-blue/20 p-4 rounded-full text-blue">
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="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>
</div>
<div>
<h2 class="text-xl font-bold text-blue group-hover:text-sky transition-colors">Settings</h2>
<p class="text-xs text-subtext0 mt-1">Site title and themes.</p>
</div>
</div>
</a>
</div>
<section>
<h2 class="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" stroke-width="2" stroke-linecap="round" stroke-linejoin="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 id="posts-list" class="space-y-4">
<!-- Posts will be loaded here -->
<div class="animate-pulse flex space-x-4 p-8 glass">
<div class="flex-1 space-y-4 py-1">
<div class="h-4 bg-surface1 rounded w-3/4"></div>
<div class="h-4 bg-surface1 rounded w-1/2"></div>
</div>
</div>
</div>
</section>
<script>
import { showAlert } from '../../components/ui/Alert';
document.addEventListener('admin-auth-ready', (e: any) => {
const token = e.detail.token;
loadPosts();
async function loadPosts() {
const postsList = document.getElementById('posts-list');
if (!postsList) return;
try {
const res = await fetch('/api/posts');
if (res.ok) {
const posts = await res.json();
if (posts.length === 0) {
postsList.innerHTML = '<div class="glass p-8 text-center text-subtext0">No posts yet.</div>';
return;
}
postsList.innerHTML = '';
posts.forEach((post: {slug: string}) => {
const div = document.createElement('div');
div.className = "glass p-6 flex justify-between items-center group hover:bg-surface0/50 transition-colors";
div.innerHTML = `
<div>
<h3 class="font-bold text-lavender text-lg">${post.slug}</h3>
<p class="text-xs text-subtext0" style="color: var(--subtext0) !important;">/posts/${post.slug}</p>
</div> <div class="flex gap-3">
<a href="/admin/editor?edit=${post.slug}" class="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" stroke-width="2" stroke-linecap="round" stroke-linejoin="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 class="p-2 text-red hover:bg-red/10 rounded transition-colors delete-btn" data-slug="${post.slug}" title="Delete">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="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>
`;
postsList.appendChild(div);
});
document.querySelectorAll('.delete-btn').forEach(btn => {
btn.addEventListener('click', async (ev) => {
const slug = (ev.currentTarget as HTMLElement).dataset.slug;
if (confirm(`Are you sure you want to delete "${slug}"?`)) {
try {
const delRes = await fetch(`/api/posts/${encodeURIComponent(slug as string)}`, {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${token}` }
});
if (delRes.ok) {
loadPosts();
} else {
showAlert('Failed to delete post.', 'error');
}
} catch (err) {
showAlert('Error connecting to server.', 'error');
}
}
});
});
}
} catch (e) {
postsList.innerHTML = '<div class="glass p-8 text-center text-red">Failed to load posts.</div>';
}
}
document.getElementById('logout-btn')?.addEventListener('click', () => {
localStorage.removeItem('admin_token');
window.location.href = '/';
});
});
</script>
</AdminLayout> </AdminLayout>

View File

@@ -1,44 +1,8 @@
--- ---
import Layout from '../../layouts/Layout.astro'; import Layout from '../../layouts/Layout.astro';
import Login from '../../components/react/admin/Login';
--- ---
<Layout title="Admin Login"> <Layout title="Admin Login">
<div class="max-w-md mx-auto mt-20"> <Login client:load />
<div class="glass p-12">
<h1 class="text-3xl font-bold mb-6 text-mauve">Admin Login</h1>
<p class="text-subtext0 mb-8">Enter your admin token to access the dashboard.</p>
<form id="login-form" class="space-y-6">
<div>
<label for="token" class="block text-sm font-medium text-subtext1 mb-2">Admin Token</label>
<input
type="password"
id="token"
name="token"
required
class="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"
class="w-full bg-mauve text-crust font-bold py-3 rounded-lg hover:bg-pink transition-colors"
>
Login
</button>
</form>
</div>
</div>
<script>
const form = document.getElementById('login-form');
form?.addEventListener('submit', (e) => {
e.preventDefault();
const token = (document.getElementById('token') as HTMLInputElement).value;
if (token) {
localStorage.setItem('admin_token', token);
window.location.href = '/admin';
}
});
</script>
</Layout> </Layout>

View File

@@ -1,132 +1,9 @@
--- ---
import AdminLayout from '../../layouts/AdminLayout.astro'; import AdminLayout from '../../layouts/AdminLayout.astro';
import Settings from '../../components/react/admin/Settings';
--- ---
<AdminLayout title="Site Settings"> <AdminLayout title="Site Settings">
<p slot="header-subtitle" class="mt-2 text-sm md:text-base" style="color: var(--text) !important;">Configure how your blog looks and feels globally.</p> <p slot="header-subtitle" class="mt-2 text-sm md:text-base" style="color: var(--text) !important;">Configure how your blog looks and feels globally.</p>
<Settings client:load />
<form id="settings-form" class="space-y-8">
<div id="alert" class="hidden p-4 rounded-lg mb-6"></div>
<section class="space-y-6">
<h2 class="text-xl font-bold text-lavender border-l-4 border-lavender pl-4">General Identity</h2>
<div class="grid md:grid-cols-2 gap-6">
<div>
<label for="title" class="block text-sm font-medium text-subtext1 mb-2">Blog Title (Nav)</label>
<input type="text" id="title" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
</div>
<div>
<label for="subtitle" class="block text-sm font-medium text-subtext1 mb-2">Nav Subtitle</label>
<input type="text" id="subtitle" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
</div>
<div>
<label for="welcome_title" class="block text-sm font-medium text-subtext1 mb-2">Welcome Title (Frontpage)</label>
<input type="text" id="welcome_title" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
</div>
<div>
<label for="welcome_subtitle" class="block text-sm font-medium text-subtext1 mb-2">Welcome Subtitle</label>
<input type="text" id="welcome_subtitle" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
</div>
</div>
<div>
<label for="favicon" class="block text-sm font-medium text-subtext1 mb-2">Favicon URL</label>
<input type="text" id="favicon" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
<p class="text-[10px] text-subtext0 mt-1">URL to the icon shown in browser tabs.</p>
</div>
</section>
<section class="space-y-6">
<h2 class="text-xl font-bold text-blue border-l-4 border-blue pl-4">Appearance</h2>
<div>
<label for="theme" class="block text-sm font-medium text-subtext1 mb-2">Color Theme (Catppuccin)</label>
<select id="theme" class="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 class="text-[10px] text-subtext0 mt-1">Select a predefined Catppuccin color palette.</p>
</div>
<div>
<label for="custom_css" class="block text-sm font-medium text-subtext1 mb-2">Custom CSS</label>
<textarea id="custom_css" rows="4" class="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 { ... }"></textarea>
<p class="text-[10px] text-subtext0 mt-1">Inject custom CSS styles globally.</p>
</div>
</section>
<section class="space-y-6">
<h2 class="text-xl font-bold text-teal border-l-4 border-teal pl-4">Footer</h2>
<div>
<label for="footer" class="block text-sm font-medium text-subtext1 mb-2">Footer Text</label>
<input type="text" id="footer" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
</div>
</section>
<button type="submit" class="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>
<script>
import { showAlert } from '../../components/ui/Alert';
document.addEventListener('admin-auth-ready', (e: any) => {
const token = e.detail.token;
loadSettings();
async function loadSettings() {
try {
const res = await fetch('/api/config');
if (res.ok) {
const data = await res.json();
(document.getElementById('title') as HTMLInputElement).value = data.title || '';
(document.getElementById('subtitle') as HTMLInputElement).value = data.subtitle || '';
(document.getElementById('welcome_title') as HTMLInputElement).value = data.welcome_title || '';
(document.getElementById('welcome_subtitle') as HTMLInputElement).value = data.welcome_subtitle || '';
(document.getElementById('footer') as HTMLInputElement).value = data.footer || '';
(document.getElementById('favicon') as HTMLInputElement).value = data.favicon || '';
(document.getElementById('theme') as HTMLSelectElement).value = data.theme || 'mocha';
(document.getElementById('custom_css') as HTMLTextAreaElement).value = data.custom_css || '';
}
} catch (err) {
showAlert('Failed to load settings from server.', 'error');
}
}
document.getElementById('settings-form')?.addEventListener('submit', async (ev) => {
ev.preventDefault();
const payload = {
title: (document.getElementById('title') as HTMLInputElement).value,
subtitle: (document.getElementById('subtitle') as HTMLInputElement).value,
welcome_title: (document.getElementById('welcome_title') as HTMLInputElement).value,
welcome_subtitle: (document.getElementById('welcome_subtitle') as HTMLInputElement).value,
footer: (document.getElementById('footer') as HTMLInputElement).value,
favicon: (document.getElementById('favicon') as HTMLInputElement).value,
theme: (document.getElementById('theme') as HTMLSelectElement).value,
custom_css: (document.getElementById('custom_css') as HTMLTextAreaElement).value,
};
try {
const res = await fetch('/api/config', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(payload)
});
if (res.ok) {
showAlert('Settings saved successfully! Refresh to see changes.', 'success');
} else {
const err = await res.json();
showAlert(`Error: ${err.error}`, 'error');
}
} catch (err) {
showAlert('Failed to save settings. Please check your connection.', 'error');
}
});
});
</script>
</AdminLayout> </AdminLayout>

View File

@@ -1,6 +1,6 @@
--- ---
import Layout from '../../layouts/Layout.astro'; import Layout from '../../layouts/Layout.astro';
import { marked } from 'marked'; import PostContent from '../../components/react/PostContent';
const { slug } = Astro.params; const { slug } = Astro.params;
const API_URL = (typeof process !== 'undefined' ? process.env.PUBLIC_API_URL : import.meta.env.PUBLIC_API_URL) || 'http://localhost:3000'; const API_URL = (typeof process !== 'undefined' ? process.env.PUBLIC_API_URL : import.meta.env.PUBLIC_API_URL) || 'http://localhost:3000';
@@ -11,16 +11,12 @@ interface PostDetail {
} }
let post: PostDetail | null = null; let post: PostDetail | null = null;
let html = '';
let error = ''; let error = '';
try { try {
const response = await fetch(`${API_URL}/api/posts/${slug}`); const response = await fetch(`${API_URL}/api/posts/${slug}`);
if (response.ok) { if (response.ok) {
post = await response.json(); post = await response.json();
if (post) {
html = await marked.parse(post.content);
}
} else { } else {
error = 'Post not found'; error = 'Post not found';
} }
@@ -41,29 +37,6 @@ function formatSlug(slug: string) {
<Layout title={post ? formatSlug(post.slug) : 'Post'}> <Layout title={post ? formatSlug(post.slug) : 'Post'}>
<article class="glass p-6 md:p-12 mb-8 md:mb-12 animate-in fade-in slide-in-from-bottom-4 duration-700"> <article class="glass p-6 md:p-12 mb-8 md:mb-12 animate-in fade-in slide-in-from-bottom-4 duration-700">
<header class="mb-8 md:mb-12 border-b border-white/5 pb-8 md:pb-12">
<a href="/" class="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) !important;">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="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>
{post && (
<div class="flex flex-col md:flex-row md:justify-between md:items-start mt-2 md:mt-4 gap-4">
<h1 class="text-3xl md:text-5xl font-extrabold text-mauve">
{formatSlug(post.slug)}
</h1>
<a
href={`/admin/editor?edit=${post.slug}`}
id="edit-btn"
class="hidden bg-surface0 hover:bg-surface1 text-blue px-3 py-1.5 md:px-4 md:py-2 rounded border border-surface1 transition-colors items-center gap-2 text-sm md:text-base self-start"
style="color: var(--blue) !important;"
>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="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>
{error && ( {error && (
<div class="text-red text-center py-12"> <div class="text-red text-center py-12">
<h2 class="text-2xl font-bold mb-4">{error}</h2> <h2 class="text-2xl font-bold mb-4">{error}</h2>
@@ -72,44 +45,7 @@ function formatSlug(slug: string) {
)} )}
{post && ( {post && (
<div class="prose max-w-none" id="post-content" set:html={html} /> <PostContent client:load content={post.content} slug={post.slug} />
)} )}
</article> </article>
<!-- KaTeX for LaTeX Math Rendering -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.css" crossorigin="anonymous">
<script is:inline src="https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.js" crossorigin="anonymous"></script>
<script is:inline src="https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/contrib/auto-render.min.js" crossorigin="anonymous"></script>
<!-- Highlight.js for Code Blocks -->
<script is:inline src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script>
if (localStorage.getItem('admin_token')) {
const editBtn = document.getElementById('edit-btn');
if (editBtn) {
editBtn.style.display = 'inline-flex';
}
}
// Initialize KaTeX and Highlight.js
document.addEventListener("DOMContentLoaded", function() {
const content = document.getElementById('post-content');
if (content) {
// @ts-ignore
renderMathInElement(content, {
delimiters: [
{left: '$$', right: '$$', display: true},
{left: '$', right: '$', display: false},
{left: '\\(', right: '\\)', display: false},
{left: '\\[', right: '\\]', display: true}
],
throwOnError: false
});
// @ts-ignore
hljs.highlightAll();
}
});
</script>
</Layout> </Layout>

View File

@@ -0,0 +1,19 @@
import { create } from 'zustand';
interface AuthState {
token: string | null;
setToken: (token: string) => void;
logout: () => void;
}
export const useAuth = create<AuthState>((set) => ({
token: typeof window !== 'undefined' ? localStorage.getItem('admin_token') : null,
setToken: (token: string) => {
localStorage.setItem('admin_token', token);
set({ token });
},
logout: () => {
localStorage.removeItem('admin_token');
set({ token: null });
},
}));

View File

@@ -1,5 +1,9 @@
{ {
"extends": "astro/tsconfigs/strict", "extends": "astro/tsconfigs/strict",
"include": [".astro/types.d.ts", "**/*"], "include": [".astro/types.d.ts", "**/*"],
"exclude": ["dist"] "exclude": ["dist"],
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "react"
}
} }