Ersetze die Builder-Liste des Formular-Editors durch eine Formularansicht mit Ziehen und Ablegen
CI Feature / test (push) Successful in 4m18s

Der Aufbau eines Formulars zeigt Bereiche als Karten, Teilbereiche als eingerahmte Einheit darin und Felder als Zeilen
(Frage, Art der Antwort, Pflicht). Hilfetext, Auswahlwerte, Bedingung und weitere Einstellungen öffnen als Pop-up.
Bereiche, Teilbereiche und Felder lassen sich ziehen (SortableJS aus Filament) oder per Pfeiltasten und über
"Verschieben nach" ordnen; Rückgängig nimmt Änderungen bis zum Speichern zurück.

Der Browser führt den Baum und übergibt ihn beim Speichern als Text; FormEditor prüft ihn (validateTree) und überführt ihn
über fromTree in dieselbe flache Ansicht wie bisher. Entwurf, Katalog und Engine bleiben unverändert, keine Migration.

Tests: Die Livewire-Tests des Editors setzen jetzt den Baumtext (editor_json) statt der Builder-Blöcke; neu sind
Baumumwandlung ohne Verlust, Teilbereich mit Feldern, Prüfung und Konfiguration. Das ist bewusst: Der Builder entfällt.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Sonnet 5.5 committed 2026-11-28 08:08:39 +01:00
1 parent 79c4e877ab
commit 380a3013c7
10 files changed
+1860 -225

No files matched your search

