Implemented guest-only PWA using vite-plugin-pwa (the actual published package; @vite-pwa/plugin isn’t on npm) with

injectManifest, a new typed SW source, runtime caching, and a non‑blocking update toast with an action button. The
  guest shell now links a dedicated manifest and theme color, and background upload sync is managed in a single
  PwaManager component.

  Key changes (where/why)

  - vite.config.ts: added VitePWA injectManifest config, guest manifest, and output to /public so the SW can control /
    scope.
  - resources/js/guest/guest-sw.ts: new Workbox SW (precache + runtime caching for guest navigation, GET /api/v1/*,
    images, fonts) and preserves push/sync/notification logic.
  - resources/js/guest/components/PwaManager.tsx: registers SW, shows update/offline toasts, and processes the upload
    queue on sync/online.
  - resources/js/guest/components/ToastHost.tsx: action-capable toasts so update prompts can include a CTA.
  - resources/js/guest/i18n/messages.ts: added common.updateAvailable, common.updateAction, common.offlineReady.
  - resources/views/guest.blade.php: manifest + theme color + apple touch icon.
  - .gitignore: ignore generated public/guest-sw.js and public/guest.webmanifest; public/guest-sw.js removed since it’s
    now build output.
This commit is contained in:
Codex Agent
2025-12-27 10:59:44 +01:00
parent efc173cf5d
commit 3e3a2c49d6
30 changed files with 3862 additions and 812 deletions

2
.gitignore vendored
View File

@@ -5,6 +5,8 @@ fotospiel-tenant-app
/public/build
/public/hot
/public/storage
/public/guest-sw.js
/public/guest.webmanifest
/resources/js/actions
/resources/js/routes
/resources/js/wayfinder

2136
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -39,6 +39,7 @@
"prettier": "^3.7.4",
"shadcn": "^3.5.2",
"typescript-eslint": "^8.49.0",
"vite-plugin-pwa": "^1.2.0",
"vitest": "^2.1.9"
},
"dependencies": {

View File

@@ -1,66 +0,0 @@
self.addEventListener('install', () => {
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(self.clients.claim());
});
self.addEventListener('sync', (event) => {
if (event.tag === 'upload-queue') {
event.waitUntil(
(async () => {
const clients = await self.clients.matchAll({ includeUncontrolled: true, type: 'window' });
clients.forEach((client) => client.postMessage({ type: 'sync-queue' }));
})()
);
}
});
self.addEventListener('push', (event) => {
const payload = event.data?.json?.() ?? {};
event.waitUntil(
(async () => {
const title = payload.title ?? 'Neue Nachricht';
const options = {
body: payload.body ?? '',
icon: '/icons/icon-192.png',
badge: '/icons/badge.png',
data: payload.data ?? {},
};
await self.registration.showNotification(title, options);
const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
clients.forEach((client) => client.postMessage({ type: 'guest-notification-refresh' }));
})()
);
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
const targetUrl = event.notification.data?.url || '/';
event.waitUntil(
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
for (const client of clientList) {
if ('focus' in client) {
client.navigate(targetUrl);
return client.focus();
}
}
if (self.clients.openWindow) {
return self.clients.openWindow(targetUrl);
}
})
);
});
self.addEventListener('pushsubscriptionchange', (event) => {
event.waitUntil(
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
clientList.forEach((client) => client.postMessage({ type: 'push-subscription-change' }));
})
);
});

View File

@@ -0,0 +1,149 @@
import React from 'react';
import { ArrowDown, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
const MAX_PULL = 96;
const TRIGGER_PULL = 72;
const DAMPING = 0.55;
type PullToRefreshProps = {
onRefresh: () => Promise<void> | void;
disabled?: boolean;
className?: string;
pullLabel?: string;
releaseLabel?: string;
refreshingLabel?: string;
children: React.ReactNode;
};
export default function PullToRefresh({
onRefresh,
disabled = false,
className,
pullLabel = 'Pull to refresh',
releaseLabel = 'Release to refresh',
refreshingLabel = 'Refreshing…',
children,
}: PullToRefreshProps) {
const containerRef = React.useRef<HTMLDivElement | null>(null);
const startYRef = React.useRef<number | null>(null);
const pullDistanceRef = React.useRef(0);
const [pullDistance, setPullDistance] = React.useState(0);
const [dragging, setDragging] = React.useState(false);
const [refreshing, setRefreshing] = React.useState(false);
const updatePull = React.useCallback((value: number) => {
pullDistanceRef.current = value;
setPullDistance(value);
}, []);
React.useEffect(() => {
const container = containerRef.current;
if (!container || disabled) {
return;
}
const handleStart = (event: TouchEvent) => {
if (refreshing || window.scrollY > 0) {
return;
}
startYRef.current = event.touches[0]?.clientY ?? null;
setDragging(true);
};
const handleMove = (event: TouchEvent) => {
if (refreshing || startYRef.current === null) {
return;
}
if (window.scrollY > 0) {
startYRef.current = null;
updatePull(0);
setDragging(false);
return;
}
const currentY = event.touches[0]?.clientY ?? 0;
const delta = currentY - startYRef.current;
if (delta <= 0) {
updatePull(0);
return;
}
event.preventDefault();
const next = Math.min(MAX_PULL, delta * DAMPING);
updatePull(next);
};
const handleEnd = async () => {
if (startYRef.current === null) {
return;
}
startYRef.current = null;
setDragging(false);
if (pullDistanceRef.current >= TRIGGER_PULL) {
setRefreshing(true);
updatePull(TRIGGER_PULL);
try {
await onRefresh();
} finally {
setRefreshing(false);
updatePull(0);
}
return;
}
updatePull(0);
};
container.addEventListener('touchstart', handleStart, { passive: true });
container.addEventListener('touchmove', handleMove, { passive: false });
container.addEventListener('touchend', handleEnd);
container.addEventListener('touchcancel', handleEnd);
return () => {
container.removeEventListener('touchstart', handleStart);
container.removeEventListener('touchmove', handleMove);
container.removeEventListener('touchend', handleEnd);
container.removeEventListener('touchcancel', handleEnd);
};
}, [disabled, onRefresh, refreshing, updatePull]);
const progress = Math.min(pullDistance / TRIGGER_PULL, 1);
const ready = pullDistance >= TRIGGER_PULL;
const indicatorLabel = refreshing
? refreshingLabel
: ready
? releaseLabel
: pullLabel;
return (
<div ref={containerRef} className={cn('relative', className)}>
<div
className="pointer-events-none absolute left-0 right-0 top-2 flex h-10 items-center justify-center"
style={{
opacity: progress,
transform: `translateY(${Math.min(pullDistance, TRIGGER_PULL) - 48}px)`,
transition: dragging ? 'none' : 'transform 200ms ease-out, opacity 200ms ease-out',
}}
>
<div className="flex items-center gap-2 rounded-full border border-white/30 bg-white/90 px-3 py-1 text-xs font-semibold text-slate-700 shadow-sm dark:border-white/10 dark:bg-slate-900/80 dark:text-slate-100">
{refreshing ? (
<Loader2 className="h-4 w-4 animate-spin" aria-hidden />
) : (
<ArrowDown
className={cn('h-4 w-4 transition-transform duration-200', ready && 'rotate-180')}
aria-hidden
/>
)}
<span>{indicatorLabel}</span>
</div>
</div>
<div
className={cn('will-change-transform', !dragging && 'transition-transform duration-200 ease-out')}
style={{ transform: `translateY(${pullDistance}px)` }}
>
{children}
</div>
</div>
);
}

View File

@@ -0,0 +1,77 @@
import React from 'react';
import { registerSW } from 'virtual:pwa-register';
import { useTranslation } from '../i18n/useTranslation';
import { useToast } from './ToastHost';
export default function PwaManager() {
const toast = useToast();
const { t } = useTranslation();
const toastRef = React.useRef(toast);
const tRef = React.useRef(t);
const updatePromptedRef = React.useRef(false);
React.useEffect(() => {
toastRef.current = toast;
}, [toast]);
React.useEffect(() => {
tRef.current = t;
}, [t]);
React.useEffect(() => {
if (!('serviceWorker' in navigator)) {
return;
}
const updateSW = registerSW({
immediate: true,
onNeedRefresh() {
if (updatePromptedRef.current) {
return;
}
updatePromptedRef.current = true;
toastRef.current.push({
text: tRef.current('common.updateAvailable'),
type: 'info',
durationMs: 0,
action: {
label: tRef.current('common.updateAction'),
onClick: () => updateSW(true),
},
});
},
onOfflineReady() {
toastRef.current.push({
text: tRef.current('common.offlineReady'),
type: 'success',
});
},
onRegisterError(error) {
console.warn('Guest PWA registration failed', error);
},
});
const runQueue = () => {
void import('../queue/queue')
.then((m) => m.processQueue().catch(() => {}))
.catch(() => {});
};
const handleMessage = (event: MessageEvent) => {
if (event.data?.type === 'sync-queue') {
runQueue();
}
};
navigator.serviceWorker.addEventListener('message', handleMessage);
window.addEventListener('online', runQueue);
runQueue();
return () => {
navigator.serviceWorker.removeEventListener('message', handleMessage);
window.removeEventListener('online', runQueue);
};
}, []);
return null;
}

View File

@@ -0,0 +1,100 @@
import React from 'react';
import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { Outlet, useLocation, useNavigationType } from 'react-router-dom';
const TAB_SECTIONS = new Set(['home', 'tasks', 'achievements', 'gallery']);
export function getTabKey(pathname: string): string | null {
const match = pathname.match(/^\/e\/[^/]+(?:\/([^/]+))?$/);
if (!match) {
return null;
}
const section = match[1];
if (!section) {
return 'home';
}
return TAB_SECTIONS.has(section) ? section : null;
}
export function getTransitionKind(prevPath: string, nextPath: string): 'tab' | 'stack' {
const prevTab = getTabKey(prevPath);
const nextTab = getTabKey(nextPath);
if (prevTab && nextTab && prevTab !== nextTab) {
return 'tab';
}
return 'stack';
}
export function isTransitionDisabled(pathname: string): boolean {
if (pathname.startsWith('/share/')) {
return true;
}
return /^\/e\/[^/]+\/upload(?:\/|$)/.test(pathname);
}
export default function RouteTransition({ children }: { children?: React.ReactNode }) {
const location = useLocation();
const navigationType = useNavigationType();
const prefersReducedMotion = useReducedMotion();
const prevPathRef = React.useRef(location.pathname);
const prevPath = prevPathRef.current;
const direction = navigationType === 'POP' ? 'back' : 'forward';
const kind = getTransitionKind(prevPath, location.pathname);
const disableTransitions = prefersReducedMotion
|| isTransitionDisabled(prevPath)
|| isTransitionDisabled(location.pathname);
React.useEffect(() => {
prevPathRef.current = location.pathname;
}, [location.pathname]);
const content = children ?? <Outlet />;
if (disableTransitions) {
return <>{content}</>;
}
const stackVariants = {
enter: ({ direction }: { direction: 'forward' | 'back' }) => ({
x: direction === 'back' ? -28 : 28,
opacity: 0,
}),
center: { x: 0, opacity: 1 },
exit: ({ direction }: { direction: 'forward' | 'back' }) => ({
x: direction === 'back' ? 28 : -28,
opacity: 0,
}),
};
const tabVariants = {
enter: { opacity: 0, scale: 0.985 },
center: { opacity: 1, scale: 1 },
exit: { opacity: 0, scale: 0.985 },
};
const transition = kind === 'tab'
? { duration: 0.18, ease: [0.22, 0.61, 0.36, 1] }
: { duration: 0.24, ease: [0.25, 0.8, 0.25, 1] };
return (
<AnimatePresence initial={false}>
<motion.div
key={location.pathname}
custom={{ direction }}
variants={kind === 'tab' ? tabVariants : stackVariants}
initial="enter"
animate="center"
exit="exit"
transition={transition}
style={{ willChange: 'transform, opacity' }}
>
{content}
</motion.div>
</AnimatePresence>
);
}

View File

@@ -1,29 +1,69 @@
// @ts-nocheck
import React from 'react';
type Toast = { id: number; text: string; type?: 'success'|'error' };
type ToastAction = { label: string; onClick: () => void };
type Toast = {
id: number;
text: string;
type?: 'success' | 'error' | 'info';
action?: ToastAction;
durationMs?: number;
};
const Ctx = React.createContext<{ push: (t: Omit<Toast,'id'>) => void } | null>(null);
export function ToastProvider({ children }: { children: React.ReactNode }) {
const [list, setList] = React.useState<Toast[]>([]);
const push = React.useCallback((t: Omit<Toast,'id'>) => {
const id = Date.now() + Math.random();
setList((arr) => [...arr, { id, ...t }]);
setTimeout(() => setList((arr) => arr.filter((x) => x.id !== id)), 3000);
const durationMs = t.durationMs ?? 3000;
setList((arr) => [...arr, { id, ...t, durationMs }]);
if (durationMs > 0) {
setTimeout(() => setList((arr) => arr.filter((x) => x.id !== id)), durationMs);
}
}, []);
const dismiss = React.useCallback((id: number) => {
setList((arr) => arr.filter((x) => x.id !== id));
}, []);
const contextValue = React.useMemo(() => ({ push }), [push]);
React.useEffect(() => {
const onEvt = (e: CustomEvent<Omit<Toast, 'id'>>) => push(e.detail);
window.addEventListener('guest-toast', onEvt);
return () => window.removeEventListener('guest-toast', onEvt);
}, [push]);
return (
<Ctx.Provider value={{ push }}>
<Ctx.Provider value={contextValue}>
{children}
<div className="pointer-events-none fixed inset-x-0 bottom-4 z-50 flex justify-center px-4">
<div className="flex w-full max-w-sm flex-col gap-2">
{list.map((t) => (
<div key={t.id} className={`pointer-events-auto rounded-md border p-3 shadow-sm ${t.type==='error'?'border-red-300 bg-red-50 text-red-700':'border-green-300 bg-green-50 text-green-700'}`}>
{t.text}
<div
key={t.id}
className={`pointer-events-auto rounded-md border p-3 shadow-sm ${
t.type === 'error'
? 'border-red-300 bg-red-50 text-red-700'
: t.type === 'info'
? 'border-blue-300 bg-blue-50 text-blue-700'
: 'border-green-300 bg-green-50 text-green-700'
}`}
>
<div className="flex flex-wrap items-center justify-between gap-3">
<span className="text-sm">{t.text}</span>
{t.action ? (
<button
type="button"
className="pointer-events-auto rounded-full border border-current/30 px-3 py-1 text-xs font-semibold uppercase tracking-wide transition hover:border-current"
onClick={() => {
try {
t.action?.onClick();
} finally {
dismiss(t.id);
}
}}
>
{t.action.label}
</button>
) : null}
</div>
</div>
))}
</div>

View File

@@ -0,0 +1,22 @@
import React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import PullToRefresh from '../PullToRefresh';
describe('PullToRefresh', () => {
it('renders children and labels', () => {
render(
<PullToRefresh
onRefresh={vi.fn()}
pullLabel="Pull"
releaseLabel="Release"
refreshingLabel="Refreshing"
>
<div>Content</div>
</PullToRefresh>
);
expect(screen.getByText('Content')).toBeInTheDocument();
expect(screen.getByText('Pull')).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,23 @@
import { describe, expect, it } from 'vitest';
import { getTabKey, getTransitionKind, isTransitionDisabled } from '../RouteTransition';
describe('RouteTransition helpers', () => {
it('detects top-level tabs', () => {
expect(getTabKey('/e/demo')).toBe('home');
expect(getTabKey('/e/demo/tasks')).toBe('tasks');
expect(getTabKey('/e/demo/achievements')).toBe('achievements');
expect(getTabKey('/e/demo/gallery')).toBe('gallery');
expect(getTabKey('/e/demo/tasks/123')).toBeNull();
});
it('detects tab vs stack transitions', () => {
expect(getTransitionKind('/e/demo', '/e/demo/gallery')).toBe('tab');
expect(getTransitionKind('/e/demo/tasks', '/e/demo/tasks/1')).toBe('stack');
});
it('disables transitions for excluded routes', () => {
expect(isTransitionDisabled('/e/demo/upload')).toBe(true);
expect(isTransitionDisabled('/share/demo-photo')).toBe(true);
expect(isTransitionDisabled('/e/demo/gallery')).toBe(false);
});
});

View File

@@ -0,0 +1,42 @@
import React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import { vi } from 'vitest';
import { ToastProvider, useToast } from '../ToastHost';
function ToastTestHarness({ onAction }: { onAction: () => void }) {
const toast = useToast();
React.useEffect(() => {
toast.push({
text: 'Update ready',
type: 'info',
durationMs: 0,
action: {
label: 'Reload',
onClick: onAction,
},
});
}, [toast, onAction]);
return null;
}
describe('ToastHost', () => {
it('renders action toasts and dismisses after action click', async () => {
const onAction = vi.fn();
render(
<ToastProvider>
<ToastTestHarness onAction={onAction} />
</ToastProvider>
);
expect(screen.getByText('Update ready')).toBeInTheDocument();
const button = screen.getByRole('button', { name: 'Reload' });
fireEvent.click(button);
expect(onAction).toHaveBeenCalledTimes(1);
expect(screen.queryByText('Update ready')).not.toBeInTheDocument();
});
});

View File

@@ -0,0 +1,157 @@
/* eslint-disable no-restricted-globals */
/// <reference lib="webworker" />
import { clientsClaim } from 'workbox-core';
import { CacheableResponsePlugin } from 'workbox-cacheable-response';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { CacheFirst, NetworkFirst, StaleWhileRevalidate } from 'workbox-strategies';
declare const self: ServiceWorkerGlobalScope & {
__WB_MANIFEST: Array<import('workbox-precaching').ManifestEntry>;
};
clientsClaim();
precacheAndRoute(self.__WB_MANIFEST);
cleanupOutdatedCaches();
const isGuestNavigation = (pathname: string) => {
if (pathname === '/event') {
return true;
}
if (pathname.startsWith('/e/')) {
return true;
}
if (pathname.startsWith('/g/')) {
return true;
}
if (pathname.startsWith('/share/')) {
return true;
}
if (pathname.startsWith('/help')) {
return true;
}
if (pathname.startsWith('/legal')) {
return true;
}
if (pathname.startsWith('/settings')) {
return true;
}
return false;
};
registerRoute(
({ request, url }) =>
request.mode === 'navigate' && url.origin === self.location.origin && isGuestNavigation(url.pathname),
new NetworkFirst({
cacheName: 'guest-pages',
networkTimeoutSeconds: 5,
plugins: [
new CacheableResponsePlugin({ statuses: [0, 200] }),
new ExpirationPlugin({ maxEntries: 40, maxAgeSeconds: 60 * 60 * 24 * 7 }),
],
})
);
registerRoute(
({ request, url }) =>
request.method === 'GET' &&
url.origin === self.location.origin &&
url.pathname.startsWith('/api/v1/'),
new NetworkFirst({
cacheName: 'guest-api',
networkTimeoutSeconds: 6,
plugins: [
new CacheableResponsePlugin({ statuses: [0, 200] }),
new ExpirationPlugin({ maxEntries: 80, maxAgeSeconds: 60 * 60 * 24 }),
],
})
);
registerRoute(
({ request, url }) => request.destination === 'image' && url.origin === self.location.origin,
new CacheFirst({
cacheName: 'guest-images',
plugins: [
new CacheableResponsePlugin({ statuses: [0, 200] }),
new ExpirationPlugin({ maxEntries: 200, maxAgeSeconds: 60 * 60 * 24 * 30 }),
],
})
);
registerRoute(
({ request, url }) => request.destination === 'font' && url.origin === self.location.origin,
new StaleWhileRevalidate({
cacheName: 'guest-fonts',
plugins: [
new CacheableResponsePlugin({ statuses: [0, 200] }),
new ExpirationPlugin({ maxEntries: 30, maxAgeSeconds: 60 * 60 * 24 * 365 }),
],
})
);
self.addEventListener('message', (event) => {
if (event.data?.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
self.addEventListener('sync', (event) => {
if (event.tag === 'upload-queue') {
event.waitUntil(
(async () => {
const clients = await self.clients.matchAll({ includeUncontrolled: true, type: 'window' });
clients.forEach((client) => client.postMessage({ type: 'sync-queue' }));
})()
);
}
});
self.addEventListener('push', (event) => {
const payload = event.data?.json?.() ?? {};
event.waitUntil(
(async () => {
const title = payload.title ?? 'Neue Nachricht';
const options = {
body: payload.body ?? '',
icon: '/apple-touch-icon.png',
badge: '/apple-touch-icon.png',
data: payload.data ?? {},
};
await self.registration.showNotification(title, options);
const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
clients.forEach((client) => client.postMessage({ type: 'guest-notification-refresh' }));
})()
);
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
const targetUrl = event.notification.data?.url || '/';
event.waitUntil(
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
for (const client of clientList) {
if ('focus' in client) {
client.navigate(targetUrl);
return client.focus();
}
}
if (self.clients.openWindow) {
return self.clients.openWindow(targetUrl);
}
})
);
});
self.addEventListener('pushsubscriptionchange', (event) => {
event.waitUntil(
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
clientList.forEach((client) => client.postMessage({ type: 'push-subscription-change' }));
})
);
});

