HifiPlanet-Website/hifi-src/src/pages/admin/HomeSections.jsx
Maaxxs 326d124a60 Let admins upload their own custom fonts
Adds a new custom_fonts table (name, a server-generated collision-free
font_family identifier, file_path) with its own upload endpoint
(CustomFontController) separate from the generic image-only /uploads,
since it needs to accept WOFF2/WOFF/TTF/OTF instead. New management UI in
WebsiteSettings.jsx ("Eigene Schriftarten"): upload with a display name,
list with delete.

CustomFontsContext.jsx fetches the list once per layout (PublicLayout.jsx
for visitors, AdminLayout.jsx for the dashboard) and exposes it two ways:
useFontOptionsWithCustom() appends the uploaded fonts to the existing
static FONT_OPTIONS list for every font picker (RichTextEditor,
TextStyleWidget, the per-section and global site-font dropdowns), and a
new CustomFontFaces.jsx component renders the @font-face rules that
actually make an uploaded font usable - without it, picking a custom font
would just reference a name the browser has no file for. refresh() lets
WebsiteSettings.jsx update every picker immediately after an
upload/delete, not just on next page load.

Fonts::isValid() replaces the three places that validated a font_family
value against the fixed Fonts::VALUES list (site-wide default, per-section
override, per-field text style) - it now also accepts any uploaded
font's generated identifier, so those endpoints don't reject a custom
font as an unknown value.

Verified locally end-to-end: migration creates the table, a simulated
upload's font_family passes validation while a nonexistent one doesn't,
index() returns the expected shape, and destroy() removes both the row
and the file from uploads/.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-10 03:28:57 +02:00

384 lines
18 KiB
JavaScript