+240
View File
@@ -2,6 +2,7 @@
namespace App\Domain\Communication;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
@@ -271,6 +272,245 @@ public function persist(array $editor): array
});
}
/** Beschriftungen der Wirkungen am Element, je Art des Ziels. */
public const EFFECT_LABELS = [
'step' => ['show' => 'Bereich nur anzeigen, wenn …', 'hide' => 'Bereich ausblenden, wenn …', 'skip' => 'Bereich überspringen, wenn …'],
'group' => ['show' => 'Teilbereich nur anzeigen, wenn …', 'hide' => 'Teilbereich ausblenden, wenn …'],
'field' => ['show' => 'Feld nur anzeigen, wenn …', 'hide' => 'Feld ausblenden, wenn …', 'require' => 'Pflichtfeld, wenn …'],
];
/**
* Baumansicht für die Formularoberfläche (ADR-62): Ein Teilbereich trägt seine Felder selbst (items), die
* Ende-Markierung der flachen Ansicht entfällt. Die Umwandlung ist verlustfrei: fromTree(toTree(x)) liefert dieselbe
* Struktur, die persist() in denselben Entwurf überführt.
*
* @param array<string, mixed> $view Ergebnis von expand()
* @return array{areas: list<array<string, mixed>>, rules: list<array<string, mixed>>}
*/
public static function toTree(array $view): array
{
$areas = [];
foreach (array_values((array) ($view['areas'] ?? [])) as $area) {
$area = is_array($area) ? $area : [];
$items = [];
$section = null;
foreach (array_values((array) ($area['items'] ?? [])) as $block) {
$block = is_array($block) ? $block : [];
$data = is_array($block['data'] ?? null) ? $block['data'] : [];
switch ((string) ($block['type'] ?? '')) {
case 'issue':
$section = null;
$items[] = ['kind' => 'issue', 'issues' => array_values(array_filter((array) ($data['issues'] ?? []), 'is_string'))];
break;
case 'end':
$section = null;
break;
case 'section':
$items[] = ['kind' => 'section', ...$data, 'items' => []];
$section = array_key_last($items);
break;
case 'field':
if ($section !== null) {
$items[$section]['items'][] = ['kind' => 'field', ...$data];
} else {
$items[] = ['kind' => 'field', ...$data];
}
break;
}
}
$areas[] = [...Arr::except($area, ['items']), 'items' => $items];
}
return ['areas' => $areas, 'rules' => array_values((array) ($view['rules'] ?? []))];
}
/**
* Umkehrung von toTree(): die flache Ansicht, die persist() erwartet. Nach jedem Teilbereich steht eine
* Ende-Markierung, damit folgende Einzelfelder nicht in ihn fallen.
*
* @param array<string, mixed> $tree
* @return array{areas: list<array<string, mixed>>, rules: list<array<string, mixed>>}
*/
public static function fromTree(array $tree): array
{
$areas = [];
$field = fn (array $item): array => ['type' => 'field', 'data' => Arr::except($item, ['kind', '_id'])];
foreach (array_values((array) ($tree['areas'] ?? [])) as $area) {
$area = is_array($area) ? $area : [];
$blocks = [];
foreach (array_values((array) ($area['items'] ?? [])) as $item) {
$item = is_array($item) ? $item : [];
switch ((string) ($item['kind'] ?? '')) {
case 'issue':
$blocks[] = ['type' => 'issue', 'data' => ['issues' => array_values(array_filter((array) ($item['issues'] ?? []), 'is_string'))]];
break;
case 'section':
$blocks[] = ['type' => 'section', 'data' => Arr::except($item, ['kind', '_id', 'items'])];
foreach (array_values((array) ($item['items'] ?? [])) as $inner) {
$blocks[] = $field(is_array($inner) ? $inner : []);
}
$blocks[] = ['type' => 'end', 'data' => []];
break;
case 'field':
$blocks[] = $field($item);
break;
}
}
$areas[] = [...Arr::except($area, ['items', '_id']), 'items' => $blocks];
}
return ['areas' => $areas, 'rules' => array_values((array) ($tree['rules'] ?? []))];
}
/**
* Prüft die Baumansicht vor dem Speichern. Was nur gekürzt oder ignoriert würde, wird hier benannt, damit die
* Verwaltung nichts stillschweigend verliert.
*
* @param array<string, mixed> $tree
* @return list<string>
*/
public function validateTree(array $tree): array
{
$errors = [];
$seen = [];
$issueQuestions = 0;
$limit = function (string $where, string $what, mixed $value, int $max) use (&$errors): void {
if (mb_strlen(trim((string) $value)) > $max) {
$errors[] = "$where: $what darf höchstens $max Zeichen lang sein.";
}
};
foreach (array_values((array) ($tree['areas'] ?? [])) as $index => $area) {
$area = is_array($area) ? $area : [];
$title = trim((string) ($area['title'] ?? ''));
$where = 'Bereich '.($index + 1).($title !== '' ? ' „'.$title.'“' : '');
if ($title === '') {
$errors[] = "$where: Der Titel fehlt.";
}
$limit($where, 'Der Titel', $title, 120);
$limit($where, 'Die Einleitung', $area['intro'] ?? '', 600);
$checkField = function (array $field) use (&$errors, &$seen, $where, $limit): void {
$label = trim((string) ($field['label'] ?? ''));
$name = $label !== '' ? '„'.$label.'“' : 'Ein Feld';
if ($label === '') {
$errors[] = "$where: Ein Feld hat keine Frage oder Beschriftung.";
}
$limit($where, "Die Frage $name", $label, 200);
$limit($where, "Der Hilfetext von $name", $field['help'] ?? '', 600);
$type = FieldType::tryFrom((string) ($field['type'] ?? ''));
if ($type === null) {
$errors[] = "$where: Bei $name fehlt die Art der Antwort.";
} elseif ($type->hasOptions()) {
$options = array_filter((array) ($field['options'] ?? []), fn (mixed $option): bool => is_array($option) && trim((string) ($option['label'] ?? '')) !== '');
if ($options === []) {
$errors[] = "$where: Bei $name fehlen die Auswahlwerte.";
}
foreach ($options as $option) {
$limit($where, "Ein Auswahlwert von $name", $option['label'], 120);
}
}
$key = (string) ($field['key'] ?? '');
if ($key !== '' && ! str_starts_with($key, 'tmp_')) {
if (isset($seen[$key])) {
$errors[] = "$where: $name steht mehrfach im Formular.";
}
$seen[$key] = true;
}
};
foreach (array_values((array) ($area['items'] ?? [])) as $item) {
$item = is_array($item) ? $item : [];
if (($item['kind'] ?? null) === 'issue') {
$issueQuestions++;
} elseif (($item['kind'] ?? null) === 'section') {
$label = trim((string) ($item['label'] ?? ''));
if ($label === '') {
$errors[] = "$where: Ein Teilbereich hat keine Überschrift.";
}
$limit($where, 'Die Überschrift eines Teilbereichs', $label, 200);
$limit($where, 'Die Erläuterung eines Teilbereichs', $item['description'] ?? '', 600);
foreach (array_values((array) ($item['items'] ?? [])) as $inner) {
$checkField(is_array($inner) ? $inner : []);
}
} elseif (($item['kind'] ?? null) === 'field') {
$checkField($item);
}
}
}
if ($issueQuestions > 1) {
$errors[] = 'Die Frage nach dem Anliegen darf nur einmal im Formular vorkommen.';
}
return array_values(array_unique($errors));
}
/**
* Auswahllisten für die Formularoberfläche: Feldarten, Verwendungen, Wirkungen, Vergleiche, Anliegen und die Felder
* des Katalogs mit Verwendung in anderen Formularen.
*
* @return array<string, mixed>
*/
public function clientConfig(?int $exceptTemplate = null): array
{
$usage = $this->usage($exceptTemplate);
return [
'types' => array_map(fn (FieldType $type): array => ['value' => $type->value, 'label' => $type->label(), 'options' => $type->hasOptions(), 'control' => $type->canControl()], FieldType::cases()),
'purposes' => array_map(fn (FieldPurpose $purpose): array => ['value' => $purpose->value, 'label' => $purpose->label(), 'types' => array_map(fn (FieldType $type): string => $type->value, $purpose->types())], FieldPurpose::cases()),
'effects' => self::EFFECT_LABELS,
'operators' => TemplateCompiler::OPERATORS,
'issues' => InquiryIssue::tree(),
'catalog' => InquiryField::query()->offered()->orderBy('name')->get()->map(fn (InquiryField $field): array => [
'key' => $field->key,
'name' => $field->name,
'label' => $field->label,
'help' => $field->help,
'type' => $field->type->value,
'options' => $field->optionList(),
'purpose' => $field->purpose?->value,
'used_in' => implode(', ', $usage['fields'][$field->key] ?? []),
])->values()->all(),
];
}
/**
* Eine neue Zeile in der Karteikarte der Bedingungen (leer: Standardwerte).
*
@@ -34,7 +34,7 @@ class InquiryTemplateResource extends CommunicationResource
public static function form(Schema $schema): Schema
{
return $schema->components(TemplateEditor::schema());
return $schema->components(TemplateEditor::schema($schema->getRecord()?->getKey()));
}
public static function table(Table $table): Table
@@ -140,16 +140,35 @@ protected function archiveBlocked(): ?string
protected function mutateFormDataBeforeFill(array $data): array
{
$data['editor'] = app(FormEditor::class)->expand((array) ($data['draft'] ?? []), $this->getRecord()->getKey());
$tree = FormEditor::toTree(app(FormEditor::class)->expand((array) ($data['draft'] ?? []), $this->getRecord()->getKey()));
// Die Formularansicht führt den Baum im Browser und übergibt ihn als Text; die weiteren Regeln bleiben eine Liste.
$data['editor'] = ['rules' => $tree['rules']];
$data['editor_json'] = json_encode(['areas' => $tree['areas']], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
return $data;
}
protected function mutateFormDataBeforeSave(array $data): array
{
$editor = app(FormEditor::class);
$tree = json_decode((string) ($data['editor_json'] ?? ''), true);
if (! is_array($tree)) {
$this->failEditor(['Der Aufbau konnte nicht gelesen werden. Bitte lade die Seite neu und versuche es noch einmal.']);
}
$errors = $editor->validateTree($tree);
if ($errors !== []) {
$this->failEditor($errors);
}
// Der Editor schreibt neue und geänderte Felder und Teilbereiche in den Katalog und liefert den Entwurf.
$saved = app(FormEditor::class)->persist((array) ($data['editor'] ?? []));
unset($data['editor']);
$view = FormEditor::fromTree($tree);
$view['rules'] = (array) ($data['editor']['rules'] ?? []);
$saved = $editor->persist($view);
unset($data['editor'], $data['editor_json']);
$data['draft'] = TemplateDraft::clean([
'texts' => (array) ($data['draft']['texts'] ?? []),
@@ -161,6 +180,17 @@ protected function mutateFormDataBeforeSave(array $data): array
return $data;
}
/**
* @param list<string> $messages
* @return never
*/
private function failEditor(array $messages): void
{
Notification::make()->title('Das Formular ist noch nicht vollständig')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, $messages)))->danger()->persistent()->send();
throw ValidationException::withMessages(['data.editor_json' => $messages]);
}
protected function afterSave(): void
{
// Neue Felder und Teilbereiche tragen jetzt ihre festen Kennungen. Ohne neues Laden würde ein zweites Speichern sie doppelt anlegen.
+26 -209
View File
@@ -2,29 +2,24 @@
namespace App\Filament\Support;
use App\Domain\Communication\FieldPurpose;
use App\Domain\Communication\FieldType;
use App\Domain\Communication\FormEditor;
use App\Domain\Communication\FormTexts;
use App\Domain\Communication\InquiryField;
use App\Domain\Communication\InquiryIssue;
use App\Domain\Communication\TemplateCompiler;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\Builder\Block;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Components\ViewField;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Illuminate\Support\Str;
/**
* Formular-Editor (ADR-61): ein Formular wird an einer Stelle bearbeitet. Es besteht aus Bereichen (im mehrstufigen Dialog
@@ -34,23 +29,17 @@
*/
final class TemplateEditor
{
private const EFFECT_LABELS = [
'step' => ['show' => 'Bereich nur anzeigen, wenn …', 'hide' => 'Bereich ausblenden, wenn …', 'skip' => 'Bereich überspringen, wenn …'],
'group' => ['show' => 'Teilbereich nur anzeigen, wenn …', 'hide' => 'Teilbereich ausblenden, wenn …'],
'field' => ['show' => 'Feld nur anzeigen, wenn …', 'hide' => 'Feld ausblenden, wenn …', 'require' => 'Pflichtfeld, wenn …'],
];
/**
* @return list<Component>
*/
public static function schema(): array
public static function schema(?int $templateId = null): array
{
return [
TextInput::make('name')->label('Name des Formulars')->required()->maxLength(120)
->helperText('So heißt das Formular in der Verwaltung und in der Auswahl des Widgets „Anfrage“.'),
Textarea::make('description')->label('Beschreibung (nur Verwaltung)')->rows(2)->maxLength(400),
Tabs::make('vorlage')->persistTabInQueryString('bereich')->tabs([
Tab::make('Aufbau')->icon('heroicon-o-queue-list')->schema(self::structure()),
Tabs::make('vorlage')->persistTabInQueryString('bereich')->columnSpanFull()->tabs([
Tab::make('Aufbau')->icon('heroicon-o-queue-list')->schema(self::structure($templateId)),
Tab::make('Texte')->icon('heroicon-o-chat-bubble-bottom-center-text')->schema(self::texts()),
Tab::make('Weitere Regeln')->icon('heroicon-o-adjustments-horizontal')->schema(self::rules()),
]),
@@ -58,175 +47,23 @@ public static function schema(): array
}
/**
* Der Aufbau ist eine eigene Formularansicht (resources/views/filament/communication/form-editor.blade.php). Sie führt
* den Baum aus Bereichen, Teilbereichen und Feldern im Browser und übergibt ihn beim Speichern als Text (editor_json);
* FormEditor prüft und speichert ihn.
*
* @return list<Component>
*/
private static function structure(): array
private static function structure(?int $templateId): array
{
return [
Text::make('Ein Formular besteht aus Bereichen. Im mehrstufigen Dialog ist jeder Bereich ein Schritt, im langen Formular stehen alle Bereiche untereinander. In einem Bereich legst du Felder an; ein Teilbereich fasst Felder unter einer Überschrift zusammen. Bedingungen stehen direkt am Feld oder Bereich. Neue Felder und Auswahlwerte stehen in Bedingungen zur Verfügung, sobald das Formular einmal gespeichert ist.'),
Repeater::make('editor.areas')
->label('Bereiche')
->schema([
Hidden::make('key')->default(fn (): string => 's'.Str::lower(Str::random(6))),
TextInput::make('title')->label('Titel des Bereichs')->required()->maxLength(120)->live(onBlur: true)
->helperText('Im mehrstufigen Dialog die Überschrift des Schritts.'),
Textarea::make('intro')->label('Einleitung (optional)')->rows(2)->maxLength(600),
self::condition('step'),
Builder::make('items')
->label('Inhalt des Bereichs')
->blocks(self::blocks())
->addActionLabel('Feld oder Teilbereich hinzufügen')
->blockPickerColumns(2)
->blockNumbers(false)
->reorderableWithButtons()
->collapsible()
->live(),
])
->reorderableWithButtons()
->collapsible()
->addActionLabel('Bereich hinzufügen')
->live()
->itemLabel(fn (array $state): string => (($state['title'] ?? '') ?: 'Neuer Bereich').(filled($state['cond']['effect'] ?? null) ? ' · mit Bedingung' : '')),
ViewField::make('editor_json')
->hiddenLabel()
->view('filament.communication.form-editor')
->viewData(['config' => app(FormEditor::class)->clientConfig($templateId)])
->columnSpanFull(),
];
}
/**
* @return list<Block>
*/
private static function blocks(): array
{
return [
Block::make('field')
->label(fn (?array $state): string => $state === null ? 'Feld' : 'Feld: '.(($state['label'] ?? '') ?: 'neu').self::fieldBadges($state))
->icon('heroicon-o-pencil-square')
->schema([
Hidden::make('key')->default(fn (): string => FormEditor::temporaryKey()),
Hidden::make('name'),
Hidden::make('used_in'),
Select::make('pick')->label('Vorhandenes Feld verwenden (optional)')->searchable()->live()->dehydrated(false)
->options(fn ($livewire): array => self::catalogFields((array) ($livewire->data['editor'] ?? [])))
->placeholder('Neues Feld anlegen')
->visible(fn (Get $get): bool => str_starts_with((string) $get('key'), 'tmp_'))
->afterStateUpdated(function ($state, Set $set): void {
$field = filled($state) ? InquiryField::query()->where('key', $state)->first() : null;
if ($field === null) {
return;
}
$set('key', $field->key);
$set('name', $field->name);
$set('label', $field->label);
$set('help', $field->help);
$set('type', $field->type->value);
$set('options', $field->optionList());
$set('purpose', $field->purpose?->value);
$set('pick', null);
})
->helperText('Felder wie „E-Mail-Adresse“ lassen sich in mehreren Formularen verwenden.'),
TextInput::make('label')->label('Frage oder Beschriftung im Formular')->required()->maxLength(200)->live(onBlur: true),
Select::make('type')->label('Art der Antwort')->required()->live()->dehydrated()
->options(FieldType::options())
->disabled(fn (Get $get): bool => ! str_starts_with((string) $get('key'), 'tmp_'))
->helperText('Nach dem Speichern nicht mehr änderbar, weil Bedingungen und bisherige Anfragen darauf aufbauen. Soll sich die Art ändern, lege ein neues Feld an.'),
Repeater::make('options')->label('Auswahlwerte')
->schema([Hidden::make('key'), TextInput::make('label')->label('Bezeichnung')->required()->maxLength(120)])
->reorderableWithButtons()
->addActionLabel('Auswahlwert hinzufügen')
->minItems(1)
->itemLabel(fn (array $state): ?string => $state['label'] ?? null)
->visible(fn (Get $get): bool => FieldType::tryFrom((string) $get('type'))?->hasOptions() ?? false)
->helperText('Jeder Wert behält seine feste interne Kennung; eine Umbenennung beschädigt keine Anfragen.'),
Textarea::make('help')->label('Hilfetext (optional)')->rows(2)->maxLength(600)->helperText('Steht unter der Frage.'),
Toggle::make('required')->label('Pflichtfeld'),
Section::make('Weitere Einstellungen')->compact()->collapsed()->schema([
Select::make('purpose')->label('Verwendung in der Anfrageübersicht')->options(FieldPurpose::options())->placeholder('Keine besondere Verwendung')
->helperText('Welche Angabe der Posteingang als Name, E-Mail-Adresse oder Nachricht zeigt. Jedes Formular braucht ein Feld „E-Mail-Adresse für Rückfragen“.'),
]),
Text::make(fn (Get $get): string => 'Dieses Feld wird auch in diesen Formularen verwendet: '.$get('used_in').'. Eine Änderung gilt dort mit der nächsten Veröffentlichung.')
->visible(fn (Get $get): bool => filled($get('used_in'))),
self::condition('field'),
]),
Block::make('section')
->label(fn (?array $state): string => $state === null ? 'Teilbereich' : 'Teilbereich: '.(($state['label'] ?? '') ?: 'neu').(filled($state['cond']['effect'] ?? null) ? ' (Bedingung)' : ''))
->icon('heroicon-o-rectangle-group')
->schema([
Hidden::make('key')->default(fn (): string => FormEditor::temporaryKey()),
Hidden::make('missing')->default(false),
Hidden::make('used_in'),
TextInput::make('label')->label('Überschrift des Teilbereichs')->required()->maxLength(200)->live(onBlur: true)
->helperText('Die Felder darunter stehen im Formular unter dieser Überschrift, bis ein weiterer Teilbereich oder „Ende des Teilbereichs“ folgt.'),
Textarea::make('description')->label('Erläuterung (optional)')->rows(2)->maxLength(600),
Text::make(fn (Get $get): string => 'Dieser Teilbereich wird auch in diesen Formularen verwendet: '.$get('used_in').'. Änderungen an seinen Feldern gelten dort mit der nächsten Veröffentlichung.')
->visible(fn (Get $get): bool => filled($get('used_in'))),
self::condition('group'),
]),
Block::make('end')
->label('Ende des Teilbereichs')
->icon('heroicon-o-arrow-uturn-down')
->schema([Text::make('Die folgenden Felder stehen wieder ohne Teilbereich.')]),
Block::make('issue')
->label('Frage nach dem Anliegen')
->icon('heroicon-o-chat-bubble-left-right')
->maxItems(1)
->schema([
Select::make('issues')->label('Angebotene Anliegen')->multiple()->live()
->options(fn (): array => InquiryIssue::query()->offered()->whereNull('parent_id')->orderBy('sort_order')->pluck('label', 'key')->all())
->helperText('Welche Anliegen dieses Formular kennt. Leer: alle angebotenen. Ein Anfragegrund im Widget kann daraus eines vorwählen; die Frage entfällt dann. Anliegen und Unteranliegen pflegst du unter „Einstellungen → Anliegen“.'),
]),
];
}
/**
* Bedingung am Element: Wirkung, Verknüpfung und eine Liste von Vergleichen. Ohne Wirkung gibt es keine Bedingung.
*/
private static function condition(string $kind): Section
{
return Section::make('Bedingung (optional)')->statePath('cond')->compact()->collapsed()->schema([
Hidden::make('pos'),
Select::make('effect')->label('Wirkung')->options(self::EFFECT_LABELS[$kind])->placeholder('Keine Bedingung')->live()
->helperText($kind === 'step' ? 'Zum Beispiel: Bereich „Angaben zur Schule“ nur anzeigen, wenn das Anliegen „Kursanfrage“ ist.' : null),
Select::make('match')->label('Es müssen zutreffen')->options(['all' => 'alle Bedingungen', 'any' => 'mindestens eine Bedingung'])->default('all')
->visible(fn (Get $get): bool => filled($get('effect'))),
Repeater::make('conditions')
->label('Bedingungen')
->schema([
Select::make('source')->label('Wenn …')->required()->live()->searchable()
->options(fn (Select $component, $livewire): array => self::sources((array) ($livewire->data['editor'] ?? []), $component->getStatePath())),
Select::make('op')->label('Vergleich')->required()->options(TemplateCompiler::OPERATORS)->default('eq')->live(),
Select::make('values')->label('Wert')->required()->multiple()
->options(fn (Get $get, $livewire): array => self::sourceValues((array) ($livewire->data['editor'] ?? []), (string) $get('source'))),
])
->addActionLabel('Bedingung hinzufügen')
->visible(fn (Get $get): bool => filled($get('effect')))
->helperText('Zur Auswahl stehen Felder, die im Formular weiter oben stehen.'),
]);
}
/**
* @param array<string, mixed>|null $state
*/
private static function fieldBadges(?array $state): string
{
$parts = [];
if (filled($state['type'] ?? null)) {
$parts[] = FieldType::tryFrom((string) $state['type'])?->label();
}
if ($state['required'] ?? false) {
$parts[] = 'Pflicht';
}
if (filled($state['cond']['effect'] ?? null)) {
$parts[] = 'Bedingung';
}
$parts = array_filter($parts);
return $parts === [] ? '' : ' ('.implode(', ', $parts).')';
}
/**
* @return list<Component>
*/
@@ -241,7 +78,7 @@ private static function rules(): array
Hidden::make('pos'),
Select::make('effect')->label('Wirkung')->required()->live()->options(TemplateCompiler::EFFECTS),
Select::make('target')->label('Ziel')->required()->live()->searchable()
->options(fn ($livewire, Get $get): array => self::targets((array) ($livewire->data['editor'] ?? []), (string) $get('effect'))),
->options(fn ($livewire, Get $get): array => self::targets(self::flat($livewire), (string) $get('effect'))),
Select::make('value')->label('Vorbelegen mit')->live()
->options(fn (Get $get): array => str_starts_with((string) $get('target'), 'field:') ? self::fieldValues(substr((string) $get('target'), 6)) : [])
->visible(fn (Get $get): bool => $get('effect') === 'preset')->required(fn (Get $get): bool => $get('effect') === 'preset'),
@@ -250,17 +87,17 @@ private static function rules(): array
->label('Bedingungen')
->schema([
Select::make('source')->label('Wenn …')->required()->live()->searchable()
->options(fn ($livewire): array => self::sources((array) ($livewire->data['editor'] ?? []), null)),
->options(fn ($livewire): array => self::sources(self::flat($livewire))),
Select::make('op')->label('Vergleich')->required()->options(TemplateCompiler::OPERATORS)->default('eq')->live(),
Select::make('values')->label('Wert')->required()->multiple()
->options(fn ($livewire, Get $get): array => self::sourceValues((array) ($livewire->data['editor'] ?? []), (string) $get('source'))),
->options(fn ($livewire, Get $get): array => self::sourceValues(self::flat($livewire), (string) $get('source'))),
])
->minItems(1)
->addActionLabel('Bedingung hinzufügen'),
])
->collapsible()
->addActionLabel('Regel hinzufügen')
->itemLabel(fn (array $state, $livewire): string => (TemplateCompiler::EFFECTS[$state['effect'] ?? ''] ?? 'Neue Regel').(($state['target'] ?? null) ? ' → '.self::targetName((string) $state['target'], (array) ($livewire->data['editor'] ?? [])) : '')),
->itemLabel(fn (array $state, $livewire): string => (TemplateCompiler::EFFECTS[$state['effect'] ?? ''] ?? 'Neue Regel').(($state['target'] ?? null) ? ' → '.self::targetName((string) $state['target'], self::flat($livewire)) : '')),
]),
];
}
@@ -288,16 +125,15 @@ private static function texts(): array
}
/**
* Felder des Katalogs, die im Formular noch nicht vorkommen.
* Der aktuelle Aufbau in der flachen Ansicht (Bereiche, Felder, Teilbereiche, Ende-Markierungen), aus dem Text der Formularansicht.
*
* @param array<string, mixed> $editor
* @return array<string, string>
* @return array<string, mixed>
*/
private static function catalogFields(array $editor): array
private static function flat(mixed $livewire): array
{
$used = array_keys(self::inventory($editor)['fields']);
$tree = json_decode((string) ($livewire->data['editor_json'] ?? ''), true);
return InquiryField::query()->offered()->whereNotIn('key', $used)->orderBy('name')->pluck('name', 'key')->all();
return FormEditor::fromTree(is_array($tree) ? $tree : []);
}
/**
@@ -389,32 +225,13 @@ private static function targetName(string $target, array $editor = []): string
* @param array<string, mixed> $editor
* @return array<string, string>
*/
private static function sources(array $editor, ?string $path): array
private static function sources(array $editor): array
{
$areaId = null;
$blockId = null;
if ($path !== null) {
$segments = explode('.', $path);
$areaAt = array_search('areas', $segments, true);
$itemAt = array_search('items', $segments, true);
$areaId = $areaAt === false ? null : ($segments[$areaAt + 1] ?? null);
$blockId = $itemAt === false ? null : ($segments[$itemAt + 1] ?? null);
}
$catalog = InquiryField::query()->get()->keyBy('key');
$sources = [];
foreach ((array) ($editor['areas'] ?? []) as $currentArea => $area) {
if ($areaId !== null && (string) $currentArea === $areaId && $blockId === null) {
break;
}
foreach ((array) ($area['items'] ?? []) as $currentBlock => $block) {
if ($areaId !== null && (string) $currentArea === $areaId && (string) $currentBlock === $blockId) {
break 2;
}
foreach ((array) ($editor['areas'] ?? []) as $area) {
foreach ((array) ($area['items'] ?? []) as $block) {
$data = (array) ($block['data'] ?? []);
$key = (string) ($data['key'] ?? '');
@@ -0,0 +1,55 @@
{{-- Zeile eines Feldes in der Formularansicht. $f ist der Name der Alpine-Variable (item oder inner). --}}
<div class="vw-fe-zeile">
<button type="button" class="vw-fe-griff" aria-label="Feld verschieben: mit der Maus ziehen oder Pfeil hoch und runter" title="Feld verschieben"
x-on:keydown.up.prevent="shift({{ $f }}, -1)" x-on:keydown.down.prevent="shift({{ $f }}, 1)">
@include('filament.verwaltung.icon', ['name' => 'griff'])
</button>
<label class="vw-fe-frage">
<span class="vw-sr">Frage oder Beschriftung des Feldes</span>
<input type="text" x-model="{{ $f }}.label" maxlength="200" placeholder="Frage oder Beschriftung, z. B. Ihre E-Mail-Adresse"
x-bind:class="{ 'is-invalid': !{{ $f }}.label.trim() }" x-bind:aria-invalid="!{{ $f }}.label.trim()" data-fe-feld="frage">
</label>
<label class="vw-fe-typ">
<span class="vw-sr">Art der Antwort</span>
<select x-model="{{ $f }}.type" x-on:change="typeChanged({{ $f }})" x-bind:disabled="!isTmp({{ $f }}.key)"
x-bind:title="isTmp({{ $f }}.key) ? '' : 'Die Art lässt sich nach dem Speichern nicht mehr ändern, weil Bedingungen und bisherige Anfragen darauf aufbauen. Lege dafür ein neues Feld an.'" data-fe-feld="typ">
<template x-for="type in cfg.types" x-bind:key="type.value">
<option x-bind:value="type.value" x-text="type.label" x-bind:selected="{{ $f }}.type === type.value"></option>
</template>
</select>
</label>
<label class="vw-fe-pflicht">
<input type="checkbox" x-model="{{ $f }}.required" data-fe-feld="pflicht">
<span>Pflicht</span>
</label>
<span class="vw-fe-symbole">
<button type="button" class="vw-fe-symbol" x-bind:class="{ 'is-gesetzt': {{ $f }}.help.trim() }" x-on:click="openModal('text', {{ $f }})" x-bind:title="{{ $f }}.help.trim() ? 'Hilfetext: ' + {{ $f }}.help : 'Hilfetext hinzufügen'" aria-label="Hilfetext des Feldes" data-fe-aktion="hilfetext">
@include('filament.verwaltung.icon', ['name' => 'frage'])
</button>
<button type="button" class="vw-fe-symbol" x-bind:class="{ 'is-versteckt': !typeOf({{ $f }}.type).options, 'is-gesetzt': {{ $f }}.options.length > 0, 'is-warnung': {{ $f }}.options.length === 0 }" x-bind:tabindex="typeOf({{ $f }}.type).options ? 0 : -1" x-bind:aria-hidden="!typeOf({{ $f }}.type).options" x-on:click="openModal('options', {{ $f }})" x-bind:title="optionsText({{ $f }})" aria-label="Auswahlwerte des Feldes" data-fe-aktion="auswahlwerte">
@include('filament.verwaltung.icon', ['name' => 'liste'])
<span class="vw-fe-zaehler" x-text="{{ $f }}.options.length"></span>
</button>
<button type="button" class="vw-fe-symbol" x-bind:class="{ 'is-gesetzt': hasCond({{ $f }}), 'is-warnung': condProblem({{ $f }}) }" x-on:click="openModal('cond', {{ $f }})" x-bind:title="condText({{ $f }}) || 'Bedingung für das Feld'" aria-label="Bedingung des Feldes" data-fe-aktion="bedingung-feld">
@include('filament.verwaltung.icon', ['name' => 'verzweigung'])
</button>
<button type="button" class="vw-fe-symbol" x-on:click="openModal('more', {{ $f }})" title="Weitere Einstellungen" aria-label="Weitere Einstellungen des Feldes">
@include('filament.verwaltung.icon', ['name' => 'mehr'])
</button>
<button type="button" class="vw-fe-symbol is-gefahr" x-on:click="remove({{ $f }})" title="Feld aus dem Formular entfernen" aria-label="Feld aus dem Formular entfernen">
@include('filament.verwaltung.icon', ['name' => 'papierkorb'])
</button>
</span>
</div>
<p class="vw-fe-bedingung" x-show="hasCond({{ $f }})" x-cloak>
@include('filament.verwaltung.icon', ['name' => 'verzweigung'])
<span x-text="condText({{ $f }})"></span>
</p>
<p class="vw-fe-bedingung is-info" x-show="{{ $f }}.used_in" x-cloak>
@include('filament.verwaltung.icon', ['name' => 'info'])
<span>Auch verwendet in: <span x-text="{{ $f }}.used_in"></span></span>
</p>
@@ -0,0 +1,828 @@
@verbatim
<script>
/*
* Formularansicht des Aufbaus (ADR-62). Der Baum besteht aus Bereichen (areas[]), darin Felder, Teilbereiche (mit eigenen
* Feldern) und höchstens einer Frage nach dem Anliegen. Der Browser führt den Baum; beim Speichern liegt er als Text im
* Formularzustand (state), den FormEditor prüft und in Katalog und Entwurf überführt. Ziehen und Ablegen: SortableJS, das
* Filament mitbringt (window.Sortable). Der Baum ist die einzige Wahrheit: Nach jedem Ablegen wird die Verschiebung im
* Baum nachvollzogen und die vom Ziehen bewegte DOM-Position zurückgesetzt, damit Alpine die Liste neu zeichnet.
*/
window.lufFormEditor = window.lufFormEditor || function (cfg) {
const letters = 'abcdefghijklmnopqrstuvwxyz0123456789';
const random = (n) => Array.from({ length: n }, () => letters[Math.floor(Math.random() * letters.length)]).join('');
const uid = () => 'n' + random(9);
const kindOfEffect = { area: 'step', section: 'group', field: 'field' };
const blankCond = () => ({ effect: '', match: 'all', conditions: [], pos: null });
const prepCond = (cond) => {
if (!cond || Array.isArray(cond)) {
return blankCond();
}
return {
effect: cond.effect || '',
match: cond.match === 'any' ? 'any' : 'all',
conditions: (cond.conditions || []).map((c) => ({ _id: uid(), source: c.source || '', op: c.op || 'eq', values: [...(c.values || [])] })),
pos: cond.pos ?? null,
};
};
const prepField = (f) => ({
_id: uid(),
kind: 'field',
key: f.key || '',
name: f.name || '',
label: f.label || '',
help: f.help || '',
type: f.type || 'text',
options: (f.options || []).map((o) => ({ _id: uid(), key: o.key || '', label: o.label || '' })),
required: !!f.required,
purpose: f.purpose || '',
used_in: f.used_in || '',
cond: prepCond(f.cond),
});
const prepItem = (item) => {
if (item.kind === 'issue') {
return { _id: uid(), kind: 'issue', issues: [...(item.issues || [])] };
}
if (item.kind === 'section') {
return {
_id: uid(),
kind: 'section',
key: item.key || '',
label: item.label || '',
description: item.description || '',
missing: !!item.missing,
used_in: item.used_in || '',
cond: prepCond(item.cond),
items: (item.items || []).map(prepField),
};
}
return prepField(item);
};
const prepArea = (a) => ({
_id: uid(),
kind: 'area',
key: a.key || 's' + random(6),
title: a.title || '',
intro: a.intro || '',
cond: prepCond(a.cond),
items: (a.items || []).map(prepItem),
});
return {
cfg,
tree: { areas: [] },
history: [],
last: '',
modal: null,
modalNode: null,
catalogSearch: '',
announcement: '',
opener: null,
refreshTimer: null,
sortables: [],
init() {
this.load(this.state);
this.$watch('state', (value) => {
// Der Server hat einen neuen Stand geliefert (nach dem Speichern: feste Kennungen statt tmp_…).
if (value !== this.last) {
this.load(value);
this.history = [];
}
});
},
/* ------------------------------------------------------------ Laden und Übergeben */
load(json) {
let data = {};
try {
data = JSON.parse(json || '{}') || {};
} catch (e) {
data = {};
}
this.tree = { areas: (data.areas || []).map(prepArea) };
this.modal = null;
this.modalNode = null;
if (this.$refs.dialog && this.$refs.dialog.open) {
this.$refs.dialog.close();
}
this.last = this.serialize();
},
serialize() {
return JSON.stringify({ areas: this.tree.areas }, (key, value) => (key === '_id' ? undefined : value));
},
commit() {
const json = this.serialize();
if (json === this.last) {
return;
}
this.last = json;
this.state = json;
this.refreshSoon();
},
// Die Regelliste im Register „Weitere Regeln“ liest den Aufbau auf dem Server; deshalb nach Änderungen kurz abgleichen.
refreshSoon() {
clearTimeout(this.refreshTimer);
this.refreshTimer = setTimeout(() => this.$wire.$refresh(), 1500);
},
snapshot() {
this.history.push(this.serialize());
if (this.history.length > 40) {
this.history.shift();
}
},
undo() {
const previous = this.history.pop();
if (previous === undefined) {
return;
}
const rest = this.history;
this.load(previous);
this.history = rest;
this.last = '';
this.commit();
this.announce('Letzte Änderung rückgängig gemacht.');
},
announce(text) {
this.announcement = '';
this.$nextTick(() => { this.announcement = text; });
},
/* ------------------------------------------------------------ Hilfen */
isTmp(key) {
return String(key || '').startsWith('tmp_');
},
typeOf(value) {
return this.cfg.types.find((type) => type.value === value) || { value, label: value, options: false, control: false };
},
typeLabel(value) {
return this.typeOf(value).label;
},
all() {
const out = [];
this.tree.areas.forEach((area) => {
out.push(area);
area.items.forEach((item) => {
out.push(item);
if (item.kind === 'section') {
item.items.forEach((inner) => out.push(inner));
}
});
});
return out;
},
find(id) {
for (let ai = 0; ai < this.tree.areas.length; ai++) {
const area = this.tree.areas[ai];
if (area._id === id) {
return { node: area, list: this.tree.areas, index: ai, parent: null };
}
for (let ii = 0; ii < area.items.length; ii++) {
const item = area.items[ii];
if (item._id === id) {
return { node: item, list: area.items, index: ii, parent: area };
}
if (item.kind === 'section') {
for (let fi = 0; fi < item.items.length; fi++) {
if (item.items[fi]._id === id) {
return { node: item.items[fi], list: item.items, index: fi, parent: item };
}
}
}
}
}
return null;
},
container(id) {
if (id === 'areas') {
return { list: this.tree.areas, node: null };
}
const hit = this.find(id.slice(2));
return hit ? { list: hit.node.items, node: hit.node } : null;
},
summary() {
const nodes = this.all();
const fields = nodes.filter((node) => node.kind === 'field').length;
const sections = nodes.filter((node) => node.kind === 'section').length;
return this.tree.areas.length + (this.tree.areas.length === 1 ? ' Bereich' : ' Bereiche') + ' · ' + fields + (fields === 1 ? ' Feld' : ' Felder') + (sections ? ' · ' + sections + (sections === 1 ? ' Teilbereich' : ' Teilbereiche') : '');
},
hasIssue() {
return this.all().some((node) => node.kind === 'issue');
},
/* ------------------------------------------------------------ Angaben, die noch fehlen */
fieldProblem(field) {
if (!field.label.trim()) {
return true;
}
return this.typeOf(field.type).options && !field.options.some((option) => option.label.trim());
},
problems() {
let count = 0;
this.tree.areas.forEach((area) => {
if (!area.title.trim()) {
count++;
}
});
this.all().forEach((node) => {
if (node.kind === 'section' && !node.label.trim()) {
count++;
} else if (node.kind === 'field' && this.fieldProblem(node)) {
count++;
}
});
return count;
},
optionsText(field) {
const count = field.options.length;
return count === 0 ? 'Auswahlwerte fehlen noch' : 'Auswahlwerte (' + count + '): ' + field.options.map((option) => option.label).filter(Boolean).join(', ');
},
issueText(item) {
if (!item.issues.length) {
return 'Alle angebotenen Anliegen';
}
return item.issues.map((key) => (this.cfg.issues.find((issue) => issue.key === key) || { label: key }).label).join(', ');
},
/* ------------------------------------------------------------ Hinzufügen und Entfernen */
addArea() {
this.snapshot();
const area = prepArea({ title: '', items: [] });
this.tree.areas.push(area);
this.afterAdd(area, '[data-fe-feld="titel"]');
},
newField(base = {}) {
return prepField({ key: 'tmp_' + random(8), type: 'text', ...base });
},
addField(target) {
this.snapshot();
const field = this.newField();
target.items.push(field);
this.afterAdd(field, '[data-fe-feld="frage"]');
},
addSection(area) {
this.snapshot();
const section = prepItem({ kind: 'section', key: 'tmp_' + random(8), label: '', items: [] });
area.items.push(section);
this.afterAdd(section, '[data-fe-feld="teil"]');
},
addIssue(area) {
if (this.hasIssue()) {
return;
}
this.snapshot();
const issue = prepItem({ kind: 'issue', issues: [] });
// Die Frage nach dem Anliegen steht üblicherweise zuoberst im Bereich.
area.items.unshift(issue);
this.afterAdd(issue, '.vw-fe-symbol');
},
afterAdd(node, selector) {
this.commit();
this.$nextTick(() => {
const el = this.$root.querySelector('[data-fe-id="' + node._id + '"] ' + selector);
if (el) {
el.scrollIntoView({ block: 'nearest' });
el.focus();
}
});
},
insertCatalog(entry) {
const target = this.modalNode;
if (!target) {
return;
}
this.snapshot();
const field = this.newField({
key: entry.key,
name: entry.name,
label: entry.label,
help: entry.help,
type: entry.type,
options: entry.options,
purpose: entry.purpose,
used_in: entry.used_in,
});
target.items.push(field);
this.commit();
this.closeModal();
this.announce('Das Feld „' + field.label + '“ wurde eingefügt.');
},
catalogEntries() {
const used = new Set(this.all().filter((node) => node.kind === 'field').map((node) => node.key));
const term = this.catalogSearch.trim().toLowerCase();
return this.cfg.catalog.filter((entry) => !used.has(entry.key) && (term === '' || (entry.label + ' ' + entry.name).toLowerCase().includes(term)));
},
remove(node) {
const hit = this.find(node._id);
if (!hit) {
return;
}
this.snapshot();
hit.list.splice(hit.index, 1);
this.commit();
if (this.modal) {
this.closeModal();
}
this.announce('Entfernt. Mit „Rückgängig“ lässt sich das zurücknehmen.');
},
typeChanged(field) {
const type = this.typeOf(field.type);
if (type.options && field.options.length === 0) {
field.options = [{ _id: uid(), key: '', label: '' }];
}
if (field.type === 'boolean') {
field.options = [{ _id: uid(), key: 'ja', label: 'Ja' }, { _id: uid(), key: 'nein', label: 'Nein' }];
}
if (field.purpose && !this.purposesFor(field).some((purpose) => purpose.value === field.purpose)) {
field.purpose = '';
}
if (type.options && field.options.every((option) => !option.label.trim())) {
this.openModal('options', field);
}
},
purposesFor(field) {
return this.cfg.purposes.filter((purpose) => purpose.types.includes(field.type));
},
/* ------------------------------------------------------------ Auswahlwerte */
addOption() {
this.modalNode.options.push({ _id: uid(), key: '', label: '' });
this.$nextTick(() => {
const inputs = this.$root.querySelectorAll('[data-fe-werte] input');
inputs[inputs.length - 1]?.focus();
});
},
removeOption(index) {
this.modalNode.options.splice(index, 1);
},
moveOption(index, delta) {
const options = this.modalNode.options;
const target = index + delta;
if (target < 0 || target >= options.length) {
return;
}
options.splice(target, 0, options.splice(index, 1)[0]);
},
/* ------------------------------------------------------------ Verschieben */
shift(node, delta) {
const hit = this.find(node._id);
if (!hit) {
return;
}
const target = hit.index + delta;
this.snapshot();
if (target >= 0 && target < hit.list.length) {
hit.list.splice(hit.index, 1);
hit.list.splice(target, 0, node);
} else if (hit.parent && hit.parent.kind === 'section') {
// Am Rand eines Teilbereichs: das Feld verlässt ihn, direkt vor oder hinter dem Teilbereich.
const outer = this.find(hit.parent._id);
hit.list.splice(hit.index, 1);
outer.list.splice(outer.index + (delta < 0 ? 0 : 1), 0, node);
} else {
this.history.pop();
return;
}
this.commit();
const now = this.find(node._id);
this.announce((node.label || node.title || 'Element') + ': Position ' + (now.index + 1) + ' von ' + now.list.length + '.');
setTimeout(() => this.$root.querySelector('[data-fe-id="' + node._id + '"] .vw-fe-griff')?.focus(), 40);
},
movable(node) {
return node && node.kind !== 'area' && this.targetsFor(node).length > 0;
},
targetsFor(node) {
const targets = [];
this.tree.areas.forEach((area, ai) => {
targets.push({ value: 'a:' + area._id, label: 'Bereich ' + (ai + 1) + (area.title.trim() ? ' „' + area.title.trim() + '“' : '') });
if (node.kind === 'field') {
area.items.filter((item) => item.kind === 'section').forEach((section) => {
targets.push({ value: 's:' + section._id, label: ' Teilbereich „' + (section.label.trim() || 'ohne Überschrift') + '“ (Bereich ' + (ai + 1) + ')' });
});
}
});
return targets;
},
moveTo(node, destination) {
if (!destination) {
return;
}
const hit = this.find(node._id);
const to = this.container(destination);
if (!hit || !to) {
return;
}
this.snapshot();
hit.list.splice(hit.index, 1);
to.list.push(node);
this.commit();
this.closeModal();
this.announce('Verschoben.');
},
// Ziehen und Ablegen -------------------------------------------------------------------------
mountList(el, id) {
if (!window.Sortable) {
return;
}
const isAreas = id === 'areas';
const inSection = id.startsWith('s:');
window.Sortable.create(el, {
group: {
name: isAreas ? 'fe-bereiche' : 'fe-elemente',
pull: true,
put: (to, from, dragged) => (isAreas ? false : (inSection ? dragged.dataset.feKind === 'field' : true)),
},
draggable: isAreas ? '[data-fe-area]' : '[data-fe-item]',
handle: isAreas ? '.vw-fe-griff-bereich' : '.vw-fe-griff',
animation: 150,
ghostClass: 'vw-fe-geist',
chosenClass: 'vw-fe-gegriffen',
dragClass: 'vw-fe-gezogen',
emptyInsertThreshold: 24,
fallbackOnBody: true,
swapThreshold: 0.6,
onEnd: (event) => this.dropped(event),
});
},
dropped(event) {
const { item, from, to, oldDraggableIndex, newDraggableIndex } = event;
const id = item.dataset.feId;
const draggable = item.hasAttribute('data-fe-area') ? '[data-fe-area]' : '[data-fe-item]';
const target = to.dataset.feList;
if (from === to && oldDraggableIndex === newDraggableIndex) {
return;
}
// Die DOM-Position zurücksetzen: Alpine zeichnet die Listen aus dem Baum neu.
item.remove();
const siblings = Array.from(from.querySelectorAll(':scope > ' + draggable));
from.insertBefore(item, siblings[oldDraggableIndex] || null);
const hit = this.find(id);
const destination = this.container(target);
if (!hit || !destination) {
return;
}
// Ein Teilbereich bleibt auf der Ebene eines Bereichs; Felder dürfen überallhin.
if (hit.node.kind === 'section' && destination.node && destination.node.kind === 'section') {
return;
}
this.snapshot();
hit.list.splice(hit.index, 1);
destination.list.splice(Math.min(newDraggableIndex, destination.list.length), 0, hit.node);
this.commit();
this.announce((hit.node.label || hit.node.title || 'Element') + ' verschoben.');
},
/* ------------------------------------------------------------ Dialog */
openModal(kind, node) {
this.opener = document.activeElement;
this.catalogSearch = '';
this.modal = { kind };
this.modalNode = node;
if (kind === 'cond' && node.cond.effect && node.cond.conditions.length === 0) {
this.addCond(node);
}
this.$nextTick(() => {
if (!this.$refs.dialog.open) {
this.$refs.dialog.showModal();
}
// Der Inhalt des Dialogs entsteht erst nach dem Öffnen; deshalb kurz warten, bis das Zielfeld da ist.
setTimeout(() => {
if (kind === 'options') {
const inputs = Array.from(this.$root.querySelectorAll('[data-fe-werte] input'));
(inputs.find((input) => input.value === '') || this.$root.querySelector('[data-fe-aktion="option-neu"]'))?.focus();
} else {
this.$refs.dialogFocus?.focus();
}
}, 60);
});
},
closeModal() {
if (this.$refs.dialog.open) {
this.$refs.dialog.close();
} else {
this.onDialogClose();
}
},
onDialogClose() {
// Leere, nie gespeicherte Auswahlwerte fallen beim Schließen weg.
if (this.modal && this.modal.kind === 'options' && this.modalNode) {
this.modalNode.options = this.modalNode.options.filter((option) => option.label.trim() || option.key);
}
this.commit();
this.modal = null;
this.modalNode = null;
if (this.opener && document.contains(this.opener)) {
this.opener.focus();
}
},
dialogTitle() {
const node = this.modalNode;
if (!this.modal || !node) {
return '';
}
const name = (node.label || node.title || '').trim();
const of = name ? ' „' + name + '“' : '';
switch (this.modal.kind) {
case 'text': return node.kind === 'field' ? 'Hilfetext' + of : (node.kind === 'area' ? 'Einleitung des Bereichs' + of : 'Erläuterung des Teilbereichs' + of);
case 'options': return 'Auswahlwerte' + of;
case 'cond': return 'Bedingung' + of;
case 'issue': return 'Frage nach dem Anliegen';
case 'more': return 'Weitere Einstellungen' + of;
case 'catalog': return 'Vorhandenes Feld einfügen';
default: return '';
}
},
textKey() {
const kind = this.modalNode?.kind;
return kind === 'field' ? 'help' : (kind === 'area' ? 'intro' : 'description');
},
textLabel() {
const kind = this.modalNode?.kind;
return kind === 'field' ? 'Hilfetext (steht unter der Frage)' : (kind === 'area' ? 'Einleitung (steht unter dem Titel des Bereichs)' : 'Erläuterung (steht unter der Überschrift)');
},
textHint() {
return this.modalNode?.kind === 'field' ? 'Ein Hilfetext erklärt, was in das Feld gehört. Leer lassen, wenn die Frage reicht.' : 'Optional. Leer lassen, wenn nichts erklärt werden muss.';
},
/* ------------------------------------------------------------ Bedingungen */
hasCond(node) {
return !!node.cond.effect && node.cond.conditions.some((c) => c.source);
},
effectOptions(node) {
return this.cfg.effects[kindOfEffect[node.kind]] || {};
},
effectChanged(node) {
if (node.cond.effect) {
if (node.cond.conditions.length === 0) {
this.addCond(node);
}
} else {
node.cond.conditions = [];
}
},
addCond(node) {
node.cond.conditions.push({ _id: uid(), source: '', op: 'eq', values: [] });
},
removeCond(node, index) {
node.cond.conditions.splice(index, 1);
if (node.cond.conditions.length === 0) {
node.cond.effect = '';
}
},
toggleValue(cond, value, on) {
const has = cond.values.includes(value);
if (on && !has) {
cond.values.push(value);
} else if (!on && has) {
cond.values.splice(cond.values.indexOf(value), 1);
}
},
toggleIssue(item, key, on) {
const has = item.issues.includes(key);
if (on && !has) {
item.issues.push(key);
} else if (!on && has) {
item.issues.splice(item.issues.indexOf(key), 1);
}
},
// Felder, auf die sich eine Bedingung stützen darf: gespeicherte Auswahl- und Ja/Nein-Felder oberhalb des Elements.
sourcesFor(node) {
const sources = [];
let issue = null;
for (const other of this.all()) {
if (other._id === node._id) {
break;
}
if (other.kind === 'issue') {
issue = other;
} else if (other.kind === 'field' && this.typeOf(other.type).control && !this.isTmp(other.key)) {
sources.push({ value: other.key, label: other.label.trim() || other.key });
}
}
if (issue) {
sources.unshift({ value: 'unteranliegen', label: 'Unteranliegen' }, { value: 'anliegen', label: 'Anliegen' });
}
return sources;
},
// Auswahl der Grundlage; eine nicht mehr gültige Grundlage bleibt sichtbar, damit sie ersetzt werden kann.
sourceChoices(node, cond) {
const sources = this.sourcesFor(node);
if (cond.source && !sources.some((source) => source.value === cond.source)) {
sources.push({ value: cond.source, label: this.sourceLabel(cond.source) + ' (nicht mehr verfügbar)' });
}
return sources;
},
sourceLabel(source) {
if (source === 'anliegen') {
return 'Anliegen';
}
if (source === 'unteranliegen') {
return 'Unteranliegen';
}
const field = this.all().find((node) => node.kind === 'field' && node.key === source);
return field ? (field.label.trim() || source) : source;
},
sourceValues(node, source) {
if (!source) {
return [];
}
if (source === 'anliegen' || source === 'unteranliegen') {
const only = (this.all().find((other) => other.kind === 'issue') || { issues: [] }).issues;
const values = [];
this.cfg.issues.forEach((issue) => {
if (only.length && !only.includes(issue.key)) {
return;
}
if (source === 'anliegen') {
values.push({ value: issue.key, label: issue.label });
} else {
issue.children.forEach((child) => values.push({ value: child.key, label: issue.label + ' › ' + child.label }));
}
});
return values;
}
const field = this.all().find((other) => other.kind === 'field' && other.key === source);
return field ? field.options.filter((option) => option.key).map((option) => ({ value: option.key, label: option.label })) : [];
},
condSourceProblem(node, cond) {
return !!cond.source && !this.sourcesFor(node).some((source) => source.value === cond.source);
},
condProblem(node) {
return !!node.cond.effect && node.cond.conditions.some((cond) => this.condSourceProblem(node, cond));
},
condText(node) {
if (!this.hasCond(node)) {
return '';
}
const effect = (this.effectOptions(node)[node.cond.effect] || '').replace(/\s*…$/, '').replace(/,\s*wenn$/, '');
const joiner = node.cond.match === 'any' ? ' oder ' : ' und ';
const parts = node.cond.conditions.filter((cond) => cond.source).map((cond) => {
const values = cond.values.map((value) => {
const found = this.sourceValues(node, cond.source).find((option) => option.value === value);
return found ? found.label : value;
});
return this.sourceLabel(cond.source) + ' ' + (this.cfg.operators[cond.op] || cond.op) + ' ' + (values.join(' / ') || '…');
});
return effect + ', wenn ' + parts.join(joiner) + (this.condProblem(node) ? ' – bitte prüfen: Grundlage steht nicht oberhalb' : '');
},
};
};
</script>
@endverbatim
@@ -0,0 +1,396 @@
{{--
Formularansicht des Aufbaus (ADR-62): Bereiche, Teilbereiche und Felder als Baum, im Browser bearbeitet und beim Speichern
als Text (editor_json) übergeben. Logik: form-editor-script.blade.php. Gestaltung: verwaltung/styles.blade.php (vw-fe-…).
--}}
@php
$statePath = $getStatePath();
@endphp
@once
@include('filament.communication.form-editor-script')
@endonce
<div class="vw-fe-aussen" data-fe-aussen>
@if ($errors->has($statePath))
<div class="vw-fe-fehler" role="alert" data-fe-fehler>
<strong>Das Formular lässt sich so noch nicht speichern:</strong>
<ul>
@foreach ($errors->get($statePath) as $message)
<li>{{ $message }}</li>
@endforeach
</ul>
</div>
@endif
<div
class="vw vw-fe"
wire:ignore
data-fe-root
x-data="{ state: $wire.$entangle('{{ $statePath }}'), ...lufFormEditor(@js($config)) }"
x-on:input="commit()"
x-on:change="commit()"
>
<div class="vw-fe-leiste">
<p class="vw-fe-hinweis">
@include('filament.verwaltung.icon', ['name' => 'info'])
<span>Ziehe Bereiche, Teilbereiche und Felder am Griff <b aria-hidden="true">⋮⋮</b> an eine beliebige Stelle. Mit der Tastatur: Griff wählen, dann Pfeil hoch oder runter.</span>
</p>
<div class="vw-fe-leiste-aktionen">
<span class="vw-fe-zahl" x-text="summary()"></span>
<button type="button" class="vw-btn is-small" x-on:click="undo()" x-bind:disabled="history.length === 0">
@include('filament.verwaltung.icon', ['name' => 'zuruecksetzen'])
Rückgängig
</button>
</div>
</div>
<p class="vw-fe-zusatz" x-show="problems() > 0" x-cloak role="status">
<span x-text="problems()"></span> <span x-text="problems() === 1 ? 'Angabe fehlt noch' : 'Angaben fehlen noch'"></span> (rot umrandet). Speichern ist erst danach möglich.
</p>
<p class="vw-sr" role="status" aria-live="polite" x-text="announcement"></p>
<div class="vw-fe-bereiche" data-fe-list="areas" x-init="mountList($el, 'areas')">
<template x-for="(area, ai) in tree.areas" x-bind:key="area._id">
<section class="vw-fe-bereich" data-fe-area x-bind:data-fe-id="area._id" x-bind:aria-label="'Bereich ' + (ai + 1)">
<header class="vw-fe-bereich-kopf">
<button type="button" class="vw-fe-griff vw-fe-griff-bereich" aria-label="Bereich verschieben: mit der Maus ziehen oder Pfeil hoch und runter" title="Bereich verschieben"
x-on:keydown.up.prevent="shift(area, -1)" x-on:keydown.down.prevent="shift(area, 1)">
@include('filament.verwaltung.icon', ['name' => 'griff'])
</button>
<span class="vw-fe-nummer" x-text="ai + 1" aria-hidden="true"></span>
<label class="vw-fe-titel">
<span class="vw-sr">Titel des Bereichs</span>
<input type="text" x-model="area.title" maxlength="120" placeholder="Titel des Bereichs, z. B. Ihre Angaben" x-bind:class="{ 'is-invalid': !area.title.trim() }" x-bind:aria-invalid="!area.title.trim()" data-fe-feld="titel">
</label>
<span class="vw-fe-symbole">
<button type="button" class="vw-fe-symbol" x-bind:class="{ 'is-gesetzt': area.intro.trim() }" x-on:click="openModal('text', area)" title="Einleitung des Bereichs" aria-label="Einleitung des Bereichs bearbeiten">
@include('filament.verwaltung.icon', ['name' => 'frage'])
</button>
<button type="button" class="vw-fe-symbol" x-bind:class="{ 'is-gesetzt': hasCond(area), 'is-warnung': condProblem(area) }" x-on:click="openModal('cond', area)" x-bind:title="condText(area) || 'Bedingung für den Bereich'" aria-label="Bedingung des Bereichs bearbeiten">
@include('filament.verwaltung.icon', ['name' => 'verzweigung'])
</button>
<button type="button" class="vw-fe-symbol" x-on:click="openModal('more', area)" title="Weitere Einstellungen" aria-label="Weitere Einstellungen des Bereichs">
@include('filament.verwaltung.icon', ['name' => 'mehr'])
</button>
<button type="button" class="vw-fe-symbol is-gefahr" x-on:click="remove(area)" title="Bereich entfernen" aria-label="Bereich entfernen">
@include('filament.verwaltung.icon', ['name' => 'papierkorb'])
</button>
</span>
</header>
<p class="vw-fe-bedingung" x-show="hasCond(area)" x-cloak>
@include('filament.verwaltung.icon', ['name' => 'verzweigung'])
<span x-text="condText(area)"></span>
</p>
<div class="vw-fe-inhalt" x-bind:data-fe-list="'a:' + area._id" x-bind:data-leer="area.items.length === 0 ? 'Dieser Bereich ist noch leer. Füge ein Feld hinzu oder ziehe eines hierher.' : false" x-init="mountList($el, 'a:' + area._id)">
<template x-for="item in area.items" x-bind:key="item._id">
<div class="vw-fe-element" data-fe-item x-bind:data-fe-id="item._id" x-bind:data-fe-kind="item.kind">
{{-- Feld im Bereich --}}
<template x-if="item.kind === 'field'">
<div class="vw-fe-feld" x-bind:class="{ 'is-ungueltig': fieldProblem(item) }">
@include('filament.communication.form-editor-feld', ['f' => 'item'])
</div>
</template>
{{-- Frage nach dem Anliegen --}}
<template x-if="item.kind === 'issue'">
<div class="vw-fe-feld vw-fe-anliegen">
<button type="button" class="vw-fe-griff" aria-label="Frage nach dem Anliegen verschieben: ziehen oder Pfeil hoch und runter" title="Verschieben"
x-on:keydown.up.prevent="shift(item, -1)" x-on:keydown.down.prevent="shift(item, 1)">
@include('filament.verwaltung.icon', ['name' => 'griff'])
</button>
<div class="vw-fe-anliegen-text">
<strong>Frage nach dem Anliegen</strong>
<span x-text="issueText(item)"></span>
</div>
<span class="vw-fe-symbole">
<button type="button" class="vw-fe-symbol is-gesetzt" x-on:click="openModal('issue', item)" title="Angebotene Anliegen" aria-label="Angebotene Anliegen wählen">
@include('filament.verwaltung.icon', ['name' => 'liste'])
</button>
<button type="button" class="vw-fe-symbol" x-on:click="openModal('more', item)" title="Weitere Einstellungen" aria-label="Weitere Einstellungen">
@include('filament.verwaltung.icon', ['name' => 'mehr'])
</button>
<button type="button" class="vw-fe-symbol is-gefahr" x-on:click="remove(item)" title="Frage entfernen" aria-label="Frage nach dem Anliegen entfernen">
@include('filament.verwaltung.icon', ['name' => 'papierkorb'])
</button>
</span>
</div>
</template>
{{-- Teilbereich mit eigenen Feldern --}}
<template x-if="item.kind === 'section'">
<div class="vw-fe-teil" data-fe-section>
<header class="vw-fe-teil-kopf">
<button type="button" class="vw-fe-griff" aria-label="Teilbereich verschieben: ziehen oder Pfeil hoch und runter" title="Teilbereich verschieben"
x-on:keydown.up.prevent="shift(item, -1)" x-on:keydown.down.prevent="shift(item, 1)">
@include('filament.verwaltung.icon', ['name' => 'griff'])
</button>
<span class="vw-fe-art">
@include('filament.verwaltung.icon', ['name' => 'teilbereich'])
Teilbereich
</span>
<label class="vw-fe-titel">
<span class="vw-sr">Überschrift des Teilbereichs</span>
<input type="text" x-model="item.label" maxlength="200" placeholder="Überschrift des Teilbereichs" x-bind:readonly="item.missing" x-bind:class="{ 'is-invalid': !item.label.trim() }" x-bind:aria-invalid="!item.label.trim()" data-fe-feld="teil">
</label>
<span class="vw-fe-symbole">
<button type="button" class="vw-fe-symbol" x-bind:class="{ 'is-gesetzt': item.description.trim() }" x-on:click="openModal('text', item)" title="Erläuterung des Teilbereichs" aria-label="Erläuterung des Teilbereichs bearbeiten">
@include('filament.verwaltung.icon', ['name' => 'frage'])
</button>
<button type="button" class="vw-fe-symbol" x-bind:class="{ 'is-gesetzt': hasCond(item), 'is-warnung': condProblem(item) }" x-on:click="openModal('cond', item)" x-bind:title="condText(item) || 'Bedingung für den Teilbereich'" aria-label="Bedingung des Teilbereichs bearbeiten">
@include('filament.verwaltung.icon', ['name' => 'verzweigung'])
</button>
<button type="button" class="vw-fe-symbol" x-on:click="openModal('more', item)" title="Weitere Einstellungen" aria-label="Weitere Einstellungen des Teilbereichs">
@include('filament.verwaltung.icon', ['name' => 'mehr'])
</button>
<button type="button" class="vw-fe-symbol is-gefahr" x-on:click="remove(item)" title="Teilbereich mit seinen Feldern entfernen" aria-label="Teilbereich entfernen">
@include('filament.verwaltung.icon', ['name' => 'papierkorb'])
</button>
</span>
</header>
<p class="vw-fe-bedingung" x-show="hasCond(item)" x-cloak>
@include('filament.verwaltung.icon', ['name' => 'verzweigung'])
<span x-text="condText(item)"></span>
</p>
<p class="vw-fe-notiz" x-show="item.used_in" x-cloak>Dieser Teilbereich wird auch in anderen Formularen verwendet: <span x-text="item.used_in"></span>. Änderungen an seinen Feldern gelten dort mit deren nächster Veröffentlichung.</p>
<p class="vw-fe-notiz is-warnung" x-show="item.missing" x-cloak>Diese Feldgruppe gibt es im Katalog nicht mehr. Entferne den Teilbereich oder lege ihn neu an.</p>
<div class="vw-fe-teil-inhalt" x-bind:data-fe-list="'s:' + item._id" x-bind:data-leer="item.items.length === 0 ? 'Noch kein Feld. Ziehe Felder hierher oder füge eines hinzu.' : false" x-init="mountList($el, 's:' + item._id)">
<template x-for="inner in item.items" x-bind:key="inner._id">
<div class="vw-fe-element" data-fe-item x-bind:data-fe-id="inner._id" data-fe-kind="field">
<div class="vw-fe-feld" x-bind:class="{ 'is-ungueltig': fieldProblem(inner) }">
@include('filament.communication.form-editor-feld', ['f' => 'inner'])
</div>
</div>
</template>
</div>
<footer class="vw-fe-fuss">
<button type="button" class="vw-btn is-small is-line" x-on:click="addField(item)">
@include('filament.verwaltung.icon', ['name' => 'plus'])
Neues Feld im Teilbereich
</button>
<button type="button" class="vw-btn is-small" x-on:click="openModal('catalog', item)">Vorhandenes Feld einfügen</button>
</footer>
</div>
</template>
</div>
</template>
</div>
<footer class="vw-fe-fuss">
<button type="button" class="vw-btn is-small is-line" x-on:click="addField(area)" data-fe-aktion="feld">
@include('filament.verwaltung.icon', ['name' => 'plus'])
Neues Feld
</button>
<button type="button" class="vw-btn is-small" x-on:click="openModal('catalog', area)">Vorhandenes Feld einfügen</button>
<button type="button" class="vw-btn is-small" x-on:click="addSection(area)" data-fe-aktion="teilbereich">
@include('filament.verwaltung.icon', ['name' => 'teilbereich'])
Teilbereich
</button>
<button type="button" class="vw-btn is-small" x-on:click="addIssue(area)" x-show="!hasIssue()" x-cloak>
@include('filament.verwaltung.icon', ['name' => 'liste'])
Frage nach dem Anliegen
</button>
</footer>
</section>
</template>
</div>
<div class="vw-fe-leer-bereich" x-show="tree.areas.length === 0" x-cloak>
<p>Das Formular hat noch keinen Bereich. Im mehrstufigen Dialog ist jeder Bereich ein Schritt, im langen Formular stehen alle Bereiche untereinander.</p>
</div>
<div class="vw-fe-ende">
<button type="button" class="vw-btn is-line" x-on:click="addArea()" data-fe-aktion="bereich">
@include('filament.verwaltung.icon', ['name' => 'plus'])
Bereich hinzufügen
</button>
</div>
{{-- Ein Dialog für Hilfetext, Auswahlwerte, Bedingung, Einstellungen und Katalog --}}
<dialog class="vw-fe-dialog" x-ref="dialog" x-on:close="onDialogClose()" x-on:click="if ($event.target === $refs.dialog) closeModal()" aria-labelledby="vw-fe-dialog-titel">
<div class="vw-fe-dialog-karte" x-show="modal" x-cloak>
<header class="vw-fe-dialog-kopf">
<h2 id="vw-fe-dialog-titel" x-text="dialogTitle()"></h2>
<button type="button" class="vw-btn is-icon is-small" x-on:click="closeModal()" aria-label="Schließen">
@include('filament.verwaltung.icon', ['name' => 'x'])
</button>
</header>
<div class="vw-fe-dialog-inhalt" x-bind:data-fe-dialog="modal ? modal.kind : ''">
{{-- Text: Hilfetext, Einleitung, Erläuterung --}}
<template x-if="modal && modal.kind === 'text' && modalNode">
<div class="vw-fe-formular">
<label class="vw-fe-etikett">
<span x-text="textLabel()"></span>
<textarea rows="5" x-model="modalNode[textKey()]" x-bind:maxlength="modalNode.kind === 'field' ? 600 : (modalNode.kind === 'area' ? 600 : 600)" x-ref="dialogFocus"></textarea>
</label>
<p class="vw-fe-notiz" x-text="textHint()"></p>
</div>
</template>
{{-- Auswahlwerte --}}
<template x-if="modal && modal.kind === 'options' && modalNode">
<div class="vw-fe-formular">
<p class="vw-fe-notiz">Jeder Wert behält seine feste interne Kennung; eine Umbenennung beschädigt keine bisherigen Anfragen.</p>
<ol class="vw-fe-werte" data-fe-werte>
<template x-for="(option, oi) in modalNode.options" x-bind:key="option._id">
<li class="vw-fe-wert">
<input type="text" x-model="option.label" maxlength="120" placeholder="Bezeichnung des Auswahlwerts" x-bind:class="{ 'is-invalid': !option.label.trim() }" x-bind:aria-label="'Auswahlwert ' + (oi + 1)">
<button type="button" class="vw-fe-symbol" x-on:click="moveOption(oi, -1)" x-bind:disabled="oi === 0" aria-label="Nach oben" title="Nach oben">@include('filament.verwaltung.icon', ['name' => 'hoch'])</button>
<button type="button" class="vw-fe-symbol" x-on:click="moveOption(oi, 1)" x-bind:disabled="oi === modalNode.options.length - 1" aria-label="Nach unten" title="Nach unten">@include('filament.verwaltung.icon', ['name' => 'runter'])</button>
<button type="button" class="vw-fe-symbol is-gefahr" x-on:click="removeOption(oi)" aria-label="Auswahlwert entfernen" title="Entfernen">@include('filament.verwaltung.icon', ['name' => 'x'])</button>
</li>
</template>
</ol>
<button type="button" class="vw-btn is-small is-line" x-on:click="addOption()" data-fe-aktion="option-neu">
@include('filament.verwaltung.icon', ['name' => 'plus'])
Auswahlwert hinzufügen
</button>
</div>
</template>
{{-- Bedingung --}}
<template x-if="modal && modal.kind === 'cond' && modalNode">
<div class="vw-fe-formular">
<label class="vw-fe-etikett">
<span>Wirkung</span>
<select x-model="modalNode.cond.effect" x-on:change="effectChanged(modalNode)" x-ref="dialogFocus" data-fe-feld="wirkung">
<option value="">Keine Bedingung</option>
<template x-for="(label, value) in effectOptions(modalNode)" x-bind:key="value">
<option x-bind:value="value" x-text="label" x-bind:selected="modalNode.cond.effect === value"></option>
</template>
</select>
</label>
<p class="vw-fe-notiz" x-show="!modalNode.cond.effect">Ohne Wirkung gilt das Element immer. Wähle eine Wirkung, um es von einer Antwort abhängig zu machen.</p>
<template x-if="modalNode.cond.effect">
<div class="vw-fe-formular">
<label class="vw-fe-etikett" x-show="modalNode.cond.conditions.length > 1">
<span>Es müssen zutreffen</span>
<select x-model="modalNode.cond.match">
<option value="all">alle Bedingungen</option>
<option value="any">mindestens eine Bedingung</option>
</select>
</label>
<p class="vw-fe-notiz" x-show="sourcesFor(modalNode).length === 0">Als Grundlage stehen Auswahlfelder, Ja/Nein-Felder und die Frage nach dem Anliegen zur Verfügung, die im Formular weiter oben stehen und schon einmal gespeichert wurden.</p>
<template x-for="(cond, ci) in modalNode.cond.conditions" x-bind:key="cond._id">
<fieldset class="vw-fe-bed" x-bind:class="{ 'is-ungueltig': condSourceProblem(modalNode, cond) }">
<legend x-text="ci === 0 ? 'Wenn …' : (modalNode.cond.match === 'any' ? 'oder …' : 'und …')"></legend>
<div class="vw-fe-bed-zeile">
<label class="vw-fe-etikett">
<span class="vw-sr">Grundlage</span>
<select x-model="cond.source" x-on:change="cond.values = []" data-fe-feld="grundlage">
<option value="">Grundlage wählen …</option>
<template x-for="source in sourceChoices(modalNode, cond)" x-bind:key="source.value">
<option x-bind:value="source.value" x-text="source.label" x-bind:selected="cond.source === source.value"></option>
</template>
</select>
</label>
<label class="vw-fe-etikett">
<span class="vw-sr">Vergleich</span>
<select x-model="cond.op">
<template x-for="(label, value) in cfg.operators" x-bind:key="value">
<option x-bind:value="value" x-text="label" x-bind:selected="cond.op === value"></option>
</template>
</select>
</label>
<button type="button" class="vw-fe-symbol is-gefahr" x-on:click="removeCond(modalNode, ci)" aria-label="Bedingung entfernen" title="Bedingung entfernen">@include('filament.verwaltung.icon', ['name' => 'x'])</button>
</div>
<p class="vw-fe-notiz is-warnung" x-show="condSourceProblem(modalNode, cond)" x-cloak>Diese Grundlage steht nicht mehr oberhalb oder gibt es nicht mehr. Wähle eine andere oder entferne die Bedingung.</p>
<div class="vw-fe-werteliste" x-show="cond.source" x-cloak>
<template x-for="value in sourceValues(modalNode, cond.source)" x-bind:key="value.value">
<label class="vw-fe-wahl">
<input type="checkbox" x-bind:value="value.value" x-bind:checked="cond.values.includes(value.value)" x-on:change="toggleValue(cond, value.value, $event.target.checked)">
<span x-text="value.label"></span>
</label>
</template>
<p class="vw-fe-notiz" x-show="sourceValues(modalNode, cond.source).length === 0">Für diese Grundlage gibt es noch keine gespeicherten Werte. Speichere das Formular, dann stehen neue Auswahlwerte hier zur Verfügung.</p>
</div>
</fieldset>
</template>
<button type="button" class="vw-btn is-small is-line" x-on:click="addCond(modalNode)" data-fe-aktion="bedingung">
@include('filament.verwaltung.icon', ['name' => 'plus'])
Bedingung hinzufügen
</button>
</div>
</template>
</div>
</template>
{{-- Anliegen --}}
<template x-if="modal && modal.kind === 'issue' && modalNode">
<div class="vw-fe-formular">
<p class="vw-fe-notiz">Welche Anliegen dieses Formular kennt. Nichts angekreuzt: alle angebotenen. Ein Anfragegrund im Widget kann daraus eines vorwählen; die Frage entfällt dann. Anliegen pflegst du unter „Einstellungen → Anliegen“.</p>
<div class="vw-fe-werteliste">
<template x-for="issue in cfg.issues" x-bind:key="issue.key">
<label class="vw-fe-wahl">
<input type="checkbox" x-bind:value="issue.key" x-bind:checked="modalNode.issues.includes(issue.key)" x-on:change="toggleIssue(modalNode, issue.key, $event.target.checked)">
<span x-text="issue.label"></span>
</label>
</template>
</div>
</div>
</template>
{{-- Weitere Einstellungen --}}
<template x-if="modal && modal.kind === 'more' && modalNode">
<div class="vw-fe-formular">
<template x-if="modalNode.kind === 'field'">
<div class="vw-fe-formular">
<label class="vw-fe-etikett">
<span>Verwendung in der Anfrageübersicht</span>
<select x-model="modalNode.purpose" x-ref="dialogFocus">
<option value="">Keine besondere Verwendung</option>
<template x-for="purpose in purposesFor(modalNode)" x-bind:key="purpose.value">
<option x-bind:value="purpose.value" x-text="purpose.label" x-bind:selected="modalNode.purpose === purpose.value"></option>
</template>
</select>
</label>
<p class="vw-fe-notiz">Welche Angabe der Posteingang als Name, E-Mail-Adresse oder Nachricht zeigt. Jedes Formular braucht ein Feld „E-Mail-Adresse für Rückfragen“.</p>
<p class="vw-fe-notiz" x-show="modalNode.used_in" x-cloak>Dieses Feld wird auch in diesen Formularen verwendet: <span x-text="modalNode.used_in"></span>. Eine Änderung gilt dort mit der nächsten Veröffentlichung.</p>
</div>
</template>
<label class="vw-fe-etikett" x-show="movable(modalNode)">
<span>Verschieben nach</span>
<select x-on:change="moveTo(modalNode, $event.target.value); $event.target.value = ''" data-fe-feld="verschieben">
<option value="">Position wählen …</option>
<template x-for="target in targetsFor(modalNode)" x-bind:key="target.value">
<option x-bind:value="target.value" x-text="target.label"></option>
</template>
</select>
</label>
<p class="vw-fe-notiz" x-show="movable(modalNode)">Das Element wird am Ende des gewählten Bereichs oder Teilbereichs eingefügt. Feinere Positionen stellst du durch Ziehen oder mit den Pfeiltasten am Griff ein.</p>
</div>
</template>
{{-- Vorhandenes Feld aus dem Katalog --}}
<template x-if="modal && modal.kind === 'catalog' && modalNode">
<div class="vw-fe-formular">
<label class="vw-fe-etikett">
<span>Suchen</span>
<input type="search" x-model="catalogSearch" placeholder="Frage oder Name des Feldes" x-ref="dialogFocus">
</label>
<ul class="vw-fe-katalog">
<template x-for="entry in catalogEntries()" x-bind:key="entry.key">
<li>
<button type="button" class="vw-fe-katalog-eintrag" x-on:click="insertCatalog(entry)">
<strong x-text="entry.label"></strong>
<span x-text="typeLabel(entry.type) + (entry.used_in ? ' · auch in: ' + entry.used_in : '')"></span>
</button>
</li>
</template>
</ul>
<p class="vw-fe-notiz" x-show="catalogEntries().length === 0">Kein weiteres Feld gefunden. Alle passenden Felder stehen schon im Formular.</p>
</div>
</template>
</div>
<footer class="vw-fe-dialog-fuss">
<button type="button" class="vw-btn is-primary" x-on:click="closeModal()" data-fe-aktion="fertig">Fertig</button>
</footer>
</div>
</dialog>
</div>
</div>
@@ -25,6 +25,12 @@
'schluessel' => '<circle cx="8" cy="14" r="4.5"/><path d="M11.3 10.8L20 2.5M16.5 6l2.5 2.5M14 8.5l2 2"/>',
'etikett' => '<path d="M3 12V4h8l10 10-8 8z"/><circle cx="7.5" cy="8.5" r="1.4"/>',
'filter' => '<path d="M4 5h16l-6.2 7.4V19l-3.6-1.8v-4.8z"/>',
'frage' => '<circle cx="12" cy="12" r="9"/><path d="M9.5 9.2a2.6 2.6 0 0 1 5 .9c0 1.7-2.5 2.1-2.5 3.9M12 16.8v.2"/>',
'liste' => '<path d="M9 6h11M9 12h11M9 18h11"/><circle cx="4.8" cy="6" r="1"/><circle cx="4.8" cy="12" r="1"/><circle cx="4.8" cy="18" r="1"/>',
'verzweigung' => '<circle cx="6" cy="5.5" r="2"/><circle cx="6" cy="18.5" r="2"/><circle cx="18" cy="9" r="2"/><path d="M6 7.5v9M18 11c0 3.5-4 3-10.5 6.2"/>',
'papierkorb' => '<path d="M4 7h16M10 11v6M14 11v6M6 7l1 12.5h10L18 7M9 7V4.5h6V7"/>',
'teilbereich' => '<rect x="3" y="4" width="18" height="16" rx="2" stroke-dasharray="3 2.5"/><path d="M7 9h10M7 13h6"/>',
'bereich' => '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 9h18"/>',
'zuruecksetzen' => '<path d="M4 12a8 8 0 1 0 2.4-5.7L4 8.5M4 4v4.5h4.5"/>',
];
$name = $name ?? 'info';
@@ -708,4 +708,136 @@
.vw-symbolfeld-kacheln { grid-template-columns: repeat(auto-fill, minmax(5.25rem, 1fr)); }
.vw-symbolfeld-panel { max-height: 18rem; }
}
/* Formularansicht des Aufbaus (Formular-Editor, ADR-62): Bereiche als Karten, Teilbereiche als eingerahmte Einheit darin */
.vw-fe { display: grid; gap: 1rem; min-width: 0; }
.vw-fe-aussen { display: grid; gap: 0.75rem; min-width: 0; }
.vw-fe-fehler { border: 1px solid var(--vw-error); background: var(--vw-error-soft); color: var(--vw-error); padding: 0.75rem 1rem; border-radius: var(--vw-radius); }
.vw-fe-fehler ul { margin: 0.35rem 0 0; padding-left: 1.25rem; }
.vw-fe-leiste { display: flex; flex-wrap: wrap; gap: 0.6rem 1.2rem; align-items: center; justify-content: space-between; }
.vw-fe-hinweis { display: flex; gap: 0.5rem; align-items: flex-start; max-width: 48rem; color: var(--vw-quiet); font-size: var(--vw-small); }
.vw-fe-hinweis svg { width: 1.1rem; height: 1.1rem; flex: none; margin-top: 0.15rem; }
.vw-fe-leiste-aktionen { display: flex; gap: 0.75rem; align-items: center; margin-left: auto; }
.vw-fe-zahl { color: var(--vw-quiet); font-size: var(--vw-small); }
.vw-fe-zusatz { color: var(--vw-error); font-weight: 600; font-size: var(--vw-small); }
.vw-fe-bereiche { container-type: inline-size; container-name: fe; display: grid; gap: 1.5rem; min-width: 0; }
.vw-fe-bereich { border: 1px solid var(--vw-line-strong); border-left: 6px solid var(--vw-pine); border-radius: var(--vw-radius); background: var(--vw-surface); box-shadow: 0 2px 6px rgb(3 37 81 / 8%); min-width: 0; }
.vw-fe-bereich-kopf { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem 0.6rem; padding: 0.7rem 0.9rem 0.7rem 0.5rem; background: var(--vw-paper); border-bottom: 1px solid var(--vw-line); border-radius: 0 var(--vw-radius) 0 0; }
.vw-fe-nummer { display: grid; place-items: center; flex: none; width: 2rem; height: 2rem; border-radius: 50%; background: var(--vw-pine); color: #fff; font-weight: 700; }
.vw-fe-titel { flex: 1 1 12rem; min-width: 0; }
.vw-fe-bereich-kopf .vw-fe-titel input { font-size: 1.15rem; font-weight: 700; }
.vw-fe-teil-kopf .vw-fe-titel input { font-weight: 650; }
.vw-fe input[type="text"], .vw-fe input[type="search"], .vw-fe select, .vw-fe textarea {
width: 100%; min-height: var(--vw-target); padding: 0.4rem 0.65rem; border: 1px solid var(--vw-line-strong); border-radius: var(--vw-radius-small);
background: #fff; color: var(--vw-ink); font: inherit; line-height: 1.35;
}
.vw-fe textarea { resize: vertical; }
.vw-fe select:disabled { background: var(--vw-paper); color: var(--vw-quiet); cursor: not-allowed; }
.vw-fe input[readonly] { background: var(--vw-paper); }
.vw-fe .is-invalid { border-color: var(--vw-error); background: var(--vw-error-soft); box-shadow: inset 0 0 0 1px var(--vw-error); }
.vw-fe-griff { display: grid; place-items: center; flex: none; width: 2rem; min-height: 2.25rem; padding: 0; border: 0; border-radius: var(--vw-radius-small); background: transparent; color: var(--vw-muted); cursor: grab; touch-action: none; }
.vw-fe-griff:hover { background: var(--vw-paper); color: var(--vw-ink); }
.vw-fe-griff:active { cursor: grabbing; }
.vw-fe-griff svg { width: 1.15rem; height: 1.15rem; }
.vw-fe-symbole { display: flex; flex: none; align-items: center; gap: 0.15rem; }
.vw-fe-symbol {
position: relative; display: inline-grid; place-items: center; width: 2.25rem; height: 2.25rem; padding: 0; border: 1px solid transparent; border-radius: var(--vw-radius-small);
background: transparent; color: var(--vw-muted); cursor: pointer;
}
.vw-fe-symbol svg { width: 1.2rem; height: 1.2rem; }
.vw-fe-symbol:hover { border-color: var(--vw-line-strong); color: var(--vw-ink); background: #fff; }
.vw-fe-symbol:disabled { opacity: 0.35; cursor: not-allowed; }
.vw-fe-symbol.is-gesetzt { border-color: #b9d6a3; background: var(--vw-pine-soft); color: var(--vw-pine-dark); }
.vw-fe-symbol.is-warnung { border-color: #ecc77a; background: var(--vw-warn-soft); color: var(--vw-warn); }
.vw-fe-symbol.is-gefahr:hover { border-color: var(--vw-error); background: var(--vw-error-soft); color: var(--vw-error); }
.vw-fe-symbol.is-versteckt { visibility: hidden; }
.vw-fe-zaehler { position: absolute; right: -0.15rem; top: -0.3rem; min-width: 1.1rem; padding: 0 0.25rem; border-radius: 999px; background: var(--vw-pine); color: #fff; font-size: 0.7rem; font-weight: 700; line-height: 1.1rem; text-align: center; }
.vw-fe-symbol.is-warnung .vw-fe-zaehler { background: var(--vw-warn); }
.vw-fe-inhalt { position: relative; display: grid; gap: 0.5rem; padding: 0.9rem; min-height: 4.5rem; align-content: start; }
.vw-fe-feld { background: #fff; border: 1px solid var(--vw-line); border-radius: var(--vw-radius-small); padding: 0.4rem 0.5rem 0.4rem 0.3rem; }
.vw-fe-feld.is-ungueltig { border-color: var(--vw-error); }
.vw-fe-zeile {
display: grid; gap: 0.4rem 0.6rem; align-items: center;
grid-template-columns: auto minmax(0, 1fr) 13rem 5.6rem auto; grid-template-areas: "griff frage typ pflicht symbole";
}
.vw-fe-zeile > .vw-fe-griff { grid-area: griff; }
.vw-fe-frage { grid-area: frage; min-width: 0; }
.vw-fe-typ { grid-area: typ; min-width: 0; }
.vw-fe-pflicht { grid-area: pflicht; display: inline-flex; align-items: center; gap: 0.4rem; white-space: nowrap; font-size: var(--vw-small); font-weight: 600; cursor: pointer; }
.vw-fe-pflicht input { width: 1.1rem; height: 1.1rem; accent-color: var(--vw-pine); }
.vw-fe-zeile > .vw-fe-symbole { grid-area: symbole; }
@container fe (max-width: 46rem) {
.vw-fe-zeile { grid-template-columns: auto minmax(0, 1fr) auto; grid-template-areas: "griff frage frage" ". typ typ" ". pflicht symbole"; }
.vw-fe-zeile > .vw-fe-symbole { justify-self: end; }
}
@container fe (max-width: 30rem) {
.vw-fe-zeile { grid-template-columns: auto minmax(0, 1fr); grid-template-areas: "griff frage" ". typ" ". pflicht" ". symbole"; }
.vw-fe-zeile > .vw-fe-symbole { justify-self: start; }
}
.vw-fe-bedingung { display: flex; align-items: flex-start; gap: 0.4rem; margin: 0.4rem 0.4rem 0.1rem 2.4rem; padding: 0.3rem 0.6rem; border: 1px solid var(--vw-info-line); border-radius: var(--vw-radius-small); background: var(--vw-info); color: var(--vw-quiet); font-size: var(--vw-small); }
.vw-fe-bedingung svg { width: 1rem; height: 1rem; flex: none; margin-top: 0.15rem; color: var(--vw-select-line); }
.vw-fe-bedingung.is-info { background: var(--vw-paper); border-color: var(--vw-line); }
.vw-fe-bereich > .vw-fe-bedingung { margin: 0.6rem 0.9rem 0 0.9rem; }
.vw-fe-teil > .vw-fe-bedingung { margin: 0.1rem 0.7rem 0.3rem 2.6rem; background: #fff; }
.vw-fe-anliegen .vw-fe-anliegen-text { display: grid; flex: 1 1 auto; min-width: 0; }
.vw-fe-anliegen .vw-fe-anliegen-text span { color: var(--vw-quiet); font-size: var(--vw-small); }
.vw-fe-anliegen { display: flex; align-items: center; gap: 0.5rem; background: var(--vw-paper); }
.vw-fe-teil { border: 1px solid #c8dbec; border-left: 5px solid var(--vw-select-line); border-radius: var(--vw-radius); background: #f3f8fc; }
.vw-fe-teil-kopf { display: flex; flex-wrap: wrap; align-items: center; gap: 0.4rem 0.5rem; padding: 0.5rem 0.6rem 0.4rem 0.3rem; }
.vw-fe-art { display: inline-flex; align-items: center; gap: 0.3rem; flex: none; color: var(--vw-select-line); font-size: var(--vw-small); font-weight: 700; }
.vw-fe-art svg { width: 1.15rem; height: 1.15rem; }
.vw-fe-teil-inhalt { position: relative; display: grid; gap: 0.5rem; padding: 0.2rem 0.7rem 0.7rem 1.4rem; min-height: 4.5rem; align-content: start; }
.vw-fe-teil .vw-fe-fuss { border-top: 0; padding: 0 0.7rem 0.7rem 1.4rem; }
.vw-fe-notiz { color: var(--vw-quiet); font-size: var(--vw-small); }
.vw-fe-teil > .vw-fe-notiz { margin: 0 0.7rem 0.4rem 2.6rem; }
.vw-fe-notiz.is-warnung { color: var(--vw-warn); font-weight: 600; }
.vw-fe-fuss { display: flex; flex-wrap: wrap; gap: 0.5rem; padding: 0.7rem 0.9rem; border-top: 1px dashed var(--vw-line-strong); }
.vw-fe-inhalt[data-leer]::before, .vw-fe-teil-inhalt[data-leer]::before {
content: attr(data-leer); display: grid; place-items: center; min-height: 3.5rem; padding: 0.5rem; border: 2px dashed var(--vw-line-strong); border-radius: var(--vw-radius-small);
color: var(--vw-muted); font-size: var(--vw-small); text-align: center; pointer-events: none;
}
.vw-fe-leer-bereich { padding: 1.5rem; border: 2px dashed var(--vw-line-strong); border-radius: var(--vw-radius); color: var(--vw-muted); text-align: center; }
.vw-fe-ende { display: flex; }
.vw-fe-geist { background: rgb(252 209 10 / 24%); outline: 2px dashed var(--vw-yellow); outline-offset: 2px; border-radius: var(--vw-radius-small); }
.vw-fe-geist > * { opacity: 0.5; }
.vw-fe-gezogen { box-shadow: 0 10px 28px rgb(3 37 81 / 22%); background: #fff; }
.vw-fe-gegriffen { cursor: grabbing; }
/* Dialog für Hilfetext, Auswahlwerte, Bedingung, weitere Einstellungen und Katalog */
.vw-fe-dialog { margin: auto; width: min(44rem, calc(100vw - 2rem)); max-height: calc(100vh - 2rem); max-height: calc(100dvh - 2rem); padding: 0; border: 0; border-radius: 0.75rem; background: var(--vw-surface); color: var(--vw-ink); box-shadow: 0 24px 60px rgb(3 37 81 / 30%); }
.vw-fe-dialog::backdrop { background: rgb(3 37 81 / 42%); }
.vw-fe-dialog-karte { display: grid; grid-template-rows: auto minmax(0, 1fr) auto; max-height: calc(100vh - 2rem); max-height: calc(100dvh - 2rem); }
.vw-fe-dialog-kopf { display: flex; align-items: flex-start; justify-content: space-between; gap: 1rem; padding: 1.1rem 1.25rem 0.6rem; }
.vw-fe-dialog-kopf h2 { font-size: 1.3rem; }
.vw-fe-dialog-inhalt { min-height: 0; overflow: auto; padding: 0.4rem 1.25rem 1rem; }
.vw-fe-dialog-fuss { display: flex; justify-content: flex-end; padding: 0.75rem 1.25rem 1rem; border-top: 1px solid var(--vw-line); }
.vw-fe-formular { display: grid; gap: 0.9rem; }
.vw-fe-etikett { display: grid; gap: 0.3rem; font-weight: 650; }
.vw-fe-werte { display: grid; gap: 0.4rem; margin: 0; padding: 0; list-style: none; }
.vw-fe-wert { display: grid; grid-template-columns: minmax(0, 1fr) auto auto auto; gap: 0.3rem; align-items: center; }
.vw-fe-bed { display: grid; gap: 0.6rem; margin: 0; padding: 0.4rem 0.8rem 0.8rem; border: 1px solid var(--vw-line-strong); border-radius: var(--vw-radius-small); }
.vw-fe-bed.is-ungueltig { border-color: var(--vw-warn); background: var(--vw-warn-soft); }
.vw-fe-bed legend { padding: 0 0.3rem; font-weight: 700; }
.vw-fe-bed-zeile { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 1fr) auto; gap: 0.5rem; align-items: end; }
.vw-fe-werteliste { display: flex; flex-wrap: wrap; gap: 0.4rem; }
.vw-fe-wahl { display: inline-flex; align-items: center; gap: 0.45rem; min-height: 2.25rem; padding: 0.25rem 0.8rem; border: 1px solid var(--vw-line-strong); border-radius: 999px; background: #fff; cursor: pointer; }
.vw-fe-wahl:has(input:checked) { border-color: var(--vw-pine); background: var(--vw-pine-soft); color: var(--vw-pine-dark); font-weight: 650; }
.vw-fe-wahl input { accent-color: var(--vw-pine); }
.vw-fe-katalog { display: grid; gap: 0.3rem; max-height: 22rem; margin: 0; padding: 0; overflow: auto; list-style: none; }
.vw-fe-katalog-eintrag { display: grid; gap: 0.1rem; width: 100%; padding: 0.5rem 0.75rem; border: 1px solid var(--vw-line); border-radius: var(--vw-radius-small); background: #fff; color: var(--vw-ink); font: inherit; text-align: left; cursor: pointer; }
.vw-fe-katalog-eintrag:hover { border-color: var(--vw-pine); background: var(--vw-pine-soft); }
.vw-fe-katalog-eintrag span { color: var(--vw-quiet); font-size: var(--vw-small); }
@media (max-width: 40rem) {
.vw-fe-bed-zeile { grid-template-columns: minmax(0, 1fr) auto; }
.vw-fe-bed-zeile > :nth-child(2) { grid-column: 1; }
.vw-fe-dialog { width: calc(100vw - 1rem); }
}
</style>
+143 -12
View File
@@ -203,26 +203,145 @@ private function emptyForm(string $key): InquiryTemplate
return InquiryTemplate::query()->create(['key' => $key, 'name' => ucfirst($key), 'draft' => [...InquiryTemplate::emptyDraft(), 'steps' => [['key' => 'sstart1', 'title' => 'Ihre Angaben', 'intro' => null, 'items' => []]]]]);
}
/**
* @param array<string, mixed> $overrides
* @return array<string, mixed>
*/
private function newField(string $label, array $overrides = []): array
{
return ['kind' => 'field', 'key' => FormEditor::temporaryKey(), 'label' => $label, 'type' => 'text', 'required' => false, 'purpose' => null, 'options' => [], 'cond' => [], ...$overrides];
}
/**
* @param list<array<string, mixed>> $items
*/
private function setTree($component, array $items): void
{
$tree = json_decode((string) $component->get('data.editor_json'), true);
$tree['areas'][0]['items'] = $items;
$component->set('data.editor_json', json_encode($tree));
}
public function test_the_tree_view_nests_fields_in_their_section_and_converts_back_without_loss(): void
{
$editor = app(FormEditor::class);
foreach (InquiryTemplate::query()->get() as $template) {
$draft = (array) $template->draft;
$view = $editor->expand($draft);
$tree = FormEditor::toTree($view);
foreach ($tree['areas'] as $area) {
foreach ($area['items'] as $item) {
$this->assertContains($item['kind'], ['field', 'section', 'issue'], 'Im Baum gibt es keine Ende-Markierung: '.$template->name);
}
}
$fieldsBefore = InquiryField::query()->get()->map->getAttributes()->all();
$groupsBefore = InquiryFieldGroup::query()->get()->map->getAttributes()->all();
$saved = $editor->persist(FormEditor::fromTree(json_decode((string) json_encode($tree), true)));
$this->assertSame($this->structure($draft), $this->structure($saved), 'Über den Baum unverändert: '.$template->name);
$this->assertSame($fieldsBefore, InquiryField::query()->get()->map->getAttributes()->all(), 'Feldkatalog unverändert: '.$template->name);
$this->assertSame($groupsBefore, InquiryFieldGroup::query()->get()->map->getAttributes()->all(), 'Feldgruppen unverändert: '.$template->name);
}
$courses = FormEditor::toTree($editor->expand((array) InquiryTemplate::query()->where('key', 'kursanfragen')->firstOrFail()->draft));
$sections = collect($courses['areas'])->flatMap(fn (array $area) => $area['items'])->where('kind', 'section');
$this->assertTrue($sections->isNotEmpty());
$this->assertTrue($sections->every(fn (array $section): bool => $section['items'] !== []), 'Ein Teilbereich trägt seine Felder selbst.');
}
public function test_a_field_after_a_section_stays_outside_it_and_a_second_section_ends_the_first(): void
{
$editor = app(FormEditor::class);
$tree = ['areas' => [['key' => 'sx1', 'title' => 'Eins', 'intro' => null, 'cond' => [], 'items' => [
['kind' => 'section', 'key' => FormEditor::temporaryKey(), 'label' => 'Erster Teil', 'items' => [$this->newField('Frage A'), $this->newField('Frage B')]],
['kind' => 'section', 'key' => FormEditor::temporaryKey(), 'label' => 'Zweiter Teil', 'items' => [$this->newField('Frage C')]],
$this->newField('Frage D'),
]]]];
$this->assertSame([], $editor->validateTree($tree));
$draft = $editor->persist(FormEditor::fromTree($tree));
$items = $draft['steps'][0]['items'];
$this->assertSame(['group', 'group', 'field'], array_column($items, 'kind'));
$this->assertSame(['frage_a', 'frage_b'], array_column(InquiryFieldGroup::query()->where('label', 'Erster Teil')->firstOrFail()->itemList(), 'field'));
$this->assertSame(['frage_c'], array_column(InquiryFieldGroup::query()->where('label', 'Zweiter Teil')->firstOrFail()->itemList(), 'field'));
$this->assertSame('frage_d', $items[2]['field']);
}
public function test_the_tree_is_checked_before_saving_and_missing_details_are_named(): void
{
$editor = app(FormEditor::class);
$tree = ['areas' => [
['key' => 'sx1', 'title' => '', 'items' => [
$this->newField(''),
$this->newField('Welche Art?', ['type' => 'select', 'options' => [['key' => '', 'label' => ' ']]]),
['kind' => 'section', 'key' => FormEditor::temporaryKey(), 'label' => '', 'items' => []],
['kind' => 'issue', 'issues' => []],
['kind' => 'issue', 'issues' => []],
]],
]];
$errors = implode("\n", $editor->validateTree($tree));
$this->assertStringContainsString('Der Titel fehlt', $errors);
$this->assertStringContainsString('keine Frage oder Beschriftung', $errors);
$this->assertStringContainsString('Bei „Welche Art?“ fehlen die Auswahlwerte', $errors);
$this->assertStringContainsString('keine Überschrift', $errors);
$this->assertStringContainsString('nur einmal', $errors);
$same = $this->newField('Doppelt', ['key' => 'email']);
$twice = ['areas' => [['key' => 'sx1', 'title' => 'Eins', 'items' => [$same, $same]]]];
$this->assertStringContainsString('steht mehrfach im Formular', implode("\n", $editor->validateTree($twice)));
}
public function test_the_client_configuration_lists_types_catalog_issues_and_effects(): void
{
$config = app(FormEditor::class)->clientConfig();
$this->assertContains('select', array_column($config['types'], 'value'));
$this->assertContains('email', array_column($config['catalog'], 'key'));
$this->assertSame(['show', 'hide', 'skip'], array_keys($config['effects']['step']));
$this->assertArrayHasKey('eq', $config['operators']);
$this->assertNotEmpty($config['issues']);
}
public function test_the_form_view_renders_the_areas_without_the_builder_blocks(): void
{
$template = InquiryTemplate::query()->where('key', 'kursanfragen')->firstOrFail();
$html = Livewire::actingAs($this->staff(), 'staff')->test(EditInquiryTemplate::class, ['record' => $template->id])->html();
$this->assertStringContainsString('data-fe-root', $html);
$this->assertStringContainsString('Bereich hinzufügen', $html);
$this->assertStringContainsString('Vorhandenes Feld einfügen', $html);
$this->assertStringNotContainsString('fi-fo-builder', $html);
}
public function test_a_form_is_built_in_the_editor_saved_twice_without_duplicates_and_published(): void
{
$editor = $this->staff();
$template = $this->emptyForm('frisch');
$component = Livewire::actingAs($editor, 'staff')->test(EditInquiryTemplate::class, ['record' => $template->id]);
$areas = $component->get('data.editor.areas');
$this->assertCount(1, $areas);
$tree = json_decode((string) $component->get('data.editor_json'), true);
$this->assertCount(1, $tree['areas']);
$areaId = array_key_first($areas);
$component->set('data.editor.areas.'.$areaId.'.items', [
'a' => ['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Ihr Rufname', 'type' => 'text', 'required' => true, 'purpose' => 'name', 'options' => [], 'cond' => []]],
'b' => ['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Ihre Mailadresse zur Antwort', 'type' => 'email', 'required' => true, 'purpose' => 'email', 'options' => [], 'cond' => []]],
])->call('save')->assertHasNoFormErrors();
$this->setTree($component, [
$this->newField('Ihr Rufname', ['required' => true, 'purpose' => 'name']),
$this->newField('Ihre Mailadresse zur Antwort', ['type' => 'email', 'required' => true, 'purpose' => 'email']),
]);
$component->call('save')->assertHasNoFormErrors();
$this->assertSame(1, InquiryField::query()->where('label', 'Ihr Rufname')->count());
$draft = $template->fresh()->draft;
$this->assertSame(['ihr_rufname', 'ihre_mailadresse_zur_antwort'], array_column($draft['steps'][0]['items'], 'field'));
// Ein zweites Speichern legt nichts doppelt an, weil die Ansicht nach dem Speichern die festen Kennungen trägt.
// Nach dem Speichern trägt der Baum die festen Kennungen; ein zweites Speichern legt nichts doppelt an.
$saved = json_decode((string) $component->get('data.editor_json'), true);
$this->assertSame('ihr_rufname', $saved['areas'][0]['items'][0]['key']);
$component->call('save')->assertHasNoFormErrors();
$this->assertSame(1, InquiryField::query()->where('label', 'Ihr Rufname')->count());
$this->assertSame($draft, $template->fresh()->draft);
@@ -232,16 +351,28 @@ public function test_a_form_is_built_in_the_editor_saved_twice_without_duplicate
$this->assertTrue($template->fresh()->isPublished());
}
public function test_an_incomplete_tree_is_rejected_with_the_reasons_and_changes_nothing(): void
{
$editor = $this->staff();
$template = $this->emptyForm('luecken');
$fieldsBefore = InquiryField::query()->count();
$component = Livewire::actingAs($editor, 'staff')->test(EditInquiryTemplate::class, ['record' => $template->id]);
$this->setTree($component, [$this->newField('Mit Frage'), $this->newField('')]);
$component->call('save')->assertHasErrors(['data.editor_json']);
$this->assertSame($fieldsBefore, InquiryField::query()->count(), 'Nichts wird angelegt, solange etwas fehlt.');
$this->assertSame([], $template->fresh()->draft['steps'][0]['items']);
}
public function test_an_invalid_form_is_not_published(): void
{
$editor = $this->staff();
$template = $this->emptyForm('ohnemail');
$component = Livewire::actingAs($editor, 'staff')->test(EditInquiryTemplate::class, ['record' => $template->id]);
$areaId = array_key_first($component->get('data.editor.areas'));
$component->set('data.editor.areas.'.$areaId.'.items', [
'a' => ['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Ihr Name', 'type' => 'text', 'required' => true, 'options' => [], 'cond' => []]],
])->call('save');
$this->setTree($component, [$this->newField('Ihr Name', ['required' => true])]);
$component->call('save');
$component->callAction('publish', ['note' => null]);
$this->assertFalse($template->fresh()->isPublished());