feat: add visual admin panel with page builder and settings editor

- Add /admin route with password-protected visual page builder
- Page Builder: manage hero images, standalone albums, subpages, and sections
- Album Picker: browse all shared Immich albums with search and filtering
- Settings Editor: theme, grid, footer, legal, SEO configuration
- YAML service with atomic writes and automatic backups (content/.backups/)
- HMAC-signed admin sessions (24h expiry, HttpOnly cookies)
- API endpoints: /api/admin/{auth,gallery,settings,albums,reload}
- Enable with ADMIN_PASSWORD env var; disabled by default
- invalidateConfigCache() export for hot-reload after saves
This commit is contained in:
ralksta
2026-05-29 17:04:37 +02:00
parent 5887706775
commit 9e52d7a0b8
18 changed files with 3127 additions and 1 deletions

View File

@@ -0,0 +1,72 @@
'use client';
import { useState } from 'react';
import PageBuilder from './PageBuilder';
import SettingsEditor from './SettingsEditor';
interface Props {
onLogout: () => void;
}
type Tab = 'pages' | 'settings';
export default function AdminDashboard({ onLogout }: Props) {
const [activeTab, setActiveTab] = useState<Tab>('pages');
const [saving, setSaving] = useState(false);
async function handleLogout() {
await fetch('/api/admin/auth', { method: 'DELETE' });
onLogout();
}
async function handleReload() {
setSaving(true);
try {
await fetch('/api/admin/reload', { method: 'POST' });
} finally {
setSaving(false);
}
}
return (
<div className="admin-dashboard">
<header className="admin-header">
<div className="admin-header-left">
<h1>Immich Folio</h1>
<nav className="admin-tabs">
<button
className={`admin-tab ${activeTab === 'pages' ? 'active' : ''}`}
onClick={() => setActiveTab('pages')}
>
Pages
</button>
<button
className={`admin-tab ${activeTab === 'settings' ? 'active' : ''}`}
onClick={() => setActiveTab('settings')}
>
Settings
</button>
</nav>
</div>
<div className="admin-header-right">
<button
className="admin-btn admin-btn-ghost"
onClick={handleReload}
disabled={saving}
title="Reload config & clear cache"
>
↻ Reload
</button>
<button className="admin-btn admin-btn-ghost" onClick={handleLogout}>
Logout
</button>
</div>
</header>
<main className="admin-main">
{activeTab === 'pages' && <PageBuilder />}
{activeTab === 'settings' && <SettingsEditor />}
</main>
</div>
);
}

View File

@@ -0,0 +1,68 @@
'use client';
import { useState } from 'react';
interface Props {
onSuccess: () => void;
}
export default function AdminLogin({ onSuccess }: Props) {
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError('');
setLoading(true);
try {
const res = await fetch('/api/admin/auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password }),
});
if (res.ok) {
onSuccess();
} else {
const data = await res.json();
setError(data.error || 'Login failed');
}
} catch {
setError('Connection error');
} finally {
setLoading(false);
}
}
return (
<div className="admin-login">
<form className="admin-login-card" onSubmit={handleSubmit}>
<div className="admin-login-header">
<h1>Immich Folio</h1>
<p>Admin Panel</p>
</div>
<div className="admin-field">
<label htmlFor="admin-password">Password</label>
<input
id="admin-password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter admin password"
autoFocus
disabled={loading}
/>
</div>
{error && <div className="admin-error">{error}</div>}
<button type="submit" className="admin-btn admin-btn-primary" disabled={loading}>
{loading ? 'Signing in...' : 'Sign In'}
</button>
</form>
</div>
);
}

View File