View File

@@ -16,6 +16,13 @@ export const messages: Record<LocaleCode, NestedMessages> = {
de: {
common: {
hi: 'Hi',
refresh: 'Aktualisieren',
pullToRefresh: 'Zum Aktualisieren ziehen',
releaseToRefresh: 'Zum Aktualisieren loslassen',
refreshing: 'Aktualisiere...',
updateAvailable: 'Neue Version verfügbar.',
updateAction: 'Aktualisieren',
offlineReady: 'Offline bereit.',
actions: {
close: 'Schließen',
loading: 'Lädt...',
@@ -137,6 +144,7 @@ export const messages: Record<LocaleCode, NestedMessages> = {
home: {
fallbackGuestName: 'Gast',
welcomeLine: 'Willkommen {name}!',
swipeHint: 'Wische für mehr Aufgaben',
introRotating: {
0: 'Hilf uns, diesen besonderen Tag mit deinen schönsten Momenten festzuhalten.',
1: 'Fang die Stimmung des Events ein und teile sie mit allen Gästen.',
@@ -703,6 +711,13 @@ export const messages: Record<LocaleCode, NestedMessages> = {
en: {
common: {
hi: 'Hi',
refresh: 'Refresh',
pullToRefresh: 'Pull to refresh',
releaseToRefresh: 'Release to refresh',
refreshing: 'Refreshing...',
updateAvailable: 'A new version is available.',
updateAction: 'Update',
offlineReady: 'Offline ready.',
actions: {
close: 'Close',
loading: 'Loading...',
@@ -824,6 +839,7 @@ export const messages: Record<LocaleCode, NestedMessages> = {
home: {
fallbackGuestName: 'Guest',
welcomeLine: 'Welcome {name}!',
swipeHint: 'Swipe for more missions',
introRotating: {
0: 'Help us capture this special day with your favourite moments.',
1: 'Capture the mood of the event and share it with everyone.',

View File

@@ -0,0 +1,41 @@
import { describe, expect, it, vi } from 'vitest';
import { FADE_SCALE, FADE_UP, STAGGER_FAST, getMotionContainerProps, getMotionItemProps, prefersReducedMotion } from '../motion';
describe('motion helpers', () => {
it('returns disabled props when motion is off', () => {
const props = getMotionContainerProps(false, STAGGER_FAST);
expect(props.initial).toBe(false);
});
it('returns variants when motion is on', () => {
const containerProps = getMotionContainerProps(true, STAGGER_FAST);
const itemProps = getMotionItemProps(true, FADE_UP);
expect(containerProps.initial).toBe('hidden');
expect(containerProps.animate).toBe('show');
expect(itemProps.variants).toBe(FADE_UP);
});
it('detects reduced motion preference safely', () => {
const original = window.matchMedia;
Object.defineProperty(window, 'matchMedia', {
configurable: true,
value: undefined,
});
expect(prefersReducedMotion()).toBe(false);
Object.defineProperty(window, 'matchMedia', {
configurable: true,
value: vi.fn().mockReturnValue({ matches: true }),
});
expect(prefersReducedMotion()).toBe(true);
Object.defineProperty(window, 'matchMedia', {
configurable: true,
value: original,
});
});
it('exposes distinct base variants', () => {
expect(FADE_UP).not.toBe(FADE_SCALE);
});
});

View File

@@ -0,0 +1,58 @@
import type { Variants } from 'framer-motion';
export const IOS_EASE = [0.22, 0.61, 0.36, 1] as const;
export const IOS_EASE_SOFT = [0.25, 0.8, 0.25, 1] as const;
export const STAGGER_FAST: Variants = {
hidden: {},
show: {
transition: {
staggerChildren: 0.06,
delayChildren: 0.04,
},
},
};
export const FADE_UP: Variants = {
hidden: { opacity: 0, y: 10 },
show: {
opacity: 1,
y: 0,
transition: {
duration: 0.24,
ease: IOS_EASE,
},
},
};
export const FADE_SCALE: Variants = {
hidden: { opacity: 0, scale: 0.98 },
show: {
opacity: 1,
scale: 1,
transition: {
duration: 0.22,
ease: IOS_EASE,
},
},
};
export function prefersReducedMotion(): boolean {
if (typeof window === 'undefined') {
return false;
}
return Boolean(window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches);
}
export function getMotionContainerProps(enabled: boolean, variants: Variants) {
if (!enabled) {
return { initial: false } as const;
}
return { variants, initial: 'hidden', animate: 'show' } as const;
}
export function getMotionItemProps(enabled: boolean, variants: Variants) {
return enabled ? { variants } : {};
}

View File

@@ -36,6 +36,7 @@ const appRoot = async () => {
const { RouterProvider } = await import('react-router-dom');
const { router } = await import('./router');
const { ToastProvider } = await import('./components/ToastHost');
const { default: PwaManager } = await import('./components/PwaManager');
const { LocaleProvider } = await import('./i18n/LocaleContext');
const { default: MatomoTracker } = await import('@/components/analytics/MatomoTracker');
const rawMatomo = (window as any).__MATOMO_GUEST__ as { enabled?: boolean; url?: string; siteId?: string } | undefined;
@@ -47,21 +48,6 @@ const appRoot = async () => {
}
: undefined;
// Register a minimal service worker for background sync (best-effort)
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/guest-sw.js').catch(() => {});
navigator.serviceWorker.addEventListener('message', (evt) => {
if (evt.data?.type === 'sync-queue') {
import('./queue/queue').then((m) => m.processQueue().catch(() => {}));
}
});
// Also attempt to process queue on load and when going online
import('./queue/queue').then((m) => m.processQueue().catch(() => {}));
window.addEventListener('online', () => {
import('./queue/queue').then((m) => m.processQueue().catch(() => {}));
});
}
createRoot(rootEl).render(
<Sentry.ErrorBoundary fallback={<GuestFallback message="Erlebnisse können nicht geladen werden." />}>
<React.StrictMode>
@@ -69,6 +55,7 @@ const appRoot = async () => {
<LocaleProvider>
<ToastProvider>
<MatomoTracker config={matomoConfig} />
<PwaManager />
<Suspense fallback={<GuestFallback message="Erlebnisse werden geladen …" />}>
<RouterProvider router={router} />
</Suspense>

View File

@@ -6,6 +6,7 @@ import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Separator } from '@/components/ui/separator';
import { AnimatePresence, motion } from 'framer-motion';
import {
AchievementBadge,
AchievementsPayload,
@@ -23,6 +24,8 @@ import type { LocaleCode } from '../i18n/messages';
import { localizeTaskLabel } from '../lib/localizeTaskLabel';
import { useEventData } from '../hooks/useEventData';
import { isTaskModeEnabled } from '../lib/engagement';
import { FADE_SCALE, FADE_UP, STAGGER_FAST, getMotionContainerProps, getMotionItemProps, prefersReducedMotion } from '../lib/motion';
import PullToRefresh from '../components/PullToRefresh';
const GENERIC_ERROR = 'GENERIC_ERROR';
@@ -356,172 +359,213 @@ export default function AchievementsPage() {
const personalName = identity.hydrated && identity.name ? identity.name : undefined;
useEffect(() => {
const loadAchievements = React.useCallback(async (signal?: AbortSignal) => {
if (!token) return;
const controller = new AbortController();
setLoading(true);
setError(null);
fetchAchievements(token, {
guestName: personalName,
locale,
signal: controller.signal,
})
.then((payload) => {
setData(payload);
if (!payload.personal) {
setActiveTab('event');
}
})
.catch((err) => {
if (err.name === 'AbortError') return;
console.error('Failed to load achievements', err);
setError(err.message || GENERIC_ERROR);
})
.finally(() => setLoading(false));
try {
const payload = await fetchAchievements(token, {
guestName: personalName,
locale,
signal,
});
setData(payload);
if (!payload.personal) {
setActiveTab('event');
}
} catch (err) {
if (err instanceof DOMException && err.name === 'AbortError') return;
console.error('Failed to load achievements', err);
setError(err instanceof Error ? err.message : GENERIC_ERROR);
} finally {
if (!signal?.aborted) {
setLoading(false);
}
}
}, [locale, personalName, token]);
useEffect(() => {
const controller = new AbortController();
void loadAchievements(controller.signal);
return () => controller.abort();
}, [token, personalName, locale]);
}, [loadAchievements]);
const hasPersonal = Boolean(data?.personal);
const motionEnabled = !prefersReducedMotion();
const containerMotion = getMotionContainerProps(motionEnabled, STAGGER_FAST);
const fadeUpMotion = getMotionItemProps(motionEnabled, FADE_UP);
const fadeScaleMotion = getMotionItemProps(motionEnabled, FADE_SCALE);
const tabMotion = motionEnabled
? { variants: FADE_UP, initial: 'hidden', animate: 'show', exit: 'hidden' as const }
: {};
const handleRefresh = React.useCallback(async () => {
await loadAchievements();
}, [loadAchievements]);
if (!token) {
return null;
}
return (
<div className="space-y-6 pb-24">
<div className="space-y-2">
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-pink-500/10 text-pink-500">
<Award className="h-5 w-5" aria-hidden />
</div>
<div>
<h1 className="text-2xl font-semibold text-foreground">{t('achievements.page.title')}</h1>
<p className="text-sm text-muted-foreground">{t('achievements.page.subtitle')}</p>
</div>
</div>
</div>
{loading && (
<div className="space-y-4">
<Skeleton className="h-24 w-full" />
<Skeleton className="h-32 w-full" />
<Skeleton className="h-48 w-full" />
</div>
)}
{!loading && error && (
<Alert variant="destructive">
<AlertDescription className="flex items-center justify-between gap-3">
<span>{error === GENERIC_ERROR ? t('achievements.page.loadError') : error}</span>
<Button variant="outline" size="sm" onClick={() => setActiveTab(hasPersonal ? 'personal' : 'event')}>
{t('achievements.page.retry')}
</Button>
</AlertDescription>
</Alert>
)}
{!loading && !error && data && (
<>
<div className="flex flex-wrap items-center gap-2">
<Button
variant={activeTab === 'personal' ? 'default' : 'outline'}
onClick={() => setActiveTab('personal')}
disabled={!hasPersonal}
className="flex items-center gap-2"
>
<Sparkles className="h-4 w-4" aria-hidden />
{t('achievements.page.buttons.personal')}
</Button>
<Button
variant={activeTab === 'event' ? 'default' : 'outline'}
onClick={() => setActiveTab('event')}
className="flex items-center gap-2"
>
<Users className="h-4 w-4" aria-hidden />
{t('achievements.page.buttons.event')}
</Button>
<Button
variant={activeTab === 'feed' ? 'default' : 'outline'}
onClick={() => setActiveTab('feed')}
className="flex items-center gap-2"
>
<BarChart2 className="h-4 w-4" aria-hidden />
{t('achievements.page.buttons.feed')}
</Button>
</div>
<Separator />
{activeTab === 'personal' && hasPersonal && data.personal && (
<div className="space-y-5">
<Card>
<CardHeader className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<CardTitle className="text-lg font-semibold">
{t('achievements.personal.greeting', { name: data.personal.guestName || identity.name || t('achievements.leaderboard.guestFallback') })}
</CardTitle>
<CardDescription>
{t('achievements.personal.stats', {
photos: formatNumber(data.personal.photos),
tasks: formatNumber(data.personal.tasks),
likes: formatNumber(data.personal.likes),
})}
</CardDescription>
</div>
<PersonalActions token={token} t={t} tasksEnabled={tasksEnabled} />
</CardHeader>
</Card>
<BadgesGrid badges={data.personal.badges} t={t} />
</div>
)}
{activeTab === 'event' && (
<div className="space-y-5">
<Highlights
topPhoto={data.highlights.topPhoto}
trendingEmotion={data.highlights.trendingEmotion}
t={t}
formatRelativeTime={formatRelative}
locale={locale}
formatNumber={formatNumber}
/>
<Timeline points={data.highlights.timeline} t={t} formatNumber={formatNumber} />
<div className="grid gap-4 lg:grid-cols-2">
<Leaderboard
title={t('achievements.leaderboard.uploadsTitle')}
description={t('achievements.leaderboard.description')}
icon={Users}
entries={data.leaderboards.uploads}
emptyCopy={t('achievements.leaderboard.uploadsEmpty')}
t={t}
formatNumber={formatNumber}
/>
<Leaderboard
title={t('achievements.leaderboard.likesTitle')}
description={t('achievements.leaderboard.description')}
icon={Trophy}
entries={data.leaderboards.likes}
emptyCopy={t('achievements.leaderboard.likesEmpty')}
t={t}
formatNumber={formatNumber}
/>
const tabContent = (
<>
{activeTab === 'personal' && hasPersonal && data?.personal && (
<div className="space-y-5">
<Card>
<CardHeader className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<CardTitle className="text-lg font-semibold">
{t('achievements.personal.greeting', { name: data.personal.guestName || identity.name || t('achievements.leaderboard.guestFallback') })}
</CardTitle>
<CardDescription>
{t('achievements.personal.stats', {
photos: formatNumber(data.personal.photos),
tasks: formatNumber(data.personal.tasks),
likes: formatNumber(data.personal.likes),
})}
</CardDescription>
</div>
</div>
)}
<PersonalActions token={token} t={t} tasksEnabled={tasksEnabled} />
</CardHeader>
</Card>
{activeTab === 'feed' && (
<Feed
feed={data.feed}
<BadgesGrid badges={data.personal.badges} t={t} />
</div>
)}
{activeTab === 'event' && data && (
<div className="space-y-5">
<Highlights
topPhoto={data.highlights.topPhoto}
trendingEmotion={data.highlights.trendingEmotion}
t={t}
formatRelativeTime={formatRelative}
locale={locale}
formatNumber={formatNumber}
/>
<Timeline points={data.highlights.timeline} t={t} formatNumber={formatNumber} />
<div className="grid gap-4 lg:grid-cols-2">
<Leaderboard
title={t('achievements.leaderboard.uploadsTitle')}
description={t('achievements.leaderboard.description')}
icon={Users}
entries={data.leaderboards.uploads}
emptyCopy={t('achievements.leaderboard.uploadsEmpty')}
t={t}
formatRelativeTime={formatRelative}
locale={locale}
formatNumber={formatNumber}
/>
)}
</>
<Leaderboard
title={t('achievements.leaderboard.likesTitle')}
description={t('achievements.leaderboard.description')}
icon={Trophy}
entries={data.leaderboards.likes}
emptyCopy={t('achievements.leaderboard.likesEmpty')}
t={t}
formatNumber={formatNumber}
/>
</div>
</div>
)}
</div>
{activeTab === 'feed' && data && (
<Feed
feed={data.feed}
t={t}
formatRelativeTime={formatRelative}
locale={locale}
formatNumber={formatNumber}
/>
)}
</>
);
return (
<PullToRefresh
onRefresh={handleRefresh}
pullLabel={t('common.pullToRefresh')}
releaseLabel={t('common.releaseToRefresh')}
refreshingLabel={t('common.refreshing')}
>
<motion.div className="space-y-6 pb-24" {...containerMotion}>
<motion.div className="space-y-2" {...fadeUpMotion}>
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-pink-500/10 text-pink-500">
<Award className="h-5 w-5" aria-hidden />
</div>
<div>
<h1 className="text-2xl font-semibold text-foreground">{t('achievements.page.title')}</h1>
<p className="text-sm text-muted-foreground">{t('achievements.page.subtitle')}</p>
</div>
</div>
</motion.div>
{loading && (
<motion.div className="space-y-4" {...fadeUpMotion}>
<Skeleton className="h-24 w-full" />
<Skeleton className="h-32 w-full" />
<Skeleton className="h-48 w-full" />
</motion.div>
)}
{!loading && error && (
<motion.div {...fadeUpMotion}>
<Alert variant="destructive">
<AlertDescription className="flex items-center justify-between gap-3">
<span>{error === GENERIC_ERROR ? t('achievements.page.loadError') : error}</span>
<Button variant="outline" size="sm" onClick={() => setActiveTab(hasPersonal ? 'personal' : 'event')}>
{t('achievements.page.retry')}
</Button>
</AlertDescription>
</Alert>
</motion.div>
)}
{!loading && !error && data && (
<>
<motion.div className="flex flex-wrap items-center gap-2" {...fadeUpMotion}>
<Button
variant={activeTab === 'personal' ? 'default' : 'outline'}
onClick={() => setActiveTab('personal')}
disabled={!hasPersonal}
className="flex items-center gap-2"
>
<Sparkles className="h-4 w-4" aria-hidden />
{t('achievements.page.buttons.personal')}
</Button>
<Button
variant={activeTab === 'event' ? 'default' : 'outline'}
onClick={() => setActiveTab('event')}
className="flex items-center gap-2"
>
<Users className="h-4 w-4" aria-hidden />
{t('achievements.page.buttons.event')}
</Button>
<Button
variant={activeTab === 'feed' ? 'default' : 'outline'}
onClick={() => setActiveTab('feed')}
className="flex items-center gap-2"
>
<BarChart2 className="h-4 w-4" aria-hidden />
{t('achievements.page.buttons.feed')}
</Button>
</motion.div>
<motion.div {...fadeUpMotion}>
<Separator />
</motion.div>
{motionEnabled ? (
<AnimatePresence mode="wait" initial={false}>
<motion.div key={activeTab} {...tabMotion}>
{tabContent}
</motion.div>
</AnimatePresence>
) : (
<motion.div {...fadeScaleMotion}>{tabContent}</motion.div>
)}
</>
)}
</motion.div>
</PullToRefresh>
);
}

View File

@@ -5,6 +5,7 @@ import { useParams, useSearchParams } from 'react-router-dom';
import { usePollGalleryDelta } from '../polling/usePollGalleryDelta';
import FiltersBar, { type GalleryFilter } from '../components/FiltersBar';
import { Heart, Image as ImageIcon, Share2 } from 'lucide-react';
import { motion } from 'framer-motion';
import { likePhoto } from '../services/photosApi';
import PhotoLightbox from './PhotoLightbox';
import { fetchEvent, type EventData } from '../services/eventApi';
@@ -15,6 +16,8 @@ import { createPhotoShareLink } from '../services/photosApi';
import { cn } from '@/lib/utils';
import { useEventBranding } from '../context/EventBrandingContext';
import ShareSheet from '../components/ShareSheet';
import { FADE_SCALE, FADE_UP, STAGGER_FAST, getMotionContainerProps, getMotionItemProps, prefersReducedMotion } from '../lib/motion';
import PullToRefresh from '../components/PullToRefresh';
const allGalleryFilters: GalleryFilter[] = ['latest', 'popular', 'mine', 'photobooth'];
type GalleryPhoto = {
@@ -54,7 +57,7 @@ export default function GalleryPage() {
const { token } = useParams<{ token?: string }>();
const { t, locale } = useTranslation();
const { branding } = useEventBranding();
const { photos, loading, newCount, acknowledgeNew } = usePollGalleryDelta(token ?? '', locale);
const { photos, loading, newCount, acknowledgeNew, refreshNow } = usePollGalleryDelta(token ?? '', locale);
const [searchParams, setSearchParams] = useSearchParams();
const photoIdParam = searchParams.get('photoId');
const modeParam = searchParams.get('mode');
@@ -63,6 +66,11 @@ export default function GalleryPage() {
const linkColor = branding.buttons?.linkColor ?? branding.secondaryColor;
const bodyFont = branding.typography?.body ?? branding.fontFamily ?? undefined;
const headingFont = branding.typography?.heading ?? branding.fontFamily ?? undefined;
const motionEnabled = !prefersReducedMotion();
const containerMotion = getMotionContainerProps(motionEnabled, STAGGER_FAST);
const fadeUpMotion = getMotionItemProps(motionEnabled, FADE_UP);
const fadeScaleMotion = getMotionItemProps(motionEnabled, FADE_SCALE);
const gridMotion = getMotionContainerProps(motionEnabled, STAGGER_FAST);
const [filter, setFilterState] = React.useState<GalleryFilter>('latest');
const [currentPhotoIndex, setCurrentPhotoIndex] = React.useState<number | null>(null);
const [hasOpenedPhoto, setHasOpenedPhoto] = useState(false);
@@ -122,24 +130,28 @@ export default function GalleryPage() {
}, [typedPhotos, photos.length, photoIdParam, currentPhotoIndex, hasOpenedPhoto]);
// Load event and package info
useEffect(() => {
const loadEventData = React.useCallback(async () => {
if (!token) return;
const loadEventData = async () => {
try {
setEventLoading(true);
const eventData = await fetchEvent(token);
setEvent(eventData);
} catch (err) {
console.error('Failed to load event data', err);
} finally {
setEventLoading(false);
}
};
loadEventData();
try {
setEventLoading(true);
const eventData = await fetchEvent(token);
setEvent(eventData);
} catch (err) {
console.error('Failed to load event data', err);
} finally {
setEventLoading(false);
}
}, [token]);
useEffect(() => {
void loadEventData();
}, [loadEventData]);
const handleRefresh = React.useCallback(async () => {
await Promise.all([refreshNow(), loadEventData()]);
acknowledgeNew();
}, [acknowledgeNew, loadEventData, refreshNow]);
const myPhotoIds = React.useMemo(() => {
try {
const raw = localStorage.getItem('my-photo-ids');
@@ -287,152 +299,167 @@ export default function GalleryPage() {
return (
<Page title="">
<div className="space-y-2" style={bodyFont ? { fontFamily: bodyFont } : undefined}>
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-pink-500/10 text-pink-500" style={{ borderRadius: radius }}>
<ImageIcon className="h-5 w-5" aria-hidden />
</div>
<div>
<h1 className="text-2xl font-semibold text-foreground" style={headingFont ? { fontFamily: headingFont } : undefined}>{t('galleryPage.title')}</h1>
<p className="text-sm text-muted-foreground">{t('galleryPage.subtitle')}</p>
</div>
<PullToRefresh
onRefresh={handleRefresh}
pullLabel={t('common.pullToRefresh')}
releaseLabel={t('common.releaseToRefresh')}
refreshingLabel={t('common.refreshing')}
>
<motion.div className="space-y-2" style={bodyFont ? { fontFamily: bodyFont } : undefined} {...containerMotion}>
<motion.div className="flex items-center gap-3" {...fadeUpMotion}>
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-pink-500/10 text-pink-500" style={{ borderRadius: radius }}>
<ImageIcon className="h-5 w-5" aria-hidden />
</div>
<div>
<h1 className="text-2xl font-semibold text-foreground" style={headingFont ? { fontFamily: headingFont } : undefined}>{t('galleryPage.title')}</h1>
<p className="text-sm text-muted-foreground">{t('galleryPage.subtitle')}</p>
</div>
{newCount > 0 ? (
<button
type="button"
onClick={acknowledgeNew}
className={`inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold transition ${badgeEmphasisClass}`}
style={{ borderRadius: radius }}
>
{newPhotosBadgeText}
</button>
) : (
<span className={`inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold ${badgeEmphasisClass}`} style={{ borderRadius: radius }}>
{newPhotosBadgeText}
</span>
)}
</div>
</div>
{newCount > 0 ? (
<button
type="button"
onClick={acknowledgeNew}
className={`inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold transition ${badgeEmphasisClass}`}
style={{ borderRadius: radius }}
>
{newPhotosBadgeText}
</button>
) : (
<span className={`inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold ${badgeEmphasisClass}`} style={{ borderRadius: radius }}>
{newPhotosBadgeText}
</span>
)}
</motion.div>
</motion.div>
<FiltersBar
value={filter}
onChange={setFilter}
className="mt-2"
showPhotobooth={showPhotoboothFilter}
styleOverride={{ borderRadius: radius, fontFamily: headingFont }}
/>
{loading && <p className="px-4" style={bodyFont ? { fontFamily: bodyFont } : undefined}>{t('galleryPage.loading', 'Lade…')}</p>}
<div className="grid grid-cols-2 gap-2 px-2 pb-16 sm:grid-cols-3 lg:grid-cols-4">
{list.map((p: GalleryPhoto) => {
const imageUrl = normalizeImageUrl(p.thumbnail_path || p.file_path);
const createdLabel = p.created_at
? new Date(p.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
: t('galleryPage.photo.justNow', 'Gerade eben');
const likeCount = counts[p.id] ?? (p.likes_count || 0);
const localizedTaskTitle = localizeTaskLabel(p.task_title ?? null, locale);
const altSuffix = localizedTaskTitle
? t('galleryPage.photo.altTaskSuffix', { task: localizedTaskTitle })
: '';
const altText = t('galleryPage.photo.alt', { id: p.id, suffix: altSuffix }, `Foto ${p.id}${altSuffix}`);
<motion.div {...fadeUpMotion}>
<FiltersBar
value={filter}
onChange={setFilter}
className="mt-2"
showPhotobooth={showPhotoboothFilter}
styleOverride={{ borderRadius: radius, fontFamily: headingFont }}
/>
</motion.div>
{loading && (
<motion.p className="px-4" style={bodyFont ? { fontFamily: bodyFont } : undefined} {...fadeUpMotion}>
{t('galleryPage.loading', 'Lade…')}
</motion.p>
)}
<motion.div className="grid grid-cols-2 gap-2 px-2 pb-16 sm:grid-cols-3 lg:grid-cols-4" {...gridMotion}>
{list.map((p: GalleryPhoto) => {
const imageUrl = normalizeImageUrl(p.thumbnail_path || p.file_path);
const createdLabel = p.created_at
? new Date(p.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
: t('galleryPage.photo.justNow', 'Gerade eben');
const likeCount = counts[p.id] ?? (p.likes_count || 0);
const localizedTaskTitle = localizeTaskLabel(p.task_title ?? null, locale);
const altSuffix = localizedTaskTitle
? t('galleryPage.photo.altTaskSuffix', { task: localizedTaskTitle })
: '';
const altText = t('galleryPage.photo.alt', { id: p.id, suffix: altSuffix }, `Foto ${p.id}${altSuffix}`);
const openPhoto = () => {
const index = list.findIndex((photo) => photo.id === p.id);
setCurrentPhotoIndex(index >= 0 ? index : null);
};
const openPhoto = () => {
const index = list.findIndex((photo) => photo.id === p.id);
setCurrentPhotoIndex(index >= 0 ? index : null);
};
return (
<div
key={p.id}
role="button"
tabIndex={0}
onClick={openPhoto}
onKeyDown={(e) => {
if (e.key === 'Enter') {
openPhoto();
}
}}
className="group relative overflow-hidden border border-white/20 bg-gray-950 text-white shadow-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-pink-400"
style={{ borderRadius: radius }}
>
<img
src={imageUrl}
alt={altText}
className="aspect-[3/4] w-full object-cover transition duration-500 group-hover:scale-105"
onError={(e) => {
(e.target as HTMLImageElement).src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjRjNGNEY2Ii8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxNCIgZmlsbD0iIzk5OSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iPk5vIEltYWdlPC90ZXh0Pjwvc3ZnPg==';
return (
<motion.div
key={p.id}
role="button"
tabIndex={0}
onClick={openPhoto}
onKeyDown={(e) => {
if (e.key === 'Enter') {
openPhoto();
}
}}
loading="lazy"
/>
<div className="pointer-events-none absolute inset-0 bg-gradient-to-t from-black/85 via-black/20 to-transparent" aria-hidden />
<div className="absolute inset-x-0 bottom-0 space-y-2 px-4 pb-4" style={bodyFont ? { fontFamily: bodyFont } : undefined}>
{localizedTaskTitle && <p className="text-sm font-medium leading-tight line-clamp-2 text-white" style={headingFont ? { fontFamily: headingFont } : undefined}>{localizedTaskTitle}</p>}
<div className="flex items-center justify-between text-xs text-white/90" style={bodyFont ? { fontFamily: bodyFont } : undefined}>
<span className="truncate">{createdLabel}</span>
<span className="ml-3 truncate text-right">{p.uploader_name || t('galleryPage.photo.anonymous', 'Gast')}</span>
className="group relative overflow-hidden border border-white/20 bg-gray-950 text-white shadow-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-pink-400"
style={{ borderRadius: radius }}
{...fadeScaleMotion}
>
<img
src={imageUrl}
alt={altText}
className="aspect-[3/4] w-full object-cover transition duration-500 group-hover:scale-105"
onError={(e) => {
(e.target as HTMLImageElement).src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjRjNGNEY2Ii8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxNCIgZmlsbD0iIzk5OSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iPk5vIEltYWdlPC90ZXh0Pjwvc3ZnPg==';
}}
loading="lazy"
/>
<div className="pointer-events-none absolute inset-0 bg-gradient-to-t from-black/85 via-black/20 to-transparent" aria-hidden />
<div className="absolute inset-x-0 bottom-0 space-y-2 px-4 pb-4" style={bodyFont ? { fontFamily: bodyFont } : undefined}>
{localizedTaskTitle && <p className="text-sm font-medium leading-tight line-clamp-2 text-white" style={headingFont ? { fontFamily: headingFont } : undefined}>{localizedTaskTitle}</p>}
<div className="flex items-center justify-between text-xs text-white/90" style={bodyFont ? { fontFamily: bodyFont } : undefined}>
<span className="truncate">{createdLabel}</span>
<span className="ml-3 truncate text-right">{p.uploader_name || t('galleryPage.photo.anonymous', 'Gast')}</span>
</div>
</div>
<div className="absolute right-3 top-3 z-10 flex items-center gap-2">
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onShare(p);
}}
className={cn(
'flex h-9 w-9 items-center justify-center border text-white transition backdrop-blur',
shareTargetId === p.id ? 'opacity-60' : 'hover:bg-white/10'
)}
aria-label={t('galleryPage.photo.shareAria', 'Foto teilen')}
disabled={shareTargetId === p.id}
style={{
borderRadius: radius,
background: buttonStyle === 'outline' ? 'transparent' : '#00000066',
border: buttonStyle === 'outline' ? `1px solid ${linkColor}` : '1px solid rgba(255,255,255,0.4)',
color: buttonStyle === 'outline' ? linkColor : undefined,
}}
>
<Share2 className="h-4 w-4" aria-hidden />
</button>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onLike(p.id);
}}
className={cn(
'flex items-center gap-1 px-3 py-1 text-sm font-medium transition backdrop-blur',
liked.has(p.id) ? 'text-pink-300' : 'text-white'
)}
aria-label={t('galleryPage.photo.likeAria', 'Foto liken')}
style={{
borderRadius: radius,
background: buttonStyle === 'outline' ? 'transparent' : '#00000066',
border: buttonStyle === 'outline' ? `1px solid ${linkColor}` : '1px solid rgba(255,255,255,0.4)',
color: buttonStyle === 'outline' ? linkColor : undefined,
}}
>
<Heart className={`h-4 w-4 ${liked.has(p.id) ? 'fill-current' : ''}`} aria-hidden />
{likeCount}
</button>
</div>
</motion.div>
);
})}
{list.length === 0 && Array.from({ length: 6 }).map((_, idx) => (
<motion.div
key={`placeholder-${idx}`}
className="relative overflow-hidden border border-muted/40 bg-[var(--guest-surface,#f7f7f7)] shadow-sm"
style={{ borderRadius: radius }}
{...fadeScaleMotion}
>
<div className="absolute inset-0 bg-gradient-to-br from-white/60 via-white/30 to-transparent dark:from-white/5 dark:via-white/0" aria-hidden />
<div className="flex aspect-[3/4] items-center justify-center gap-2 p-4 text-muted-foreground/70">
<ImageIcon className="h-6 w-6" aria-hidden />
<div className="h-2 w-10 rounded-full bg-muted/40" />
</div>
<div className="absolute right-3 top-3 z-10 flex items-center gap-2">
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onShare(p);
}}
className={cn(
'flex h-9 w-9 items-center justify-center border text-white transition backdrop-blur',
shareTargetId === p.id ? 'opacity-60' : 'hover:bg-white/10'
)}
aria-label={t('galleryPage.photo.shareAria', 'Foto teilen')}
disabled={shareTargetId === p.id}
style={{
borderRadius: radius,
background: buttonStyle === 'outline' ? 'transparent' : '#00000066',
border: buttonStyle === 'outline' ? `1px solid ${linkColor}` : '1px solid rgba(255,255,255,0.4)',
color: buttonStyle === 'outline' ? linkColor : undefined,
}}
>
<Share2 className="h-4 w-4" aria-hidden />
</button>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onLike(p.id);
}}
className={cn(
'flex items-center gap-1 px-3 py-1 text-sm font-medium transition backdrop-blur',
liked.has(p.id) ? 'text-pink-300' : 'text-white'
)}
aria-label={t('galleryPage.photo.likeAria', 'Foto liken')}
style={{
borderRadius: radius,
background: buttonStyle === 'outline' ? 'transparent' : '#00000066',
border: buttonStyle === 'outline' ? `1px solid ${linkColor}` : '1px solid rgba(255,255,255,0.4)',
color: buttonStyle === 'outline' ? linkColor : undefined,
}}
>
<Heart className={`h-4 w-4 ${liked.has(p.id) ? 'fill-current' : ''}`} aria-hidden />
{likeCount}
</button>
</div>
</div>
);
})}
{list.length === 0 && Array.from({ length: 6 }).map((_, idx) => (
<div
key={`placeholder-${idx}`}
className="relative overflow-hidden border border-muted/40 bg-[var(--guest-surface,#f7f7f7)] shadow-sm"
style={{ borderRadius: radius }}
>
<div className="absolute inset-0 bg-gradient-to-br from-white/60 via-white/30 to-transparent dark:from-white/5 dark:via-white/0" aria-hidden />
<div className="flex aspect-[3/4] items-center justify-center gap-2 p-4 text-muted-foreground/70">
<ImageIcon className="h-6 w-6" aria-hidden />
<div className="h-2 w-10 rounded-full bg-muted/40" />
</div>
<div className="absolute inset-0 animate-pulse bg-white/30 dark:bg-white/5" aria-hidden />
</div>
))}
</div>
<div className="absolute inset-0 animate-pulse bg-white/30 dark:bg-white/5" aria-hidden />
</motion.div>
))}
</motion.div>
</PullToRefresh>
{currentPhotoIndex !== null && list.length > 0 && (
<PhotoLightbox
photos={list}

View File

@@ -6,6 +6,7 @@ import { Page } from './_util';
import { useLocale } from '../i18n/LocaleContext';
import { useTranslation } from '../i18n/useTranslation';
import { getHelpArticle, type HelpArticleDetail } from '../services/helpApi';
import PullToRefresh from '../components/PullToRefresh';
export default function HelpArticlePage() {
const params = useParams<{ token?: string; slug: string }>();
@@ -40,69 +41,76 @@ export default function HelpArticlePage() {
return (
<Page title={title}>
<div className="mb-4">
<Button variant="ghost" size="sm" asChild>
<Link to={basePath}>
{t('help.article.back')}
</Link>
</Button>
</div>
{state === 'loading' && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
{t('common.actions.loading')}
</div>
)}
{state === 'error' && (
<div className="space-y-3 rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-sm text-destructive">
<p>{t('help.article.unavailable')}</p>
<Button variant="secondary" size="sm" onClick={loadArticle}>
{t('help.article.reload')}
<PullToRefresh
onRefresh={loadArticle}
pullLabel={t('common.pullToRefresh')}
releaseLabel={t('common.releaseToRefresh')}
refreshingLabel={t('common.refreshing')}
>
<div className="mb-4">
<Button variant="ghost" size="sm" asChild>
<Link to={basePath}>
{t('help.article.back')}
</Link>
</Button>
</div>
)}
{state === 'ready' && article && (
<article className="space-y-6">
<div className="space-y-2 text-sm text-muted-foreground">
{article.updated_at && (
<div>{t('help.article.updated', { date: formatDate(article.updated_at, locale) })}</div>
)}
<Button variant="ghost" size="sm" asChild>
<Link to={basePath}>
{t('help.article.back')}
</Link>
{state === 'loading' && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
{t('common.actions.loading')}
</div>
)}
{state === 'error' && (
<div className="space-y-3 rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-sm text-destructive">
<p>{t('help.article.unavailable')}</p>
<Button variant="secondary" size="sm" onClick={loadArticle}>
{t('help.article.reload')}
</Button>
</div>
<div className="overflow-x-auto">
<div
className="prose prose-sm max-w-none dark:prose-invert [&_table]:w-full [&_table]:text-sm [&_:where(p,ul,ol,li)]:text-foreground [&_:where(h1,h2,h3,h4,h5,h6)]:text-foreground"
dangerouslySetInnerHTML={{ __html: article.body_html ?? article.body_markdown ?? '' }}
/>
</div>
{article.related && article.related.length > 0 && (
<section className="space-y-3">
<h3 className="text-base font-semibold text-foreground">{t('help.article.relatedTitle')}</h3>
<div className="flex flex-wrap gap-2">
{article.related.map((rel) => (
<Button
key={rel.slug}
variant="outline"
size="sm"
asChild
>
<Link to={`${basePath}/${encodeURIComponent(rel.slug)}`}>
{rel.title ?? rel.slug}
</Link>
</Button>
))}
</div>
</section>
)}
</article>
)}
)}
{state === 'ready' && article && (
<article className="space-y-6">
<div className="space-y-2 text-sm text-muted-foreground">
{article.updated_at && (
<div>{t('help.article.updated', { date: formatDate(article.updated_at, locale) })}</div>
)}
<Button variant="ghost" size="sm" asChild>
<Link to={basePath}>
{t('help.article.back')}
</Link>
</Button>
</div>
<div className="overflow-x-auto">
<div
className="prose prose-sm max-w-none dark:prose-invert [&_table]:w-full [&_table]:text-sm [&_:where(p,ul,ol,li)]:text-foreground [&_:where(h1,h2,h3,h4,h5,h6)]:text-foreground"
dangerouslySetInnerHTML={{ __html: article.body_html ?? article.body_markdown ?? '' }}
/>
</div>
{article.related && article.related.length > 0 && (
<section className="space-y-3">
<h3 className="text-base font-semibold text-foreground">{t('help.article.relatedTitle')}</h3>
<div className="flex flex-wrap gap-2">
{article.related.map((rel) => (
<Button
key={rel.slug}
variant="outline"
size="sm"
asChild
>
<Link to={`${basePath}/${encodeURIComponent(rel.slug)}`}>
{rel.title ?? rel.slug}
</Link>
</Button>
))}
</div>
</section>
)}
</article>
)}
</PullToRefresh>
</Page>
);
}

View File

@@ -8,6 +8,7 @@ import { Page } from './_util';
import { useLocale } from '../i18n/LocaleContext';
import { useTranslation } from '../i18n/useTranslation';
import { getHelpArticles, type HelpArticleSummary } from '../services/helpApi';
import PullToRefresh from '../components/PullToRefresh';
export default function HelpCenterPage() {
const params = useParams<{ token?: string }>();
@@ -48,94 +49,101 @@ export default function HelpCenterPage() {
return (
<Page title={t('help.center.title')}>
<p className="mb-4 text-sm text-muted-foreground">{t('help.center.subtitle')}</p>
<PullToRefresh
onRefresh={() => loadArticles(true)}
pullLabel={t('common.pullToRefresh')}
releaseLabel={t('common.releaseToRefresh')}
refreshingLabel={t('common.refreshing')}
>
<p className="mb-4 text-sm text-muted-foreground">{t('help.center.subtitle')}</p>
<div className="flex flex-col gap-2 rounded-xl border border-border/60 bg-background/50 p-3">
<div className="flex flex-col gap-3 sm:flex-row">
<Input
placeholder={t('help.center.searchPlaceholder')}
value={query}
onChange={(event) => setQuery(event.target.value)}
className="flex-1"
aria-label={t('help.center.searchPlaceholder')}
/>
<Button
variant="outline"
className="sm:w-auto"
onClick={() => loadArticles(true)}
disabled={state === 'loading'}
>
{state === 'loading' ? (
<span className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
{t('common.actions.loading')}
</span>
) : (
<span className="flex items-center gap-2">
<RefreshCcw className="h-4 w-4" />
{t('help.center.retry')}
</span>
)}
</Button>
</div>
{servedFromCache && (
<div className="flex items-center gap-2 rounded-lg bg-amber-50/70 px-3 py-2 text-xs text-amber-900 dark:bg-amber-400/10 dark:text-amber-200">
<Badge variant="secondary" className="bg-amber-200/80 text-amber-900 dark:bg-amber-500/40 dark:text-amber-100">
{t('help.center.offlineBadge')}
</Badge>
<span>{t('help.center.offlineDescription')}</span>
</div>
)}
</div>
<section className="mt-6 space-y-4">
<h2 className="text-base font-semibold text-foreground">{t('help.center.listTitle')}</h2>
{state === 'loading' && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
{t('common.actions.loading')}
</div>
)}
{state === 'error' && (
<div className="rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-sm text-destructive">
<p>{t('help.center.error')}</p>
<div className="flex flex-col gap-2 rounded-xl border border-border/60 bg-background/50 p-3">
<div className="flex flex-col gap-3 sm:flex-row">
<Input
placeholder={t('help.center.searchPlaceholder')}
value={query}
onChange={(event) => setQuery(event.target.value)}
className="flex-1"
aria-label={t('help.center.searchPlaceholder')}
/>
<Button
variant="secondary"
size="sm"
className="mt-3"
onClick={() => loadArticles(false)}
variant="outline"
className="sm:w-auto"
onClick={() => loadArticles(true)}
disabled={state === 'loading'}
>
{t('help.center.retry')}
{state === 'loading' ? (
<span className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
{t('common.actions.loading')}
</span>
) : (
<span className="flex items-center gap-2">
<RefreshCcw className="h-4 w-4" />
{t('help.center.retry')}
</span>
)}
</Button>
</div>
)}
{state === 'ready' && filteredArticles.length === 0 && (
<div className="rounded-lg border border-dashed border-muted-foreground/30 p-4 text-sm text-muted-foreground">
{t('help.center.empty')}
</div>
)}
{state === 'ready' && filteredArticles.length > 0 && (
<div className="space-y-3">
{filteredArticles.map((article) => (
<Link
key={article.slug}
to={`${basePath}/${encodeURIComponent(article.slug)}`}
className="block rounded-2xl border border-border/60 bg-card/70 p-4 transition-colors hover:border-primary/60"
{servedFromCache && (
<div className="flex items-center gap-2 rounded-lg bg-amber-50/70 px-3 py-2 text-xs text-amber-900 dark:bg-amber-400/10 dark:text-amber-200">
<Badge variant="secondary" className="bg-amber-200/80 text-amber-900 dark:bg-amber-500/40 dark:text-amber-100">
{t('help.center.offlineBadge')}
</Badge>
<span>{t('help.center.offlineDescription')}</span>
</div>
)}
</div>
<section className="mt-6 space-y-4">
<h2 className="text-base font-semibold text-foreground">{t('help.center.listTitle')}</h2>
{state === 'loading' && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
{t('common.actions.loading')}
</div>
)}
{state === 'error' && (
<div className="rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-sm text-destructive">
<p>{t('help.center.error')}</p>
<Button
variant="secondary"
size="sm"
className="mt-3"
onClick={() => loadArticles(false)}
>
<div className="flex items-start justify-between gap-3">
<div>
<h3 className="text-base font-semibold text-foreground">{article.title}</h3>
<p className="mt-1 text-sm text-muted-foreground line-clamp-3">{article.summary}</p>
{t('help.center.retry')}
</Button>
</div>
)}
{state === 'ready' && filteredArticles.length === 0 && (
<div className="rounded-lg border border-dashed border-muted-foreground/30 p-4 text-sm text-muted-foreground">
{t('help.center.empty')}
</div>
)}
{state === 'ready' && filteredArticles.length > 0 && (
<div className="space-y-3">
{filteredArticles.map((article) => (
<Link
key={article.slug}
to={`${basePath}/${encodeURIComponent(article.slug)}`}
className="block rounded-2xl border border-border/60 bg-card/70 p-4 transition-colors hover:border-primary/60"
>
<div className="flex items-start justify-between gap-3">
<div>
<h3 className="text-base font-semibold text-foreground">{article.title}</h3>
<p className="mt-1 text-sm text-muted-foreground line-clamp-3">{article.summary}</p>
</div>
<span className="text-xs text-muted-foreground">
{article.updated_at ? formatDate(article.updated_at, locale) : ''}
</span>
</div>
<span className="text-xs text-muted-foreground">
{article.updated_at ? formatDate(article.updated_at, locale) : ''}
</span>
</div>
</Link>
))}
</div>
)}
</section>
</Link>
))}
</div>
)}
</section>
</PullToRefresh>
</Page>
);
}

View File

@@ -7,12 +7,13 @@ import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Progress } from '@/components/ui/progress';
import { Skeleton } from '@/components/ui/skeleton';
import { Separator } from '@/components/ui/separator';
import { AnimatePresence, motion } from 'framer-motion';
import EmotionPicker from '../components/EmotionPicker';
import GalleryPreview from '../components/GalleryPreview';
import { useGuestIdentity } from '../context/GuestIdentityContext';
import { useEventData } from '../hooks/useEventData';
import { useGuestTaskProgress } from '../hooks/useGuestTaskProgress';
import { Camera, ChevronDown, Sparkles, UploadCloud, X, RefreshCw, Timer } from 'lucide-react';
import { ArrowLeft, ArrowRight, Camera, ChevronDown, Sparkles, UploadCloud, X, RefreshCw, Timer } from 'lucide-react';
import { useTranslation, type TranslateFn } from '../i18n/useTranslation';
import { useEventBranding } from '../context/EventBrandingContext';
import type { EventBranding } from '../types/event-branding';
@@ -25,6 +26,7 @@ import { getDeviceId } from '../lib/device';
import { useDirectUpload } from '../hooks/useDirectUpload';
import { useNavigate } from 'react-router-dom';
import { isTaskModeEnabled } from '../lib/engagement';
import { FADE_SCALE, FADE_UP, STAGGER_FAST, getMotionContainerProps, getMotionItemProps, prefersReducedMotion } from '../lib/motion';
export default function HomePage() {
const { token } = useParams<{ token: string }>();
@@ -74,6 +76,10 @@ export default function HomePage() {
const uploadsRequireApproval =
(event?.guest_upload_visibility as 'immediate' | 'review' | undefined) !== 'immediate';
const tasksEnabled = isTaskModeEnabled(event);
const motionEnabled = !prefersReducedMotion();
const containerMotion = getMotionContainerProps(motionEnabled, STAGGER_FAST);
const fadeUpMotion = getMotionItemProps(motionEnabled, FADE_UP);
const fadeScaleMotion = getMotionItemProps(motionEnabled, FADE_SCALE);
const [missionDeck, setMissionDeck] = React.useState<MissionPreview[]>([]);
const [missionPool, setMissionPool] = React.useState<MissionPreview[]>([]);
@@ -288,15 +294,19 @@ export default function HomePage() {
if (!tasksEnabled) {
return (
<div className="space-y-3 pb-24" style={bodyFont ? { fontFamily: bodyFont } : undefined}>
<section className="space-y-1 px-4" style={headingFont ? { fontFamily: headingFont } : undefined}>
<motion.div className="space-y-3 pb-24" style={bodyFont ? { fontFamily: bodyFont } : undefined} {...containerMotion}>
<motion.section
className="space-y-1 px-4"
style={headingFont ? { fontFamily: headingFont } : undefined}
{...fadeUpMotion}
>
<p className="text-sm font-semibold text-foreground">
{t('home.welcomeLine').replace('{name}', displayName)}
</p>
{introMessage && <p className="text-xs text-muted-foreground">{introMessage}</p>}
</section>
</motion.section>
<section className="space-y-2 px-4">
<motion.section className="space-y-2 px-4" {...fadeUpMotion}>
<UploadActionCard
token={token}
accentColor={accentColor}
@@ -305,18 +315,26 @@ export default function HomePage() {
bodyFont={bodyFont}
requiresApproval={uploadsRequireApproval}
/>
</section>
</motion.section>
<Separator />
<motion.div {...fadeUpMotion}>
<Separator />
</motion.div>
<GalleryPreview token={token} />
</div>
<motion.div {...fadeUpMotion}>
<GalleryPreview token={token} />
</motion.div>
</motion.div>
);
}
return (
<div className="space-y-0.5 pb-24" style={bodyFont ? { fontFamily: bodyFont } : undefined}>
<section className="space-y-1 px-4" style={headingFont ? { fontFamily: headingFont } : undefined}>
<motion.div className="space-y-0.5 pb-24" style={bodyFont ? { fontFamily: bodyFont } : undefined} {...containerMotion}>
<motion.section
className="space-y-1 px-4"
style={headingFont ? { fontFamily: headingFont } : undefined}
{...fadeUpMotion}
>
<p className="text-sm font-semibold text-foreground">
{t('home.welcomeLine').replace('{name}', displayName)}
</p>
@@ -325,22 +343,24 @@ export default function HomePage() {
{introMessage}
</p>
)}
</section>
</motion.section>
{heroVisible && (
<HeroCard
name={displayName}
eventName={eventNameDisplay}
tasksCompleted={completedCount}
t={t}
branding={branding}
onDismiss={dismissHero}
ctaLabel={t('home.actions.items.tasks.label')}
ctaHref={`/e/${encodeURIComponent(token)}/tasks`}
/>
<motion.div {...fadeScaleMotion}>
<HeroCard
name={displayName}
eventName={eventNameDisplay}
tasksCompleted={completedCount}
t={t}
branding={branding}
onDismiss={dismissHero}
ctaLabel={t('home.actions.items.tasks.label')}
ctaHref={`/e/${encodeURIComponent(token)}/tasks`}
/>
</motion.div>
)}
<section className="space-y-0.5" style={headingFont ? { fontFamily: headingFont } : undefined}>
<motion.section className="space-y-0.5" style={headingFont ? { fontFamily: headingFont } : undefined} {...fadeUpMotion}>
<div className="space-y-0.5">
<MissionActionCard
token={token}
@@ -349,6 +369,7 @@ export default function HomePage() {
onAdvance={advanceDeck}
stack={missionDeck.slice(1)}
initialIndex={poolIndexRef.current}
swipeHintLabel={t('home.swipeHint')}
onIndexChange={(idx, total) => {
poolIndexRef.current = idx % Math.max(1, total);
if (sliderStateKey && typeof window !== 'undefined') {
@@ -371,12 +392,16 @@ export default function HomePage() {
/>
<EmotionActionCard />
</div>
</section>
</motion.section>
<Separator />
<motion.div {...fadeUpMotion}>
<Separator />
</motion.div>
<GalleryPreview token={token} />
</div>
<motion.div {...fadeUpMotion}>
<GalleryPreview token={token} />
</motion.div>
</motion.div>
);
}
@@ -462,6 +487,7 @@ export function MissionActionCard({
initialIndex,
onIndexChange,
swiperRef,
swipeHintLabel,
}: {
token: string;
mission: MissionPreview | null;
@@ -471,6 +497,7 @@ export function MissionActionCard({
initialIndex: number;
onIndexChange: (index: number, total: number) => void;
swiperRef: React.MutableRefObject<any>;
swipeHintLabel?: string;
}) {
const { branding } = useEventBranding();
const radius = branding.buttons?.radius ?? 12;
@@ -486,6 +513,64 @@ export function MissionActionCard({
const lastSlideIndexRef = React.useRef<number>(initialIndex);
const titleRefs = React.useRef(new Map<number, HTMLParagraphElement | null>());
const [expandableTitles, setExpandableTitles] = React.useState<Record<number, boolean>>({});
const [showSwipeHint, setShowSwipeHint] = React.useState(false);
const hintTimeoutRef = React.useRef<number | null>(null);
const hintStorageKey = token ? `guestMissionSwipeHintSeen_${token}` : 'guestMissionSwipeHintSeen';
const motionEnabled = !prefersReducedMotion();
const shouldShowHint = motionEnabled && cards.length > 1 && Boolean(swipeHintLabel);
const dismissSwipeHint = React.useCallback((persist = true) => {
if (!showSwipeHint) {
return;
}
setShowSwipeHint(false);
if (hintTimeoutRef.current) {
window.clearTimeout(hintTimeoutRef.current);
hintTimeoutRef.current = null;
}
if (persist && typeof window !== 'undefined') {
try {
window.sessionStorage.setItem(hintStorageKey, '1');
} catch {
// ignore storage exceptions
}
}
}, [hintStorageKey, showSwipeHint]);
React.useEffect(() => {
if (!shouldShowHint) {
setShowSwipeHint(false);
return;
}
if (typeof window === 'undefined') {
return;
}
try {
if (window.sessionStorage.getItem(hintStorageKey)) {
setShowSwipeHint(false);
return;
}
} catch {
// ignore storage exceptions
}
setShowSwipeHint(true);
hintTimeoutRef.current = window.setTimeout(() => {
setShowSwipeHint(false);
try {
window.sessionStorage.setItem(hintStorageKey, '1');
} catch {
// ignore storage exceptions
}
}, 3200);
return () => {
if (hintTimeoutRef.current) {
window.clearTimeout(hintTimeoutRef.current);
hintTimeoutRef.current = null;
}
};
}, [hintStorageKey, shouldShowHint]);
const measureTitleOverflow = React.useCallback(() => {
setExpandableTitles((prev) => {
@@ -686,7 +771,10 @@ export function MissionActionCard({
type="button"
variant="secondary"
className="w-full border border-slate-200 bg-white/80 text-slate-800 shadow-sm backdrop-blur"
onClick={onAdvance}
onClick={() => {
dismissSwipeHint();
onAdvance();
}}
disabled={loading}
style={{
borderRadius: `${radius}px`,
@@ -708,6 +796,33 @@ export function MissionActionCard({
<Card className="border-0 bg-transparent py-2 shadow-none" style={{ fontFamily: bodyFont }}>
<CardContent className="px-0 py-0">
<div className="relative min-h-[240px] px-2 sm:min-h-[260px]" data-testid="mission-card-stack">
<AnimatePresence initial={false}>
{showSwipeHint ? (
<motion.div
className="pointer-events-none absolute inset-x-0 bottom-2 z-10 flex justify-center"
initial={{ opacity: 0, y: 6 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 6 }}
transition={{ duration: 0.2, ease: [0.22, 0.61, 0.36, 1] }}
>
<div className="flex items-center gap-2 rounded-full border border-white/40 bg-white/85 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-700 shadow-sm backdrop-blur">
<motion.span
animate={{ x: [-6, 0, -6] }}
transition={{ duration: 1.6, repeat: Infinity, ease: 'easeInOut' }}
>
<ArrowLeft className="h-3.5 w-3.5" aria-hidden />
</motion.span>
<span>{swipeHintLabel}</span>
<motion.span
animate={{ x: [6, 0, 6] }}
transition={{ duration: 1.6, repeat: Infinity, ease: 'easeInOut' }}
>
<ArrowRight className="h-3.5 w-3.5" aria-hidden />
</motion.span>
</div>
</motion.div>
) : null}
</AnimatePresence>
<Swiper
effect="cards"
modules={[EffectCards]}
@@ -731,6 +846,7 @@ export function MissionActionCard({
const realIndex = typeof instance.realIndex === 'number' ? instance.realIndex : instance.activeIndex ?? 0;
if (realIndex !== lastSlideIndexRef.current) {
setExpandedTaskId(null);
dismissSwipeHint();
}
lastSlideIndexRef.current = realIndex;
onIndexChange(realIndex, slides.length);

View File

@@ -7,6 +7,8 @@ import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { useTranslation } from '../i18n/useTranslation';
import { motion } from 'framer-motion';
import { FADE_SCALE, FADE_UP, STAGGER_FAST, getMotionContainerProps, getMotionItemProps, prefersReducedMotion } from '../lib/motion';
export default function ProfileSetupPage() {
const { token } = useParams<{ token: string }>();
@@ -16,6 +18,10 @@ export default function ProfileSetupPage() {
const [name, setName] = useState(storedName);
const [submitting, setSubmitting] = useState(false);
const { t } = useTranslation();
const motionEnabled = !prefersReducedMotion();
const containerMotion = getMotionContainerProps(motionEnabled, STAGGER_FAST);
const fadeUpMotion = getMotionItemProps(motionEnabled, FADE_UP);
const fadeScaleMotion = getMotionItemProps(motionEnabled, FADE_SCALE);
useEffect(() => {
if (!token) {
@@ -67,9 +73,10 @@ export default function ProfileSetupPage() {
}
return (
<div className="min-h-screen bg-gradient-to-b from-pink-50 to-purple-50 flex flex-col">
<div className="flex-1 flex flex-col justify-center items-center px-4 py-8">
<Card className="w-full max-w-md">
<motion.div className="min-h-screen bg-gradient-to-b from-pink-50 to-purple-50 flex flex-col" {...containerMotion}>
<motion.div className="flex-1 flex flex-col justify-center items-center px-4 py-8" {...fadeUpMotion}>
<motion.div {...fadeScaleMotion} className="w-full max-w-md">
<Card>
<CardHeader className="text-center space-y-2">
<CardTitle className="text-2xl font-bold text-gray-900">{event.name}</CardTitle>
<CardDescription className="text-lg text-gray-600">
@@ -97,8 +104,9 @@ export default function ProfileSetupPage() {
{submitting ? t('profileSetup.form.submitting') : t('profileSetup.form.submit')}
</Button>
</CardContent>
</Card>
</div>
</div>
</Card>
</motion.div>
</motion.div>
</motion.div>
);
}

View File

@@ -10,6 +10,7 @@ import { cn } from '@/lib/utils';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { useEventBranding } from '../context/EventBrandingContext';
import { useTranslation, type TranslateFn } from '../i18n/useTranslation';
import { motion } from 'framer-motion';
import {
getEmotionIcon,
getEmotionTheme,
@@ -17,6 +18,8 @@ import {
type EmotionTheme,
} from '../lib/emotionTheme';
import { getDeviceId } from '../lib/device';
import { FADE_SCALE, FADE_UP, STAGGER_FAST, getMotionContainerProps, getMotionItemProps, prefersReducedMotion } from '../lib/motion';
import PullToRefresh from '../components/PullToRefresh';
interface Task {
id: number;
@@ -243,6 +246,13 @@ export default function TaskPickerPage() {
fetchTasks();
};
const handleRefresh = React.useCallback(async () => {
tasksCacheRef.current.clear();
await fetchTasks();
setPhotoPool([]);
setPhotoPoolError(null);
}, [fetchTasks]);
const handlePhotoPreview = React.useCallback(
(photoId: number) => {
if (!eventKey) return;
@@ -354,6 +364,10 @@ export default function TaskPickerPage() {
[emotionOptions, recentEmotionSlug]
);
const toggleValue = selectedEmotion === 'all' ? 'none' : 'recent';
const motionEnabled = !prefersReducedMotion();
const containerMotion = getMotionContainerProps(motionEnabled, STAGGER_FAST);
const fadeUpMotion = getMotionItemProps(motionEnabled, FADE_UP);
const fadeScaleMotion = getMotionItemProps(motionEnabled, FADE_SCALE);
const handleToggleChange = React.useCallback(
(value: string) => {
@@ -379,211 +393,225 @@ export default function TaskPickerPage() {
return (
<>
<div className="space-y-6">
<header className="space-y-4">
<div className="space-y-1">
<p className="text-[11px] uppercase tracking-[0.4em] text-muted-foreground">{t('tasks.page.eyebrow')}</p>
<h1 className="text-2xl font-semibold text-foreground">{t('tasks.page.title')}</h1>
<p className="text-sm text-muted-foreground">{t('tasks.page.subtitle')}</p>
</div>
{emotionOptions.length > 0 && (
<div className="overflow-x-auto pb-1 [-ms-overflow-style:none] [scrollbar-width:none]">
<ToggleGroup
type="single"
aria-label="Stimmung filtern"
value={toggleValue}
onValueChange={handleToggleChange}
className="inline-flex gap-1 rounded-full bg-muted/60 p-1"
variant="outline"
size="sm"
>
<ToggleGroupItem
value="none"
className="rounded-full !rounded-full px-4 py-2 text-sm font-medium first:!rounded-full last:!rounded-full"
>
<span className="mr-2">🎲</span>
{t('tasks.page.filters.none')}
</ToggleGroupItem>
<ToggleGroupItem
value="recent"
disabled={!recentEmotionOption}
className="rounded-full !rounded-full px-4 py-2 text-sm font-medium first:!rounded-full last:!rounded-full"
>
<span className="mr-2">{getEmotionIcon(recentEmotionOption)}</span>
{recentEmotionOption?.name ?? t('tasks.page.filters.recentFallback')}
</ToggleGroupItem>
<ToggleGroupItem
value="picker"
className="rounded-full !rounded-full px-4 py-2 text-sm font-medium first:!rounded-full last:!rounded-full"
>
<span className="mr-2">🗂</span>
{t('tasks.page.filters.showAll')}
</ToggleGroupItem>
</ToggleGroup>
<PullToRefresh
onRefresh={handleRefresh}
pullLabel={t('common.pullToRefresh')}
releaseLabel={t('common.releaseToRefresh')}
refreshingLabel={t('common.refreshing')}
>
<motion.div className="space-y-6" {...containerMotion}>
<motion.header className="space-y-4" {...fadeUpMotion}>
<div className="space-y-1">
<p className="text-[11px] uppercase tracking-[0.4em] text-muted-foreground">{t('tasks.page.eyebrow')}</p>
<h1 className="text-2xl font-semibold text-foreground">{t('tasks.page.title')}</h1>
<p className="text-sm text-muted-foreground">{t('tasks.page.subtitle')}</p>
</div>
)}
</header>
{loading && (
<div className="space-y-4">
<SkeletonBlock />
<SkeletonBlock />
</div>
)}
{error && !loading && (
<Alert variant="destructive">
<AlertDescription className="flex items-center justify-between gap-3">
<span>{error}</span>
<Button variant="outline" size="sm" onClick={handleRetryFetch} disabled={isFetching}>
Erneut versuchen
</Button>
</AlertDescription>
</Alert>
)}
{emptyState && (
<EmptyState
hasTasks={Boolean(tasks.length)}
onRetry={handleRetryFetch}
emotionOptions={emotionOptions}
onEmotionSelect={handleSelectEmotion}
t={t}
/>
)}
{!emptyState && currentTask && (
<div className="space-y-8">
<section
ref={heroCardRef}
className={cn(
'relative overflow-hidden rounded-3xl p-5 text-white shadow-lg transition-[background] duration-700',
'bg-gradient-to-br',
heroTheme.gradientClass
)}
style={{ background: heroTheme.gradientBackground }}
>
<div className="relative space-y-5">
<div className="flex flex-wrap items-center justify-between gap-3 text-xs font-semibold uppercase tracking-[0.25em] text-white/70">
<span className="flex items-center gap-2 tracking-[0.3em]">
<Sparkles className="h-4 w-4" />
{heroEmotionIcon} {currentTask.emotion?.name ?? 'Neue Mission'}
</span>
<span className="flex items-center gap-1 text-white tracking-normal">
<TimerIcon className="h-4 w-4" />
{currentTask.duration} Min
</span>
</div>
<div className="space-y-3">
<h2 className="text-3xl font-semibold leading-tight drop-shadow-sm">{currentTask.title}</h2>
<p className="text-sm leading-relaxed text-white/80">{currentTask.description}</p>
</div>
{!hasSwiped && (
<p className="text-[11px] uppercase tracking-[0.4em] text-white/70">
{t('tasks.page.swipeHint')}
</p>
)}
{currentTask.instructions && (
<div className="rounded-2xl bg-white/15 p-3 text-sm font-medium text-white/90">
{currentTask.instructions}
</div>
)}
<div className="flex flex-wrap gap-2 text-sm text-white/80">
{isCompleted(currentTask.id) && (
<span className="rounded-full border border-white/30 px-3 py-1">
<CheckCircle2 className="mr-1 inline h-4 w-4" />
{t('tasks.page.completedLabel')}
</span>
)}
</div>
<div className="grid grid-cols-3 gap-3">
<Button
onClick={handleStartUpload}
className="col-span-2 flex h-14 items-center justify-center gap-2 rounded-2xl text-base font-semibold text-white shadow-lg shadow-black/10 transition hover:scale-[1.01]"
style={cameraButtonStyle}
{emotionOptions.length > 0 && (
<motion.div className="overflow-x-auto pb-1 [-ms-overflow-style:none] [scrollbar-width:none]" {...fadeUpMotion}>
<ToggleGroup
type="single"
aria-label="Stimmung filtern"
value={toggleValue}
onValueChange={handleToggleChange}
className="inline-flex gap-1 rounded-full bg-muted/60 p-1"
variant="outline"
size="sm"
>
<ToggleGroupItem
value="none"
className="rounded-full !rounded-full px-4 py-2 text-sm font-medium first:!rounded-full last:!rounded-full"
>
<Camera className="h-6 w-6" />
{t('tasks.page.ctaStart')}
</Button>
<HeroActionButton
icon={RefreshCw}
label={t('tasks.page.shuffleCta')}
onClick={handleNewTask}
className="h-12 justify-center px-3 py-2"
/>
</div>
<span className="mr-2">🎲</span>
{t('tasks.page.filters.none')}
</ToggleGroupItem>
<ToggleGroupItem
value="recent"
disabled={!recentEmotionOption}
className="rounded-full !rounded-full px-4 py-2 text-sm font-medium first:!rounded-full last:!rounded-full"
>
<span className="mr-2">{getEmotionIcon(recentEmotionOption)}</span>
{recentEmotionOption?.name ?? t('tasks.page.filters.recentFallback')}
</ToggleGroupItem>
<ToggleGroupItem
value="picker"
className="rounded-full !rounded-full px-4 py-2 text-sm font-medium first:!rounded-full last:!rounded-full"
>
<span className="mr-2">🗂</span>
{t('tasks.page.filters.showAll')}
</ToggleGroupItem>
</ToggleGroup>
</motion.div>
)}
</motion.header>
{(photoPoolLoading || photoPoolError || similarPhotos.length > 0) && (
<div className="space-y-2 rounded-2xl border border-white/25 bg-white/10 p-3">
<div className="flex items-center justify-between text-xs font-semibold uppercase tracking-[0.3em] text-white/70">
<span>{t('tasks.page.inspirationTitle')}</span>
{photoPoolLoading && <span className="text-[10px] text-white/70">{t('tasks.page.inspirationLoading')}</span>}
{loading && (
<motion.div className="space-y-4" {...fadeUpMotion}>
<SkeletonBlock />
<SkeletonBlock />
</motion.div>
)}
{error && !loading && (
<motion.div {...fadeUpMotion}>
<Alert variant="destructive">
<AlertDescription className="flex items-center justify-between gap-3">
<span>{error}</span>
<Button variant="outline" size="sm" onClick={handleRetryFetch} disabled={isFetching}>
Erneut versuchen
</Button>
</AlertDescription>
</Alert>
</motion.div>
)}
{emptyState && (
<motion.div {...fadeUpMotion}>
<EmptyState
hasTasks={Boolean(tasks.length)}
onRetry={handleRetryFetch}
emotionOptions={emotionOptions}
onEmotionSelect={handleSelectEmotion}
t={t}
/>
</motion.div>
)}
{!emptyState && currentTask && (
<motion.div className="space-y-8" {...fadeUpMotion}>
<motion.section
ref={heroCardRef}
className={cn(
'relative overflow-hidden rounded-3xl p-5 text-white shadow-lg transition-[background] duration-700',
'bg-gradient-to-br',
heroTheme.gradientClass
)}
style={{ background: heroTheme.gradientBackground }}
{...fadeScaleMotion}
>
<div className="relative space-y-5">
<div className="flex flex-wrap items-center justify-between gap-3 text-xs font-semibold uppercase tracking-[0.25em] text-white/70">
<span className="flex items-center gap-2 tracking-[0.3em]">
<Sparkles className="h-4 w-4" />
{heroEmotionIcon} {currentTask.emotion?.name ?? 'Neue Mission'}
</span>
<span className="flex items-center gap-1 text-white tracking-normal">
<TimerIcon className="h-4 w-4" />
{currentTask.duration} Min
</span>
</div>
<div className="space-y-3">
<h2 className="text-3xl font-semibold leading-tight drop-shadow-sm">{currentTask.title}</h2>
<p className="text-sm leading-relaxed text-white/80">{currentTask.description}</p>
</div>
{!hasSwiped && (
<p className="text-[11px] uppercase tracking-[0.4em] text-white/70">
{t('tasks.page.swipeHint')}
</p>
)}
{currentTask.instructions && (
<div className="rounded-2xl bg-white/15 p-3 text-sm font-medium text-white/90">
{currentTask.instructions}
</div>
{photoPoolError && similarPhotos.length === 0 ? (
<p className="text-xs text-white/80">{photoPoolError}</p>
) : similarPhotos.length > 0 ? (
<div className="flex gap-3 overflow-x-auto pb-2 [-ms-overflow-style:none] [scrollbar-width:none]">
{similarPhotos.map((photo) => (
<SimilarPhotoChip key={photo.id} photo={photo} onOpen={handlePhotoPreview} />
))}
<button
type="button"
onClick={handleViewSimilar}
className="flex h-16 min-w-[64px] flex-col items-center justify-center rounded-2xl border border-dashed border-white/40 px-3 text-center text-[11px] font-semibold uppercase tracking-[0.3em] text-white/80"
>
{t('tasks.page.inspirationMore')}
</button>
</div>
) : (
<button
type="button"
onClick={handleStartUpload}
className="flex items-center justify-between rounded-2xl border border-white/30 bg-white/10 px-4 py-3 text-sm text-white/80 transition hover:bg-white/20"
>
<div className="text-left">
<p className="font-semibold">{t('tasks.page.inspirationEmptyTitle')}</p>
<p className="text-xs text-white/70">{t('tasks.page.inspirationEmptyDescription')}</p>
</div>
<Camera className="h-4 w-4" />
</button>
)}
<div className="flex flex-wrap gap-2 text-sm text-white/80">
{isCompleted(currentTask.id) && (
<span className="rounded-full border border-white/30 px-3 py-1">
<CheckCircle2 className="mr-1 inline h-4 w-4" />
{t('tasks.page.completedLabel')}
</span>
)}
</div>
)}
</div>
</section>
{alternativeTasks.length > 0 && (
<section className="space-y-3">
<div className="flex items-center justify-between">
<div>
<p className="text-sm uppercase tracking-[0.2em] text-muted-foreground">{t('tasks.page.suggestionsEyebrow')}</p>
<h2 className="text-lg font-semibold text-foreground">{t('tasks.page.suggestionsTitle')}</h2>
<div className="grid grid-cols-3 gap-3">
<Button
onClick={handleStartUpload}
className="col-span-2 flex h-14 items-center justify-center gap-2 rounded-2xl text-base font-semibold text-white shadow-lg shadow-black/10 transition hover:scale-[1.01]"
style={cameraButtonStyle}
>
<Camera className="h-6 w-6" />
{t('tasks.page.ctaStart')}
</Button>
<HeroActionButton
icon={RefreshCw}
label={t('tasks.page.shuffleCta')}
onClick={handleNewTask}
className="h-12 justify-center px-3 py-2"
/>
</div>
<Button variant="outline" size="sm" onClick={handleNewTask} className="shrink-0">
{t('tasks.page.shuffleButton')}
</Button>
</div>
<div className="flex gap-3 overflow-x-auto pb-2 [-ms-overflow-style:none] [scrollbar-width:none]">
{alternativeTasks.map((task) => (
<TaskSuggestionCard key={task.id} task={task} onSelect={handleSelectTask} />
))}
</div>
</section>
)}
</div>
)}
{!loading && !tasks.length && !error && (
<Alert>
<AlertDescription>{t('tasks.page.noTasksAlert')}</AlertDescription>
</Alert>
)}
</div>
{(photoPoolLoading || photoPoolError || similarPhotos.length > 0) && (
<div className="space-y-2 rounded-2xl border border-white/25 bg-white/10 p-3">
<div className="flex items-center justify-between text-xs font-semibold uppercase tracking-[0.3em] text-white/70">
<span>{t('tasks.page.inspirationTitle')}</span>
{photoPoolLoading && <span className="text-[10px] text-white/70">{t('tasks.page.inspirationLoading')}</span>}
</div>
{photoPoolError && similarPhotos.length === 0 ? (
<p className="text-xs text-white/80">{photoPoolError}</p>
) : similarPhotos.length > 0 ? (
<div className="flex gap-3 overflow-x-auto pb-2 [-ms-overflow-style:none] [scrollbar-width:none]">
{similarPhotos.map((photo) => (
<SimilarPhotoChip key={photo.id} photo={photo} onOpen={handlePhotoPreview} />
))}
<button
type="button"
onClick={handleViewSimilar}
className="flex h-16 min-w-[64px] flex-col items-center justify-center rounded-2xl border border-dashed border-white/40 px-3 text-center text-[11px] font-semibold uppercase tracking-[0.3em] text-white/80"
>
{t('tasks.page.inspirationMore')}
</button>
</div>
) : (
<button
type="button"
onClick={handleStartUpload}
className="flex items-center justify-between rounded-2xl border border-white/30 bg-white/10 px-4 py-3 text-sm text-white/80 transition hover:bg-white/20"
>
<div className="text-left">
<p className="font-semibold">{t('tasks.page.inspirationEmptyTitle')}</p>
<p className="text-xs text-white/70">{t('tasks.page.inspirationEmptyDescription')}</p>
</div>
<Camera className="h-4 w-4" />
</button>
)}
</div>
)}
</div>
</motion.section>
{alternativeTasks.length > 0 && (
<motion.section className="space-y-3" {...fadeUpMotion}>
<div className="flex items-center justify-between">
<div>
<p className="text-sm uppercase tracking-[0.2em] text-muted-foreground">{t('tasks.page.suggestionsEyebrow')}</p>
<h2 className="text-lg font-semibold text-foreground">{t('tasks.page.suggestionsTitle')}</h2>
</div>
<Button variant="outline" size="sm" onClick={handleNewTask} className="shrink-0">
{t('tasks.page.shuffleButton')}
</Button>
</div>
<div className="flex gap-3 overflow-x-auto pb-2 [-ms-overflow-style:none] [scrollbar-width:none]">
{alternativeTasks.map((task) => (
<TaskSuggestionCard key={task.id} task={task} onSelect={handleSelectTask} />
))}
</div>
</motion.section>
)}
</motion.div>
)}
{!loading && !tasks.length && !error && (
<motion.div {...fadeUpMotion}>
<Alert>
<AlertDescription>{t('tasks.page.noTasksAlert')}</AlertDescription>
</Alert>
</motion.div>
)}
</motion.div>
</PullToRefresh>
<Dialog open={emotionPickerOpen} onOpenChange={setEmotionPickerOpen}>
<DialogContent className="max-h-[90vh] overflow-y-auto" hideClose>
<DialogHeader>

View File

@@ -4,6 +4,7 @@ import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { motion } from 'framer-motion';
import {
Dialog,
DialogContent,
@@ -38,6 +39,7 @@ import { resolveUploadErrorDialog, type UploadErrorDialog } from '../lib/uploadE
import { useEventStats } from '../context/EventStatsContext';
import { useEventBranding } from '../context/EventBrandingContext';
import { compressPhoto, formatBytes } from '../lib/image';
import { FADE_SCALE, FADE_UP, prefersReducedMotion } from '../lib/motion';
import { useGuestIdentity } from '../context/GuestIdentityContext';
import { useEventData } from '../hooks/useEventData';
import { isTaskModeEnabled } from '../lib/engagement';
@@ -147,6 +149,9 @@ export default function UploadPage() {
const uploadsRequireApproval =
(event?.guest_upload_visibility as 'immediate' | 'review' | undefined) !== 'immediate';
const demoReadOnly = Boolean(event?.demo_read_only);
const motionEnabled = !prefersReducedMotion();
const overlayMotion = motionEnabled ? { initial: 'hidden', animate: 'show', variants: FADE_SCALE } : {};
const fadeUpMotion = motionEnabled ? { initial: 'hidden', animate: 'show', variants: FADE_UP } : {};
const taskIdParam = searchParams.get('task');
const emotionSlug = searchParams.get('emotion') || '';
@@ -958,10 +963,11 @@ const [canUpload, setCanUpload] = useState(true);
}, [beginCapture, isCameraActive, startCamera]);
const taskFloatingCard = showTaskOverlay && task ? (
<button
<motion.button
type="button"
onClick={() => setTaskDetailsExpanded((prev) => !prev)}
className="absolute left-4 right-4 top-6 z-30 rounded-3xl border border-white/40 bg-black/60 p-4 text-left text-white shadow-2xl backdrop-blur transition hover:bg-black/70 focus:outline-none focus:ring-2 focus:ring-white/60 sm:left-6 sm:right-6 sm:top-8"
{...overlayMotion}
>
<div className="flex items-center gap-3">
<Badge variant="secondary" className="flex items-center gap-2 rounded-full text-[11px]">
@@ -1001,11 +1007,11 @@ const [canUpload, setCanUpload] = useState(true);
</div>
</div>
) : null}
</button>
</motion.button>
) : null;
const heroOverlay = !task && showHeroOverlay && mode !== 'uploading' ? (
<div className="absolute left-4 right-4 top-4 z-30 rounded-2xl border border-white/25 bg-black/60 px-4 py-3 text-white shadow-2xl backdrop-blur sm:left-6 sm:right-6 sm:top-5">
<motion.div className="absolute left-4 right-4 top-4 z-30 rounded-2xl border border-white/25 bg-black/60 px-4 py-3 text-white shadow-2xl backdrop-blur sm:left-6 sm:right-6 sm:top-5" {...fadeUpMotion}>
<div className="flex items-center justify-between gap-2">
<div className="space-y-1">
<p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-white/70">Bereit für dein Foto?</p>
@@ -1015,7 +1021,7 @@ const [canUpload, setCanUpload] = useState(true);
Live
</Badge>
</div>
</div>
</motion.div>
) : null;
const dialogToneIconClass: Record<Exclude<UploadErrorDialog['tone'], undefined>, string> = {
@@ -1079,7 +1085,10 @@ const renderWithDialog = (content: ReactNode, wrapperClassName = 'space-y-6 pb-[
const renderPrimer = () => (
showPrimer && (
<div className="rounded-[28px] border border-pink-200/60 bg-white/90 p-4 text-sm text-pink-900 shadow-lg dark:border-pink-500/40 dark:bg-pink-500/10 dark:text-pink-50">
<motion.div
className="rounded-[28px] border border-pink-200/60 bg-white/90 p-4 text-sm text-pink-900 shadow-lg dark:border-pink-500/40 dark:bg-pink-500/10 dark:text-pink-50"
{...fadeUpMotion}
>
<div className="flex items-start gap-3">
<Info className="mt-0.5 h-5 w-5 flex-shrink-0" />
<div className="text-left">
@@ -1093,7 +1102,7 @@ const renderWithDialog = (content: ReactNode, wrapperClassName = 'space-y-6 pb-[
{t('upload.primer.dismiss')}
</Button>
</div>
</div>
</motion.div>
)
);
@@ -1133,9 +1142,10 @@ const renderWithDialog = (content: ReactNode, wrapperClassName = 'space-y-6 pb-[
: null;
return (
<div
<motion.div
className="rounded-[32px] border border-white/15 bg-white/85 p-5 text-slate-900 shadow-lg dark:border-white/10 dark:bg-white/5 dark:text-white"
style={{ borderRadius: radius, fontFamily: bodyFont }}
{...fadeUpMotion}
>
<div className="flex items-center gap-3">
<div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-slate-900/10 dark:bg-white/10">
@@ -1179,7 +1189,7 @@ const renderWithDialog = (content: ReactNode, wrapperClassName = 'space-y-6 pb-[
{t('upload.galleryButton')}
</Button>
</div>
</div>
</motion.div>
);
};

View File

@@ -1,11 +1,18 @@
import React from 'react';
import { motion } from 'framer-motion';
import { FADE_UP, STAGGER_FAST, getMotionContainerProps, getMotionItemProps, prefersReducedMotion } from '../lib/motion';
export function Page({ title, children }: { title: string; children?: React.ReactNode }) {
const motionEnabled = !prefersReducedMotion();
const containerProps = getMotionContainerProps(motionEnabled, STAGGER_FAST);
const itemProps = getMotionItemProps(motionEnabled, FADE_UP);
return (
<div style={{ maxWidth: 720, margin: '0 auto', padding: 16 }}>
<h1 style={{ fontSize: 20, fontWeight: 600, marginBottom: 12 }}>{title}</h1>
<div>{children}</div>
</div>
<motion.div {...containerProps} style={{ maxWidth: 720, margin: '0 auto', padding: 16 }}>
<motion.h1 {...itemProps} style={{ fontSize: 20, fontWeight: 600, marginBottom: 12 }}>
{title}
</motion.h1>
<motion.div {...itemProps}>{children}</motion.div>
</motion.div>
);
}

View File

@@ -150,6 +150,18 @@ export function usePollGalleryDelta(token: string, locale: LocaleCode) {
};
}, [token, visible, locale, fetchDelta]);
const refreshNow = useCallback(async () => {
if (!token) {
return;
}
setLoading(true);
latestAt.current = null;
etagRef.current = null;
setNewCount(0);
setPhotos([]);
await fetchDelta();
}, [fetchDelta, token]);
function acknowledgeNew() { setNewCount(0); }
return { loading, photos, newCount, acknowledgeNew };
return { loading, photos, newCount, acknowledgeNew, refreshNow };
}

View File

@@ -1,8 +1,9 @@
import React from 'react';
import { Button } from '@/components/ui/button';
import { createBrowserRouter, Outlet, useParams, Link, Navigate } from 'react-router-dom';
import { createBrowserRouter, useParams, Link, Navigate } from 'react-router-dom';
import Header from './components/Header';
import BottomNav from './components/BottomNav';
import RouteTransition from './components/RouteTransition';
import { useEventData } from './hooks/useEventData';
import { AlertTriangle, Loader2 } from 'lucide-react';
import { EventStatsProvider } from './context/EventStatsContext';
@@ -44,7 +45,7 @@ function HomeLayout() {
<div className="pb-16">
<Header title="Event" />
<div className="px-4 py-3">
<Outlet />
<RouteTransition />
</div>
<BottomNav />
</div>
@@ -123,7 +124,7 @@ function EventBoundary({ token }: { token: string }) {
<div className="pb-16">
<Header eventToken={token} />
<div className="px-4 py-3">
<Outlet />
<RouteTransition />
</div>
<BottomNav />
</div>
@@ -164,7 +165,7 @@ function SetupLayout() {
<NotificationCenterProvider eventToken={token}>
<div className="pb-0">
<Header eventToken={token} />
<Outlet />
<RouteTransition />
</div>
</NotificationCenterProvider>
</EventStatsProvider>
@@ -325,7 +326,7 @@ function SimpleLayout({ title, children }: { title: string; children: React.Reac
<div className="pb-16">
<Header title={title} />
<div className="px-4 py-3">
{children}
<RouteTransition>{children}</RouteTransition>
</div>
<BottomNav />
</div>

View File

@@ -1,4 +1,5 @@
/// <reference types="vite/client" />
/// <reference types="vite-plugin-pwa/client" />
interface ImportMetaEnv {
readonly VITE_ENABLE_TENANT_SWITCHER?: string;

View File

@@ -6,6 +6,9 @@
<title>{{ config('app.name', 'Fotospiel') }}</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="icon" href="{{ asset('favicon.ico') }}" type="image/x-icon">
<link rel="manifest" href="{{ asset('guest.webmanifest') }}">
<link rel="apple-touch-icon" href="{{ asset('apple-touch-icon.png') }}">
<meta name="theme-color" content="#0f172a">
@viteReactRefresh
@vite(['resources/css/app.css', 'resources/js/guest/main.tsx'])
@php

View File

@@ -6,6 +6,7 @@ import { defineConfig, type PluginOption } from 'vite';
import path from 'path';
import { tamaguiPlugin } from '@tamagui/vite-plugin';
import { sentryVitePlugin } from '@sentry/vite-plugin';
import { VitePWA } from 'vite-plugin-pwa';
const devServerHost = process.env.VITE_DEV_SERVER_HOST ?? 'fotospiel-app.test';
const devServerPort = Number.parseInt(process.env.VITE_DEV_SERVER_PORT ?? '5173', 10);
@@ -36,6 +37,63 @@ const plugins: PluginOption[] = [
wayfinder({
formVariants: true,
}),
VitePWA({
strategies: 'injectManifest',
srcDir: 'resources/js/guest',
filename: 'guest-sw.ts',
manifestFilename: 'guest.webmanifest',
outDir: 'public',
injectRegister: null,
registerType: 'prompt',
includeAssets: [
'favicon.ico',
'favicon.svg',
'apple-touch-icon.png',
'logo-transparent-md.png',
'logo-transparent-lg.png',
],
injectManifest: {
globDirectory: 'public/build',
globPatterns: ['**/*.{js,css,woff,woff2,svg,png,webp,ico,txt}'],
},
manifest: {
name: 'Fotospiel',
short_name: 'Fotospiel',
id: '/event',
start_url: '/event',
scope: '/',
display: 'standalone',
lang: 'de-DE',
description: 'Offline-fähige Event-Galerie für Gäste Fotos aufnehmen, Aufgaben lösen und teilen.',
background_color: '#0f172a',
theme_color: '#ec4899',
orientation: 'portrait',
categories: ['photo-video', 'social'],
icons: [
{
src: '/favicon.svg',
sizes: 'any',
type: 'image/svg+xml',
purpose: 'any',
},
{
src: '/apple-touch-icon.png',
sizes: '166x169',
type: 'image/png',
purpose: 'any',
},
{
src: '/logo-transparent-lg.png',
sizes: '698x684',
type: 'image/png',
purpose: 'any',
},
],
},
devOptions: {
enabled: false,
},
}),
tamaguiPlugin({
config: './tamagui.config.ts',
components: ['@tamagui/core', '@tamagui/stacks', '@tamagui/text', '@tamagui/button'],