HifiPlanet-Website/hifi-src/src/components/Navbar.jsx
Max Olchov ad3d1b081d
Live-Bearbeiten-Modus: Texte direkt auf der Website ändern
Eingeloggte Admins schalten über den Stift in der Navbar (oder "Website live
bearbeiten" im Dashboard) einen Bearbeiten-Modus ein und ändern Texte direkt
auf der Seite. Gesammelte Änderungen gehen mit "Speichern" an PUT /live-edit,
das jede Änderung gegen Feld-Whitelist und Berechtigung prüft und alles in
einer Transaktion schreibt.

- Startseite: Vorspann, Überschriften, Texte, Buttons inkl. Ziel, FAQ, Partner
- Leistungen, Paketkacheln (Name, Preistext, Stichpunkte), Marken, Modelle,
  Galerie-Marken/-Projekte, Impressum/Datenschutz/AGB
- Feste Texte (Buttons, Menü, Beschriftungen) je Seite über eine Liste,
  gespeichert in der neuen Tabelle text_overrides (Auto-Migration)
- Bearbeitet wird jeweils die gerade angezeigte Sprache
- .schema-version wird nicht mehr versioniert und vom Self-Update geschont

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

389 lines
16 KiB
JavaScript

import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { Link, useLocation } from 'react-router-dom';
import { LayoutDashboard, MessageCircle, Pencil, Phone, ShoppingBag } from 'lucide-react';
import ThemeToggle from './ThemeToggle.jsx';
import { useAuth } from '../context/AuthContext.jsx';
import { useIsAreaHidden, useSiteSettings } from '../context/SiteSettingsContext.jsx';
import { useLanguage } from '../context/LanguageContext.jsx';
import { useLiveEdit } from '../context/LiveEditContext.jsx';
import logoDark from '../assets/logo-dark.png';
import { telHref, waHref } from '../utils/contactLinks.js';
import { trackEvent } from '../utils/analytics.js';
const SHOP_URL = 'https://www.audio4cars.de/';
const ITEM_DELAY_MS = 70;
const FLY_DURATION_MS = 500;
function FlagDE({ className }) {
return (
<svg viewBox="0 0 3 2" className={className} aria-hidden="true">
<rect width="3" height="0.667" y="0" fill="#000" />
<rect width="3" height="0.667" y="0.667" fill="#D00" />
<rect width="3" height="0.666" y="1.334" fill="#FFCE00" />
</svg>
);
}
function FlagGB({ className }) {
return (
<svg viewBox="0 0 60 30" className={className} aria-hidden="true">
<clipPath id="fgb-t">
<path d="M30,15 h30 v15 z v15 h-30 z h-30 v-15 z v-15 h30 z" />
</clipPath>
<path d="M0,0 v30 h60 v-30 z" fill="#00247d" />
<path d="M0,0 L60,30 M60,0 L0,30" stroke="#fff" strokeWidth="6" />
<path d="M0,0 L60,30 M60,0 L0,30" clipPath="url(#fgb-t)" stroke="#cf142b" strokeWidth="4" />
<path d="M30,0 v30 M0,15 h60" stroke="#fff" strokeWidth="10" />
<path d="M30,0 v30 M0,15 h60" stroke="#cf142b" strokeWidth="6" />
</svg>
);
}
const LANGUAGE_OPTIONS = [
{ code: 'de', label: 'Deutsch', Flag: FlagDE },
{ code: 'en', label: 'English', Flag: FlagGB },
];
function LanguageSwitcher({ overHero = false }) {
const { language, setLanguage, t } = useLanguage();
const [isOpen, setIsOpen] = useState(false);
const containerRef = useRef(null);
const current = LANGUAGE_OPTIONS.find((opt) => opt.code === language) || LANGUAGE_OPTIONS[0];
useEffect(() => {
if (!isOpen) return undefined;
const handleClickOutside = (e) => {
if (containerRef.current && !containerRef.current.contains(e.target)) setIsOpen(false);
};
const handleKeyDown = (e) => {
if (e.key === 'Escape') setIsOpen(false);
};
document.addEventListener('mousedown', handleClickOutside);
document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
document.removeEventListener('keydown', handleKeyDown);
};
}, [isOpen]);
return (
<div className="relative" ref={containerRef}>
<button
type="button"
onClick={() => setIsOpen((v) => !v)}
aria-haspopup="listbox"
aria-expanded={isOpen}
aria-label={t('languageToggle.label')}
className={`flex items-center gap-1 rounded-full p-1.5 transition ${overHero ? 'hover:bg-white/10' : 'hover:bg-neutral-800'}`}
>
<span className={`block h-4 w-6 shrink-0 overflow-hidden rounded-[3px] ring-1 ${overHero ? 'ring-white/50' : 'ring-neutral-600'}`}>
<current.Flag className="h-full w-full" />
</span>
<svg
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
className={`h-3 w-3 transition-transform ${overHero ? 'text-white/70' : 'text-neutral-400'} ${isOpen ? 'rotate-180' : ''}`}
>
<path fillRule="evenodd" clipRule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z" />
</svg>
</button>
{isOpen && (
<div role="listbox" className="absolute right-0 z-50 mt-2 min-w-[9rem] overflow-hidden rounded-lg border border-neutral-700 bg-neutral-900 py-1 shadow-lg">
{LANGUAGE_OPTIONS.map((opt) => (
<button
key={opt.code}
type="button"
role="option"
aria-selected={opt.code === language}
onClick={() => {
setLanguage(opt.code);
setIsOpen(false);
}}
className={`flex w-full items-center gap-2 px-3 py-2 text-left text-sm transition hover:bg-neutral-800 ${
opt.code === language ? 'font-semibold text-brand-400' : 'text-neutral-200'
}`}
>
<span className="block h-4 w-6 shrink-0 overflow-hidden rounded-[3px] ring-1 ring-neutral-600">
<opt.Flag className="h-full w-full" />
</span>
{opt.label}
</button>
))}
</div>
)}
</div>
);
}
export default function Navbar() {
const [open, setOpen] = useState(false);
const [mounted, setMounted] = useState(false);
const [menuVisible, setMenuVisible] = useState(false);
const { user } = useAuth();
const { phone, whatsapp, logo_dark_path: logoDarkPath, has_downloads: hasDownloads } = useSiteSettings();
const isHidden = useIsAreaHidden();
const { t } = useLanguage();
// Hauptlinks, die im Dashboard ausgeblendet werden koennen, fallen hier raus.
const showVehicles = !isHidden('page.vehicles');
const showServices = !isHidden('page.services');
const showGallery = !isHidden('page.gallery');
const showDownloads = hasDownloads && !isHidden('page.downloads');
// Kontakt + Trennlinie + Shop, dazu die optionalen Eintraege.
const totalItems = 3 + [showVehicles, showServices, showGallery, showDownloads, phone, whatsapp].filter(Boolean).length;
const location = useLocation();
const isHome = location.pathname === '/';
const [scrolled, setScrolled] = useState(!isHome);
// Auf der Startseite beginnt der Header transparent, verschmolzen mit dem Hero-Bild,
// und wird erst zur weissen/dunklen Leiste, sobald man zu scrollen beginnt.
useEffect(() => {
if (!isHome) {
setScrolled(true);
return;
}
const handleScroll = () => setScrolled(window.scrollY > 24);
handleScroll();
window.addEventListener('scroll', handleScroll, { passive: true });
return () => window.removeEventListener('scroll', handleScroll);
}, [isHome]);
const transparent = isHome && !scrolled;
// Menue-Overlay als echter Dialog: Escape schliesst, Tab bleibt im Menue, die Seite
// dahinter scrollt nicht mit, und der Fokus springt beim Oeffnen auf "Schliessen".
const overlayRef = useRef(null);
const burgerRef = useRef(null);
useEffect(() => {
if (!open) return undefined;
const previousOverflow = document.body.style.overflow;
document.body.style.overflow = 'hidden';
const focusTimer = setTimeout(() => overlayRef.current?.querySelector('button, a')?.focus(), 50);
const handleKeyDown = (e) => {
if (e.key === 'Escape') {
setOpen(false);
return;
}
if (e.key !== 'Tab' || !overlayRef.current) return;
const focusable = [...overlayRef.current.querySelectorAll('a[href], button')];
if (!focusable.length) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (e.shiftKey && document.activeElement === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault();
first.focus();
}
};
document.addEventListener('keydown', handleKeyDown);
return () => {
clearTimeout(focusTimer);
document.body.style.overflow = previousOverflow;
document.removeEventListener('keydown', handleKeyDown);
burgerRef.current?.focus({ preventScroll: true });
};
}, [open]);
useEffect(() => {
if (open) {
setMounted(true);
// Doppeltes rAF: nach dem Mounten braucht der Browser einen echten Paint mit der
// "versteckten" Ausgangsposition, bevor wir auf "sichtbar" umschalten - sonst
// fasst er beide Zustandsänderungen in einem Frame zusammen und es gibt keinen
// sichtbaren Übergang (kein Fade-in).
let rafInner;
const rafOuter = requestAnimationFrame(() => {
rafInner = requestAnimationFrame(() => setMenuVisible(true));
});
return () => {
cancelAnimationFrame(rafOuter);
if (rafInner) cancelAnimationFrame(rafInner);
};
}
setMenuVisible(false);
const closeDuration = FLY_DURATION_MS + (totalItems - 1) * ITEM_DELAY_MS;
const id = setTimeout(() => setMounted(false), closeDuration);
return () => clearTimeout(id);
}, [open, totalItems]);
const flyIn = () => `transition-all duration-500 ease-out ${menuVisible ? 'opacity-100' : 'opacity-0'}`;
const flyInStyle = (index) => {
const delayIndex = menuVisible ? index : totalItems - 1 - index;
return {
transitionDelay: `${delayIndex * ITEM_DELAY_MS}ms`,
transform: menuVisible ? 'translateY(0)' : 'translateY(-140px)',
};
};
const AdminIcon = user && (
<Link
to="/admin"
aria-label={t('nav.adminPanel')}
title={t('nav.adminPanel')}
className={`rounded-full p-2 transition ${
transparent ? 'text-white hover:bg-white/10' : 'text-neutral-300 hover:bg-neutral-800'
}`}
>
<LayoutDashboard className="h-5 w-5" />
</Link>
);
// Nur fuer eingeloggte Admins mit Inhalts-Rechten: Live-Bearbeiten-Modus an/aus (siehe
// context/LiveEditContext.jsx). Besucher sehen davon nichts.
const live = useLiveEdit();
const LiveEditToggle = live.available && (
<button
type="button"
onClick={() => live.setEnabled(!live.enabled)}
aria-pressed={live.enabled}
aria-label="Seite bearbeiten"
title={live.enabled ? 'Bearbeiten beenden' : 'Seite bearbeiten'}
className={`rounded-full p-2 transition ${
live.enabled
? 'bg-brand-500 text-white hover:bg-brand-600'
: transparent
? 'text-white hover:bg-white/10'
: 'text-neutral-300 hover:bg-neutral-800'
}`}
>
<Pencil className="h-5 w-5" />
</button>
);
// Fortlaufender Index fuer die gestaffelte Einflug-Animation - optionale Eintraege
// (Downloads, Telefon, WhatsApp) verschieben so die nachfolgenden automatisch.
let flyIndex = 0;
const nextFly = () => flyInStyle(flyIndex++);
return (
// Die Hintergrund-/Text-/Rahmenfarben hier sind bewusst die "dunklen" Werte fest verdrahtet
// statt per dark:-Utility bedingt (Kundenwunsch: die Navbar soll immer im Dark-Theme
// bleiben, unabhaengig vom Light-/Dark-Mode-Toggle des Besuchers).
<header
className={`sticky top-0 z-30 border-b transition-colors duration-300 ${
transparent
? 'border-transparent bg-transparent'
: 'border-neutral-800 bg-neutral-950/90 backdrop-blur'
}`}
>
<div className="mx-auto grid max-w-6xl grid-cols-[1fr_auto_1fr] items-center gap-3 px-4 py-3 sm:px-6">
<div className="flex items-center justify-self-start">
<button
ref={burgerRef}
onClick={() => setOpen(true)}
aria-label={t('nav.openMenu')}
aria-expanded={open}
aria-haspopup="dialog"
className={`rounded-md p-2 transition ${
transparent ? 'text-white hover:bg-white/10' : 'text-neutral-300 hover:bg-neutral-800'
}`}
>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="h-6 w-6">
<path strokeLinecap="round" strokeLinejoin="round" d="M4 6h16M4 12h16M4 18h16" />
</svg>
</button>
</div>
{/* Immer die Dark-Mode-Logovariante (weisse Wortmarke) - passend zur immer dunklen
Navbar, unabhaengig vom Light-/Dark-Mode-Toggle des Besuchers. */}
<Link to="/" className="flex items-center justify-self-center rounded-lg px-2 py-1">
<img src={logoDarkPath || logoDark} alt="HifiPlanet" className="h-14 w-auto sm:h-16" />
</Link>
<div className="flex items-center justify-self-end gap-1">
{LiveEditToggle}
{AdminIcon}
{!open && <LanguageSwitcher overHero={transparent} />}
<ThemeToggle overHero={transparent} forceDark />
</div>
</div>
{mounted &&
createPortal(
<div
ref={overlayRef}
role="dialog"
aria-modal="true"
aria-label={t('nav.menu')}
className="fixed inset-0 z-[100] overflow-y-auto text-left backdrop-blur-xl"
style={{ background: 'linear-gradient(135deg, rgba(241,245,249,0.55) 0%, rgba(227,240,207,0.55) 50%, rgba(248,250,252,0.55) 100%)' }}
>
<div className="relative mx-auto flex min-h-full max-w-6xl flex-col items-start justify-center gap-5 py-24 pl-6 pr-8 sm:pl-8">
<button
onClick={() => setOpen(false)}
aria-label={t('nav.closeMenu')}
className="absolute left-6 top-8 flex items-center gap-2 text-neutral-600 hover:text-brand-600 sm:left-8 sm:top-[65px]"
>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="h-6 w-6">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 6l12 12M18 6 6 18" />
</svg>
<span className="text-xs font-semibold uppercase tracking-wide">{t('nav.close')}</span>
</button>
{showVehicles && (
<Link to="/fahrzeuge" onClick={() => setOpen(false)} className={`text-3xl font-extrabold tracking-tight text-neutral-900 hover:text-brand-600 ${flyIn()}`} style={nextFly()}>
{t('nav.vehicles')}
</Link>
)}
{showServices && (
<Link to="/leistungen" onClick={() => setOpen(false)} className={`text-3xl font-extrabold tracking-tight text-neutral-900 hover:text-brand-600 ${flyIn()}`} style={nextFly()}>
{t('nav.services')}
</Link>
)}
{showGallery && (
<Link to="/galerie" onClick={() => setOpen(false)} className={`text-3xl font-extrabold tracking-tight text-neutral-900 hover:text-brand-600 ${flyIn()}`} style={nextFly()}>
{t('nav.gallery')}
</Link>
)}
<Link to="/kontakt" onClick={() => setOpen(false)} className={`text-3xl font-extrabold tracking-tight text-neutral-900 hover:text-brand-600 ${flyIn()}`} style={nextFly()}>
{t('nav.contact')}
</Link>
{showDownloads && (
<Link to="/downloads" onClick={() => setOpen(false)} className={`text-3xl font-extrabold tracking-tight text-neutral-900 hover:text-brand-600 ${flyIn()}`} style={nextFly()}>
{t('nav.downloads')}
</Link>
)}
<div className={`h-px w-16 bg-brand-500/60 ${flyIn()}`} style={nextFly()} />
{phone && (
<a href={telHref(phone)} onClick={() => trackEvent('contact_call')} className={`flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-neutral-600 hover:text-brand-600 ${flyIn()}`} style={nextFly()}>
<Phone className="h-4 w-4" />
{phone}
</a>
)}
{whatsapp && (
<a
href={waHref(whatsapp)}
onClick={() => trackEvent('contact_whatsapp')}
target="_blank"
rel="noopener noreferrer"
className={`flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-neutral-600 hover:text-brand-600 ${flyIn()}`}
style={nextFly()}
>
<MessageCircle className="h-4 w-4" />
{t('nav.whatsapp')}
</a>
)}
<a
href={SHOP_URL}
target="_blank"
rel="noopener noreferrer"
className={`flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-neutral-600 hover:text-brand-600 ${flyIn()}`}
style={nextFly()}
>
<ShoppingBag className="h-4 w-4" />
{t('nav.shop')}
</a>
</div>
</div>,
document.body
)}
</header>
);
}