@@ -0,0 +1,97 @@
'use client';
import { useState, useMemo } from 'react';
interface ImmichAlbumInfo {
id: string;
albumName: string;
description: string;
thumbnailAssetId: string | null;
assetCount: number;
isConfigured: boolean;
}
interface Props {
albums: ImmichAlbumInfo[];
onSelect: (albumId: string) => void;
onClose: () => void;
usedAlbumIds: Set<string>;
}
export default function AlbumPicker({ albums, onSelect, onClose, usedAlbumIds }: Props) {
const [search, setSearch] = useState('');
const filtered = useMemo(() => {
if (!search.trim()) return albums;
const q = search.toLowerCase();
return albums.filter(
(a) =>
a.albumName.toLowerCase().includes(q) ||
a.description.toLowerCase().includes(q) ||
a.id.includes(q),
);
}, [albums, search]);
return (
<div className="picker-overlay" onClick={onClose}>
<div className="picker-modal" onClick={(e) => e.stopPropagation()}>
<div className="picker-header">
<h3>Select Album</h3>
<button className="admin-btn-icon" onClick={onClose}>
×
</button>
</div>
<div className="picker-search">
<input
type="text"
placeholder="Search albums by name or UUID..."
value={search}
onChange={(e) => setSearch(e.target.value)}
autoFocus
/>
</div>
<div className="picker-list">
{filtered.length === 0 && (
<p className="empty-hint">
No albums found. Make sure you have shared albums in Immich.
</p>
)}
{filtered.map((album) => {
const isUsed = usedAlbumIds.has(album.id);
return (
<div
key={album.id}
className={`picker-item ${isUsed ? 'used' : ''}`}
onClick={() => !isUsed && onSelect(album.id)}
>
<div className="picker-item-thumb">
{album.thumbnailAssetId ? (
<div className="picker-thumb-placeholder">📷</div>
) : (
<div className="picker-thumb-placeholder">📁</div>
)}
</div>
<div className="picker-item-info">
<span className="picker-item-name">{album.albumName}</span>
<span className="picker-item-meta">
{album.assetCount} photos
{album.description && ` · ${album.description.slice(0, 40)}`}
</span>
</div>
<div className="picker-item-action">
{isUsed ? (
<span className="picker-used-badge">In use</span>
) : (
<span className="picker-select-badge">Select</span>
)}
</div>
</div>
);
})}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,831 @@
'use client';
import { useState, useEffect, useCallback } from 'react';
import AlbumPicker from './AlbumPicker';
// ── Types ──────────────────────────────────────────────────────
interface AlbumEntry {
id: string;
title?: string;
description?: string;
password?: string;
}
interface Section {
title: string;
description?: string;
albums: AlbumEntry[];
}
interface Subpage {
name: string;
title?: string;
subtitle?: string;
password?: string;
sections?: Section[];
albums: AlbumEntry[];
grid?: { columns?: number; gap?: number; aspectRatio?: string; layout?: string };
}
interface GalleryState {
hero: string[];
albums: AlbumEntry[];
subpages: Subpage[];
}
interface ImmichAlbumInfo {
id: string;
albumName: string;
description: string;
thumbnailAssetId: string | null;
assetCount: number;
isConfigured: boolean;
}
// ── Helpers ────────────────────────────────────────────────────
function parseAlbumEntries(
raw:
| Array<
string | Record<string, string | { title: string; description?: string; password?: string }>
>
| undefined,
): AlbumEntry[] {
if (!raw) return [];
return raw.map((entry) => {
if (typeof entry === 'string') return { id: entry };
const [id, value] = Object.entries(entry)[0];
if (typeof value === 'string') return { id, title: value };
return { id, title: value.title, description: value.description, password: value.password };
});
}
function serializeAlbumEntries(
entries: AlbumEntry[],
): Array<
string | Record<string, string | { title: string; description?: string; password?: string }>
> {
return entries.map((entry) => {
if (!entry.title && !entry.description && !entry.password) return entry.id;
if (entry.title && !entry.description && !entry.password) {
return { [entry.id]: entry.title };
}
const val: { title: string; description?: string; password?: string } = {
title: entry.title || '',
};
if (entry.description) val.description = entry.description;
if (entry.password) val.password = entry.password;
return { [entry.id]: val };
});
}
// ── Component ──────────────────────────────────────────────────
export default function PageBuilder() {
const [gallery, setGallery] = useState<GalleryState>({ hero: [], albums: [], subpages: [] });
const [immichAlbums, setImmichAlbums] = useState<ImmichAlbumInfo[]>([]);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [dirty, setDirty] = useState(false);
const [saveMessage, setSaveMessage] = useState('');
const [pickerTarget, setPickerTarget] = useState<{
type: 'standalone' | 'subpage' | 'section';
subpageIndex?: number;
sectionIndex?: number;
} | null>(null);
// Load data
useEffect(() => {
loadData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
async function loadData() {
setLoading(true);
try {
const [galleryRes, albumsRes] = await Promise.all([
fetch('/api/admin/gallery'),
fetch('/api/admin/albums'),
]);
if (galleryRes.ok) {
const { gallery: raw } = await galleryRes.json();
setGallery(parseGalleryYaml(raw));
}
if (albumsRes.ok) {
const { albums } = await albumsRes.json();
setImmichAlbums(albums);
}
} catch (err) {
console.error('Failed to load admin data:', err);
} finally {
setLoading(false);
}
}
function parseGalleryYaml(raw: Record<string, unknown>): GalleryState {
const hero = Array.isArray(raw.hero) ? raw.hero : raw.hero ? [raw.hero as string] : [];
const albums = parseAlbumEntries(
raw.albums as Array<string | Record<string, string>> | undefined,
);
let subpages: Subpage[] = [];
if (Array.isArray(raw.subpages)) {
subpages = (raw.subpages as Array<Record<string, unknown>>).map((sp) => ({
name: (sp.name as string) || '',
title: sp.title as string | undefined,
subtitle: sp.subtitle as string | undefined,
password: sp.password as string | undefined,
albums: parseAlbumEntries(sp.albums as Array<string | Record<string, string>> | undefined),
sections: sp.sections
? (sp.sections as Array<Record<string, unknown>>).map((sec) => ({
title: (sec.title as string) || '',
description: sec.description as string | undefined,
albums: parseAlbumEntries(sec.albums as Array<string | Record<string, string>>),
}))
: undefined,
grid: sp.grid as Subpage['grid'],
}));
} else if (raw.subpages && typeof raw.subpages === 'object') {
subpages = Object.entries(raw.subpages as Record<string, unknown>).map(([name, value]) => {
if (Array.isArray(value)) {
return { name, albums: parseAlbumEntries(value), sections: undefined };
}
const sp = value as Record<string, unknown>;
return {
name,
title: sp.title as string | undefined,
subtitle: sp.subtitle as string | undefined,
password: sp.password as string | undefined,
albums: parseAlbumEntries(
sp.albums as Array<string | Record<string, string>> | undefined,
),
sections: undefined,
grid: sp.grid as Subpage['grid'],
};
});
}
return { hero, albums, subpages };
}
const markDirty = useCallback(() => {
setDirty(true);
setSaveMessage('');
}, []);
// ── Save ──────────────────────────────────────────────────────
async function handleSave() {
setSaving(true);
setSaveMessage('');
// Serialize back to YAML-compatible format
const yamlData: Record<string, unknown> = {};
if (gallery.hero.length > 0) {
yamlData.hero = gallery.hero;
}
if (gallery.albums.length > 0) {
yamlData.albums = serializeAlbumEntries(gallery.albums);
}
if (gallery.subpages.length > 0) {
yamlData.subpages = gallery.subpages.map((sp) => {
const entry: Record<string, unknown> = { name: sp.name };
if (sp.title) entry.title = sp.title;
if (sp.subtitle) entry.subtitle = sp.subtitle;
if (sp.password) entry.password = sp.password;
if (sp.grid) entry.grid = sp.grid;
if (sp.sections && sp.sections.length > 0) {
entry.sections = sp.sections.map((sec) => {
const s: Record<string, unknown> = {
title: sec.title,
albums: serializeAlbumEntries(sec.albums),
};
if (sec.description) s.description = sec.description;
return s;
});
// Also include top-level albums if they exist alongside sections
if (sp.albums.length > 0) {
entry.albums = serializeAlbumEntries(sp.albums);
}
} else {
entry.albums = serializeAlbumEntries(sp.albums);
}
return entry;
});
}
try {
const res = await fetch('/api/admin/gallery', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ gallery: yamlData }),
});
if (res.ok) {
setDirty(false);
setSaveMessage('Saved successfully!');
setTimeout(() => setSaveMessage(''), 3000);
} else {
const err = await res.json();
setSaveMessage(`Error: ${err.error}`);
}
} catch {
setSaveMessage('Error: Failed to save');
} finally {
setSaving(false);
}
}
// ── Album Picker Handlers ────────────────────────────────────
function handlePickAlbum(albumId: string) {
if (!pickerTarget) return;
const entry: AlbumEntry = { id: albumId };
if (pickerTarget.type === 'standalone') {
setGallery((g) => ({ ...g, albums: [...g.albums, entry] }));
} else if (pickerTarget.type === 'subpage' && pickerTarget.subpageIndex != null) {
setGallery((g) => {
const subpages = [...g.subpages];
const sp = { ...subpages[pickerTarget.subpageIndex!] };
sp.albums = [...sp.albums, entry];
subpages[pickerTarget.subpageIndex!] = sp;
return { ...g, subpages };
});
} else if (
pickerTarget.type === 'section' &&
pickerTarget.subpageIndex != null &&
pickerTarget.sectionIndex != null
) {
setGallery((g) => {
const subpages = [...g.subpages];
const sp = { ...subpages[pickerTarget.subpageIndex!] };
const sections = [...(sp.sections || [])];
const sec = { ...sections[pickerTarget.sectionIndex!] };
sec.albums = [...sec.albums, entry];
sections[pickerTarget.sectionIndex!] = sec;
sp.sections = sections;
subpages[pickerTarget.subpageIndex!] = sp;
return { ...g, subpages };
});
}
setPickerTarget(null);
markDirty();
}
// ── Subpage Management ────────────────────────────────────────
function addSubpage() {
setGallery((g) => ({
...g,
subpages: [
...g.subpages,
{ name: `New Page ${g.subpages.length + 1}`, albums: [], sections: undefined },
],
}));
markDirty();
}
function removeSubpage(index: number) {
if (!confirm('Remove this subpage?')) return;
setGallery((g) => ({
...g,
subpages: g.subpages.filter((_, i) => i !== index),
}));
markDirty();
}
function updateSubpage(index: number, updates: Partial<Subpage>) {
setGallery((g) => {
const subpages = [...g.subpages];
subpages[index] = { ...subpages[index], ...updates };
return { ...g, subpages };
});
markDirty();
}
// ── Section Management ────────────────────────────────────────
function addSection(subpageIndex: number) {
setGallery((g) => {
const subpages = [...g.subpages];
const sp = { ...subpages[subpageIndex] };
sp.sections = [...(sp.sections || []), { title: 'New Section', albums: [] }];
subpages[subpageIndex] = sp;
return { ...g, subpages };
});
markDirty();
}
function removeSection(subpageIndex: number, sectionIndex: number) {
setGallery((g) => {
const subpages = [...g.subpages];
const sp = { ...subpages[subpageIndex] };
sp.sections = (sp.sections || []).filter((_, i) => i !== sectionIndex);
subpages[subpageIndex] = sp;
return { ...g, subpages };
});
markDirty();
}
function updateSection(subpageIndex: number, sectionIndex: number, updates: Partial<Section>) {
setGallery((g) => {
const subpages = [...g.subpages];
const sp = { ...subpages[subpageIndex] };
const sections = [...(sp.sections || [])];
sections[sectionIndex] = { ...sections[sectionIndex], ...updates };
sp.sections = sections;
subpages[subpageIndex] = sp;
return { ...g, subpages };
});
markDirty();
}
// ── Album Removal ────────────────────────────────────────────
function removeStandaloneAlbum(index: number) {
setGallery((g) => ({
...g,
albums: g.albums.filter((_, i) => i !== index),
}));
markDirty();
}
function removeSubpageAlbum(subpageIndex: number, albumIndex: number) {
setGallery((g) => {
const subpages = [...g.subpages];
const sp = { ...subpages[subpageIndex] };
sp.albums = sp.albums.filter((_, i) => i !== albumIndex);
subpages[subpageIndex] = sp;
return { ...g, subpages };
});
markDirty();
}
function removeSectionAlbum(subpageIndex: number, sectionIndex: number, albumIndex: number) {
setGallery((g) => {
const subpages = [...g.subpages];
const sp = { ...subpages[subpageIndex] };
const sections = [...(sp.sections || [])];
const sec = { ...sections[sectionIndex] };
sec.albums = sec.albums.filter((_, i) => i !== albumIndex);
sections[sectionIndex] = sec;
sp.sections = sections;
subpages[subpageIndex] = sp;
return { ...g, subpages };
});
markDirty();
}
// ── Hero Management ──────────────────────────────────────────
function removeHero(index: number) {
setGallery((g) => ({
...g,
hero: g.hero.filter((_, i) => i !== index),
}));
markDirty();
}
function addHero() {
const uuid = prompt('Enter Immich asset UUID for hero image:');
if (uuid?.trim()) {
setGallery((g) => ({ ...g, hero: [...g.hero, uuid.trim()] }));
markDirty();
}
}
// ── Move helpers ──────────────────────────────────────────────
function moveSubpage(index: number, direction: -1 | 1) {
const newIndex = index + direction;
if (newIndex < 0 || newIndex >= gallery.subpages.length) return;
setGallery((g) => {
const subpages = [...g.subpages];
[subpages[index], subpages[newIndex]] = [subpages[newIndex], subpages[index]];
return { ...g, subpages };
});
markDirty();
}
// ── Helpers ──────────────────────────────────────────────────
function getAlbumName(id: string): string {
const found = immichAlbums.find((a) => a.id === id);
return found?.albumName || id.slice(0, 8) + '...';
}
function getAlbumCount(id: string): number {
const found = immichAlbums.find((a) => a.id === id);
return found?.assetCount || 0;
}
// ── Render ───────────────────────────────────────────────────
if (loading) {
return (
<div className="admin-loading">
<div className="admin-spinner" />
</div>
);
}
return (
<div className="page-builder">
{/* Save Bar */}
<div className={`save-bar ${dirty ? 'dirty' : ''}`}>
<div className="save-bar-left">
{dirty && <span className="unsaved-badge">Unsaved changes</span>}
{saveMessage && (
<span
className={`save-message ${saveMessage.startsWith('Error') ? 'error' : 'success'}`}
>
{saveMessage}
</span>
)}
</div>
<button
className="admin-btn admin-btn-primary"
onClick={handleSave}
disabled={!dirty || saving}
>
{saving ? 'Saving...' : 'Save Changes'}
</button>
</div>
{/* Hero Section */}
<section className="builder-section">
<div className="builder-section-header">
<h2>🏠 Homepage Hero</h2>
<button className="admin-btn admin-btn-sm" onClick={addHero}>
+ Add Hero
</button>
</div>
<div className="hero-list">
{gallery.hero.length === 0 && (
<p className="empty-hint">
No hero images configured. Add asset UUIDs to show a hero carousel.
</p>
)}
{gallery.hero.map((id, i) => (
<div key={i} className="hero-item">
<span className="hero-uuid" title={id}>
{id.slice(0, 8)}...{id.slice(-4)}
</span>
<button className="admin-btn-icon" onClick={() => removeHero(i)} title="Remove">
×
</button>
</div>
))}
</div>
</section>
{/* Standalone Albums */}
<section className="builder-section">
<div className="builder-section-header">
<h2>📷 Standalone Albums</h2>
<button
className="admin-btn admin-btn-sm"
onClick={() => setPickerTarget({ type: 'standalone' })}
>
+ Add Album
</button>
</div>
<div className="album-list">
{gallery.albums.length === 0 && (
<p className="empty-hint">No standalone albums. These show directly on the homepage.</p>
)}
{gallery.albums.map((album, i) => (
<AlbumCard
key={`${album.id}-${i}`}
album={album}
name={getAlbumName(album.id)}
count={getAlbumCount(album.id)}
onRemove={() => removeStandaloneAlbum(i)}
onUpdate={(updates) => {
setGallery((g) => {
const albums = [...g.albums];
albums[i] = { ...albums[i], ...updates };
return { ...g, albums };
});
markDirty();
}}
/>
))}
</div>
</section>
{/* Subpages */}
<section className="builder-section">
<div className="builder-section-header">
<h2>📂 Subpages</h2>
<button className="admin-btn admin-btn-sm" onClick={addSubpage}>
+ New Subpage
</button>
</div>
{gallery.subpages.length === 0 && (
<p className="empty-hint">
No subpages. Create one to group albums under a custom URL path.
</p>
)}
{gallery.subpages.map((sp, spIndex) => (
<div key={spIndex} className="subpage-card">
<div className="subpage-header">
<div className="subpage-header-left">
<div className="subpage-move-btns">
<button
className="admin-btn-icon"
onClick={() => moveSubpage(spIndex, -1)}
disabled={spIndex === 0}
title="Move up"
>
↑
</button>
<button
className="admin-btn-icon"
onClick={() => moveSubpage(spIndex, 1)}
disabled={spIndex === gallery.subpages.length - 1}
title="Move down"
>
↓
</button>
</div>
<input
className="subpage-name-input"
value={sp.name}
onChange={(e) => updateSubpage(spIndex, { name: e.target.value })}
placeholder="Page name (used for URL)"
/>
</div>
<div className="subpage-header-right">
<button
className="admin-btn-icon"
onClick={() => removeSubpage(spIndex)}
title="Delete subpage"
>
🗑
</button>
</div>
</div>
{/* Subpage metadata */}
<div className="subpage-meta">
<div className="admin-field-row">
<div className="admin-field">
<label>Title (optional)</label>
<input
value={sp.title || ''}
onChange={(e) => updateSubpage(spIndex, { title: e.target.value || undefined })}
placeholder="Display title (defaults to name)"
/>
</div>
<div className="admin-field">
<label>Subtitle</label>
<input
value={sp.subtitle || ''}
onChange={(e) =>
updateSubpage(spIndex, { subtitle: e.target.value || undefined })
}
placeholder="Subtitle text"
/>
</div>
</div>
<div className="admin-field-row">
<div className="admin-field">
<label>Password (optional)</label>
<input
type="password"
value={sp.password || ''}
onChange={(e) =>
updateSubpage(spIndex, { password: e.target.value || undefined })
}
placeholder="Leave empty for public"
/>
</div>
</div>
</div>
{/* Albums (if no sections) */}
{(!sp.sections || sp.sections.length === 0) && (
<div className="subpage-albums">
<div className="subpage-albums-header">
<span>Albums</span>
<button
className="admin-btn admin-btn-xs"
onClick={() => setPickerTarget({ type: 'subpage', subpageIndex: spIndex })}
>
+ Add
</button>
</div>
<div className="album-list">
{sp.albums.map((album, aIndex) => (
<AlbumCard
key={`${album.id}-${aIndex}`}
album={album}
name={getAlbumName(album.id)}
count={getAlbumCount(album.id)}
onRemove={() => removeSubpageAlbum(spIndex, aIndex)}
onUpdate={(updates) => {
setGallery((g) => {
const subpages = [...g.subpages];
const sp2 = { ...subpages[spIndex] };
const albums = [...sp2.albums];
albums[aIndex] = { ...albums[aIndex], ...updates };
sp2.albums = albums;
subpages[spIndex] = sp2;
return { ...g, subpages };
});
markDirty();
}}
/>
))}
</div>
</div>
)}
{/* Sections */}
{sp.sections && sp.sections.length > 0 && (
<div className="subpage-sections">
{sp.sections.map((sec, secIndex) => (
<div key={secIndex} className="section-card">
<div className="section-header">
<input
className="section-title-input"
value={sec.title}
onChange={(e) =>
updateSection(spIndex, secIndex, { title: e.target.value })
}
placeholder="Section title"
/>
<button
className="admin-btn-icon"
onClick={() => removeSection(spIndex, secIndex)}
title="Remove section"
>
×
</button>
</div>
<div className="admin-field">
<input
value={sec.description || ''}
onChange={(e) =>
updateSection(spIndex, secIndex, {
description: e.target.value || undefined,
})
}
placeholder="Section description (optional)"
className="section-desc-input"
/>
</div>
<div className="album-list">
{sec.albums.map((album, aIndex) => (
<AlbumCard
key={`${album.id}-${aIndex}`}
album={album}
name={getAlbumName(album.id)}
count={getAlbumCount(album.id)}
onRemove={() => removeSectionAlbum(spIndex, secIndex, aIndex)}
onUpdate={(updates) => {
setGallery((g) => {
const subpages = [...g.subpages];
const sp2 = { ...subpages[spIndex] };
const sections = [...(sp2.sections || [])];
const sec2 = { ...sections[secIndex] };
const albums = [...sec2.albums];
albums[aIndex] = { ...albums[aIndex], ...updates };
sec2.albums = albums;
sections[secIndex] = sec2;
sp2.sections = sections;
subpages[spIndex] = sp2;
return { ...g, subpages };
});
markDirty();
}}
/>
))}
</div>
<button
className="admin-btn admin-btn-xs"
onClick={() =>
setPickerTarget({
type: 'section',
subpageIndex: spIndex,
sectionIndex: secIndex,
})
}
>
+ Add Album
</button>
</div>
))}
</div>
)}
<div className="subpage-actions">
<button className="admin-btn admin-btn-xs" onClick={() => addSection(spIndex)}>
+ Add Section
</button>
{sp.sections && sp.sections.length > 0 && (
<button
className="admin-btn admin-btn-xs"
onClick={() => setPickerTarget({ type: 'subpage', subpageIndex: spIndex })}
>
+ Add Album (outside sections)
</button>
)}
</div>
</div>
))}
</section>
{/* Album Picker Modal */}
{pickerTarget && (
<AlbumPicker
albums={immichAlbums}
onSelect={handlePickAlbum}
onClose={() => setPickerTarget(null)}
usedAlbumIds={getAllUsedAlbumIds()}
/>
)}
</div>
);
function getAllUsedAlbumIds(): Set<string> {
const ids = new Set<string>();
gallery.albums.forEach((a) => ids.add(a.id));
gallery.subpages.forEach((sp) => {
sp.albums.forEach((a) => ids.add(a.id));
sp.sections?.forEach((sec) => sec.albums.forEach((a) => ids.add(a.id)));
});
return ids;
}
}
// ── Album Card Sub-component ───────────────────────────────────
interface AlbumCardProps {
album: AlbumEntry;
name: string;
count: number;
onRemove: () => void;
onUpdate: (updates: Partial<AlbumEntry>) => void;
}
function AlbumCard({ album, name, count, onRemove, onUpdate }: AlbumCardProps) {
const [expanded, setExpanded] = useState(false);
return (
<div className="album-card">
<div className="album-card-main">
<div className="album-card-info">
<span className="album-card-name">{album.title || name}</span>
<span className="album-card-count">{count} photos</span>
</div>
<div className="album-card-actions">
<button
className="admin-btn-icon"
onClick={() => setExpanded(!expanded)}
title="Edit details"
>
✏️
</button>
<button className="admin-btn-icon" onClick={onRemove} title="Remove">
×
</button>
</div>
</div>
{expanded && (
<div className="album-card-details">
<div className="admin-field">
<label>Title override</label>
<input
value={album.title || ''}
onChange={(e) => onUpdate({ title: e.target.value || undefined })}
placeholder={name}
/>
</div>
<div className="admin-field">
<label>Description</label>
<input
value={album.description || ''}
onChange={(e) => onUpdate({ description: e.target.value || undefined })}
placeholder="Optional description"
/>
</div>
<div className="admin-field">
<label>Password</label>
<input
type="password"
value={album.password || ''}
onChange={(e) => onUpdate({ password: e.target.value || undefined })}
placeholder="Leave empty for public"
/>
</div>
<div className="album-card-uuid">
<code>{album.id}</code>
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,559 @@
'use client';
import { useState, useEffect } from 'react';
interface Settings {
title?: string;
subtitle?: string;
lang?: string;
exifOnHover?: boolean;
map?: boolean;
transitions?: boolean;
theme?: {
preset?: string;
accent?: string;
photoFrame?: string;
grain?: boolean;
headerDot?: boolean;
heroStyle?: string;
};
grid?: {
columns?: number;
gap?: number;
aspectRatio?: string;
layout?: string;
};
footer?: {
name?: string;
instagram?: string;
email?: string;
website?: string;
};
legal?: {
enabled?: boolean;
name?: string;
address?: string;
zipCity?: string;
country?: string;
email?: string;
phone?: string;
taxId?: string;
vatId?: string;
extraInfo?: string;
};
seo?: {
title?: string;
description?: string;
noIndex?: boolean;
noFollow?: boolean;
};
}
const PRESETS = ['studio', 'minimal', 'editorial', 'classic', 'noir', 'monograph'];
const LAYOUTS = ['masonry', 'uniform', 'showcase', 'filmstrip', 'editorial-flow'];
const PHOTO_FRAMES = ['none', 'passepartout', 'shadow'];
const HERO_STYLES = ['split', 'fullbleed', 'minimal', 'stacked', 'typographic', 'mosaic'];
const ASPECT_RATIOS = ['1', '3/2', '2/3', '16/9', 'auto'];
export default function SettingsEditor() {
const [settings, setSettings] = useState<Settings>({});
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [dirty, setDirty] = useState(false);
const [saveMessage, setSaveMessage] = useState('');
const [activeSection, setActiveSection] = useState('general');
useEffect(() => {
loadSettings();
}, []);
async function loadSettings() {
setLoading(true);
try {
const res = await fetch('/api/admin/settings');
if (res.ok) {
const { settings: data } = await res.json();
setSettings(data || {});
}
} catch (err) {
console.error('Failed to load settings:', err);
} finally {
setLoading(false);
}
}
function update(path: string, value: unknown) {
setSettings((s) => {
const copy = JSON.parse(JSON.stringify(s));
const parts = path.split('.');
let obj = copy;
for (let i = 0; i < parts.length - 1; i++) {
if (!obj[parts[i]]) obj[parts[i]] = {};
obj = obj[parts[i]];
}
const key = parts[parts.length - 1];
if (value === '' || value === undefined) {
delete obj[key];
} else {
obj[key] = value;
}
return copy;
});
setDirty(true);
setSaveMessage('');
}
async function handleSave() {
setSaving(true);
setSaveMessage('');
// Clean up empty objects
const cleaned = JSON.parse(JSON.stringify(settings));
for (const key of Object.keys(cleaned)) {
if (typeof cleaned[key] === 'object' && Object.keys(cleaned[key]).length === 0) {
delete cleaned[key];
}
}
try {
const res = await fetch('/api/admin/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ settings: cleaned }),
});
if (res.ok) {
setDirty(false);
setSaveMessage('Saved!');
setTimeout(() => setSaveMessage(''), 3000);
} else {
const err = await res.json();
setSaveMessage(`Error: ${err.error}`);
}
} catch {
setSaveMessage('Error: Failed to save');
} finally {
setSaving(false);
}
}
if (loading) {
return (
<div className="admin-loading">
<div className="admin-spinner" />
</div>
);
}
const sections = [
{ id: 'general', label: 'General' },
{ id: 'theme', label: 'Theme' },
{ id: 'grid', label: 'Grid' },
{ id: 'footer', label: 'Footer' },
{ id: 'legal', label: 'Legal' },
{ id: 'seo', label: 'SEO' },
];
return (
<div className="settings-editor">
{/* Save Bar */}
<div className={`save-bar ${dirty ? 'dirty' : ''}`}>
<div className="save-bar-left">
{dirty && <span className="unsaved-badge">Unsaved changes</span>}
{saveMessage && (
<span
className={`save-message ${saveMessage.startsWith('Error') ? 'error' : 'success'}`}
>
{saveMessage}
</span>
)}
</div>
<button
className="admin-btn admin-btn-primary"
onClick={handleSave}
disabled={!dirty || saving}
>
{saving ? 'Saving...' : 'Save Settings'}
</button>
</div>
<div className="settings-layout">
{/* Sidebar */}
<nav className="settings-nav">
{sections.map((sec) => (
<button
key={sec.id}
className={`settings-nav-item ${activeSection === sec.id ? 'active' : ''}`}
onClick={() => setActiveSection(sec.id)}
>
{sec.label}
</button>
))}
</nav>
{/* Content */}
<div className="settings-content">
{activeSection === 'general' && (
<div className="settings-panel">
<h3>General</h3>
<div className="admin-field">
<label>Site Title</label>
<input
value={settings.title || ''}
onChange={(e) => update('title', e.target.value)}
placeholder="My Portfolio"
/>
</div>
<div className="admin-field">
<label>Subtitle</label>
<input
value={settings.subtitle || ''}
onChange={(e) => update('subtitle', e.target.value)}
placeholder="A visual journal"
/>
</div>
<div className="admin-field">
<label>Language</label>
<select
value={settings.lang || 'en'}
onChange={(e) => update('lang', e.target.value)}
>
<option value="en">English</option>
<option value="de">Deutsch</option>
<option value="fr">Français</option>
<option value="es">Español</option>
<option value="ja">日本語</option>
</select>
</div>
<div className="admin-field-checks">
<label>
<input
type="checkbox"
checked={settings.exifOnHover !== false}
onChange={(e) => update('exifOnHover', e.target.checked)}
/>
EXIF on Hover
</label>
<label>
<input
type="checkbox"
checked={settings.map === true}
onChange={(e) => update('map', e.target.checked)}
/>
Map enabled
</label>
<label>
<input
type="checkbox"
checked={settings.transitions !== false}
onChange={(e) => update('transitions', e.target.checked)}
/>
Page Transitions
</label>
</div>
</div>
)}
{activeSection === 'theme' && (
<div className="settings-panel">
<h3>Theme</h3>
<div className="admin-field">
<label>Preset</label>
<div className="preset-grid">
{PRESETS.map((p) => (
<button
key={p}
className={`preset-btn ${(settings.theme?.preset || 'studio') === p ? 'active' : ''}`}
onClick={() => update('theme.preset', p)}
>
{p}
</button>
))}
</div>
</div>
<div className="admin-field">
<label>Accent Color</label>
<div className="color-field">
<input
type="color"
value={settings.theme?.accent || '#e60012'}
onChange={(e) => update('theme.accent', e.target.value)}
/>
<input
type="text"
value={settings.theme?.accent || ''}
onChange={(e) => update('theme.accent', e.target.value)}
placeholder="#e60012"
/>
</div>
</div>
<div className="admin-field">
<label>Photo Frame</label>
<div className="radio-group">
{PHOTO_FRAMES.map((f) => (
<label key={f}>
<input
type="radio"
name="photoFrame"
checked={(settings.theme?.photoFrame || 'none') === f}
onChange={() => update('theme.photoFrame', f)}
/>
{f}
</label>
))}
</div>
</div>
<div className="admin-field">
<label>Hero Style</label>
<select
value={settings.theme?.heroStyle || 'split'}
onChange={(e) => update('theme.heroStyle', e.target.value)}
>
{HERO_STYLES.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</select>
</div>
<div className="admin-field-checks">
<label>
<input
type="checkbox"
checked={settings.theme?.grain === true}
onChange={(e) => update('theme.grain', e.target.checked)}
/>
Film Grain
</label>
<label>
<input
type="checkbox"
checked={settings.theme?.headerDot !== false}
onChange={(e) => update('theme.headerDot', e.target.checked)}
/>
Header Dot
</label>
</div>
</div>
)}
{activeSection === 'grid' && (
<div className="settings-panel">
<h3>Grid Layout</h3>
<div className="admin-field">
<label>Layout</label>
<div className="preset-grid">
{LAYOUTS.map((l) => (
<button
key={l}
className={`preset-btn ${(settings.grid?.layout || 'masonry') === l ? 'active' : ''}`}
onClick={() => update('grid.layout', l)}
>
{l}
</button>
))}
</div>
</div>
<div className="admin-field-row">
<div className="admin-field">
<label>Columns</label>
<input
type="number"
min={1}
max={6}
value={settings.grid?.columns ?? 3}
onChange={(e) => update('grid.columns', parseInt(e.target.value) || 3)}
/>
</div>
<div className="admin-field">
<label>Gap (px)</label>
<input
type="number"
min={0}
max={48}
value={settings.grid?.gap ?? 12}
onChange={(e) => update('grid.gap', parseInt(e.target.value) || 0)}
/>
</div>
</div>
<div className="admin-field">
<label>Aspect Ratio</label>
<div className="preset-grid">
{ASPECT_RATIOS.map((r) => (
<button
key={r}
className={`preset-btn ${(settings.grid?.aspectRatio || '1') === r ? 'active' : ''}`}
onClick={() => update('grid.aspectRatio', r)}
>
{r === '1' ? 'Square' : r}
</button>
))}
</div>
</div>
</div>
)}
{activeSection === 'footer' && (
<div className="settings-panel">
<h3>Footer</h3>
<div className="admin-field">
<label>Name</label>
<input
value={settings.footer?.name || ''}
onChange={(e) => update('footer.name', e.target.value)}
placeholder="My Photography"
/>
</div>
<div className="admin-field">
<label>Instagram URL</label>
<input
value={settings.footer?.instagram || ''}
onChange={(e) => update('footer.instagram', e.target.value)}
placeholder="https://instagram.com/your-handle"
/>
</div>
<div className="admin-field">
<label>Email</label>
<input
value={settings.footer?.email || ''}
onChange={(e) => update('footer.email', e.target.value)}
placeholder="hello@example.com"
/>
</div>
<div className="admin-field">
<label>Website</label>
<input
value={settings.footer?.website || ''}
onChange={(e) => update('footer.website', e.target.value)}
placeholder="https://example.com"
/>
</div>
</div>
)}
{activeSection === 'legal' && (
<div className="settings-panel">
<h3>Legal / Impressum</h3>
<div className="admin-field-checks">
<label>
<input
type="checkbox"
checked={settings.legal?.enabled === true}
onChange={(e) => update('legal.enabled', e.target.checked)}
/>
Enable Impressum page
</label>
</div>
{settings.legal?.enabled && (
<>
<div className="admin-field">
<label>Full Name</label>
<input
value={settings.legal?.name || ''}
onChange={(e) => update('legal.name', e.target.value)}
placeholder="Max Mustermann"
/>
</div>
<div className="admin-field">
<label>Address</label>
<input
value={settings.legal?.address || ''}
onChange={(e) => update('legal.address', e.target.value)}
placeholder="Musterstraße 1"
/>
</div>
<div className="admin-field-row">
<div className="admin-field">
<label>ZIP & City</label>
<input
value={settings.legal?.zipCity || ''}
onChange={(e) => update('legal.zipCity', e.target.value)}
placeholder="12345 Berlin"
/>
</div>
<div className="admin-field">
<label>Country</label>
<input
value={settings.legal?.country || ''}
onChange={(e) => update('legal.country', e.target.value)}
placeholder="Germany"
/>
</div>
</div>
<div className="admin-field-row">
<div className="admin-field">
<label>Email</label>
<input
value={settings.legal?.email || ''}
onChange={(e) => update('legal.email', e.target.value)}
placeholder="legal@example.com"
/>
</div>
<div className="admin-field">
<label>Phone</label>
<input
value={settings.legal?.phone || ''}
onChange={(e) => update('legal.phone', e.target.value)}
placeholder="+49 123 456789"
/>
</div>
</div>
<div className="admin-field">
<label>Extra Info</label>
<textarea
value={settings.legal?.extraInfo || ''}
onChange={(e) => update('legal.extraInfo', e.target.value)}
placeholder="Verantwortlich für den Inhalt..."
rows={3}
/>
</div>
</>
)}
</div>
)}
{activeSection === 'seo' && (
<div className="settings-panel">
<h3>SEO & Metadata</h3>
<div className="admin-field">
<label>SEO Title</label>
<input
value={settings.seo?.title || ''}
onChange={(e) => update('seo.title', e.target.value)}
placeholder="Overrides site title for search engines"
/>
</div>
<div className="admin-field">
<label>SEO Description</label>
<textarea
value={settings.seo?.description || ''}
onChange={(e) => update('seo.description', e.target.value)}
placeholder="A curated selection of photography work."
rows={3}
/>
</div>
<div className="admin-field-checks">
<label>
<input
type="checkbox"
checked={settings.seo?.noIndex === true}
onChange={(e) => update('seo.noIndex', e.target.checked)}
/>
noindex (hide from search engines)
</label>
<label>
<input
type="checkbox"
checked={settings.seo?.noFollow === true}
onChange={(e) => update('seo.noFollow', e.target.checked)}
/>
nofollow (don&apos;t follow links)
</label>
</div>
</div>
)}
</div>
</div>
</div>
);
}