diff --git a/.gitignore b/.gitignore index 3e7f985..8280acb 100644 --- a/.gitignore +++ b/.gitignore @@ -35,6 +35,11 @@ # (GitUpdateService) - pro Umgebung unterschiedlich, wird automatisch geschrieben. /hifi/api/config/update-state.php +# Dateien des Download-Bereichs (Songs usw., vom Admin hochgeladen) - koennen sehr gross +# sein und sind Inhalte der jeweiligen Umgebung, kein Code. Der Ordner samt Schutz-.htaccess +# wird vom DownloadController beim ersten Upload selbst angelegt. +/hifi/api/uploads/downloads/ + # Arbeits-/Backup-Verzeichnis des Auto-Update-Features. Die Backup-ZIPs darin enthalten # zwangsläufig db.php (siehe oben) - darf NIE ins Repo gelangen, sonst landen # Datenbank-Zugangsdaten im (öffentlichen!) Git-Repo. diff --git a/hifi-src/index.html b/hifi-src/index.html index b70de4d..534e126 100644 --- a/hifi-src/index.html +++ b/hifi-src/index.html @@ -4,11 +4,8 @@ - - - - + HifiPlanet | Car-Hifi Umbauten nach Maß diff --git a/hifi-src/package-lock.json b/hifi-src/package-lock.json index c15c1a4..21c6b19 100644 --- a/hifi-src/package-lock.json +++ b/hifi-src/package-lock.json @@ -8,6 +8,9 @@ "name": "hifi-frontend", "version": "1.0.0", "dependencies": { + "@fontsource/barlow": "^5.3.0", + "@fontsource/barlow-condensed": "^5.3.0", + "@fontsource/michroma": "^5.3.0", "@tiptap/extension-font-family": "^3.31.3", "@tiptap/extension-link": "^3.31.3", "@tiptap/extension-text-style": "^3.31.3", @@ -744,6 +747,33 @@ "license": "MIT", "optional": true }, + "node_modules/@fontsource/barlow": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/barlow/-/barlow-5.3.0.tgz", + "integrity": "sha512-tGR0y6QObRtKv71MOth44222+mdNFM/ZWFWDV1VLzNbG4oK9PNRlyJzmkck4vHAi9ibHBXgt4SlY51amFP55CA==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource/barlow-condensed": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/barlow-condensed/-/barlow-condensed-5.3.0.tgz", + "integrity": "sha512-RA7MmIx0v3eQ6Gcf74qLVLOwLB0GpPOzx+eU9iG/AmCnSJGcIWYeU8y6CEMGZ210MGwGg5CZhzLkkvyZdTTk1g==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource/michroma": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/michroma/-/michroma-5.3.0.tgz", + "integrity": "sha512-9sbGD7ek1hGvq0TmgNPFbuI3k7qwXVdZ+zCDsTHDGRIQqfYrpYWwEYcwH2fzOtvn8uiGqzAoJ72vuFE3v/hDdg==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", diff --git a/hifi-src/package.json b/hifi-src/package.json index 0eba79b..3e8d9dc 100644 --- a/hifi-src/package.json +++ b/hifi-src/package.json @@ -10,6 +10,9 @@ "preview": "vite preview" }, "dependencies": { + "@fontsource/barlow": "^5.3.0", + "@fontsource/barlow-condensed": "^5.3.0", + "@fontsource/michroma": "^5.3.0", "@tiptap/extension-font-family": "^3.31.3", "@tiptap/extension-link": "^3.31.3", "@tiptap/extension-text-style": "^3.31.3", diff --git a/hifi-src/src/App.jsx b/hifi-src/src/App.jsx index 061ba6f..51f783a 100644 --- a/hifi-src/src/App.jsx +++ b/hifi-src/src/App.jsx @@ -1,3 +1,4 @@ +import { lazy, Suspense } from 'react'; import { Routes, Route, Navigate } from 'react-router-dom'; import ScrollToTop from './components/ScrollToTop.jsx'; import CustomCursor from './components/CustomCursor.jsx'; @@ -16,38 +17,76 @@ import GalleryBrandPage from './pages/public/GalleryBrandPage.jsx'; import GalleryProjectPage from './pages/public/GalleryProjectPage.jsx'; import Leistungen from './pages/public/Leistungen.jsx'; import ContactPage from './pages/public/ContactPage.jsx'; +import DownloadsPage from './pages/public/DownloadsPage.jsx'; import Impressum from './pages/public/Impressum.jsx'; import Datenschutz from './pages/public/Datenschutz.jsx'; import AGB from './pages/public/AGB.jsx'; -import SetupWizard from './pages/public/SetupWizard.jsx'; -import Login from './pages/admin/Login.jsx'; -import Dashboard from './pages/admin/Dashboard.jsx'; -import Brands from './pages/admin/Brands.jsx'; -import Models from './pages/admin/Models.jsx'; -import GalleryBrands from './pages/admin/GalleryBrands.jsx'; -import GalleryProjects from './pages/admin/GalleryProjects.jsx'; -import GalleryPhotos from './pages/admin/GalleryPhotos.jsx'; -import Packages from './pages/admin/Packages.jsx'; -import Services from './pages/admin/Services.jsx'; -import Faqs from './pages/admin/Faqs.jsx'; -import Partners from './pages/admin/Partners.jsx'; -import HomeSections from './pages/admin/HomeSections.jsx'; -import PackageProducts from './pages/admin/PackageProducts.jsx'; -import PackageUpgrades from './pages/admin/PackageUpgrades.jsx'; -import ContactRequests from './pages/admin/ContactRequests.jsx'; -import AccountSettings from './pages/admin/AccountSettings.jsx'; -import AdminUsers from './pages/admin/AdminUsers.jsx'; -import PermissionGroups from './pages/admin/PermissionGroups.jsx'; -import SettingsLayout from './pages/admin/settings/SettingsLayout.jsx'; -import WebsiteSettings from './pages/admin/settings/WebsiteSettings.jsx'; -import LegalSettings from './pages/admin/settings/LegalSettings.jsx'; -import UpdateSettings from './pages/admin/settings/UpdateSettings.jsx'; -import EmailSettings from './pages/admin/settings/EmailSettings.jsx'; -import DatabaseSettings from './pages/admin/settings/DatabaseSettings.jsx'; -import ExportImportSettings from './pages/admin/settings/ExportImportSettings.jsx'; -import MaintenanceSettings from './pages/admin/settings/MaintenanceSettings.jsx'; -import ResetSettings from './pages/admin/settings/ResetSettings.jsx'; +// Oeffentliche Seiten bleiben im Haupt-Bundle (sofort da beim Navigieren). Admin-Bereich, +// Login und Einrichtungs-Assistent werden erst geladen, wenn man sie aufruft - vorher lud +// jeder Besucher den kompletten Admin-Code (Editor, Bildzuschnitt, QR-Codes, ...) mit. +// +// Nach einem Deploy existieren die alten Chunk-Dateien nicht mehr (prebuild leert +// hifi/assets) - wer noch einen alten Stand offen hat, bekaeme beim ersten Aufruf eines +// Admin-Bereichs einen Ladefehler. Dann einmal neu laden, das holt die aktuelle index.html. +const RELOAD_FLAG = 'hifi-chunk-reload'; +const lazyPage = (load) => + lazy(() => + load().then( + (module) => { + try { + sessionStorage.removeItem(RELOAD_FLAG); + } catch { + // sessionStorage nicht verfuegbar (z. B. gesperrte Website-Daten) - egal + } + return module; + }, + (err) => { + let alreadyReloaded = true; + try { + alreadyReloaded = !!sessionStorage.getItem(RELOAD_FLAG); + sessionStorage.setItem(RELOAD_FLAG, '1'); + } catch { + // ohne sessionStorage kein Reload-Versuch, sonst droht eine Endlosschleife + } + if (alreadyReloaded) throw err; + window.location.reload(); + return new Promise(() => {}); + } + ) + ); + +const SetupWizard = lazyPage(() => import('./pages/public/SetupWizard.jsx')); +const Login = lazyPage(() => import('./pages/admin/Login.jsx')); +const Dashboard = lazyPage(() => import('./pages/admin/Dashboard.jsx')); +const Brands = lazyPage(() => import('./pages/admin/Brands.jsx')); +const Models = lazyPage(() => import('./pages/admin/Models.jsx')); +const GalleryBrands = lazyPage(() => import('./pages/admin/GalleryBrands.jsx')); +const GalleryProjects = lazyPage(() => import('./pages/admin/GalleryProjects.jsx')); +const GalleryPhotos = lazyPage(() => import('./pages/admin/GalleryPhotos.jsx')); +const Packages = lazyPage(() => import('./pages/admin/Packages.jsx')); +const Services = lazyPage(() => import('./pages/admin/Services.jsx')); +const Faqs = lazyPage(() => import('./pages/admin/Faqs.jsx')); +const Partners = lazyPage(() => import('./pages/admin/Partners.jsx')); +const Downloads = lazyPage(() => import('./pages/admin/Downloads.jsx')); +const HomeSections = lazyPage(() => import('./pages/admin/HomeSections.jsx')); +const PackageProducts = lazyPage(() => import('./pages/admin/PackageProducts.jsx')); +const PackageUpgrades = lazyPage(() => import('./pages/admin/PackageUpgrades.jsx')); +const ContactRequests = lazyPage(() => import('./pages/admin/ContactRequests.jsx')); +const AccountSettings = lazyPage(() => import('./pages/admin/AccountSettings.jsx')); +const AdminUsers = lazyPage(() => import('./pages/admin/AdminUsers.jsx')); +const PermissionGroups = lazyPage(() => import('./pages/admin/PermissionGroups.jsx')); +const SettingsLayout = lazyPage(() => import('./pages/admin/settings/SettingsLayout.jsx')); +const WebsiteSettings = lazyPage(() => import('./pages/admin/settings/WebsiteSettings.jsx')); +const LegalSettings = lazyPage(() => import('./pages/admin/settings/LegalSettings.jsx')); +const UpdateSettings = lazyPage(() => import('./pages/admin/settings/UpdateSettings.jsx')); +const EmailSettings = lazyPage(() => import('./pages/admin/settings/EmailSettings.jsx')); +const DatabaseSettings = lazyPage(() => import('./pages/admin/settings/DatabaseSettings.jsx')); +const ExportImportSettings = lazyPage(() => import('./pages/admin/settings/ExportImportSettings.jsx')); +const MaintenanceSettings = lazyPage(() => import('./pages/admin/settings/MaintenanceSettings.jsx')); +const ResetSettings = lazyPage(() => import('./pages/admin/settings/ResetSettings.jsx')); + +const blankScreen =
; export default function App() { return ( @@ -55,6 +94,9 @@ export default function App() { + {/* Faengt nur Login/Einrichtung ab - Admin-Seiten haben eine eigene Suspense-Grenze in + AdminLayout, damit Seitenleiste und Kopf beim Nachladen stehen bleiben. */} + } /> @@ -68,6 +110,7 @@ export default function App() { } /> } /> } /> + } /> } /> } /> } /> @@ -90,6 +133,7 @@ export default function App() { } /> } /> } /> + } /> } /> } /> } /> @@ -114,6 +158,7 @@ export default function App() { + ); diff --git a/hifi-src/src/api/client.js b/hifi-src/src/api/client.js index 40c0da4..a2e9edb 100644 --- a/hifi-src/src/api/client.js +++ b/hifi-src/src/api/client.js @@ -2,7 +2,30 @@ // abschließendem Slash, z.B. "/hifi/" lokal oder "/" auf IONOS). export const API_BASE = `${import.meta.env.BASE_URL.replace(/\/$/, '')}/api`; +// Zaehlt laufende API-Anfragen - PageImageLoader wartet damit genau so lange, bis die Daten +// einer Seite da sind, statt pauschal eine feste Zeit. +let pendingRequests = 0; +const pendingListeners = new Set(); +const setPending = (delta) => { + pendingRequests += delta; + pendingListeners.forEach((listener) => listener(pendingRequests)); +}; +export const getPendingRequests = () => pendingRequests; +export const subscribePendingRequests = (listener) => { + pendingListeners.add(listener); + return () => pendingListeners.delete(listener); +}; + async function request(path, options = {}) { + setPending(1); + try { + return await send(path, options); + } finally { + setPending(-1); + } +} + +async function send(path, options) { const res = await fetch(`${API_BASE}${path}`, { credentials: 'include', headers: options.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }, @@ -34,7 +57,7 @@ async function request(path, options = {}) { } export const api = { - get: (path) => request(path), + get: (path, options) => request(path, options), post: (path, body) => request(path, { method: 'POST', body: body instanceof FormData ? body : JSON.stringify(body) }), put: (path, body) => request(path, { method: 'PUT', body: JSON.stringify(body) }), patch: (path, body) => request(path, { method: 'PATCH', body: JSON.stringify(body) }), diff --git a/hifi-src/src/assets/videos/youtube-hintergrund.mp4 b/hifi-src/src/assets/videos/youtube-hintergrund.mp4 index 13ad9ac..4fc14e9 100644 Binary files a/hifi-src/src/assets/videos/youtube-hintergrund.mp4 and b/hifi-src/src/assets/videos/youtube-hintergrund.mp4 differ diff --git a/hifi-src/src/components/AdminLayout.jsx b/hifi-src/src/components/AdminLayout.jsx index 89fe195..22e5706 100644 --- a/hifi-src/src/components/AdminLayout.jsx +++ b/hifi-src/src/components/AdminLayout.jsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { Suspense, useEffect, useState } from 'react'; import { Link, NavLink, Outlet, useNavigate } from 'react-router-dom'; import { useAuth } from '../context/AuthContext.jsx'; import { api } from '../api/client.js'; @@ -21,6 +21,7 @@ const ICONS = { sliders: 'M4 6h16M4 6a2 2 0 1 0 4 0 2 2 0 0 0-4 0Zm16 6H4m10 0a2 2 0 1 0 4 0 2 2 0 0 0-4 0ZM4 18h16m-12 0a2 2 0 1 0 4 0 2 2 0 0 0-4 0Z', image: 'M4 5h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm2 12 4.5-5.5L14 16l2.5-3L20 17H6ZM8 9.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0Z', help: 'M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Zm0-5.5v.01M9.5 9.25a2.5 2.5 0 1 1 3.5 2.29c-.7.32-1 .77-1 1.46v.3', + download: 'M12 4v11m0 0-4-4m4 4 4-4M5 19h14', }; const Icon = ({ path }) => ( @@ -69,6 +70,7 @@ export default function AdminLayout() { { to: '/admin/services', label: 'Leistungen', icon: 'briefcase', permission: 'services.manage' }, { to: '/admin/faqs', label: 'FAQ', icon: 'help', permission: 'content.manage' }, { to: '/admin/partners', label: 'Partner', icon: 'tag', permission: 'content.manage' }, + { to: '/admin/downloads', label: 'Downloads', icon: 'download', permission: 'downloads.manage' }, ], }, { @@ -188,7 +190,11 @@ export default function AdminLayout() { )}
- + {/* Admin-Seiten werden einzeln nachgeladen (App.jsx) - Seitenleiste und Kopf + bleiben dabei stehen, nur der Inhaltsbereich zeigt kurz "Lädt…". */} + Lädt…

}> + +
diff --git a/hifi-src/src/components/DynamicIcon.jsx b/hifi-src/src/components/DynamicIcon.jsx index e829ec6..5187c90 100644 --- a/hifi-src/src/components/DynamicIcon.jsx +++ b/hifi-src/src/components/DynamicIcon.jsx @@ -1,8 +1,31 @@ -import { DynamicIcon as LucideDynamicIcon } from 'lucide-react/dynamic'; +import { lazy, Suspense } from 'react'; +import { Boxes, Car, CarFront, Caravan, Cog, ShieldAlert, Video, Zap } from 'lucide-react'; + +// Die Icons der Standard-Leistungen (SettingsController::defaultServices) direkt im Bundle - +// damit kommt die oeffentliche Leistungen-Seite im Normalfall ganz ohne Nachladen aus. +const COMMON_ICONS = { + car: Car, + caravan: Caravan, + 'car-front': CarFront, + cog: Cog, + zap: Zap, + boxes: Boxes, + 'shield-alert': ShieldAlert, + video: Video, +}; + +// Alle anderen (im Admin per IconPicker frei waehlbaren) Icons stecken in einem eigenen +// Chunk, der erst geladen wird, wenn wirklich eines davon gebraucht wird. Vorher hing die +// komplette Bibliothek (~1,1 MB JavaScript) an jedem einzelnen Seitenaufruf. +const RegistryIcon = lazy(() => import('./iconRegistry.jsx')); -// Lädt pro Icon-Name nur den einzelnen benötigten Icon-Chunk nach, statt die -// komplette ~2000-Icon-Bibliothek ins Bundle zu ziehen (siehe lucide-react/dynamic). export default function DynamicIcon({ name, className = 'h-6 w-6', ...props }) { if (!name) return null; - return ; + const Common = COMMON_ICONS[name]; + if (Common) return ; + return ( + + ); } diff --git a/hifi-src/src/components/Footer.jsx b/hifi-src/src/components/Footer.jsx index d9abe74..d20129a 100644 --- a/hifi-src/src/components/Footer.jsx +++ b/hifi-src/src/components/Footer.jsx @@ -1,5 +1,5 @@ import { Link, useLocation } from 'react-router-dom'; -import DynamicIcon from './DynamicIcon.jsx'; +import { Clock, MapPin, Navigation, Phone } from 'lucide-react'; import { useCookieConsent } from '../context/CookieConsentContext.jsx'; import { useSiteSettings } from '../context/SiteSettingsContext.jsx'; import { useLanguage } from '../context/LanguageContext.jsx'; @@ -15,6 +15,7 @@ export default function Footer() { address_zip: addressZip, address_city: addressCity, business_hours: businessHours, + has_downloads: hasDownloads, } = useSiteSettings(); const open = isOpenNow(businessHours); const { openSettings } = useCookieConsent(); @@ -40,7 +41,7 @@ export default function Footer() {
- +