import { useEffect, useRef, useState } from 'react';
import { api } from '../../api/client.js';
import RichTextEditor from '../../components/RichTextEditor.jsx';
import TextStyleWidget from '../../components/TextStyleWidget.jsx';
import { dragAnchorStyle } from '../../utils/dragAnchorPosition.js';
import { useFontOptionsWithCustom } from '../../context/CustomFontsContext.jsx';
const SECTIONS = [
{ slug: 'hero', label: 'Hero (ganz oben)' },
{ slug: 'youtube', label: 'YouTube-Sektion' },
{ slug: 'craft', label: 'Handwerk' },
{ slug: 'advice', label: 'Beratung' },
{ slug: 'insights', label: 'Einblicke (Bildergalerie-Intro)' },
{ slug: 'more', label: 'Mehr als Car-Hifi' },
];
// Hero und YouTube haben einen echten Hintergrund (Bild bzw. Video) und der Textblock liegt
// darueber - dort ist eine frei ziehbare 2D-Position sinnvoll, genau wie bei den
// Bildergalerie-Kacheln (siehe WebsiteSettings.jsx). Die anderen vier Abschnitte sind
// normaler, neben einem separaten Bild fliessender bzw. umbrechender Text ohne eigenen
// Hintergrund - dort bleibt links/mittig/rechts (text-align auf ganzen Absaetzen) das
// richtige Werkzeug, keine frei ziehbare Position wie bei einem einzelnen ueberlagerten Label.
const POSITIONABLE_SLUGS = ['hero', 'youtube'];
const ALIGN_OPTIONS = [
{ value: 'left', label: 'Links' },
{ value: 'center', label: 'Mittig' },
{ value: 'right', label: 'Rechts' },
];
// Feste Klassen (nicht dynamisch zusammengesetzt) fuer Tailwinds Build-Zeit-Scanner - siehe
// Kommentar bei dragAnchorPosition.js/Home.jsx.
const ALIGN_OPTIONS_TEXT = { left: 'text-left', center: 'text-center', right: 'text-right' };
function stripHtml(html) {
const div = document.createElement('div');
div.innerHTML = html || '';
return div.textContent || '';
}
export default function HomeSections() {
const fontOptions = useFontOptionsWithCustom();
const [sections, setSections] = useState(null);
const [activeSlug, setActiveSlug] = useState('hero');
const [activeLang, setActiveLang] = useState('de');
const [saveBusy, setSaveBusy] = useState(false);
const [saveError, setSaveError] = useState('');
const [saveSuccess, setSaveSuccess] = useState(false);
// Fuer eine realistischere Hero-Vorschau (echtes Hero-Bild, falls schon eines hochgeladen ist).
const [heroImagePath, setHeroImagePath] = useState('');
const previewRef = useRef(null);
const [dragging, setDragging] = useState(false);
useEffect(() => {
api.get('/home-sections').then(setSections);
api.get('/site-settings').then((res) => setHeroImagePath(res.hero_image_path || ''));
}, []);
if (!sections) {
return <p className="text-sm text-neutral-400">Lädt…</p>;
}
const active = sections[activeSlug];
const isPositionable = POSITIONABLE_SLUGS.includes(activeSlug);
const update = (field, value) => {
setSections((s) => ({ ...s, [activeSlug]: { ...s[activeSlug], [field]: value } }));
setSaveSuccess(false);
};
const updatePosition = (x, y) => {
setSections((s) => ({ ...s, [activeSlug]: { ...s[activeSlug], text_align_x: x, text_align_y: y } }));
setSaveSuccess(false);
};
const positionFromPointer = (clientX, clientY) => {
const rect = previewRef.current.getBoundingClientRect();
return {
x: Math.max(0, Math.min(100, Math.round(((clientX - rect.left) / rect.width) * 100))),
y: Math.max(0, Math.min(100, Math.round(((clientY - rect.top) / rect.height) * 100))),
};
};
const handleDragStart = (e) => {
e.preventDefault();
e.currentTarget.setPointerCapture(e.pointerId);
setDragging(true);
const { x, y } = positionFromPointer(e.clientX, e.clientY);
updatePosition(x, y);
};
const handleDragMove = (e) => {
if (!dragging) return;
const { x, y } = positionFromPointer(e.clientX, e.clientY);
updatePosition(x, y);
};
const handleDragEnd = (e) => {
setDragging(false);
e.currentTarget.releasePointerCapture(e.pointerId);
};
const handleSave = async () => {
setSaveBusy(true);
setSaveError('');
setSaveSuccess(false);
try {
await api.put(`/home-sections/${activeSlug}`, active);
setSaveSuccess(true);
} catch (err) {
setSaveError(err.message);
} finally {
setSaveBusy(false);
}
};
const previewEyebrow = active[`eyebrow_${activeLang}`] || '';
const previewTitle = active[`title_${activeLang}`] || SECTIONS.find((s) => s.slug === activeSlug)?.label || '';
const previewBody = stripHtml(active[`body_html_${activeLang}`]);
return (
<div className="max-w-3xl space-y-6">
<div>
<h1 className="mb-1 text-xl font-bold text-neutral-900 dark:text-white">Startseite</h1>
<p className="mb-4 text-sm text-neutral-500 dark:text-neutral-400">
Text, Position/Ausrichtung und (falls vorhanden) Button-Ziel der wichtigsten Textabschnitte auf der
Startseite. Bilder, Statistik-Kacheln, Marken-Streifen, Bewertungen und FAQ werden an anderer
Stelle verwaltet.
</p>
</div>
<div className="rounded-xl border border-neutral-200 bg-white p-6 dark:border-neutral-800 dark:bg-neutral-900">
<div className="mb-4 flex flex-wrap gap-2">
{SECTIONS.map((s) => (
<button
key={s.slug}
type="button"
onClick={() => {
setActiveSlug(s.slug);
setSaveSuccess(false);
setSaveError('');
}}
className={`rounded-md px-3 py-1.5 text-sm font-medium transition ${
activeSlug === s.slug
? 'bg-brand-500 text-white'
: 'border border-neutral-300 text-neutral-600 hover:bg-neutral-100 dark:border-neutral-700 dark:text-neutral-300 dark:hover:bg-neutral-800'
}`}
>
{s.label}
</button>
))}
</div>
<div className="mb-4 flex gap-1 border-b border-neutral-200 pb-4 dark:border-neutral-800">
{[
['de', 'Deutsch'],
['en', 'English'],
].map(([lang, label]) => (
<button
key={lang}
type="button"
onClick={() => setActiveLang(lang)}
className={`rounded-md px-3 py-1 text-sm font-medium transition ${
activeLang === lang
? 'bg-neutral-800 text-white dark:bg-neutral-100 dark:text-neutral-900'
: 'text-neutral-500 hover:bg-neutral-100 dark:text-neutral-400 dark:hover:bg-neutral-800'
}`}
>
{label}
</button>
))}
</div>
{isPositionable ? (
<div className="mb-5 grid gap-4 border-b border-neutral-200 pb-5 dark:border-neutral-800 sm:grid-cols-[16rem_1fr] sm:items-start">
<div>
<div
ref={previewRef}
className="relative aspect-video select-none overflow-hidden rounded-xl bg-neutral-900 shadow-sm"
>
{activeSlug === 'hero' && heroImagePath ? (
<img src={heroImagePath} alt="" draggable={false} className="h-full w-full object-cover" />
) : (
<div className="flex h-full w-full items-center justify-center bg-gradient-to-br from-neutral-700 to-neutral-900 text-xs uppercase tracking-wide text-neutral-500">
{activeSlug === 'youtube' ? 'Video-Hintergrund' : 'Hero-Bild'}
</div>
)}
<div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/20 to-black/40" />
<div
onPointerDown={handleDragStart}
onPointerMove={handleDragMove}
onPointerUp={handleDragEnd}
style={{
...dragAnchorStyle(active.text_align_x, active.text_align_y, { x: 50, y: 50 }),
touchAction: 'none',
}}
className={`absolute max-w-[85%] select-none whitespace-nowrap rounded p-2 text-center transition-colors ${
dragging ? 'cursor-grabbing bg-white/10 ring-2 ring-brand-400' : 'cursor-grab hover:bg-white/10'
}`}
>
{previewEyebrow && (
<p className="truncate text-[10px] font-semibold uppercase tracking-wide text-brand-300">
{previewEyebrow}
</p>
)}
<p className="truncate text-sm font-extrabold text-white">{previewTitle}</p>
</div>
</div>
<p className="mt-1.5 text-center text-xs text-neutral-400">Zum Verschieben ziehen</p>
</div>
<div className="flex flex-col gap-3 sm:pt-1">
<p className="text-sm text-neutral-500 dark:text-neutral-400">
Position:{' '}
<span className="font-mono font-semibold text-neutral-700 dark:text-neutral-200">
{active.text_align_x}% / {active.text_align_y}%
</span>
</p>
<div>
<p className="mb-1.5 text-xs font-medium uppercase tracking-wide text-neutral-400">
Schnellauswahl waagerecht
</p>
<div className="flex flex-wrap gap-2">
<button type="button" onClick={() => updatePosition(0, active.text_align_y)} className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm text-neutral-600 hover:bg-neutral-100 dark:border-neutral-700 dark:text-neutral-300 dark:hover:bg-neutral-800">
Links
</button>
<button type="button" onClick={() => updatePosition(50, active.text_align_y)} className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm text-neutral-600 hover:bg-neutral-100 dark:border-neutral-700 dark:text-neutral-300 dark:hover:bg-neutral-800">
Mittig
</button>
<button type="button" onClick={() => updatePosition(100, active.text_align_y)} className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm text-neutral-600 hover:bg-neutral-100 dark:border-neutral-700 dark:text-neutral-300 dark:hover:bg-neutral-800">
Rechts
</button>
</div>
</div>
<div>
<p className="mb-1.5 text-xs font-medium uppercase tracking-wide text-neutral-400">
Schnellauswahl senkrecht
</p>
<div className="flex flex-wrap gap-2">
<button type="button" onClick={() => updatePosition(active.text_align_x, 0)} className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm text-neutral-600 hover:bg-neutral-100 dark:border-neutral-700 dark:text-neutral-300 dark:hover:bg-neutral-800">
Oben
</button>
<button type="button" onClick={() => updatePosition(active.text_align_x, 50)} className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm text-neutral-600 hover:bg-neutral-100 dark:border-neutral-700 dark:text-neutral-300 dark:hover:bg-neutral-800">
Mittig
</button>
<button type="button" onClick={() => updatePosition(active.text_align_x, 100)} className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm text-neutral-600 hover:bg-neutral-100 dark:border-neutral-700 dark:text-neutral-300 dark:hover:bg-neutral-800">
Unten
</button>
</div>
</div>
</div>
</div>
) : (
<div className="mb-5 grid gap-4 border-b border-neutral-200 pb-5 dark:border-neutral-800 sm:grid-cols-[10rem_1fr] sm:items-center">
<div className="aspect-square rounded-xl bg-neutral-100 dark:bg-neutral-800" aria-hidden />
<div>
<div className={`rounded-lg border border-neutral-200 p-3 dark:border-neutral-700 ${ALIGN_OPTIONS_TEXT[active.text_align] || 'text-left'}`}>
{previewEyebrow && (
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-brand-600 dark:text-brand-400">
{previewEyebrow}
</p>
)}
<p className="mb-1 font-bold text-neutral-900 dark:text-white">{previewTitle}</p>
<p className="line-clamp-2 text-xs text-neutral-500 dark:text-neutral-400">
{previewBody || 'Text erscheint hier…'}
</p>
</div>
<div className="mt-2 flex flex-wrap gap-2">
{ALIGN_OPTIONS.map((opt) => (
<button
key={opt.value}
type="button"
onClick={() => update('text_align', opt.value)}
className={`rounded-md border px-3 py-1.5 text-sm font-medium transition ${
active.text_align === opt.value
? 'border-brand-500 bg-brand-500 text-white'
: 'border-neutral-300 text-neutral-600 hover:bg-neutral-100 dark:border-neutral-700 dark:text-neutral-300 dark:hover:bg-neutral-800'
}`}
>
{opt.label}
</button>
))}
</div>
</div>
</div>
)}
<div className="space-y-3">
<div>
<label className="mb-1 block text-sm font-medium text-neutral-700 dark:text-neutral-300">
Kurzer Vorspann (optional)
</label>
<input
value={active[`eyebrow_${activeLang}`] || ''}
onChange={(e) => update(`eyebrow_${activeLang}`, e.target.value)}
className="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm dark:border-neutral-700 dark:bg-neutral-900"
/>
<TextStyleWidget
fieldKey={`home_sections.${activeSlug}.eyebrow`}
previewText={active[`eyebrow_${activeLang}`] || 'Beispieltext'}
/>
</div>
<div>
<label className="mb-1 block text-sm font-medium text-neutral-700 dark:text-neutral-300">Überschrift</label>
<input
value={active[`title_${activeLang}`] || ''}
onChange={(e) => update(`title_${activeLang}`, e.target.value)}
className="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm dark:border-neutral-700 dark:bg-neutral-900"
/>
<TextStyleWidget
fieldKey={`home_sections.${activeSlug}.title`}
previewText={active[`title_${activeLang}`] || 'Beispieltext'}
/>
</div>
<RichTextEditor
label="Text"
value={active[`body_html_${activeLang}`] || ''}
onChange={(html) => update(`body_html_${activeLang}`, html)}
/>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<div>
<label className="mb-1 block text-sm font-medium text-neutral-700 dark:text-neutral-300">
Button-Beschriftung (optional)
</label>
<input
value={active[`button_label_${activeLang}`] || ''}
onChange={(e) => update(`button_label_${activeLang}`, e.target.value)}
className="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm dark:border-neutral-700 dark:bg-neutral-900"
/>
<TextStyleWidget
fieldKey={`home_sections.${activeSlug}.button_label`}
previewText={active[`button_label_${activeLang}`] || 'Beispieltext'}
/>
</div>
<div>
<label className="mb-1 block text-sm font-medium text-neutral-700 dark:text-neutral-300">
Button-Ziel (Link, für beide Sprachen gleich)
</label>
<input
value={active.button_url || ''}
onChange={(e) => update('button_url', e.target.value)}
placeholder="/leistungen oder https://…"
className="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm dark:border-neutral-700 dark:bg-neutral-900"
/>
<p className="mt-1 text-xs text-neutral-400">
Ohne Beschriftung UND Ziel wird kein Button angezeigt. Mit "/" beginnende Ziele bleiben
innerhalb der Seite, alles andere öffnet extern in einem neuen Tab.
</p>
</div>
</div>
<div>
<label className="mb-1 block text-sm font-medium text-neutral-700 dark:text-neutral-300">
Schriftart (für beide Sprachen gleich)
</label>
<select
value={active.font_family || ''}
onChange={(e) => update('font_family', e.target.value || null)}
className="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm dark:border-neutral-700 dark:bg-neutral-900"
>
<option value="">Standard (globale Schriftart)</option>
{fontOptions.filter((f) => f.value).map((f) => (
<option key={f.label} value={f.value}>{f.label}</option>
))}
</select>
</div>
</div>
{active.updated_at && (
<p className="mt-3 text-xs text-neutral-400">
Zuletzt geändert: {new Date(active.updated_at.replace(' ', 'T')).toLocaleString('de-DE')}
</p>
)}
{saveError && <p className="mt-3 text-sm text-red-600">{saveError}</p>}
{saveSuccess && <p className="mt-3 text-sm text-green-600 dark:text-green-400">Gespeichert.</p>}
<button
type="button"
onClick={handleSave}
disabled={saveBusy}
className="mt-4 rounded-md bg-brand-500 px-4 py-2 text-sm font-semibold text-white hover:bg-brand-600 disabled:opacity-50"
>
{saveBusy ? 'Speichere…' : 'Speichern'}
</button>
</div>
</div>
);
}