diff --git a/AGENTS.md b/AGENTS.md index a5dae84..81dd635 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -95,7 +95,7 @@ The Laravel Boost guidelines are specifically curated by Laravel maintainers for ## Foundational Context This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions. -- php - 8.3.6 +- php - 8.3.24 - filament/filament (FILAMENT) - v4 - inertiajs/inertia-laravel (INERTIA) - v2 - laravel/framework (LARAVEL) - v12 @@ -207,108 +207,20 @@ protected function isAccessible(User $user, ?string $path = null): bool - Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`. -=== filament/core rules === +=== herd rules === -## Filament -- Filament is used by this application, check how and where to follow existing application conventions. -- Filament is a Server-Driven UI (SDUI) framework for Laravel. It allows developers to define user interfaces in PHP using structured configuration objects. It is built on top of Livewire, Alpine.js, and Tailwind CSS. -- You can use the `search-docs` tool to get information from the official Filament documentation when needed. This is very useful for Artisan command arguments, specific code examples, testing functionality, relationship management, and ensuring you're following idiomatic practices. -- Utilize static `make()` methods for consistent component initialization. +## Laravel Herd -### Artisan -- You must use the Filament specific Artisan commands to create new files or components for Filament. You can find these with the `list-artisan-commands` tool, or with `php artisan` and the `--help` option. -- Inspect the required options, always pass `--no-interaction`, and valid arguments for other options when applicable. - -### Filament's Core Features -- Actions: Handle doing something within the application, often with a button or link. Actions encapsulate the UI, the interactive modal window, and the logic that should be executed when the modal window is submitted. They can be used anywhere in the UI and are commonly used to perform one-time actions like deleting a record, sending an email, or updating data in the database based on modal form input. -- Forms: Dynamic forms rendered within other features, such as resources, action modals, table filters, and more. -- Infolists: Read-only lists of data. -- Notifications: Flash notifications displayed to users within the application. -- Panels: The top-level container in Filament that can include all other features like pages, resources, forms, tables, notifications, actions, infolists, and widgets. -- Resources: Static classes that are used to build CRUD interfaces for Eloquent models. Typically live in `app/Filament/Resources`. -- Schemas: Represent components that define the structure and behavior of the UI, such as forms, tables, or lists. -- Tables: Interactive tables with filtering, sorting, pagination, and more. -- Widgets: Small component included within dashboards, often used for displaying data in charts, tables, or as a stat. - -### Relationships -- Determine if you can use the `relationship()` method on form components when you need `options` for a select, checkbox, repeater, or when building a `Fieldset`: - - -Forms\Components\Select::make('user_id') - ->label('Author') - ->relationship('author') - ->required(), - +- The application is served by Laravel Herd and will be available at: https?://[kebab-case-project-dir].test. Use the `get-absolute-url` tool to generate URLs for the user to ensure valid URLs. +- You must not run any commands to make the site available via HTTP(s). It is _always_ available through Laravel Herd. -## Testing -- It's important to test Filament functionality for user satisfaction. -- Ensure that you are authenticated to access the application within the test. -- Filament uses Livewire, so start assertions with `livewire()` or `Livewire::test()`. +=== tests rules === -### Example Tests +## Test Enforcement - - livewire(ListUsers::class) - ->assertCanSeeTableRecords($users) - ->searchTable($users->first()->name) - ->assertCanSeeTableRecords($users->take(1)) - ->assertCanNotSeeTableRecords($users->skip(1)) - ->searchTable($users->last()->email) - ->assertCanSeeTableRecords($users->take(-1)) - ->assertCanNotSeeTableRecords($users->take($users->count() - 1)); - - - - livewire(CreateUser::class) - ->fillForm([ - 'name' => 'Howdy', - 'email' => 'howdy@example.com', - ]) - ->call('create') - ->assertNotified() - ->assertRedirect(); - - assertDatabaseHas(User::class, [ - 'name' => 'Howdy', - 'email' => 'howdy@example.com', - ]); - - - - use Filament\Facades\Filament; - - Filament::setCurrentPanel('app'); - - - - livewire(EditInvoice::class, [ - 'invoice' => $invoice, - ])->callAction('send'); - - expect($invoice->refresh())->isSent()->toBeTrue(); - - - -=== filament/v4 rules === - -## Filament 4 - -### Important Version 4 Changes -- File visibility is now `private` by default. -- The `deferFilters` method from Filament v3 is now the default behavior in Filament v4, so users must click a button before the filters are applied to the table. To disable this behavior, you can use the `deferFilters(false)` method. -- The `Grid`, `Section`, and `Fieldset` layout components no longer span all columns by default. -- The `all` pagination page method is not available for tables by default. -- All action classes extend `Filament\Actions\Action`. No action classes exist in `Filament\Tables\Actions`. -- The `Form` & `Infolist` layout components have been moved to `Filament\Schemas\Components`, for example `Grid`, `Section`, `Fieldset`, `Tabs`, `Wizard`, etc. -- A new `Repeater` component for Forms has been added. -- Icons now use the `Filament\Support\Icons\Heroicon` Enum by default. Other options are available and documented. - -### Organize Component Classes Structure -- Schema components: `Schemas/Components/` -- Table columns: `Tables/Columns/` -- Table filters: `Tables/Filters/` -- Actions: `Actions/` +- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass. +- Run the minimum number of tests needed to ensure code quality and speed. Use `php artisan test` with a specific filename or filter. === inertia-laravel/core rules === @@ -356,7 +268,7 @@ Route::get('/users', function () { ## Do Things the Laravel Way - Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool. -- If you're creating a generic PHP class, use `artisan make:class`. +- If you're creating a generic PHP class, use `php artisan make:class`. - Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior. ### Database @@ -391,7 +303,7 @@ Route::get('/users', function () { ### Testing - When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model. - Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`. -- When creating tests, make use of `php artisan make:test [options] ` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests. +- When creating tests, make use of `php artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests. ### Vite Error - If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `npm run build` or ask the user to run `npm run dev` or `composer run dev`. @@ -421,6 +333,60 @@ Route::get('/users', function () { - Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models. +=== wayfinder/core rules === + +## Laravel Wayfinder + +Wayfinder generates TypeScript functions and types for Laravel controllers and routes which you can import into your client side code. It provides type safety and automatic synchronization between backend routes and frontend code. + +### Development Guidelines +- Always use `search-docs` to check wayfinder correct usage before implementing any features. +- Always Prefer named imports for tree-shaking (e.g., `import { show } from '@/actions/...'`) +- Avoid default controller imports (prevents tree-shaking) +- Run `php artisan wayfinder:generate` after route changes if Vite plugin isn't installed + +### Feature Overview +- Form Support: Use `.form()` with `--with-form` flag for HTML form attributes — `
` → `action="/posts" method="post"` +- HTTP Methods: Call `.get()`, `.post()`, `.patch()`, `.put()`, `.delete()` for specific methods — `show.head(1)` → `{ url: "/posts/1", method: "head" }` +- Invokable Controllers: Import and invoke directly as functions. For example, `import StorePost from '@/actions/.../StorePostController'; StorePost()` +- Named Routes: Import from `@/routes/` for non-controller routes. For example, `import { show } from '@/routes/post'; show(1)` for route name `post.show` +- Parameter Binding: Detects route keys (e.g., `{post:slug}`) and accepts matching object properties — `show("my-post")` or `show({ slug: "my-post" })` +- Query Merging: Use `mergeQuery` to merge with `window.location.search`, set values to `null` to remove — `show(1, { mergeQuery: { page: 2, sort: null } })` +- Query Parameters: Pass `{ query: {...} }` in options to append params — `show(1, { query: { page: 1 } })` → `"/posts/1?page=1"` +- Route Objects: Functions return `{ url, method }` shaped objects — `show(1)` → `{ url: "/posts/1", method: "get" }` +- URL Extraction: Use `.url()` to get URL string — `show.url(1)` → `"/posts/1"` + +### Example Usage + + + // Import controller methods (tree-shakable) + import { show, store, update } from '@/actions/App/Http/Controllers/PostController' + + // Get route object with URL and method... + show(1) // { url: "/posts/1", method: "get" } + + // Get just the URL... + show.url(1) // "/posts/1" + + // Use specific HTTP methods... + show.get(1) // { url: "/posts/1", method: "get" } + show.head(1) // { url: "/posts/1", method: "head" } + + // Import named routes... + import { show as postShow } from '@/routes/post' // For route name 'post.show' + postShow(1) // { url: "/posts/1", method: "get" } + + + +### Wayfinder + Inertia +If your application uses the `` component from Inertia, you can use Wayfinder to generate form action and method automatically. + + + + +
+ + === livewire/core rules === ## Livewire Core @@ -516,7 +482,7 @@ document.addEventListener('livewire:init', function () { ## PHPUnit Core -- This application uses PHPUnit for testing. All tests must be written as PHPUnit classes. Use `php artisan make:test --phpunit ` to create a new test. +- This application uses PHPUnit for testing. All tests must be written as PHPUnit classes. Use `php artisan make:test --phpunit {name}` to create a new test. - If you see a test using "Pest", convert it to PHPUnit. - Every time a test has been updated, run that singular test. - When the tests relating to your feature are passing, ask the user if they would like to also run the entire test suite to make sure everything is still passing. @@ -613,6 +579,13 @@ export default () => ( - Always use Tailwind CSS v4 - do not use the deprecated utilities. - `corePlugins` is not supported in Tailwind v4. +- In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed. + +@theme { + --color-brand: oklch(0.72 0.11 178); +} + + - In Tailwind v4, you import Tailwind using a regular CSS `@import` statement, not using the `@tailwind` directives used in v3: @@ -640,12 +613,4 @@ export default () => ( | overflow-ellipsis | text-ellipsis | | decoration-slice | box-decoration-slice | | decoration-clone | box-decoration-clone | - - -=== tests rules === - -## Test Enforcement - -- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass. -- Run the minimum number of tests needed to ensure code quality and speed. Use `php artisan test` with a specific filename or filter. diff --git a/app/Support/JoinTokenLayoutRegistry.php b/app/Support/JoinTokenLayoutRegistry.php index dbcc69c..e34b51a 100644 --- a/app/Support/JoinTokenLayoutRegistry.php +++ b/app/Support/JoinTokenLayoutRegistry.php @@ -6,6 +6,30 @@ use App\Models\InviteLayout; class JoinTokenLayoutRegistry { + private const DEFAULT_DESCRIPTION = 'Helft uns, diesen besonderen Tag mit euren schönen Momenten festzuhalten.'; + + private const DEFAULT_INSTRUCTIONS = [ + 'QR-Code scannen'."\n".'Kamera-App öffnen und auf den Code richten.', + 'Webseite öffnen'."\n".'Der Link öffnet direkt das gemeinsame Jubiläumsalbum.', + 'Fotos hochladen'."\n".'Zeigt eure Lieblingsmomente oder erfüllt kleine Fotoaufgaben, um besondere Erinnerungen beizusteuern.', + ]; + + private const SLOTS_PORTRAIT = [ + 'headline' => ['x' => 0.08, 'y' => 0.1, 'w' => 0.84, 'h' => 0.12, 'fontSize' => 30, 'fontWeight' => 800, 'align' => 'center'], + 'subtitle' => ['x' => 0.1, 'y' => 0.13, 'w' => 0.8, 'h' => 0.08, 'fontSize' => 18, 'fontWeight' => 600, 'align' => 'center'], + 'description' => ['x' => 0.1, 'y' => 0.18, 'w' => 0.8, 'h' => 0.12, 'fontSize' => 16, 'lineHeight' => 1.4, 'align' => 'center'], + 'qr' => ['x' => 0.35, 'y' => 0.4, 'w' => 0.3, 'h' => 0.3], + 'instructions' => ['x' => 0.12, 'y' => 0.72, 'w' => 0.76, 'h' => 0.16, 'fontSize' => 12, 'lineHeight' => 1.3, 'align' => 'center'], + ]; + + private const SLOTS_FOLDABLE = [ + 'headline' => ['x' => 0.1, 'y' => 0.1, 'w' => 0.8, 'h' => 0.12, 'fontSize' => 28, 'fontWeight' => 800, 'align' => 'center'], + 'subtitle' => ['x' => 0.12, 'y' => 0.18, 'w' => 0.76, 'h' => 0.08, 'fontSize' => 18, 'fontWeight' => 600, 'align' => 'center'], + 'description' => ['x' => 0.12, 'y' => 0.24, 'w' => 0.76, 'h' => 0.12, 'fontSize' => 15, 'lineHeight' => 1.4, 'align' => 'center'], + 'qr' => ['x' => 0.36, 'y' => 0.4, 'w' => 0.28, 'h' => 0.28], + 'instructions' => ['x' => 0.14, 'y' => 0.72, 'w' => 0.72, 'h' => 0.16, 'fontSize' => 12, 'lineHeight' => 1.3, 'align' => 'center'], + ]; + /** * Layout definitions for printable invite cards. * @@ -16,15 +40,17 @@ class JoinTokenLayoutRegistry 'id' => 'foldable-table-a5', 'name' => 'Foldable Table Card (A5)', 'subtitle' => 'Doppelseitige Tischkarte zum Falten – QR vorn & hinten.', - 'description' => 'Zwei identische Hälften auf A4 quer, rechte Seite gespiegelt für sauberes Falten.', - 'paper' => 'a4', - 'orientation' => 'landscape', - 'panel_mode' => 'double-mirror', - 'container_padding_px' => 28, - 'background' => '#F8FAFC', - 'background_gradient' => [ - 'angle' => 180, - 'stops' => ['#F8FAFC', '#EEF2FF', '#F8FAFC'], + 'description' => self::DEFAULT_DESCRIPTION, + 'paper' => 'a4', + 'orientation' => 'landscape', + 'panel_mode' => 'double-mirror', + 'format_hint' => 'foldable-a5', + 'slots' => self::SLOTS_FOLDABLE, + 'container_padding_px' => 28, + 'background' => '#F8FAFC', + 'background_gradient' => [ + 'angle' => 180, + 'stops' => ['#F8FAFC', '#EEF2FF', '#F8FAFC'], ], 'text' => '#0F172A', 'accent' => '#2563EB', @@ -38,25 +64,22 @@ class JoinTokenLayoutRegistry 'link_label' => 'fotospiel.app/DEINCODE', 'qr' => ['size_px' => 520], 'svg' => ['width' => 1754, 'height' => 1240], - 'instructions' => [ - 'QR-Code scannen oder Kurzlink öffnen.', - 'Anzeigenamen wählen – kein Account nötig.', - 'Fotos hochladen, liken & kommentieren.', - 'Challenges spielen und Punkte sammeln.', - ], + 'instructions' => self::DEFAULT_INSTRUCTIONS, ], 'evergreen-vows' => [ 'id' => 'evergreen-vows', 'name' => 'Evergreen Vows', 'subtitle' => 'Romantische Einladung für Trauung & Empfang.', - 'description' => 'Weiche Pastelltöne, florale Akzente und viel Raum für eine herzliche Begrüßung.', - 'paper' => 'a4', - 'orientation' => 'portrait', - 'background' => '#FBF7F2', - 'background_gradient' => [ - 'angle' => 165, - 'stops' => ['#FBF7F2', '#FDECEF', '#F4F0FF'], - ], + 'description' => self::DEFAULT_DESCRIPTION, + 'paper' => 'a4', + 'orientation' => 'portrait', + 'format_hint' => 'poster-a4', + 'slots' => self::SLOTS_PORTRAIT, + 'background' => '#FBF7F2', + 'background_gradient' => [ + 'angle' => 165, + 'stops' => ['#FBF7F2', '#FDECEF', '#F4F0FF'], + ], 'text' => '#2C1A27', 'accent' => '#B85C76', 'secondary' => '#E7D6DC', @@ -69,26 +92,22 @@ class JoinTokenLayoutRegistry 'cta_caption' => 'Sofort starten', 'qr' => ['size_px' => 640], 'svg' => ['width' => 1240, 'height' => 1754], - 'instructions' => [ - 'QR-Code scannen oder fotospiel.app/DEINCODE eingeben.', - 'Anzeigenamen wählen – kein Account nötig.', - 'Fotos hochladen und Aufgaben erfüllen, so oft ihr wollt.', - 'Highlights liken, Kommentare und Grüße dalassen.', - 'Datenschutz ready: anonyme Sessions, keine App-Installation.', - ], + 'instructions' => self::DEFAULT_INSTRUCTIONS, ], 'midnight-gala' => [ 'id' => 'midnight-gala', 'name' => 'Midnight Gala', 'subtitle' => 'Eleganter Auftritt für Corporate Events & Galas.', - 'description' => 'Dunkle Bühne mit goldenen Akzenten und kräftiger Typografie.', - 'paper' => 'a4', - 'orientation' => 'portrait', - 'background' => '#0B132B', - 'background_gradient' => [ - 'angle' => 200, - 'stops' => ['#0B132B', '#1C2541', '#274690'], - ], + 'description' => self::DEFAULT_DESCRIPTION, + 'paper' => 'a4', + 'orientation' => 'portrait', + 'format_hint' => 'poster-a4', + 'slots' => self::SLOTS_PORTRAIT, + 'background' => '#0B132B', + 'background_gradient' => [ + 'angle' => 200, + 'stops' => ['#0B132B', '#1C2541', '#274690'], + ], 'text' => '#F8FAFC', 'accent' => '#F9C74F', 'secondary' => '#4E5D8F', @@ -101,26 +120,22 @@ class JoinTokenLayoutRegistry 'cta_caption' => 'Keine App nötig', 'qr' => ['size_px' => 640], 'svg' => ['width' => 1240, 'height' => 1754], - 'instructions' => [ - 'QR-Code scannen oder fotospiel.app/DEINCODE eingeben.', - 'Anzeigenamen wählen – kein Account nötig.', - 'Fotos hochladen und Aufgaben erfüllen, so oft ihr wollt.', - 'Highlights liken, Kommentare und Grüße dalassen.', - 'Datenschutz ready: anonyme Sessions, keine App-Installation.', - ], + 'instructions' => self::DEFAULT_INSTRUCTIONS, ], 'garden-brunch' => [ 'id' => 'garden-brunch', 'name' => 'Garden Brunch', 'subtitle' => 'Luftiges Layout für Tages-Events & Familienfeiern.', - 'description' => 'Sanfte Grüntöne, natürliche Formen und Platz für Hinweise.', - 'paper' => 'a4', - 'orientation' => 'portrait', - 'background' => '#F6F9F4', - 'background_gradient' => [ - 'angle' => 120, - 'stops' => ['#F6F9F4', '#EEF5E7', '#F8FAF0'], - ], + 'description' => self::DEFAULT_DESCRIPTION, + 'paper' => 'a4', + 'orientation' => 'portrait', + 'format_hint' => 'poster-a4', + 'slots' => self::SLOTS_PORTRAIT, + 'background' => '#F6F9F4', + 'background_gradient' => [ + 'angle' => 120, + 'stops' => ['#F6F9F4', '#EEF5E7', '#F8FAF0'], + ], 'text' => '#2F4030', 'accent' => '#6BAA75', 'secondary' => '#DDE9D8', @@ -133,26 +148,22 @@ class JoinTokenLayoutRegistry 'cta_caption' => 'Los geht’s', 'qr' => ['size_px' => 660], 'svg' => ['width' => 1240, 'height' => 1754], - 'instructions' => [ - 'QR-Code scannen oder fotospiel.app/DEINCODE eingeben.', - 'Anzeigenamen wählen – kein Account nötig.', - 'Fotos hochladen und Aufgaben erfüllen, so oft ihr wollt.', - 'Highlights liken, Kommentare und Grüße dalassen.', - 'Datenschutz ready: anonyme Sessions, keine App-Installation.', - ], + 'instructions' => self::DEFAULT_INSTRUCTIONS, ], 'sparkler-soiree' => [ 'id' => 'sparkler-soiree', 'name' => 'Sparkler Soirée', 'subtitle' => 'Abendliches Layout mit funkelndem Verlauf.', - 'description' => 'Dynamische Typografie mit zentralem Fokus auf dem QR-Code.', - 'paper' => 'a4', - 'orientation' => 'portrait', - 'background' => '#1B1A44', - 'background_gradient' => [ - 'angle' => 205, - 'stops' => ['#1B1A44', '#42275A', '#734B8F'], - ], + 'description' => self::DEFAULT_DESCRIPTION, + 'paper' => 'a4', + 'orientation' => 'portrait', + 'format_hint' => 'poster-a4', + 'slots' => self::SLOTS_PORTRAIT, + 'background' => '#1B1A44', + 'background_gradient' => [ + 'angle' => 205, + 'stops' => ['#1B1A44', '#42275A', '#734B8F'], + ], 'text' => '#FDF7FF', 'accent' => '#F9A826', 'secondary' => '#DDB7FF', @@ -165,26 +176,22 @@ class JoinTokenLayoutRegistry 'cta_caption' => 'Challenges spielen', 'qr' => ['size_px' => 680], 'svg' => ['width' => 1240, 'height' => 1754], - 'instructions' => [ - 'QR-Code scannen oder fotospiel.app/DEINCODE eingeben.', - 'Anzeigenamen wählen – kein Account nötig.', - 'Fotos hochladen und Aufgaben erfüllen, so oft ihr wollt.', - 'Highlights liken, Kommentare und Grüße dalassen.', - 'Datenschutz ready: anonyme Sessions, keine App-Installation.', - ], + 'instructions' => self::DEFAULT_INSTRUCTIONS, ], 'confetti-bash' => [ 'id' => 'confetti-bash', 'name' => 'Confetti Bash', 'subtitle' => 'Verspielter Look für Geburtstage & Jubiläen.', - 'description' => 'Konfetti-Sprenkel, fröhliche Farben und viel Platz für Hinweise.', - 'paper' => 'a4', - 'orientation' => 'portrait', - 'background' => '#FFF9F0', - 'background_gradient' => [ - 'angle' => 145, - 'stops' => ['#FFF9F0', '#FFEFEF', '#FFF5D6'], - ], + 'description' => self::DEFAULT_DESCRIPTION, + 'paper' => 'a4', + 'orientation' => 'portrait', + 'format_hint' => 'poster-a4', + 'slots' => self::SLOTS_PORTRAIT, + 'background' => '#FFF9F0', + 'background_gradient' => [ + 'angle' => 145, + 'stops' => ['#FFF9F0', '#FFEFEF', '#FFF5D6'], + ], 'text' => '#31291F', 'accent' => '#FF6F61', 'secondary' => '#F9D6A5', @@ -197,13 +204,7 @@ class JoinTokenLayoutRegistry 'cta_caption' => 'Likes vergeben', 'qr' => ['size_px' => 680], 'svg' => ['width' => 1240, 'height' => 1754], - 'instructions' => [ - 'QR-Code scannen oder fotospiel.app/DEINCODE eingeben.', - 'Anzeigenamen wählen – kein Account nötig.', - 'Fotos hochladen und Aufgaben erfüllen, so oft ihr wollt.', - 'Highlights liken, Kommentare und Grüße dalassen.', - 'Datenschutz ready: anonyme Sessions, keine App-Installation.', - ], + 'instructions' => self::DEFAULT_INSTRUCTIONS, ], ]; @@ -280,7 +281,7 @@ class JoinTokenLayoutRegistry 'height' => 1754, ], 'background_gradient' => null, - 'instructions' => [], + 'instructions' => self::DEFAULT_INSTRUCTIONS, 'formats' => ['pdf', 'png'], ]; @@ -308,11 +309,22 @@ class JoinTokenLayoutRegistry return $normalized; } + private static function defaultSlotsPortrait(): array + { + return self::SLOTS_PORTRAIT; + } + + private static function defaultSlotsFoldable(): array + { + return self::SLOTS_FOLDABLE; + } + private static function fromModel(InviteLayout $layout): array { $preview = $layout->preview ?? []; $options = $layout->layout_options ?? []; $instructions = $layout->instructions ?? []; + $slots = $options['slots'] ?? null; return array_filter([ 'id' => $layout->slug, @@ -321,6 +333,7 @@ class JoinTokenLayoutRegistry 'description' => $layout->description, 'paper' => $layout->paper, 'orientation' => $layout->orientation, + 'format_hint' => self::resolveFormatHint($layout->paper, $layout->orientation, $layout->panel_mode), 'background' => $preview['background'] ?? null, 'background_gradient' => $preview['background_gradient'] ?? null, 'text' => $preview['text'] ?? null, @@ -334,6 +347,7 @@ class JoinTokenLayoutRegistry 'cta_caption' => $options['cta_caption'] ?? null, 'link_label' => $options['link_label'] ?? null, 'logo_url' => $options['logo_url'] ?? null, + 'slots' => is_array($slots) ? $slots : null, 'qr' => array_filter([ 'size_px' => $preview['qr']['size_px'] ?? $options['qr']['size_px'] ?? $preview['qr_size_px'] ?? $options['qr_size_px'] ?? null, ]), @@ -346,6 +360,23 @@ class JoinTokenLayoutRegistry ], fn ($value) => $value !== null && $value !== []); } + private static function resolveFormatHint(?string $paper, ?string $orientation, ?string $panelMode): ?string + { + $paperVal = strtolower((string) $paper); + $orientationVal = strtolower((string) $orientation); + $panelVal = strtolower((string) $panelMode); + + if ($paperVal === 'a4' && $orientationVal === 'portrait' && $panelVal !== 'double-mirror') { + return 'poster-a4'; + } + + if ($paperVal === 'a4' && $orientationVal === 'landscape' && $panelVal === 'double-mirror') { + return 'foldable-a5'; + } + + return null; + } + /** * Map layouts into an API-ready response structure, attaching URLs. * @@ -365,18 +396,23 @@ class JoinTokenLayoutRegistry 'paper' => $layout['paper'] ?? 'a4', 'orientation' => $layout['orientation'] ?? 'portrait', 'panel_mode' => $layout['panel_mode'] ?? null, + 'format_hint' => $layout['format_hint'] ?? self::resolveFormatHint($layout['paper'] ?? null, $layout['orientation'] ?? null, $layout['panel_mode'] ?? null), 'badge_label' => $layout['badge_label'] ?? null, 'instructions_heading' => $layout['instructions_heading'] ?? null, 'link_heading' => $layout['link_heading'] ?? null, 'cta_label' => $layout['cta_label'] ?? null, 'cta_caption' => $layout['cta_caption'] ?? null, 'instructions' => $layout['instructions'] ?? [], + 'slots' => $layout['slots'] ?? null, 'preview' => [ 'background' => $layout['background'], 'background_gradient' => $layout['background_gradient'], 'accent' => $layout['accent'], 'text' => $layout['text'], 'qr_size_px' => $layout['qr']['size_px'] ?? null, + 'aspect_ratio' => isset($layout['svg']['width'], $layout['svg']['height']) && $layout['svg']['width'] && $layout['svg']['height'] + ? (float) $layout['svg']['width'] / (float) $layout['svg']['height'] + : null, ], 'formats' => $formats, 'download_urls' => collect($formats) diff --git a/resources/js/admin/mobile/QrLayoutCustomizePage.tsx b/resources/js/admin/mobile/QrLayoutCustomizePage.tsx new file mode 100644 index 0000000..8ba2ae8 --- /dev/null +++ b/resources/js/admin/mobile/QrLayoutCustomizePage.tsx @@ -0,0 +1,1246 @@ +import React from 'react'; +import { useNavigate, useParams, useSearchParams } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; +import { ArrowLeft, RefreshCcw, Plus } from 'lucide-react'; +import { YStack, XStack } from '@tamagui/stacks'; +import { SizableText as Text } from '@tamagui/text'; +import { Pressable } from '@tamagui/react-native-web-lite'; +import { Input, TextArea } from 'tamagui'; +import type { fabric as FabricNS } from 'fabric'; +import { MobileShell } from './components/MobileShell'; +import { MobileCard, CTAButton, PillBadge } from './components/Primitives'; +import { + TenantEvent, + EventQrInvite, + EventQrInviteLayout, + getEvent, + getEventQrInvites, + updateEventQrInvite, +} from '../api'; +import { isAuthError } from '../auth/tokens'; +import { getApiErrorMessage } from '../lib/apiError'; +import toast from 'react-hot-toast'; +import { + generatePdfBytes, + generatePngDataUrl, + triggerDownloadFromBlob, + triggerDownloadFromDataUrl, +} from '../pages/components/invite-layout/export-utils'; +import { LayoutElement, CANVAS_WIDTH, CANVAS_HEIGHT } from '../pages/components/invite-layout/schema'; + +type Step = 'background' | 'text' | 'preview'; + +const BACKGROUND_PRESETS = [ + { id: 'bg-blue-floral', src: '/storage/layouts/backgrounds-portrait/bg-blue-floral.png', label: 'Blue Floral' }, + { id: 'bg-goldframe', src: '/storage/layouts/backgrounds-portrait/bg-goldframe.png', label: 'Gold Frame' }, + { id: 'gr-green-floral', src: '/storage/layouts/backgrounds-portrait/gr-green-floral.png', label: 'Green Floral' }, +]; + +export function buildInitialTextFields({ + customization, + layoutDefaults, + eventName, +}: { + customization: Record | null | undefined; + layoutDefaults: EventQrInviteLayout | null | undefined; + eventName?: string | null; +}): { headline: string; subtitle: string; description: string; instructions: string[] } { + const initialInstructions = + Array.isArray(customization?.instructions) && customization.instructions.length + ? customization.instructions + .map((item: unknown) => String(item ?? '')) + .filter((item: string) => item.length > 0) + : [ + 'QR-Code scannen\nKamera-App öffnen und auf den Code richten.', + 'Webseite öffnen\nDer Link öffnet direkt das gemeinsame Jubiläumsalbum.', + 'Fotos hochladen\nZeigt eure Lieblingsmomente oder erfüllt kleine Fotoaufgaben, um besondere Erinnerungen beizusteuern.', + ]; + + return { + headline: + (typeof customization?.headline === 'string' && customization.headline.length ? customization.headline : null) ?? + (typeof eventName === 'string' && eventName.length ? eventName : null) ?? + (typeof layoutDefaults?.name === 'string' ? layoutDefaults.name : '') ?? + '', + subtitle: typeof customization?.subtitle === 'string' ? customization.subtitle : '', + description: + (typeof customization?.description === 'string' && customization.description.length ? customization.description : null) ?? + (typeof layoutDefaults?.description === 'string' ? layoutDefaults.description : null) ?? + 'Helft uns, diesen besonderen Tag mit euren schönen Momenten festzuhalten.', + instructions: initialInstructions, + }; +} + +export default function MobileQrLayoutCustomizePage() { + const { slug: slugParam, tokenId: tokenParam } = useParams<{ slug?: string; tokenId?: string }>(); + const [searchParams] = useSearchParams(); + const slug = slugParam ?? null; + const tokenId = tokenParam ? Number(tokenParam) : null; + const layoutParam = searchParams.get('layout'); + const navigate = useNavigate(); + const { t } = useTranslation('management'); + + const [event, setEvent] = React.useState(null); + const [invite, setInvite] = React.useState(null); + const [selectedLayoutId, setSelectedLayoutId] = React.useState(layoutParam); + const [backgroundPreset, setBackgroundPreset] = React.useState(null); + const [backgroundGradient, setBackgroundGradient] = React.useState<{ angle: number; stops: string[] } | null>(null); + const [backgroundSolid, setBackgroundSolid] = React.useState(null); + const [textFields, setTextFields] = React.useState({ + headline: '', + subtitle: '', + description: '', + instructions: [''], + }); + const [qrPngUrl, setQrPngUrl] = React.useState(null); + const [step, setStep] = React.useState('background'); + const [saving, setSaving] = React.useState(false); + const [loading, setLoading] = React.useState(true); + const [error, setError] = React.useState(null); + + const handleSelectPreset = React.useCallback((id: string | null) => { + setBackgroundPreset(id); + if (id) { + setBackgroundGradient(null); + setBackgroundSolid(null); + } + }, []); + + const handleSelectGradient = React.useCallback((gradient: { angle: number; stops: string[] } | null) => { + setBackgroundGradient(gradient); + if (gradient) { + setBackgroundPreset(null); + setBackgroundSolid(null); + } + }, []); + + const handleSelectSolid = React.useCallback((color: string | null) => { + setBackgroundSolid(color); + if (color) { + setBackgroundPreset(null); + setBackgroundGradient(null); + } + }, []); + + React.useEffect(() => { + if (!slug) return; + (async () => { + setLoading(true); + try { + const eventData = await getEvent(slug); + const invites = await getEventQrInvites(slug); + const matchedInvite = tokenId ? invites.find((item) => item.id === tokenId) : invites.find((i) => i.is_active) ?? invites[0] ?? null; + setEvent(eventData); + setInvite(matchedInvite ?? null); + setQrPngUrl(matchedInvite?.qr_code_data_url ?? null); + const customization = (matchedInvite?.metadata as any)?.layout_customization ?? {}; + const initialLayoutId = layoutParam ?? customization.layout_id ?? matchedInvite?.layouts?.[0]?.id ?? null; + const layoutDefaults = matchedInvite?.layouts?.find((l) => l.id === initialLayoutId) ?? matchedInvite?.layouts?.[0] ?? null; + setBackgroundPreset(typeof customization.background_preset === 'string' ? customization.background_preset : null); + setSelectedLayoutId(initialLayoutId); + setBackgroundGradient(customization.background_gradient ?? null); + setBackgroundSolid(customization.background_color ?? null); + setTextFields( + buildInitialTextFields({ + customization, + layoutDefaults, + eventName: eventData?.name ?? null, + }) + ); + setError(null); + } catch (err) { + if (!isAuthError(err)) { + setError(getApiErrorMessage(err, t('events.errors.loadFailed', 'QR-Daten konnten nicht geladen werden.'))); + } + } finally { + setLoading(false); + } + })(); + }, [slug, tokenId, layoutParam, t]); + + const selectedLayout = invite?.layouts.find((l) => l.id === selectedLayoutId) ?? invite?.layouts?.[0] ?? null; + const isFoldable = (selectedLayout?.panel_mode ?? '').toLowerCase() === 'double-mirror'; + + const handleSave = async () => { + if (!slug || !invite || !selectedLayout) { + toast.error(t('events.qr.missing', 'Kein QR-Link vorhanden')); + return; + } + setSaving(true); + try { + const payload = { + metadata: { + layout_customization: { + layout_id: selectedLayout.id, + background_preset: backgroundPreset, + background_gradient: backgroundGradient ?? undefined, + background_color: backgroundSolid ?? undefined, + headline: textFields.headline || null, + subtitle: textFields.subtitle || null, + description: textFields.description || null, + instructions: textFields.instructions.filter((item) => item.trim().length > 0), + }, + }, + }; + const updated = await updateEventQrInvite(slug, invite.id, payload); + setInvite(updated); + toast.success(t('common.saved', 'Gespeichert')); + } catch (err) { + toast.error(getApiErrorMessage(err, t('events.errors.saveFailed', 'Speichern fehlgeschlagen.'))); + } finally { + setSaving(false); + } + }; + + return ( + navigate(-1)} + headerActions={ + window.location.reload()}> + + + } + > + {error ? ( + + + {error} + + + ) : null} + + + + + {step === 'background' && ( + navigate(-1)} + presets={BACKGROUND_PRESETS} + selectedPreset={backgroundPreset} + onSelectPreset={handleSelectPreset} + selectedLayout={selectedLayout} + layouts={invite?.layouts ?? []} + onSelectGradient={handleSelectGradient} + onSelectSolid={handleSelectSolid} + selectedGradient={backgroundGradient} + selectedSolid={backgroundSolid} + onSave={() => { + handleSave(); + setStep('text'); + }} + saving={saving || loading} + /> + )} + + {step === 'text' && ( + setStep('background')} + textFields={textFields} + onChange={(fields) => setTextFields(fields)} + onSave={() => { + handleSave(); + setStep('preview'); + }} + saving={saving || loading} + /> + )} + + {step === 'preview' && ( + setStep('text')} + layout={selectedLayout} + backgroundPreset={backgroundPreset} + backgroundGradient={backgroundGradient} + backgroundSolid={backgroundSolid} + presets={BACKGROUND_PRESETS} + textFields={textFields} + qrUrl={qrPngUrl ?? invite?.url ?? ''} + isFoldable={isFoldable} + onExport={(format) => { + const layout = selectedLayout; + const url = layout?.download_urls?.[format]; + if (!url) { + toast.error(t('events.qr.missing', 'Kein QR-Link vorhanden')); + return; + } + window.open(url, '_blank', 'noopener'); + }} + /> + )} + + + ); +} + +function Stepper({ current, onStepChange }: { current: Step; onStepChange: (step: Step) => void }) { + const { t } = useTranslation('management'); + const steps: { key: Step; label: string }[] = [ + { key: 'background', label: t('events.qr.background', 'Hintergrund') }, + { key: 'text', label: t('events.qr.text', 'Text') }, + { key: 'preview', label: t('events.qr.preview', 'Vorschau') }, + ]; + const currentIndex = steps.findIndex((s) => s.key === current); + const progress = ((currentIndex + 1) / steps.length) * 100; + + return ( + + + {steps.map((step, idx) => { + const active = step.key === current; + const completed = idx < currentIndex; + return ( + onStepChange(step.key)} style={{ flex: 1 }}> + + + {step.label} + + + {t('events.qr.step', 'Schritt')} {idx + 1} + + + + ); + })} + + + + + + ); +} + +type SlotDefinition = { + x: number; + y: number; + w: number; + h?: number; + fontSize?: number; + fontWeight?: string | number; + lineHeight?: number; + align?: 'left' | 'center' | 'right'; +}; + +function getDefaultSlots(): Record { + return { + headline: { x: 0.08, y: 0.08, w: 0.84, fontSize: 30, fontWeight: 800, align: 'center' }, + subtitle: { x: 0.1, y: 0.16, w: 0.8, fontSize: 18, fontWeight: 600, align: 'center' }, + description: { x: 0.1, y: 0.22, w: 0.8, fontSize: 16, lineHeight: 1.4, align: 'center' }, + instructions: { x: 0.1, y: 0.34, w: 0.8, fontSize: 14, lineHeight: 1.35 }, + qr: { x: 0.35, y: 0.55, w: 0.3 }, + }; +} + +function resolveSlots(layout: EventQrInviteLayout | null, isFoldable: boolean): Record { + const fromLayout = (layout as any)?.slots; + if (fromLayout && typeof fromLayout === 'object') { + return Object.entries(fromLayout as Record).reduce>((acc, [key, value]) => { + if (value && typeof value === 'object') { + const slot = value as Record; + acc[key] = { + x: Number(slot.x ?? 0), + y: Number(slot.y ?? 0), + w: Number(slot.w ?? 0.8), + h: typeof slot.h === 'number' ? slot.h : undefined, + fontSize: typeof slot.fontSize === 'number' ? slot.fontSize : undefined, + fontWeight: typeof slot.fontWeight === 'string' || typeof slot.fontWeight === 'number' ? slot.fontWeight : undefined, + lineHeight: typeof slot.lineHeight === 'number' ? slot.lineHeight : undefined, + align: typeof slot.align === 'string' ? (slot.align as SlotDefinition['align']) : undefined, + }; + } + return acc; + }, {}); + } + + if (isFoldable) { + return { + headline: { x: 0.1, y: 0.1, w: 0.8, fontSize: 28, fontWeight: 800, align: 'center' }, + subtitle: { x: 0.12, y: 0.18, w: 0.76, fontSize: 18, fontWeight: 600, align: 'center' }, + description: { x: 0.12, y: 0.24, w: 0.76, fontSize: 15, lineHeight: 1.4, align: 'center' }, + instructions: { x: 0.12, y: 0.36, w: 0.76, fontSize: 13, lineHeight: 1.3 }, + qr: { x: 0.36, y: 0.56, w: 0.28 }, + }; + } + + return getDefaultSlots(); +} + +function getCanvasSize(layout: EventQrInviteLayout | null, isFoldable: boolean): { width: number; height: number } { + const svgWidth = (layout as any)?.preview?.svg?.width; + const svgHeight = (layout as any)?.preview?.svg?.height; + if (svgWidth && svgHeight) { + return { width: svgWidth, height: svgHeight }; + } + if ((layout?.orientation || '').toLowerCase() === 'landscape' || isFoldable) { + return { width: 1754, height: 1240 }; // A4 landscape fallback + } + return { width: 1240, height: 1754 }; // A4 portrait fallback +} + +function FabricCanvasPreview({ + layout, + isFoldable, + backgroundPresetSrc, + backgroundGradient, + backgroundSolid, + textFields, + qrUrl, +}: { + layout: EventQrInviteLayout | null; + isFoldable: boolean; + backgroundPresetSrc: string | null; + backgroundGradient: { angle: number; stops: string[] } | null; + backgroundSolid: string | null; + textFields: { headline: string; subtitle: string; description: string; instructions: string[] }; + qrUrl: string; +}) { + const canvasRef = React.useRef(null); + const slots = React.useMemo(() => resolveSlots(layout, isFoldable), [layout, isFoldable]); + const containerRef = React.useRef(null); + const [frame, setFrame] = React.useState<{ width: number; height: number } | null>(null); + + React.useLayoutEffect(() => { + const measure = () => { + if (!containerRef.current) return; + const rect = containerRef.current.getBoundingClientRect(); + const width = rect.width || 320; + const aspect = + layout?.preview?.aspect_ratio ?? + ((layout?.orientation || '').toLowerCase() === 'landscape' || isFoldable ? 297 / 210 : 210 / 297); + const height = width / aspect; + setFrame({ width, height }); + }; + measure(); + window.addEventListener('resize', measure); + return () => window.removeEventListener('resize', measure); + }, [layout?.orientation, layout?.preview?.aspect_ratio, isFoldable]); + + React.useEffect(() => { + if (!frame) return; + const baseWidth = frame.width; + const baseHeight = frame.height; + let canvas: FabricNS.Canvas | null = null; + let disposed = false; + + async function render() { + const mod = await import('fabric'); + const fabricLib: typeof FabricNS | undefined = (mod as any)?.fabric ?? (mod as any)?.default ?? (mod as any); + const canvasEl = canvasRef.current; + const fallbackColor = backgroundSolid ?? '#f8fafc'; + if (canvasEl) { + const ctx = canvasEl.getContext('2d'); + if (ctx) { + ctx.fillStyle = fallbackColor; + ctx.fillRect(0, 0, baseWidth, baseHeight); + } + } + if (!fabricLib || !fabricLib.Canvas || !canvasEl) { + return; + } + if (disposed || !canvasRef.current) return; + const fabric: typeof FabricNS = fabricLib as unknown as typeof FabricNS; + + canvasEl.width = baseWidth; + canvasEl.height = baseHeight; + + canvas = new fabric.Canvas(canvasRef.current, { + selection: false, + hoverCursor: 'default', + }); + canvas.setWidth(baseWidth); + canvas.setHeight(baseHeight); + canvas.clear(); + const lower = (canvas as any).lowerCanvasEl as HTMLCanvasElement | undefined; + const upper = (canvas as any).upperCanvasEl as HTMLCanvasElement | undefined; + [lower, upper].forEach((el, idx) => { + if (!el) return; + el.style.position = 'absolute'; + el.style.left = '0'; + el.style.top = '0'; + el.style.width = '100%'; + el.style.height = '100%'; + el.style.setProperty('background-color', 'transparent', 'important'); + el.style.pointerEvents = 'none'; + el.style.zIndex = idx === 0 ? '1' : '2'; + }); + canvas.set('backgroundColor', 'transparent'); + canvas.renderAll(); + + const textColor = layout?.preview?.text ?? '#0f172a'; + const panelWidth = isFoldable ? baseWidth / 2 : baseWidth; + const panelHeight = baseHeight; + + const drawPanel = async (offset: number, mirrored: boolean) => { + const placeX = (slotX: number, slotW: number) => + mirrored ? offset + (panelWidth - (slotX + slotW) * panelWidth) : offset + slotX * panelWidth; + + // Headline + if (textFields.headline) { + const slot = slots.headline; + const txt = new fabric.Textbox(textFields.headline, { + left: placeX(slot.x, slot.w), + top: slot.y * panelHeight, + width: slot.w * panelWidth, + fontSize: slot.fontSize ?? 28, + fontWeight: slot.fontWeight ?? '800', + fill: textColor, + textAlign: slot.align ?? 'center', + selectable: false, + evented: false, + }); + canvas!.add(txt); + } + + if (textFields.subtitle) { + const slot = slots.subtitle; + const txt = new fabric.Textbox(textFields.subtitle, { + left: placeX(slot.x, slot.w), + top: slot.y * panelHeight, + width: slot.w * panelWidth, + fontSize: slot.fontSize ?? 18, + fontWeight: slot.fontWeight ?? '600', + fill: textColor, + textAlign: slot.align ?? 'center', + selectable: false, + evented: false, + }); + canvas!.add(txt); + } + + if (textFields.description) { + const slot = slots.description; + const txt = new fabric.Textbox(textFields.description, { + left: placeX(slot.x, slot.w), + top: slot.y * panelHeight, + width: slot.w * panelWidth, + fontSize: slot.fontSize ?? 16, + lineHeight: slot.lineHeight ?? 1.35, + fill: textColor, + textAlign: slot.align ?? 'center', + selectable: false, + evented: false, + }); + canvas!.add(txt); + } + + const instructions = textFields.instructions.filter((i) => i.trim().length > 0); + if (instructions.length) { + const slot = slots.instructions; + const txt = new fabric.Textbox( + instructions + .map((line, idx) => `${idx + 1}. ${line}`) + .join('\n'), + { + left: placeX(slot.x, slot.w), + top: slot.y * panelHeight, + width: slot.w * panelWidth, + fontSize: slot.fontSize ?? 14, + lineHeight: slot.lineHeight ?? 1.3, + fill: textColor, + textAlign: slot.align ?? 'left', + selectable: false, + evented: false, + } + ); + canvas!.add(txt); + } + + if (qrUrl) { + const slot = slots.qr; + const size = slot.w * panelWidth; + const left = placeX(slot.x, slot.w); + const top = slot.y * panelHeight; + await new Promise((resolve) => { + fabric.Image.fromURL( + qrUrl, + (img) => { + if (!img) return resolve(); + img.set({ + left, + top, + selectable: false, + evented: false, + objectCaching: false, + }); + img.scaleToWidth(size); + img.scaleToHeight(size); + canvas!.add(img); + resolve(); + }, + { crossOrigin: qrUrl.startsWith(window.location.origin) ? undefined : 'anonymous' } + ); + }); + } + }; + + await drawPanel(0, false); + if (isFoldable) { + await drawPanel(panelWidth, true); + } + + canvas.renderAll(); + } + + render(); + + return () => { + disposed = true; + if (canvas) { + canvas.dispose(); + } + }; + }, [ + backgroundGradient, + backgroundPresetSrc, + backgroundSolid, + frame, + isFoldable, + layout?.preview?.text, + qrUrl, + slots, + textFields.description, + textFields.headline, + textFields.instructions, + textFields.subtitle, + ]); + + return ( + + + + ); +} + +function buildFabricOptions({ + layout, + isFoldable, + backgroundGradient, + backgroundSolid, + backgroundImageUrl, + textFields, + qrUrl, + qrPngUrl, + baseWidth = CANVAS_WIDTH, + baseHeight = CANVAS_HEIGHT, +}: { + layout: EventQrInviteLayout | null; + isFoldable: boolean; + backgroundGradient: { angle: number; stops: string[] } | null; + backgroundSolid: string | null; + backgroundImageUrl: string | null; + textFields: { headline: string; subtitle: string; description: string; instructions: string[] }; + qrUrl: string; + qrPngUrl?: string | null; + baseWidth?: number; + baseHeight?: number; +}) { + const scaleX = CANVAS_WIDTH / baseWidth; + const scaleY = CANVAS_HEIGHT / baseHeight; + const panelWidth = isFoldable ? baseWidth / 2 : baseWidth; + const panelHeight = baseHeight; + const slots = resolveSlots(layout, isFoldable); + + const elements: LayoutElement[] = []; + const textColor = layout?.preview?.text ?? '#0f172a'; + const accentColor = layout?.preview?.accent ?? '#2563EB'; + const secondaryColor = layout?.preview?.secondary ?? '#1f2937'; + const badgeColor = layout?.preview?.badge ?? accentColor; + + const addTextElement = ( + type: LayoutElement['type'], + content: string, + slot: SlotDefinition, + opts: { panelOffset: number; mirrored: boolean } + ) => { + if (!content) return; + const widthPx = slot.w * panelWidth * scaleX; + const heightPx = (slot.h ?? 0.12) * panelHeight * scaleY; + const xBase = opts.mirrored + ? opts.panelOffset + (panelWidth - (slot.x + slot.w) * panelWidth) + : opts.panelOffset + slot.x * panelWidth; + const xPx = xBase * scaleX; + const yPx = slot.y * panelHeight * scaleY; + + elements.push({ + id: `${type}-${opts.panelOffset}-${opts.mirrored ? 'm' : 'n'}`, + type, + x: xPx, + y: yPx, + width: widthPx, + height: heightPx, + fontSize: slot.fontSize ?? (type === 'headline' ? 30 : type === 'subtitle' ? 18 : 16), + align: slot.align ?? 'center', + lineHeight: slot.lineHeight ?? 1.35, + content, + fill: textColor, + }); + }; + + const addQr = (slot: SlotDefinition, opts: { panelOffset: number; mirrored: boolean }) => { + if (!qrUrl) return; + const sizePx = slot.w * panelWidth * scaleX; + const xBase = opts.mirrored + ? opts.panelOffset + (panelWidth - (slot.x + slot.w) * panelWidth) + : opts.panelOffset + slot.x * panelWidth; + const xPx = xBase * scaleX; + const yPx = slot.y * panelHeight * scaleY; + elements.push({ + id: `qr-${opts.panelOffset}-${opts.mirrored ? 'm' : 'n'}`, + type: 'qr', + x: xPx, + y: yPx, + width: sizePx, + height: sizePx, + }); + }; + + const instructions = textFields.instructions.filter((i) => i.trim().length > 0); + const instructionContent = instructions.map((line, idx) => `${idx + 1}. ${line}`).join('\n'); + + const drawPanelElements = (panelOffset: number, mirrored: boolean) => { + addTextElement('headline', textFields.headline, slots.headline, { panelOffset, mirrored }); + addTextElement('subtitle', textFields.subtitle, slots.subtitle, { panelOffset, mirrored }); + addTextElement('description', textFields.description, slots.description, { panelOffset, mirrored }); + if (instructionContent) { + addTextElement('description', instructionContent, slots.instructions, { panelOffset, mirrored }); + } + addQr(slots.qr, { panelOffset, mirrored }); + }; + + drawPanelElements(0, false); + if (isFoldable) { + drawPanelElements(panelWidth, true); + } + + return { + elements, + accentColor, + textColor, + secondaryColor, + badgeColor, + qrCodeDataUrl: qrPngUrl ?? (qrUrl ? `https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=${encodeURIComponent(qrUrl)}` : null), + logoDataUrl: null, + backgroundColor: backgroundSolid ?? layout?.preview?.background ?? '#ffffff', + backgroundGradient, + backgroundImageUrl, + readOnly: true, + } as const; +} + +function BackgroundStep({ + onBack, + presets, + selectedPreset, + onSelectPreset, + selectedLayout, + layouts, + onSelectGradient, + onSelectSolid, + selectedGradient, + selectedSolid, + onSave, + saving, +}: { + onBack: () => void; + presets: { id: string; src: string; label: string }[]; + selectedPreset: string | null; + onSelectPreset: (id: string) => void; + selectedLayout: EventQrInviteLayout | null; + layouts: EventQrInviteLayout[]; + onSelectGradient: (gradient: { angle: number; stops: string[] } | null) => void; + onSelectSolid: (color: string | null) => void; + selectedGradient: { angle: number; stops: string[] } | null; + selectedSolid: string | null; + onSave: () => void; + saving: boolean; +}) { + const { t } = useTranslation('management'); + const resolvedLayout = + selectedLayout ?? + layouts.find((layout) => { + const panel = (layout.panel_mode ?? '').toLowerCase(); + const orientation = (layout.orientation ?? '').toLowerCase(); + return panel === 'double-mirror' || orientation === 'landscape'; + }) ?? + layouts[0] ?? + null; + + const isFoldable = (resolvedLayout?.panel_mode ?? '').toLowerCase() === 'double-mirror'; + const formatLabel = isFoldable ? 'A4 Landscape (Double/Mirror)' : 'A4 Portrait'; + const disablePresets = isFoldable; + const gradientPresets = [ + { angle: 180, stops: ['#F8FAFC', '#EEF2FF', '#F8FAFC'], label: 'Soft Lilac' }, + { angle: 135, stops: ['#FEE2E2', '#EFF6FF', '#ECFDF3'], label: 'Pastell' }, + { angle: 210, stops: ['#0B132B', '#1C2541', '#274690'], label: 'Midnight' }, + ]; + const solidPresets = ['#FFFFFF', '#F8FAFC', '#0F172A', '#2563EB', '#F59E0B']; + + return ( + + + + + + + {t('common.back', 'Zurück')} + + + + {formatLabel} + + + + + {disablePresets + ? t('events.qr.backgroundPicker', 'Hintergrund für A5 (Gradient/Farbe)') + : t('events.qr.backgroundPicker', `Hintergrund auswählen (${formatLabel})`)} + + {!disablePresets ? ( + <> + + {presets.map((preset) => { + const isSelected = selectedPreset === preset.id; + return ( + onSelectPreset(preset.id)} style={{ width: '48%' }}> + + + + + {preset.label} + + {isSelected ? {t('common.selected', 'Ausgewählt')} : null} + + + + ); + })} + + + {t('events.qr.backgroundNote', 'Diese Presets sind für A4 Hochformat. Spiegelung erfolgt automatisch bei Tischkarten.')} + + + ) : ( + + {t('events.qr.foldableBackgroundNote', 'Für A5 Tischkarten bitte Gradient oder Vollfarbe wählen.')} + + )} + + + + {t('events.qr.gradients', 'Gradienten')} + + + {gradientPresets.map((gradient, idx) => { + const isSelected = + selectedGradient && + selectedGradient.angle === gradient.angle && + JSON.stringify(selectedGradient.stops) === JSON.stringify(gradient.stops); + const style = { + backgroundImage: `linear-gradient(${gradient.angle}deg, ${gradient.stops.join(',')})`, + } as React.CSSProperties; + return ( + onSelectGradient(gradient)} style={{ width: '30%' }}> + + + ); + })} + + + + + + {t('events.qr.colors', 'Vollfarbe')} + + + {solidPresets.map((color) => { + const isSelected = selectedSolid === color; + return ( + onSelectSolid(color)} style={{ width: '20%' }}> + + + ); + })} + + + + + + + ); +} + +function TextStep({ + onBack, + textFields, + onChange, + onSave, + saving, +}: { + onBack: () => void; + textFields: { headline: string; subtitle: string; description: string; instructions: string[] }; + onChange: (fields: { headline: string; subtitle: string; description: string; instructions: string[] }) => void; + onSave: () => void; + saving: boolean; +}) { + const { t } = useTranslation('management'); + + const updateField = (key: 'headline' | 'subtitle' | 'description', value: string) => { + onChange({ ...textFields, [key]: value }); + }; + + const updateInstruction = (idx: number, value: string) => { + const next = [...textFields.instructions]; + next[idx] = value; + onChange({ ...textFields, instructions: next }); + }; + + const addInstruction = () => { + onChange({ ...textFields, instructions: [...textFields.instructions, ''] }); + }; + + const removeInstruction = (idx: number) => { + const next = textFields.instructions.filter((_, i) => i !== idx); + onChange({ ...textFields, instructions: next.length ? next : [''] }); + }; + + return ( + + + + + + + {t('common.back', 'Zurück')} + + + + {t('events.qr.textStep', 'Texte & Hinweise')} + + + + + {t('events.qr.textFields', 'Texte')} + + updateField('headline', val)} + size="$4" + /> + updateField('subtitle', val)} + size="$4" + /> +