HifiPlanet-Website/hifi-src/src/pages/admin/HomeSections.jsx
Max Olchov b915972a12
Optimierungspaket: Kontaktformular, Admin-Komfort, Rechte, Übersetzungen
- Kontaktformular mit Spam-Schutz (Honeypot, Mindestzeit, Rate-Limit), klarer
  Bestätigung, Paketpreis vom Server, WhatsApp mit vorbereitetem Text
- Preis-Hinweis unter Paketpreisen, eigene 404-Seite, verständliche Fehler
- Admin: Toasts, Speicherleiste, Warnung bei ungespeicherten Änderungen,
  Re-Login bei abgelaufener Sitzung, Sortieren per Drag & Drop
- Neues Recht system.admin für DB, Mail, Google, Export/Import, Reset
- Englische Texte für Leistungen/Pakete/Upgrades (content_translations)
- Automatische Schema-Migration beim ersten Aufruf nach git pull
- Build in hifi/ neu erzeugt

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Dgc8etkq7JkjyZgD2DEbv
2026-10-19 21:39:01 +00:00

405 lines
19 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';
import { useToast, useUnsavedChanges } from '../../context/AdminUiContext.jsx';
import SaveBar from '../../components/admin/SaveBar.jsx';
const SECTIONS = [
{ slug: 'hero', label: 'Großes Titelbild (ganz oben)' },
{ slug: 'youtube', label: 'Video-Abschnitt' },
{ 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 [saved, setSaved] = useState(null);
const [saveBusy, setSaveBusy] = useState(false);
const [saveError, setSaveError] = useState('');
const [savedAt, setSavedAt] = useState(null);
const toast = useToast();
// 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);
// Alle Abschnitte mit Aenderungen gegenueber dem zuletzt gespeicherten Stand - damit ein
// Wechsel zwischen den Reitern nichts verliert und "Speichern" alles auf einmal sichert.
const dirtySlugs = sections && saved
? SECTIONS.map((s) => s.slug).filter((slug) => JSON.stringify(sections[slug]) !== JSON.stringify(saved[slug]))
: [];
useUnsavedChanges(dirtySlugs.length > 0, 'home-sections');
useEffect(() => {
api.get('/home-sections').then((res) => {
setSections(res);
setSaved(res);
});
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 } }));
};
const updatePosition = (x, y) => {
setSections((s) => ({ ...s, [activeSlug]: { ...s[activeSlug], text_align_x: x, text_align_y: y } }));
};
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('');
const done = [];
try {
for (const slug of dirtySlugs) {
await api.put(`/home-sections/${slug}`, sections[slug]);
done.push(slug);
}
setSavedAt(new Date());
toast.success(dirtySlugs.length > 1 ? `${dirtySlugs.length} Abschnitte gespeichert.` : 'Gespeichert.');
} catch (err) {
setSaveError(err.message);
toast.error(`Speichern fehlgeschlagen: ${err.message}`);
} finally {
if (done.length) {
setSaved((prev) => {
const next = { ...prev };
done.forEach((slug) => { next[slug] = sections[slug]; });
return next;
});
}
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);
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}
{dirtySlugs.includes(s.slug) && <span className="ml-1 text-amber-400" title="Ungespeicherte Änderungen">●</span>}
</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' : 'Titelbild'}
</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>}
</div>
<SaveBar
dirty={dirtySlugs.length > 0}
busy={saveBusy}
savedAt={savedAt}
onSave={handleSave}
label={dirtySlugs.length > 1 ? `Alle ${dirtySlugs.length} Abschnitte speichern` : 'Speichern'}
/>
</div>
);
}