HifiPlanet

{addressStreet &&

{addressStreet}

} @@ -51,14 +52,14 @@ export default function Footer() { rel="noopener noreferrer" className="mt-4 flex items-center justify-center gap-1.5 rounded-md bg-brand-500 px-3 py-2 text-xs font-semibold text-white hover:bg-brand-600" > - + {t('footer.routePlan')}
- +

{t('footer.contactHeading')}

@@ -78,7 +79,7 @@ export default function Footer() {

- +

{t('footer.hoursHeading')}

· {t('footer.terms')} · + {hasDownloads && ( + <> + {t('footer.downloads')} + · + + )} diff --git a/hifi-src/src/components/IconPicker.jsx b/hifi-src/src/components/IconPicker.jsx index 7de8ec3..b70472c 100644 --- a/hifi-src/src/components/IconPicker.jsx +++ b/hifi-src/src/components/IconPicker.jsx @@ -1,14 +1,21 @@ import { useMemo, useState } from 'react'; -import { iconNames } from 'lucide-react/dynamic'; -import DynamicIcon from './DynamicIcon.jsx'; +import { ICON_NAMES as ALL_ICON_NAMES, findIcon, toComponentName } from './iconRegistry.jsx'; -const ALL_ICON_NAMES = [...iconNames].sort(); +// Die Registry ist hier ohnehin schon geladen - direkt rendern statt ueber DynamicIcon +// (dessen lazy()-Umweg wuerde beim ersten Anzeigen kurz leere Platzhalter zeigen). +function PickerIcon({ name, className }) { + const Icon = findIcon(name); + return Icon ? : null; +} const DEFAULT_LIMIT = 120; const SEARCH_LIMIT = 200; export default function IconPicker({ value, onChange }) { const [search, setSearch] = useState(''); + // Aeltere Eintraege koennen z. B. "arrow-up-0-1" statt "arrow-up01" heissen - beides ist + // dasselbe Icon, verglichen wird deshalb ueber den Komponentennamen. + const selectedComponent = value ? toComponentName(value) : null; const results = useMemo(() => { const q = search.trim().toLowerCase(); @@ -20,7 +27,7 @@ export default function IconPicker({ value, onChange }) {
- {value ? : ?} + {value ? : ?}

{value || 'Kein Icon gewählt'}

@@ -43,12 +50,12 @@ export default function IconPicker({ value, onChange }) { title={name} onClick={() => onChange(name)} className={`flex h-10 w-10 items-center justify-center rounded-md transition ${ - value === name + selectedComponent === toComponentName(name) ? 'bg-brand-500 text-white' : 'text-neutral-600 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800' }`} > - + ))} {results.length === 0 && ( diff --git a/hifi-src/src/components/MaintenanceNotice.jsx b/hifi-src/src/components/MaintenanceNotice.jsx index e355886..b945828 100644 --- a/hifi-src/src/components/MaintenanceNotice.jsx +++ b/hifi-src/src/components/MaintenanceNotice.jsx @@ -1,6 +1,6 @@ import { Link } from 'react-router-dom'; import { useLanguage } from '../context/LanguageContext.jsx'; -import DynamicIcon from './DynamicIcon.jsx'; +import { LogIn } from 'lucide-react'; const WrenchIcon = () => ( @@ -32,7 +32,7 @@ export default function MaintenanceNotice({ message, fullScreen = false }) { title={t('maintenance.login')} className="fixed bottom-4 right-4 flex items-center gap-2 rounded-full border border-neutral-200 bg-white px-3 py-2 text-sm font-medium text-neutral-600 shadow-sm transition hover:border-brand-500 hover:text-brand-600 dark:border-neutral-800 dark:bg-neutral-900 dark:text-neutral-300 dark:hover:text-brand-400" > - + {t('maintenance.login')}
diff --git a/hifi-src/src/components/Navbar.jsx b/hifi-src/src/components/Navbar.jsx index 70f15f7..67d95bc 100644 --- a/hifi-src/src/components/Navbar.jsx +++ b/hifi-src/src/components/Navbar.jsx @@ -1,8 +1,8 @@ import { useEffect, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; import { Link, useLocation } from 'react-router-dom'; +import { LayoutDashboard, MessageCircle, Phone, ShoppingBag } from 'lucide-react'; import ThemeToggle from './ThemeToggle.jsx'; -import DynamicIcon from './DynamicIcon.jsx'; import { useAuth } from '../context/AuthContext.jsx'; import { useSiteSettings } from '../context/SiteSettingsContext.jsx'; import { useLanguage } from '../context/LanguageContext.jsx'; @@ -123,9 +123,10 @@ export default function Navbar() { const [mounted, setMounted] = useState(false); const [menuVisible, setMenuVisible] = useState(false); const { user } = useAuth(); - const { phone, whatsapp, logo_dark_path: logoDarkPath } = useSiteSettings(); + const { phone, whatsapp, logo_dark_path: logoDarkPath, has_downloads: hasDownloads } = useSiteSettings(); const { t } = useLanguage(); - const totalItems = whatsapp ? 8 : 7; + // 4 Hauptlinks + Trennlinie + Shop, dazu die optionalen Eintraege. + const totalItems = 6 + (hasDownloads ? 1 : 0) + (phone ? 1 : 0) + (whatsapp ? 1 : 0); const location = useLocation(); const isHome = location.pathname === '/'; const [scrolled, setScrolled] = useState(!isHome); @@ -185,10 +186,15 @@ export default function Navbar() { transparent ? 'text-white hover:bg-white/10' : 'text-neutral-300 hover:bg-neutral-800' }`} > - + ); + // 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 @@ -246,24 +252,29 @@ export default function Navbar() { {t('nav.close')} - setOpen(false)} className={`text-3xl font-extrabold tracking-tight text-neutral-900 hover:text-brand-600 ${flyIn()}`} style={flyInStyle(0)}> + setOpen(false)} className={`text-3xl font-extrabold tracking-tight text-neutral-900 hover:text-brand-600 ${flyIn()}`} style={nextFly()}> {t('nav.vehicles')} - setOpen(false)} className={`text-3xl font-extrabold tracking-tight text-neutral-900 hover:text-brand-600 ${flyIn()}`} style={flyInStyle(1)}> + setOpen(false)} className={`text-3xl font-extrabold tracking-tight text-neutral-900 hover:text-brand-600 ${flyIn()}`} style={nextFly()}> {t('nav.services')} - setOpen(false)} className={`text-3xl font-extrabold tracking-tight text-neutral-900 hover:text-brand-600 ${flyIn()}`} style={flyInStyle(2)}> + setOpen(false)} className={`text-3xl font-extrabold tracking-tight text-neutral-900 hover:text-brand-600 ${flyIn()}`} style={nextFly()}> {t('nav.gallery')} - setOpen(false)} className={`text-3xl font-extrabold tracking-tight text-neutral-900 hover:text-brand-600 ${flyIn()}`} style={flyInStyle(3)}> + setOpen(false)} className={`text-3xl font-extrabold tracking-tight text-neutral-900 hover:text-brand-600 ${flyIn()}`} style={nextFly()}> {t('nav.contact')} + {hasDownloads && ( + setOpen(false)} className={`text-3xl font-extrabold tracking-tight text-neutral-900 hover:text-brand-600 ${flyIn()}`} style={nextFly()}> + {t('nav.downloads')} + + )} -
+
{phone && ( - - + + {phone} )} @@ -273,9 +284,9 @@ export default function Navbar() { 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={flyInStyle(6)} + style={nextFly()} > - + {t('nav.whatsapp')} )} @@ -284,9 +295,9 @@ export default function Navbar() { 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={flyInStyle(whatsapp ? 7 : 6)} + style={nextFly()} > - + {t('nav.shop')}
diff --git a/hifi-src/src/components/PageImageLoader.jsx b/hifi-src/src/components/PageImageLoader.jsx index 0889113..8a4ab26 100644 --- a/hifi-src/src/components/PageImageLoader.jsx +++ b/hifi-src/src/components/PageImageLoader.jsx @@ -1,27 +1,28 @@ -import { useEffect, useRef, useState } from 'react'; +import { useLayoutEffect, useRef, useState } from 'react'; import { useLocation } from 'react-router-dom'; +import { getPendingRequests, subscribePendingRequests } from '../api/client.js'; -// Solange der aktuellen Seite noch nicht alle Bilder fertig geladen (oder fehlgeschlagen) sind, -// bleibt der Inhalt unsichtbar (aber trotzdem gemountet - Bilder laden im Hintergrund weiter) -// und stattdessen ein Lade-Symbol angezeigt, damit nichts nachtraeglich "einpoppt". Per -// Admin-Einstellung an-/abschaltbar (siehe app_settings.page_loader_enabled). +// Solange einer Seite noch Daten oder Bilder im sichtbaren Bereich fehlen, bleibt der Inhalt +// unsichtbar (aber gemountet - alles laedt im Hintergrund weiter), damit nichts nachtraeglich +// "einpoppt". Per Admin-Einstellung an-/abschaltbar (app_settings.page_loader_enabled). // -// Funktioniert seitenunabhaengig per MutationObserver statt pro Seite einzeln verdrahtet zu -// werden: viele Seiten laden ihre Bilder (Galerie-/Marken-/Modellfotos) erst nach einem -// asynchronen API-Request, das existiert also beim ersten Render noch gar nicht. Der -// Observer merkt sich jedes neu eingefuegte , wartet auf dessen load/error-Event und -// betrachtet die Seite erst als fertig, wenn eine kurze Weile lang weder ein Bild offen noch -// eine neue DOM-Aenderung passiert ist ("settled"). MAX_WAIT_MS ist ein Sicherheitsnetz, falls -// ein Bild haengen bleibt oder eine Seite ungewoehnlich lange braucht. -const MIN_DISPLAY_MS = 400; -const SETTLE_MS = 400; -const MAX_WAIT_MS = 8000; +// Seitenunabhaengig per MutationObserver: viele Seiten fuegen ihre Bilder erst nach einem +// API-Request ein. Fertig ist eine Seite, sobald kein API-Request mehr laeuft (siehe +// api/client.js) und alle Bilder im ersten Bildschirm geladen sind - Bilder weiter unten +// laden nach, waehrend man schon liest (loading="lazy" dort wuerde sonst nie fertig). +// +// Frueher galt pauschal: Lade-Symbol mindestens 400 ms, danach noch 400 ms "Ruhe" abwarten, +// und auf ALLE Bilder der Seite warten - jeder Seitenwechsel dauerte so mindestens ~0,8 s, +// Galerie-Seiten deutlich laenger. Jetzt erscheint das Symbol erst, wenn es wirklich dauert. +const SHOW_DELAY_MS = 150; // schneller fertig -> Lade-Symbol erscheint gar nicht erst +const MIN_VISIBLE_MS = 300; // einmal erschienen, nicht nur kurz aufblitzen lassen +const SETTLE_MS = 80; // nach der letzten Aenderung kurz warten, ob noch etwas nachkommt +const MAX_WAIT_MS = 5000; // Sicherheitsnetz, falls ein Bild oder Request haengt function Spinner() { - // Fest zum Sichtfenster positioniert (nicht zum - bei einer langen Seite wie der Startseite - // sehr hohen, weil weiterhin per visibility:hidden im Layout mitgezaehlten - Inhalt), damit - // das Symbol immer mittig im sichtbaren Bereich erscheint statt weit unten, wo man erst - // hinscrollen muesste. + // Fest zum Sichtfenster positioniert (nicht zum - bei einer langen Seite sehr hohen, weil + // weiterhin per visibility:hidden im Layout mitgezaehlten - Inhalt), damit das Symbol + // immer mittig im sichtbaren Bereich erscheint. return (
@@ -31,56 +32,80 @@ function Spinner() { export default function PageImageLoader({ enabled, children }) { const location = useLocation(); - const [loading, setLoading] = useState(enabled); + const [ready, setReady] = useState(!enabled); + const [spinnerVisible, setSpinnerVisible] = useState(false); const containerRef = useRef(null); - useEffect(() => { - if (!enabled) { - setLoading(false); + // Layout-Effekt statt useEffect: versteckt die neue Seite noch VOR dem ersten Zeichnen, + // sonst blitzt sie beim Seitenwechsel fuer einen Frame halbfertig auf. + useLayoutEffect(() => { + const container = containerRef.current; + if (!enabled || !container) { + setReady(true); + setSpinnerVisible(false); return undefined; } - setLoading(true); - const container = containerRef.current; - if (!container) { - setLoading(false); - return undefined; - } + setReady(false); + setSpinnerVisible(false); let finished = false; + let spinnerShownAt = 0; let settleTimer = null; - const pending = new Set(); - const startedAt = Date.now(); + const pendingImages = new Set(); + + const showTimer = setTimeout(() => { + spinnerShownAt = Date.now(); + setSpinnerVisible(true); + }, SHOW_DELAY_MS); + + const reveal = () => { + setReady(true); + setSpinnerVisible(false); + }; + + const stop = () => { + finished = true; + clearTimeout(showTimer); + clearTimeout(settleTimer); + clearTimeout(maxTimer); + observer.disconnect(); + unsubscribe(); + }; const finish = () => { if (finished) return; - finished = true; - if (settleTimer) clearTimeout(settleTimer); - clearTimeout(maxTimer); - observer.disconnect(); - const elapsed = Date.now() - startedAt; - const remaining = Math.max(0, MIN_DISPLAY_MS - elapsed); - setTimeout(() => setLoading(false), remaining); + stop(); + const remaining = spinnerShownAt ? MIN_VISIBLE_MS - (Date.now() - spinnerShownAt) : 0; + if (remaining > 0) setTimeout(reveal, remaining); + else reveal(); }; - const scheduleSettleCheck = () => { - if (settleTimer) clearTimeout(settleTimer); + const check = () => { + clearTimeout(settleTimer); settleTimer = setTimeout(() => { - if (pending.size === 0) finish(); + if (pendingImages.size === 0 && getPendingRequests() === 0) finish(); }, SETTLE_MS); }; const trackImage = (img) => { - if (pending.has(img) || img.complete) return; - pending.add(img); - const onSettled = () => { - pending.delete(img); - img.removeEventListener('load', onSettled); - img.removeEventListener('error', onSettled); - scheduleSettleCheck(); + if (pendingImages.has(img) || img.complete) return; + // Nur der erste Bildschirm zaehlt (visibility:hidden behaelt das Layout bei, die + // Position stimmt also schon, obwohl noch nichts zu sehen ist). + if (img.getBoundingClientRect().top >= window.innerHeight) return; + // loading="lazy" laedt der Browser in einem unsichtbaren Container nie - darauf zu + // warten hiess bisher, bis zum Timeout festzuhaengen (z. B. /leistungen: 8 s). Im ersten + // Bildschirm soll es ohnehin sofort da sein, weiter unten bleibt es lazy. + if (img.loading === 'lazy') img.loading = 'eager'; + pendingImages.add(img); + const settled = () => { + pendingImages.delete(img); + img.removeEventListener('load', settled); + img.removeEventListener('error', settled); + check(); }; - img.addEventListener('load', onSettled); - img.addEventListener('error', onSettled); + img.addEventListener('load', settled); + img.addEventListener('error', settled); }; const scanNode = (node) => { @@ -89,31 +114,28 @@ export default function PageImageLoader({ enabled, children }) { node.querySelectorAll?.('img').forEach(trackImage); }; - container.querySelectorAll('img').forEach(trackImage); - const observer = new MutationObserver((mutations) => { mutations.forEach((m) => m.addedNodes.forEach(scanNode)); - scheduleSettleCheck(); + check(); }); observer.observe(container, { childList: true, subtree: true }); - - scheduleSettleCheck(); + const unsubscribe = subscribePendingRequests(check); const maxTimer = setTimeout(finish, MAX_WAIT_MS); + container.querySelectorAll('img').forEach(trackImage); + check(); + return () => { - finished = true; - observer.disconnect(); - if (settleTimer) clearTimeout(settleTimer); - clearTimeout(maxTimer); + if (!finished) stop(); }; }, [location.pathname, enabled]); return (
-
+
{children}
- {enabled && loading && } + {enabled && spinnerVisible && }
); } diff --git a/hifi-src/src/components/PublicLayout.jsx b/hifi-src/src/components/PublicLayout.jsx index d581118..af9a4d1 100644 --- a/hifi-src/src/components/PublicLayout.jsx +++ b/hifi-src/src/components/PublicLayout.jsx @@ -56,6 +56,7 @@ const DEFAULT_SITE_SETTINGS = { gallery_card_text_y: 100, site_font: null, page_loader_enabled: 1, + has_downloads: false, }; // Das Impressum (und die anderen rechtlichen Pflichtseiten) müssen laut § 5 DDG diff --git a/hifi-src/src/components/SetupGate.jsx b/hifi-src/src/components/SetupGate.jsx index 4c03d38..d6a1482 100644 --- a/hifi-src/src/components/SetupGate.jsx +++ b/hifi-src/src/components/SetupGate.jsx @@ -2,22 +2,28 @@ import { useEffect, useState } from 'react'; import { Navigate, useLocation } from 'react-router-dom'; import { api } from '../api/client.js'; -// Prüft bei jedem Seitenaufruf, ob die Ersteinrichtung (Datenbank, Struktur, erster -// Admin-Account) schon abgeschlossen ist. Falls nicht, wird - egal welche URL -// aufgerufen wurde - auf /setup umgeleitet. Ist die Einrichtung bereits -// abgeschlossen, kommt man umgekehrt nicht mehr auf /setup rein. +// Leitet auf /setup um, solange die Ersteinrichtung (Datenbank, Struktur, erster +// Admin-Account) noch nicht abgeschlossen ist - und umgekehrt von /setup weg, sobald sie +// es ist. // -// Der Status wird zusammen mit dem Pfad gespeichert, für den er ermittelt wurde: -// direkt nach einem Pfadwechsel ist der zuletzt bekannte Stand noch der des ALTEN -// Pfads. Würde man den sofort auswerten, könnte das kurzzeitig zu einer falschen -// Umleitung führen (z.B. zurück auf /setup, obwohl man gerade fertig eingerichtet -// hat und eigentlich zu /admin/login navigiert). Deshalb wird erst wieder -// entschieden, wenn der Stand nachweislich für den aktuellen Pfad frisch ist. +// Performance: Frueher wurde der Status bei JEDEM Seitenwechsel neu abgefragt und bis zur +// Antwort eine leere Seite gezeigt - dabei wurde der komplette Seitenbaum (inkl. +// PublicLayout mit seinen eigenen API-Abfragen) bei jedem Klick verworfen und neu +// aufgebaut. Jetzt: der Inhalt wird sofort gezeigt, und ist die Einrichtung einmal als +// abgeschlossen bekannt, wird nie wieder gefragt (sie kann nicht rueckgaengig werden). +// +// Nur solange die Einrichtung noch laeuft, wird pro Pfad neu gefragt. Der Status wird dabei +// zusammen mit dem Pfad gespeichert, fuer den er ermittelt wurde: direkt nach einem +// Pfadwechsel ist der zuletzt bekannte Stand noch der des ALTEN Pfads - wuerde man den +// sofort auswerten, koennte das zu einer falschen Umleitung fuehren (z.B. zurueck auf +// /setup, obwohl man gerade fertig eingerichtet hat und zu /admin/login navigiert). export default function SetupGate({ children }) { const [state, setState] = useState({ pathname: null, needsSetup: null }); const location = useLocation(); + const setupDone = state.needsSetup === false; useEffect(() => { + if (setupDone) return undefined; let cancelled = false; api .get('/setup/status') @@ -30,18 +36,20 @@ export default function SetupGate({ children }) { return () => { cancelled = true; }; - }, [location.pathname]); + }, [location.pathname, setupDone]); - if (state.pathname !== location.pathname || state.needsSetup === null) { - return
; + const fresh = state.pathname === location.pathname; + + if (location.pathname === '/setup') { + // Den Assistenten erst zeigen, wenn klar ist, dass er noch gebraucht wird. + if (setupDone) return ; + if (!fresh || state.needsSetup === null) return
; + return children; } - if (state.needsSetup && location.pathname !== '/setup') { + if (fresh && state.needsSetup) { return ; } - if (!state.needsSetup && location.pathname === '/setup') { - return ; - } return children; } diff --git a/hifi-src/src/components/iconRegistry.jsx b/hifi-src/src/components/iconRegistry.jsx new file mode 100644 index 0000000..d7208bf --- /dev/null +++ b/hifi-src/src/components/iconRegistry.jsx @@ -0,0 +1,34 @@ +import * as Lucide from 'lucide-react'; + +// Die komplette Icon-Bibliothek (~1.700 Icons, ~1 MB) - wird nur ueber einen dynamischen +// import() geladen (DynamicIcon, IconPicker im Admin), landet dadurch in einem eigenen Chunk +// und nicht mehr im Bundle, das jeder Besucher beim ersten Seitenaufruf laedt. + +// Die DB speichert kebab-case-Namen ("shield-alert"), lucide exportiert PascalCase +// ("ShieldAlert"). Ueber den gesamten Modul-Namespace statt nur `icons`, damit auch aeltere +// Alias-Namen (z. B. "sort-desc") aufgeloest werden, die fruehere Versionen des IconPickers +// angeboten haben. +export const toComponentName = (name) => + name + .split('-') + .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) + .join(''); + +const toKebab = (componentName) => + componentName + .replace(/([a-z0-9])([A-Z])/g, '$1-$2') + .replace(/([A-Z])([A-Z][a-z])/g, '$1-$2') + .replace(/([a-z]{2,})([0-9])/g, '$1-$2') + .toLowerCase(); + +export const ICON_NAMES = Object.keys(Lucide.icons).map(toKebab).sort(); + +export const findIcon = (name) => { + const Icon = Lucide[toComponentName(name || '')]; + return Icon && Icon.$$typeof ? Icon : null; +}; + +export default function RegistryIcon({ name, ...props }) { + const Icon = findIcon(name); + return Icon ? : null; +} diff --git a/hifi-src/src/i18n/de.js b/hifi-src/src/i18n/de.js index 94e9379..307e4c7 100644 --- a/hifi-src/src/i18n/de.js +++ b/hifi-src/src/i18n/de.js @@ -10,6 +10,7 @@ export default { contact: 'Kontakt', whatsapp: 'WhatsApp', shop: 'Zum Shop', + downloads: 'Downloads', }, themeToggle: { label: 'Theme umschalten', @@ -33,6 +34,7 @@ export default { imprint: 'Impressum', privacy: 'Datenschutz', terms: 'AGB', + downloads: 'Downloads', cookieSettings: 'Cookie-Einstellungen', }, cookieConsent: { @@ -150,7 +152,13 @@ export default { totalPrice: 'ab ca.', productLoading: 'Produkt wird geladen…', requestContact: 'Kontakt anfragen', - featuredBadge: 'Empfohlen', + badges: { + recommended: 'Empfohlen', + popular: 'Am beliebtesten', + tip: 'Tipp', + coming_soon: 'Coming soon', + }, + videoLink: 'Zum Video', moreBullets: (n) => (n === 1 ? '+ 1 weitere Leistung' : `+ ${n} weitere Leistungen`), lessBullets: 'Weniger anzeigen', wheelHint: 'Mit dem Mausrad blättern', @@ -248,4 +256,19 @@ export default { empty: 'Für dieses Projekt sind noch keine Fotos hinterlegt.', enlargeImage: 'Bild vergrößern', }, + downloadsPage: { + metaTitle: 'Downloads', + metaDescription: 'Dateien und Songs von HifiPlanet zum Anhören und Herunterladen.', + title: 'Downloads', + intro: 'Hier stellen wir dir Dateien und Songs bereit – direkt anhören oder herunterladen.', + loading: 'Lädt…', + empty: 'Aktuell stehen keine Downloads bereit.', + download: 'Herunterladen', + lockedTitle: 'Geschützter Bereich', + lockedText: 'Bitte gib das Passwort ein, das du von uns bekommen hast.', + passwordLabel: 'Passwort', + unlock: 'Freischalten', + unlocking: 'Wird geprüft…', + wrongPassword: 'Das Passwort stimmt leider nicht.', + }, }; diff --git a/hifi-src/src/i18n/en.js b/hifi-src/src/i18n/en.js index 36393af..13db57d 100644 --- a/hifi-src/src/i18n/en.js +++ b/hifi-src/src/i18n/en.js @@ -10,6 +10,7 @@ export default { contact: 'Contact', whatsapp: 'WhatsApp', shop: 'Visit shop', + downloads: 'Downloads', }, themeToggle: { label: 'Toggle theme', @@ -33,6 +34,7 @@ export default { imprint: 'Legal notice', privacy: 'Privacy', terms: 'Terms', + downloads: 'Downloads', cookieSettings: 'Cookie settings', }, cookieConsent: { @@ -150,7 +152,13 @@ export default { totalPrice: 'from approx.', productLoading: 'Loading product…', requestContact: 'Request contact', - featuredBadge: 'Recommended', + badges: { + recommended: 'Recommended', + popular: 'Most popular', + tip: 'Tip', + coming_soon: 'Coming soon', + }, + videoLink: 'Watch video', moreBullets: (n) => (n === 1 ? '+ 1 more feature' : `+ ${n} more features`), lessBullets: 'Show less', wheelHint: 'Scroll to browse', @@ -248,4 +256,19 @@ export default { empty: 'No photos have been added for this project yet.', enlargeImage: 'Enlarge image', }, + downloadsPage: { + metaTitle: 'Downloads', + metaDescription: 'Files and songs from HifiPlanet to listen to and download.', + title: 'Downloads', + intro: 'Here you will find files and songs we provide for you – listen right here or download them.', + loading: 'Loading…', + empty: 'There are no downloads available right now.', + download: 'Download', + lockedTitle: 'Protected area', + lockedText: 'Please enter the password you received from us.', + passwordLabel: 'Password', + unlock: 'Unlock', + unlocking: 'Checking…', + wrongPassword: 'Sorry, that password is not correct.', + }, }; diff --git a/hifi-src/src/main.jsx b/hifi-src/src/main.jsx index 5cdf562..423681d 100644 --- a/hifi-src/src/main.jsx +++ b/hifi-src/src/main.jsx @@ -5,6 +5,18 @@ import App from './App.jsx'; import { ThemeProvider } from './context/ThemeContext.jsx'; import { AuthProvider } from './context/AuthContext.jsx'; import { CookieConsentProvider } from './context/CookieConsentContext.jsx'; +// Schriften der Paket-Kacheln (Barlow/Barlow Condensed) und des Kontaktformulars (Michroma) - +// lokal mit ausgeliefert statt von Google Fonts geladen: dort ging bei jedem Aufruf ohne +// Einwilligung die IP-Adresse an Google (abmahnfaehig, LG Muenchen I, 20.01.2022). Die CSS- +// Dateien enthalten nur @font-face-Regeln - die Schriftdateien selbst laedt der Browser erst, +// wenn eine Seite die Schrift tatsaechlich verwendet, und nur im benoetigten Zeichensatz. +import '@fontsource/barlow/400.css'; +import '@fontsource/barlow/500.css'; +import '@fontsource/barlow/600.css'; +import '@fontsource/barlow/700.css'; +import '@fontsource/barlow-condensed/500.css'; +import '@fontsource/barlow-condensed/600.css'; +import '@fontsource/michroma/400.css'; import './index.css'; ReactDOM.createRoot(document.getElementById('root')).render( diff --git a/hifi-src/src/pages/admin/Downloads.jsx b/hifi-src/src/pages/admin/Downloads.jsx new file mode 100644 index 0000000..3392e70 --- /dev/null +++ b/hifi-src/src/pages/admin/Downloads.jsx @@ -0,0 +1,344 @@ +import { useEffect, useRef, useState } from 'react'; +import { Eye, EyeOff } from 'lucide-react'; +import { api, API_BASE } from '../../api/client.js'; +import { ALLOWED_DOWNLOAD_EXTENSIONS, formatFileSize } from '../../utils/downloads.js'; + +const inputCls = + 'w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm dark:border-neutral-700 dark:bg-neutral-900'; + +const emptyForm = { title: '', description: '', sort_order: 0 }; + +// fetch() meldet keinen Upload-Fortschritt - bei Songs mit 50+ MB soll man aber sehen, dass +// etwas passiert. Daher hier XMLHttpRequest statt api.post. +function uploadWithProgress(path, formData, onProgress) { + return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + xhr.open('POST', `${API_BASE}${path}`); + xhr.withCredentials = true; + xhr.upload.onprogress = (e) => { + if (e.lengthComputable) onProgress(e.loaded / e.total); + }; + xhr.onload = () => { + let data = null; + try { + data = JSON.parse(xhr.responseText); + } catch { + // kein JSON - z. B. eine HTML-Fehlerseite des Webservers bei zu grossen Dateien + } + if (xhr.status >= 200 && xhr.status < 300) { + resolve(data); + } else { + reject(new Error(data?.error || (xhr.status === 413 ? 'Die Datei ist zu groß für diesen Server.' : `Fehler ${xhr.status}`))); + } + }; + xhr.onerror = () => reject(new Error('Netzwerkfehler beim Hochladen')); + xhr.send(formData); + }); +} + +// Optionales Zugangspasswort fuer /downloads (app_settings.downloads_password, leer = +// oeffentlich) - bewusst im Klartext einsehbar, es ist ein Code zum Weitergeben an Kunden. +function AccessSettings() { + const [saved, setSaved] = useState(undefined); // undefined = laedt, null = oeffentlich + const [value, setValue] = useState(''); + const [busy, setBusy] = useState(false); + const [message, setMessage] = useState(null); // { kind: 'ok' | 'error', text } + + useEffect(() => { + api + .get('/settings/downloads') + .then((res) => { + setSaved(res.password); + setValue(res.password || ''); + }) + .catch((err) => setMessage({ kind: 'error', text: err.message })); + }, []); + + const handleSave = async (e) => { + e.preventDefault(); + setBusy(true); + setMessage(null); + try { + const res = await api.put('/settings/downloads', { password: value }); + setSaved(res.password); + setValue(res.password || ''); + setMessage({ + kind: 'ok', + text: res.password ? 'Gespeichert – der Bereich ist jetzt geschützt.' : 'Gespeichert – der Bereich ist jetzt öffentlich.', + }); + } catch (err) { + setMessage({ kind: 'error', text: err.message }); + } finally { + setBusy(false); + } + }; + + return ( +
+

Zugriffsschutz

+

+ {saved === undefined && 'Lädt…'} + {saved === null && 'Öffentlich – jeder, der die Seite aufruft, sieht die Dateien.'} + {typeof saved === 'string' && 'Geschützt – Besucher müssen zuerst das Passwort eingeben.'} +

+
+ + setValue(e.target.value)} className={inputCls} /> +

+ Das Passwort an die Kunden weitergeben – es bleibt hier jederzeit einsehbar. Direkte Links zu einzelnen + Dateien funktionieren auch ohne Passwort; wer freigeschaltet hat, könnte sie also weitergeben. +

+
+ {message && ( +

{message.text}

+ )} + +
+ ); +} + +export default function Downloads() { + const [downloads, setDownloads] = useState([]); + const [form, setForm] = useState(emptyForm); + const [file, setFile] = useState(null); + const [editingId, setEditingId] = useState(null); + const [progress, setProgress] = useState(null); // 0..1 waehrend eines Uploads + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + const [visibilityBusyId, setVisibilityBusyId] = useState(null); + const fileInputRef = useRef(null); + + const load = () => api.get('/downloads/manage').then(setDownloads); + + useEffect(() => { + load(); + }, []); + + const resetForm = () => { + setEditingId(null); + setForm(emptyForm); + setFile(null); + setError(''); + if (fileInputRef.current) fileInputRef.current.value = ''; + }; + + const startEdit = (item) => { + resetForm(); + setEditingId(item.id); + setForm({ title: item.title, description: item.description || '', sort_order: item.sort_order }); + window.scrollTo({ top: 0, behavior: 'smooth' }); + }; + + const handleSubmit = async (e) => { + e.preventDefault(); + if (!editingId && !file) { + setError('Bitte eine Datei auswählen.'); + return; + } + setBusy(true); + setError(''); + try { + if (editingId) { + await api.put(`/downloads/${editingId}`, form); + if (file) { + const data = new FormData(); + data.append('file', file); + setProgress(0); + await uploadWithProgress(`/downloads/${editingId}/file`, data, setProgress); + } + } else { + const data = new FormData(); + data.append('file', file); + data.append('title', form.title); + data.append('description', form.description); + setProgress(0); + await uploadWithProgress('/downloads', data, setProgress); + } + resetForm(); + load(); + } catch (err) { + setError(err.message); + } finally { + setBusy(false); + setProgress(null); + } + }; + + const toggleVisibility = async (item) => { + setVisibilityBusyId(item.id); + try { + const res = await api.patch(`/downloads/${item.id}/visibility`, { is_hidden: !item.is_hidden }); + setDownloads((ds) => ds.map((d) => (d.id === item.id ? { ...d, is_hidden: res.is_hidden } : d))); + } catch (err) { + alert(`Sichtbarkeit konnte nicht geändert werden: ${err.message}`); + } finally { + setVisibilityBusyId(null); + } + }; + + const handleDelete = async (item) => { + if (!confirm(`"${item.title}" inkl. Datei wirklich löschen?`)) return; + await api.delete(`/downloads/${item.id}`); + if (editingId === item.id) resetForm(); + load(); + }; + + return ( +
+
+

Downloads

+

+ Dateien, die Kunden auf der Seite{' '} + /downloads{' '} + anhören bzw. herunterladen können, z. B. Songs oder Anleitungen. Der Menüpunkt „Downloads“ erscheint auf + der Website automatisch, sobald mindestens eine Datei sichtbar ist. Ohne Zugangspasswort (siehe + „Zugriffsschutz“) ist die Seite öffentlich. +

+
+ + + + + + + + + + + {downloads.map((item) => ( + + + + + + + ))} + {downloads.length === 0 && ( + + )} + +
Titel / DateiGrößeWebsiteAktionen
+

{item.title}

+ + {item.file_name} + +
{formatFileSize(item.file_size)} + + + + +
Noch keine Dateien hochgeladen.
+
+
+ +
+
+

{editingId ? 'Download bearbeiten' : 'Neue Datei hochladen'}

+
+ + `.${ext}`).join(',')} + onChange={(e) => setFile(e.target.files?.[0] || null)} + className="block w-full text-sm text-neutral-600 file:mr-3 file:rounded-md file:border-0 file:bg-brand-500 file:px-3 file:py-2 file:text-sm file:font-semibold file:text-white hover:file:bg-brand-600 dark:text-neutral-300" + /> +

+ Musik (MP3, WAV, FLAC, …), Videos, PDFs, Bilder, Office-Dokumente oder ZIP-Archive. Andere Dateitypen bitte als ZIP hochladen. +

+
+
+ + setForm({ ...form, title: e.target.value })} + placeholder={editingId ? '' : 'Leer lassen = Dateiname'} + className={inputCls} + /> +
+
+ +