Formulare: visueller Baukasten, CSV-Auswahl, Einbindung unter Beiträgen
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m59s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 2m5s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 2m11s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 2m6s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 3m2s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 3m3s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 2m37s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 2m39s
CI / Build-Artefakte aktuell (pull_request) Failing after 52s

- Visueller Formularbaukasten im Portal (/redaktion/formulare/{id}): Formular
  wie ausgefüllt, Bezeichnungen/Optionen/Hinweise direkt bearbeiten, Ziehen
  und Ablegen aus der Palette, Pflicht/Breite in der Werkzeugleiste,
  Einstellungen und Bedingungen in der Seitenleiste, Vorschau mit Bedingungen
- Admin: Felder-Reiter führt in den Baukasten; nach dem Anlegen direkt dorthin
- CSV: in der Formularliste, im Redaktionsbereich und für ausgewählte Einsendungen
- Neuigkeiten: Formular unter dem Beitrag (über den Pagebuilder-Block, ohne
  Abhängigkeit vom Formular-Plugin)
- Kein Menüpunkt „Formulare“ im Portal; Redaktionsbereich „Formulare“

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 09:35:39 +00:00
parent 11123fecc0
commit 435960725d
139 changed files with 1735 additions and 432 deletions

View file

@ -2,6 +2,7 @@
import { computed } from 'vue';
import { useForm, usePage } from '@inertiajs/vue3';
import { CircleCheck, EyeOff, LoaderCircle, Paperclip, Send, X } from '@lucide/vue';
import { toast } from 'vue-sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
@ -14,6 +15,8 @@ import NativeSelect from '@/components/NativeSelect.vue';
const props = defineProps({
form: { type: Object, required: true },
compact: { type: Boolean, default: false },
// Vorschau im Baukasten: nichts wird gesendet.
preview: { type: Boolean, default: false },
});
const page = usePage();
@ -76,6 +79,12 @@ function removeFile(field, index) {
}
function submit() {
if (props.preview) {
toast.info('Vorschau – es wird nichts gesendet.');
return;
}
const visibleKeys = new Set(visibleFields.value.map((f) => f.key));
data.transform((values) => ({

View file

@ -0,0 +1,172 @@
<script setup>
import { computed, inject } from 'vue';
import { Asterisk, Calendar, ChevronDown, Copy, GitBranch, GripVertical, Paperclip, Plus, Trash2, X } from '@lucide/vue';
import { fieldTypes, layoutTypes, operators, optionTypes } from '../../lib/fields';
/**
* Ein Feld im Baukasten – dargestellt wie im fertigen Formular.
* Bezeichnung, Hinweis und Auswahlmöglichkeiten werden direkt hier bearbeitet.
*/
const props = defineProps({
field: { type: Object, required: true },
index: { type: Number, required: true },
});
const builder = inject('forms:builder');
const selected = computed(() => builder.selectedId.value === props.field._id);
const hasError = computed(() => builder.errorIndex.value === props.index);
const isLayout = computed(() => layoutTypes.includes(props.field.type));
const d = computed(() => props.field.data);
const conditionText = computed(() => {
if (!d.value.condition_field) return null;
const other = builder.fields.find((f) => f.data.key === d.value.condition_field);
const label = other?.data.label ?? d.value.condition_field;
const op = operators[d.value.condition_operator ?? 'equals'];
return ['filled', 'empty'].includes(d.value.condition_operator) ? `${label} ${op}` : `${label} ${op} „${d.value.condition_value ?? ''}“`;
});
function addOption() {
d.value.options = [...(d.value.options ?? []), `Option ${(d.value.options?.length ?? 0) + 1}`];
requestAnimationFrame(() => document.querySelector(`[data-option="${props.field._id}-${d.value.options.length - 1}"]`)?.select());
}
function removeOption(i) {
d.value.options = d.value.options.filter((_, index) => index !== i);
}
function optionKeydown(event, i) {
if (event.key === 'Enter') {
event.preventDefault();
d.value.options.splice(i + 1, 0, '');
requestAnimationFrame(() => document.querySelector(`[data-option="${props.field._id}-${i + 1}"]`)?.focus());
} else if (event.key === 'Backspace' && d.value.options[i] === '' && d.value.options.length > 1) {
event.preventDefault();
removeOption(i);
requestAnimationFrame(() => document.querySelector(`[data-option="${props.field._id}-${Math.max(0, i - 1)}"]`)?.focus());
}
}
// Unauffällige Eingabefelder, die wie normaler Text aussehen
const inline = 'w-full min-w-0 rounded-sm bg-transparent outline-none placeholder:text-muted-foreground/60 focus:bg-brand-soft/40';
// Bezeichnung nur so breit wie ihr Text – das Pflicht-Sternchen steht direkt dahinter.
const labelInput = 'field-sizing-content min-w-6 max-w-full rounded-sm bg-transparent outline-none placeholder:text-muted-foreground/60 focus:bg-brand-soft/40';
const fake = 'flex h-9 w-full items-center rounded-md border border-input bg-card px-3 text-sm text-muted-foreground shadow-xs';
</script>
<template>
<div
class="group relative rounded-md p-3 outline-offset-2 transition-[outline-color]"
:class="[
field.data.width === 'half' && !isLayout ? '' : '@xl:col-span-2',
selected ? 'bg-brand-soft/30 outline-2 outline-brand-500' : hasError ? 'outline-2 outline-destructive' : 'outline-1 outline-transparent hover:outline-brand-300',
]"
:data-field-id="field._id"
@click.stop="builder.select(field._id)"
>
<!-- Werkzeugleiste -->
<div class="absolute -top-3.5 right-2 z-10 items-center gap-0.5 rounded-md border bg-card px-1 py-0.5 text-xs shadow-sm" :class="selected ? 'flex' : 'hidden group-hover:flex'" @click.stop>
<span class="fb-handle flex cursor-grab items-center gap-1 px-1 py-0.5 font-medium text-muted-foreground active:cursor-grabbing" title="Ziehen zum Verschieben">
<GripVertical class="size-3.5" />
<component :is="fieldTypes[field.type].icon" class="size-3.5" />
{{ builder.types[field.type] }}
</span>
<template v-if="!isLayout">
<span class="mx-0.5 h-4 w-px bg-border" />
<button
type="button"
class="flex h-6 items-center gap-1 rounded px-1.5"
:class="d.required ? 'bg-brand-soft text-brand-soft-foreground' : 'text-muted-foreground hover:bg-accent'"
:aria-pressed="!!d.required"
title="Pflichtfeld"
@click="d.required = !d.required"
>
<Asterisk class="size-3.5" /> Pflicht
</button>
<button type="button" class="h-6 rounded px-1.5 text-muted-foreground hover:bg-accent" :title="d.width === 'half' ? 'Volle Breite' : 'Halbe Breite'" @click="d.width = d.width === 'half' ? 'full' : 'half'">
{{ d.width === 'half' ? '½' : '1/1' }}
</button>
</template>
<span class="mx-0.5 h-4 w-px bg-border" />
<button type="button" class="grid size-6 place-items-center rounded hover:bg-accent" title="Duplizieren" @click="builder.duplicate(field._id)"><Copy class="size-3.5" /></button>
<button type="button" class="grid size-6 place-items-center rounded text-destructive hover:bg-destructive/10" title="Entfernen" @click="builder.remove(field._id)"><Trash2 class="size-3.5" /></button>
</div>
<p v-if="conditionText" class="mb-1.5 inline-flex items-center gap-1 rounded bg-amber-100 px-1.5 py-0.5 text-[11px] text-amber-800 dark:bg-amber-900/50 dark:text-amber-200">
<GitBranch class="size-3" /> Nur wenn {{ conditionText }}
</p>
<!-- Gestaltung -->
<input v-if="field.type === 'heading'" v-model="d.text" :class="[inline, 'text-lg font-semibold']" placeholder="Zwischenüberschrift" aria-label="Zwischenüberschrift" />
<textarea
v-else-if="field.type === 'paragraph'"
v-model="d.text"
:class="[inline, 'field-sizing-content resize-none text-sm leading-relaxed text-muted-foreground']"
rows="1"
placeholder="Hinweistext"
aria-label="Hinweistext"
/>
<!-- Kontrollkästchen: Bezeichnung neben dem Kasten -->
<div v-else-if="field.type === 'checkbox'" class="flex items-start gap-2.5">
<span class="mt-0.5 size-4 shrink-0 rounded-[4px] border border-input bg-card" />
<input v-model="d.label" :class="[labelInput, 'text-sm']" placeholder="Text neben dem Kästchen" aria-label="Bezeichnung" />
<span v-if="d.required" class="text-destructive">*</span>
</div>
<!-- Eingabefelder -->
<div v-else class="grid gap-1.5">
<div class="flex items-center gap-0.5 text-[13px] font-medium">
<input v-model="d.label" :class="labelInput" placeholder="Bezeichnung" aria-label="Bezeichnung" />
<span v-if="d.required" class="text-destructive">*</span>
</div>
<div v-if="field.type === 'textarea'" class="rounded-md border border-input bg-card shadow-xs" :style="{ height: `${(d.rows ?? 4) * 1.5 + 1}rem` }">
<input v-model="d.placeholder" class="w-full bg-transparent px-3 py-2 text-sm outline-none placeholder:text-muted-foreground/50" placeholder="Platzhalter (optional)" aria-label="Platzhalter" />
</div>
<div v-else-if="field.type === 'select'" class="grid gap-1.5">
<div :class="[fake, 'justify-between']">Bitte wählen … <ChevronDown class="size-4" /></div>
<div v-if="selected" class="grid gap-1 rounded-md border border-dashed p-2">
<p class="text-xs text-muted-foreground">Auswahlmöglichkeiten</p>
<div v-for="(option, i) in d.options" :key="i" class="flex items-center gap-2">
<span class="w-5 text-right text-xs text-muted-foreground">{{ i + 1 }}.</span>
<input v-model="d.options[i]" :data-option="`${field._id}-${i}`" :class="[inline, 'text-sm']" placeholder="Auswahlmöglichkeit" @keydown="optionKeydown($event, i)" />
<button type="button" class="grid size-6 place-items-center rounded text-muted-foreground hover:bg-accent" title="Entfernen" @click.stop="removeOption(i)"><X class="size-3.5" /></button>
</div>
<button type="button" class="inline-flex items-center gap-1 justify-self-start text-[13px] font-medium text-brand-text hover:underline" @click.stop="addOption"><Plus class="size-3.5" /> Auswahlmöglichkeit</button>
</div>
</div>
<div v-else-if="optionTypes.includes(field.type)" class="grid gap-1.5">
<div v-for="(option, i) in d.options" :key="i" class="flex items-center gap-2.5">
<span class="size-4 shrink-0 border border-input bg-card" :class="field.type === 'radio' ? 'rounded-full' : 'rounded-[4px]'" />
<input v-model="d.options[i]" :data-option="`${field._id}-${i}`" :class="[inline, 'text-sm']" placeholder="Auswahlmöglichkeit" @keydown="optionKeydown($event, i)" @focus="builder.select(field._id)" />
<button v-if="selected" type="button" class="grid size-6 shrink-0 place-items-center rounded text-muted-foreground hover:bg-accent" title="Entfernen" @click.stop="removeOption(i)"><X class="size-3.5" /></button>
</div>
<button v-if="selected" type="button" class="ml-6.5 inline-flex items-center gap-1 justify-self-start text-[13px] font-medium text-brand-text hover:underline" @click.stop="addOption"><Plus class="size-3.5" /> Auswahlmöglichkeit</button>
</div>
<div v-else-if="field.type === 'file'" class="flex h-10 items-center justify-center gap-2 rounded-md border border-dashed text-sm text-muted-foreground">
<Paperclip class="size-4" /> {{ d.multiple ? 'Dateien auswählen' : 'Datei auswählen' }}
</div>
<div v-else-if="field.type === 'date'" :class="[fake, 'justify-between']">TT.MM.JJJJ <Calendar class="size-4" /></div>
<div v-else class="rounded-md border border-input bg-card shadow-xs">
<input v-model="d.placeholder" class="h-9 w-full bg-transparent px-3 text-sm outline-none placeholder:text-muted-foreground/50" :placeholder="field.type === 'text' ? 'Platzhalter (optional)' : ''" :disabled="field.type !== 'text'" aria-label="Platzhalter" />
</div>
<input
v-if="selected || d.help"
v-model="d.help"
:class="[inline, 'text-[13px] text-muted-foreground']"
placeholder="Hinweis unter dem Feld hinzufügen …"
aria-label="Hinweis"
/>
</div>
</div>
</template>

View file

@ -0,0 +1,193 @@
<script setup>
import { computed, inject } from 'vue';
import { ArrowDown, ArrowUp, Plus, X } from '@lucide/vue';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import NativeSelect from '@/components/NativeSelect.vue';
import { fieldTypes, layoutTypes, operators, optionTypes } from '../../lib/fields';
const props = defineProps({
field: { type: Object, required: true },
});
const builder = inject('forms:builder');
const d = computed(() => props.field.data);
const isLayout = computed(() => layoutTypes.includes(props.field.type));
// Bedingung: nur andere Eingabefelder, die davor stehen
const conditionFields = computed(() => {
const index = builder.fields.findIndex((f) => f._id === props.field._id);
return builder.fields.slice(0, index)
.filter((f) => !layoutTypes.includes(f.type))
.map((f) => ({ value: f.data.key, label: f.data.label || f.data.key }));
});
const conditionTarget = computed(() => builder.fields.find((f) => f.data.key === d.value.condition_field));
const valueOptions = computed(() => {
const target = conditionTarget.value;
if (!target) return null;
if (target.type === 'checkbox') return [{ value: '1', label: 'angehakt' }];
if (optionTypes.includes(target.type)) return (target.data.options ?? []).filter(Boolean).map((o) => ({ value: o, label: o }));
return null;
});
function setCondition(key) {
if (!key) {
delete d.value.condition_field;
delete d.value.condition_operator;
delete d.value.condition_value;
return;
}
d.value.condition_field = key;
d.value.condition_operator ??= 'equals';
}
function moveOption(i, dir) {
const options = [...d.value.options];
const j = i + dir;
if (j < 0 || j >= options.length) return;
[options[i], options[j]] = [options[j], options[i]];
d.value.options = options;
}
const number = (key) => ({
get: () => d.value[key] ?? '',
set: (value) => (value === '' || value === null ? delete d.value[key] : (d.value[key] = Number(value))),
});
const min = computed(number('min'));
const max = computed(number('max'));
const rows = computed(number('rows'));
const maxSize = computed(number('max_size'));
</script>
<template>
<div class="grid gap-5">
<header class="flex items-center gap-3">
<span class="grid size-9 shrink-0 place-items-center rounded-md bg-brand-soft text-brand-text"><component :is="fieldTypes[field.type].icon" class="size-4.5" /></span>
<div class="min-w-0">
<h2 class="font-semibold">{{ builder.types[field.type] }}</h2>
<p class="text-xs text-muted-foreground">Bezeichnung und Auswahlmöglichkeiten bearbeiten Sie direkt im Formular.</p>
</div>
</header>
<template v-if="isLayout">
<label class="grid gap-1.5">
<span class="text-[13px] font-medium">Text</span>
<Textarea v-if="field.type === 'paragraph'" v-model="d.text" rows="4" maxlength="3000" />
<Input v-else v-model="d.text" maxlength="200" />
</label>
</template>
<template v-else>
<label class="grid gap-1.5">
<span class="text-[13px] font-medium">Bezeichnung</span>
<Input v-model="d.label" maxlength="200" />
</label>
<label class="flex items-center justify-between gap-3 text-[13px] font-medium">
Pflichtfeld
<Switch :model-value="!!d.required" @update:model-value="(v) => (d.required = v)" />
</label>
<div class="grid gap-1.5">
<span class="text-[13px] font-medium">Breite</span>
<div class="grid grid-cols-2 rounded-md border p-0.5 text-[13px]" role="group">
<button
v-for="option in [{ value: 'full', label: 'Volle Breite' }, { value: 'half', label: 'Halbe Breite' }]"
:key="option.value"
type="button"
class="rounded py-1.5"
:class="(d.width ?? 'full') === option.value ? 'bg-brand-soft font-medium text-brand-soft-foreground' : 'text-muted-foreground hover:bg-accent'"
:aria-pressed="(d.width ?? 'full') === option.value"
@click="d.width = option.value"
>
{{ option.label }}
</button>
</div>
</div>
<label class="grid gap-1.5">
<span class="text-[13px] font-medium">Hinweis unter dem Feld</span>
<Input v-model="d.help" maxlength="300" />
</label>
<label v-if="['text', 'email', 'phone'].includes(field.type)" class="grid gap-1.5">
<span class="text-[13px] font-medium">Vorbelegen mit</span>
<NativeSelect :model-value="d.prefill ?? null" :options="builder.prefillOptions" placeholder="– nicht vorbelegen –" @update:model-value="(v) => (v ? (d.prefill = v) : delete d.prefill)" />
<span class="text-xs text-muted-foreground">Aus dem Profil der ausfüllenden Person; änderbar.</span>
</label>
<div v-if="['text', 'textarea', 'number', 'checkboxes'].includes(field.type)" class="grid grid-cols-2 gap-3">
<label v-if="['number', 'checkboxes'].includes(field.type)" class="grid gap-1.5">
<span class="text-[13px] font-medium">{{ field.type === 'checkboxes' ? 'Mindestens wählen' : 'Mindestens' }}</span>
<Input v-model="min" type="number" />
</label>
<label class="grid gap-1.5">
<span class="text-[13px] font-medium">{{ { text: 'Höchstlänge', textarea: 'Höchstlänge', number: 'Höchstens', checkboxes: 'Höchstens wählen' }[field.type] }}</span>
<Input v-model="max" type="number" min="1" />
</label>
<label v-if="field.type === 'textarea'" class="grid gap-1.5">
<span class="text-[13px] font-medium">Zeilen</span>
<Input v-model="rows" type="number" min="2" max="20" />
</label>
</div>
<template v-if="field.type === 'file'">
<label class="grid gap-1.5">
<span class="text-[13px] font-medium">Erlaubte Dateien</span>
<NativeSelect v-model="d.accept" :options="[{ value: 'documents', label: 'Dokumente (PDF, Office …)' }, { value: 'images', label: 'Bilder' }, { value: 'any', label: 'Dokumente und Bilder' }]" />
</label>
<label class="grid gap-1.5">
<span class="text-[13px] font-medium">Höchstgröße in MB</span>
<Input v-model="maxSize" type="number" min="1" max="50" />
</label>
<label class="flex items-center justify-between gap-3 text-[13px] font-medium">
Mehrere Dateien (bis 10)
<Switch :model-value="!!d.multiple" @update:model-value="(v) => (d.multiple = v)" />
</label>
</template>
<div v-if="optionTypes.includes(field.type)" class="grid gap-1.5">
<span class="text-[13px] font-medium">Auswahlmöglichkeiten</span>
<div v-for="(option, i) in d.options" :key="i" class="flex items-center gap-1">
<Input v-model="d.options[i]" class="h-8" maxlength="200" />
<button type="button" class="grid size-7 shrink-0 place-items-center rounded hover:bg-accent" title="Nach oben" @click="moveOption(i, -1)"><ArrowUp class="size-3.5" /></button>
<button type="button" class="grid size-7 shrink-0 place-items-center rounded hover:bg-accent" title="Nach unten" @click="moveOption(i, 1)"><ArrowDown class="size-3.5" /></button>
<button type="button" class="grid size-7 shrink-0 place-items-center rounded hover:bg-accent" title="Entfernen" @click="d.options = d.options.filter((_, j) => j !== i)"><X class="size-3.5" /></button>
</div>
<button type="button" class="inline-flex items-center gap-1 justify-self-start text-[13px] font-medium text-brand-text hover:underline" @click="d.options = [...(d.options ?? []), '']"><Plus class="size-3.5" /> Hinzufügen</button>
</div>
</template>
<details class="rounded-md border" :open="!!d.condition_field">
<summary class="cursor-pointer px-3 py-2 text-[13px] font-medium">Nur anzeigen, wenn …</summary>
<div class="grid gap-3 border-t px-3 py-3">
<p v-if="!conditionFields.length" class="text-xs text-muted-foreground">Bedingungen beziehen sich auf Felder weiter oben im Formular.</p>
<template v-else>
<NativeSelect :model-value="d.condition_field ?? null" :options="conditionFields" placeholder="– immer anzeigen –" aria-label="Feld" @update:model-value="setCondition" />
<template v-if="d.condition_field">
<NativeSelect v-model="d.condition_operator" :options="Object.entries(operators).map(([value, label]) => ({ value, label }))" aria-label="Bedingung" />
<template v-if="!['filled', 'empty'].includes(d.condition_operator)">
<NativeSelect v-if="valueOptions" v-model="d.condition_value" :options="valueOptions" placeholder="Wert wählen …" aria-label="Wert" />
<Input v-else v-model="d.condition_value" placeholder="Wert" aria-label="Wert" />
</template>
</template>
</template>
</div>
</details>
<label v-if="!isLayout" class="grid gap-1.5">
<span class="text-[13px] font-medium">Technischer Schlüssel</span>
<Input :model-value="d.key" disabled class="font-mono text-xs" />
<span class="text-xs text-muted-foreground">Für Export und Bedingungen. Wird aus der Bezeichnung gebildet und bleibt danach gleich.</span>
</label>
</div>
</template>

View file

@ -0,0 +1,33 @@
<script setup>
import { Link } from '@inertiajs/vue3';
import { Download, PencilLine, Plus, TableProperties } from '@lucide/vue';
import { Button } from '@/components/ui/button';
import Panel from '@/components/Panel.vue';
defineProps({
forms: { type: Array, required: true },
createUrl: { type: String, default: null },
});
</script>
<template>
<Panel title="Formulare">
<template #actions>
<Button v-if="createUrl" size="sm" variant="outline" as-child><a :href="createUrl"><Plus /> Neues Formular</a></Button>
</template>
<ul v-if="forms.length" class="-mx-5 divide-y border-t">
<li v-for="form in forms" :key="form.id" class="flex items-center gap-3 px-5 py-2.5">
<div class="min-w-0 flex-1">
<Link :href="form.url" class="block truncate text-sm font-medium hover:underline">{{ form.title }}</Link>
<p class="text-xs text-muted-foreground">
{{ form.open ? 'offen' : 'geschlossen' }} · {{ form.submissions }} Einsendungen<template v-if="form.unread">, <span class="font-medium text-brand-text">{{ form.unread }} neu</span></template>
</p>
</div>
<Button v-if="form.builder_url" size="icon" variant="ghost" as-child title="Felder bearbeiten"><Link :href="form.builder_url"><PencilLine /></Link></Button>
<Button v-if="form.results_url" size="icon" variant="ghost" as-child title="Ergebnisse"><a :href="form.results_url"><TableProperties /></a></Button>
<Button v-if="form.csv_url" size="icon" variant="ghost" as-child title="Ergebnisse als CSV herunterladen"><a :href="form.csv_url"><Download /></a></Button>
</li>
</ul>
<p v-else class="text-sm text-muted-foreground">Noch keine Formulare.</p>
</Panel>
</template>

View file

@ -0,0 +1,110 @@
import {
AtSign,
Calendar,
CheckSquare,
ChevronsUpDown,
CircleDot,
Hash,
Heading,
Info,
ListChecks,
Paperclip,
Phone,
Text,
TextCursorInput,
} from '@lucide/vue';
/**
* Feldtypen des Formularbaukastens – passend zu Inhaus\Plugins\Forms\FormFields.
*/
export const fieldTypes = {
text: { icon: TextCursorInput, group: 'Eingabe', defaults: { label: 'Textzeile', width: 'full' } },
textarea: { icon: Text, group: 'Eingabe', defaults: { label: 'Mehrzeiliger Text', rows: 4, width: 'full' } },
email: { icon: AtSign, group: 'Eingabe', defaults: { label: 'E-Mail-Adresse', width: 'half' } },
phone: { icon: Phone, group: 'Eingabe', defaults: { label: 'Telefonnummer', width: 'half' } },
number: { icon: Hash, group: 'Eingabe', defaults: { label: 'Zahl', width: 'half' } },
date: { icon: Calendar, group: 'Eingabe', defaults: { label: 'Datum', width: 'half' } },
select: { icon: ChevronsUpDown, group: 'Auswahl', defaults: { label: 'Auswahlliste', options: ['Option 1', 'Option 2'], width: 'full' } },
radio: { icon: CircleDot, group: 'Auswahl', defaults: { label: 'Einfachauswahl', options: ['Ja', 'Nein'], width: 'full' } },
checkboxes: { icon: ListChecks, group: 'Auswahl', defaults: { label: 'Mehrfachauswahl', options: ['Option 1', 'Option 2', 'Option 3'], width: 'full' } },
checkbox: { icon: CheckSquare, group: 'Auswahl', defaults: { label: 'Ich stimme zu.', width: 'full' } },
file: { icon: Paperclip, group: 'Sonstiges', defaults: { label: 'Datei', accept: 'any', max_size: 10, width: 'full' } },
heading: { icon: Heading, group: 'Gestaltung', defaults: { text: 'Zwischenüberschrift' } },
paragraph: { icon: Info, group: 'Gestaltung', defaults: { text: 'Hinweistext' } },
};
export const layoutTypes = ['heading', 'paragraph'];
export const optionTypes = ['select', 'radio', 'checkboxes'];
/** Wie Str::slug($label, '_', 'de') auf dem Server. */
export function slugify(text) {
return String(text ?? '')
.toLowerCase()
.replace(/ä/g, 'ae').replace(/ö/g, 'oe').replace(/ü/g, 'ue').replace(/ß/g, 'ss')
.normalize('NFKD').replace(/[̀-ͯ]/g, '')
.replace(/@/g, '_at_')
.replace(/[^a-z0-9]+/g, '_')
.replace(/^_+|_+$/g, '')
.slice(0, 60);
}
export function uid() {
return Math.random().toString(36).slice(2, 10);
}
/** Schlüssel für neue Felder aus der Bezeichnung ableiten, eindeutig im Formular. */
export function assignKeys(fields) {
const used = new Set(fields.filter((f) => !f._new && f.data.key).map((f) => f.data.key));
for (const field of fields) {
if (!field._new) continue;
const base = slugify(field.data.label || field.data.text || field.type) || field.type;
let key = base;
for (let i = 2; used.has(key); i++) key = `${base}_${i}`;
field.data.key = key;
used.add(key);
}
}
export function createField(type) {
return { _id: uid(), _new: true, type, data: structuredClone(fieldTypes[type].defaults) };
}
/** Darstellung für die Vorschau – wie FormFields::forFrontend(). */
export function toFrontend(fields) {
const accept = {
documents: '.pdf,.doc,.docx,.xls,.xlsx,.odt,.ods,.ppt,.pptx,.txt,.csv,.rtf',
images: '.jpg,.jpeg,.png,.webp,.gif,.heic',
any: '',
};
return fields.map(({ type, data }) => ({
type,
key: data.key,
label: data.label,
text: data.text,
help: data.help,
placeholder: data.placeholder,
required: !!data.required,
options: (data.options ?? []).filter((o) => o !== ''),
width: data.width ?? 'full',
min: data.min,
max: data.max,
rows: data.rows,
multiple: !!data.multiple,
accept: accept[data.accept ?? 'any'] || undefined,
max_size: data.max_size,
condition: data.condition_field ? { field: data.condition_field, operator: data.condition_operator ?? 'equals', value: String(data.condition_value ?? '') } : null,
}));
}
export const operators = {
equals: 'ist gleich',
not_equals: 'ist nicht',
contains: 'enthält',
filled: 'ist ausgefüllt',
empty: 'ist leer',
};

View file

@ -0,0 +1,325 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, provide, reactive, ref, watch } from 'vue';
import { Head, Link, router } from '@inertiajs/vue3';
import { VueDraggable } from 'vue-draggable-plus';
import { ArrowLeft, CircleCheck, Eye, LoaderCircle, PencilLine, Plus, Save, Settings2, TableProperties } from '@lucide/vue';
import { toast } from 'vue-sonner';
import { Button } from '@/components/ui/button';
import { Toaster } from '@/components/ui/sonner';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { http } from '@/lib/http';
import BuilderField from '../components/builder/BuilderField.vue';
import FieldSettings from '../components/builder/FieldSettings.vue';
import FormRenderer from '../components/FormRenderer.vue';
import { assignKeys, createField, fieldTypes, toFrontend, uid } from '../lib/fields';
const props = defineProps({
form: { type: Object, required: true },
types: { type: Object, required: true },
prefillOptions: { type: Array, required: true },
settingsUrl: { type: String, required: true },
resultsUrl: { type: String, default: null },
});
const state = reactive({
title: props.form.title,
description: props.form.description ?? '',
fields: props.form.fields.map((field) => ({ _id: uid(), type: field.type, data: { ...field.data } })),
});
const selectedId = ref(null);
const errorIndex = ref(null);
const mode = ref('edit');
const saving = ref(false);
const saved = ref(JSON.stringify(state));
const dirty = computed(() => JSON.stringify(state) !== saved.value);
const selected = computed(() => state.fields.find((f) => f._id === selectedId.value) ?? null);
// Schlüssel neuer Felder folgen der Bezeichnung, bis gespeichert wurde.
watch(() => state.fields.map((f) => [f._new, f.data.label, f.data.text]), () => assignKeys(state.fields), { deep: true, immediate: true });
function select(id) {
selectedId.value = id;
}
function add(type, index = null) {
const field = createField(type);
const selectedIndex = state.fields.findIndex((f) => f._id === selectedId.value);
const at = index ?? (selectedIndex >= 0 ? selectedIndex + 1 : state.fields.length);
state.fields.splice(at, 0, field);
select(field._id);
requestAnimationFrame(() => {
const el = document.querySelector(`[data-field-id="${field._id}"]`);
el?.scrollIntoView({ behavior: 'smooth', block: 'center' });
el?.querySelector('input, textarea')?.select();
});
}
function remove(id) {
const field = state.fields.find((f) => f._id === id);
const dependents = state.fields.filter((f) => f.data.condition_field && f.data.condition_field === field?.data.key);
if (dependents.length && !window.confirm(`${dependents.length} Feld(er) hängen von diesem Feld ab. Die Bedingung wird dort entfernt. Trotzdem löschen?`)) return;
dependents.forEach((f) => {
delete f.data.condition_field;
delete f.data.condition_operator;
delete f.data.condition_value;
});
state.fields = state.fields.filter((f) => f._id !== id);
if (selectedId.value === id) select(null);
}
function duplicate(id) {
const index = state.fields.findIndex((f) => f._id === id);
const copy = { _id: uid(), _new: true, type: state.fields[index].type, data: structuredClone({ ...state.fields[index].data, key: undefined }) };
state.fields.splice(index + 1, 0, copy);
select(copy._id);
}
// „fields“ wird beim Löschen und Verschieben neu zugewiesen – daher als Getter.
provide('forms:builder', {
get fields() {
return state.fields;
},
types: props.types,
prefillOptions: props.prefillOptions,
selectedId,
errorIndex,
select,
remove,
duplicate,
});
async function save() {
if (saving.value) return;
saving.value = true;
errorIndex.value = null;
try {
const payload = {
title: state.title,
description: state.description,
fields: state.fields.map(({ type, data }) => ({ type, data })),
};
const result = await http.put(`/redaktion/formulare/${props.form.id}`, payload);
// Gespeicherte Schlüssel übernehmen; die Felder gelten nun als bestehend.
result.fields.forEach((field, i) => {
if (state.fields[i]) {
state.fields[i].data.key = field.data.key;
delete state.fields[i]._new;
}
});
saved.value = JSON.stringify(state);
toast.success('Formular gespeichert');
} catch (error) {
const [key, message] = Object.entries(error.fieldErrors ?? {})[0] ?? [];
const match = key?.match(/^fields\.(\d+)/);
if (match) {
errorIndex.value = Number(match[1]);
select(state.fields[errorIndex.value]?._id);
document.querySelector(`[data-field-id="${selectedId.value}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
toast.error(message ?? error.message);
} finally {
saving.value = false;
}
}
function onKeydown(event) {
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {
event.preventDefault();
save();
} else if (event.key === 'Escape') {
select(null);
}
}
function beforeUnload(event) {
if (dirty.value) {
event.preventDefault();
event.returnValue = '';
}
}
let removeRouterGuard;
onMounted(() => {
window.addEventListener('keydown', onKeydown);
window.addEventListener('beforeunload', beforeUnload);
removeRouterGuard = router.on('before', (event) => {
if (dirty.value && event.detail.visit.method === 'get' && !window.confirm('Es gibt ungespeicherte Änderungen. Seite trotzdem verlassen?')) {
return false;
}
});
});
onBeforeUnmount(() => {
window.removeEventListener('keydown', onKeydown);
window.removeEventListener('beforeunload', beforeUnload);
removeRouterGuard?.();
});
// Vorschau: echtes Formular mit Bedingungen, ohne Absenden
const previewForm = computed(() => ({
id: -1,
title: state.title,
description: state.description,
url: '#',
fields: toFrontend(state.fields),
prefill: {},
submit_label: 'Absenden',
confirmation: '',
open: true,
}));
const palette = computed(() => {
const groups = {};
for (const [type, meta] of Object.entries(fieldTypes)) {
(groups[meta.group] ??= []).push({ type, label: props.types[type], icon: meta.icon });
}
return Object.entries(groups);
});
</script>
<template>
<Head :title="`Formular: ${state.title}`" />
<div class="flex h-dvh flex-col bg-background">
<header class="z-30 flex h-14 shrink-0 items-center gap-2 border-b bg-card px-2 sm:px-3">
<Link href="/redaktion" class="grid size-9 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground" title="Zurück zur Redaktion">
<ArrowLeft class="size-5" />
</Link>
<div class="min-w-0 flex-1">
<p class="truncate text-sm font-semibold">{{ state.title || 'Ohne Titel' }}</p>
<p class="flex items-center gap-1 truncate text-xs text-muted-foreground" aria-live="polite">
<template v-if="saving"><LoaderCircle class="size-3 animate-spin" /> Speichert …</template>
<template v-else-if="dirty">Ungespeicherte Änderungen</template>
<template v-else><CircleCheck class="size-3" /> Gespeichert · {{ form.submissions }} Einsendungen</template>
</p>
</div>
<div class="flex rounded-md border p-0.5 text-sm" role="group" aria-label="Ansicht">
<button type="button" class="flex items-center gap-1.5 rounded px-2.5 py-1" :class="mode === 'edit' ? 'bg-brand-soft font-medium text-brand-soft-foreground' : 'text-muted-foreground hover:bg-accent'" @click="mode = 'edit'">
<PencilLine class="size-4" /> <span class="hidden sm:inline">Bearbeiten</span>
</button>
<button type="button" class="flex items-center gap-1.5 rounded px-2.5 py-1" :class="mode === 'preview' ? 'bg-brand-soft font-medium text-brand-soft-foreground' : 'text-muted-foreground hover:bg-accent'" @click="mode = 'preview'; select(null)">
<Eye class="size-4" /> <span class="hidden sm:inline">Vorschau</span>
</button>
</div>
<Button variant="ghost" size="icon" as-child title="Einstellungen, Benachrichtigung und Zugriff"><a :href="settingsUrl"><Settings2 /></a></Button>
<Button v-if="resultsUrl" variant="ghost" size="icon" as-child title="Ergebnisse"><a :href="resultsUrl"><TableProperties /></a></Button>
<Button :disabled="saving || !dirty" @click="save"><Save /> <span class="hidden sm:inline">Speichern</span></Button>
</header>
<div class="flex min-h-0 flex-1">
<main class="min-w-0 flex-1 overflow-y-auto" @click="select(null)">
<div class="mx-auto max-w-3xl px-4 py-8">
<p v-if="form.submissions && mode === 'edit'" class="mb-4 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-[13px] text-amber-900 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-100">
Es gibt bereits {{ form.submissions }} Einsendungen. Umbenennen ist unproblematisch – gelöschte Felder fehlen nur in neuen Einsendungen.
</p>
<template v-if="mode === 'edit'">
<input v-model="state.title" class="w-full rounded-sm bg-transparent text-3xl font-semibold tracking-tight outline-none focus:bg-brand-soft/40" placeholder="Titel des Formulars" aria-label="Titel" maxlength="200" @click.stop />
<textarea
v-model="state.description"
class="field-sizing-content mt-3 w-full resize-none rounded-sm bg-transparent leading-relaxed text-muted-foreground outline-none placeholder:text-muted-foreground/50 focus:bg-brand-soft/40"
placeholder="Einleitung (optional) – z. B. wofür das Formular gedacht ist und wer es bearbeitet"
aria-label="Einleitung"
rows="1"
maxlength="2000"
@click.stop
/>
<div class="@container mt-8 rounded-lg border bg-card p-5 sm:p-8">
<VueDraggable
v-model="state.fields"
:group="{ name: 'form-fields' }"
handle=".fb-handle"
:animation="150"
ghost-class="pb-ghost"
class="grid min-h-24 gap-x-5 gap-y-3 @xl:grid-cols-2"
@add="(event) => select(state.fields[event.newIndex]?._id)"
>
<BuilderField v-for="(field, index) in state.fields" :key="field._id" :field="field" :index="index" />
</VueDraggable>
<p v-if="!state.fields.length" class="rounded-md border border-dashed p-6 text-center text-sm text-muted-foreground">
Noch keine Felder. Felder aus der rechten Spalte hierher ziehen oder anklicken.
</p>
<Popover>
<PopoverTrigger class="mt-4 flex h-9 w-full items-center justify-center gap-1.5 rounded-md border border-dashed text-sm font-medium text-muted-foreground hover:border-brand-300 hover:bg-brand-soft hover:text-brand-soft-foreground" @click.stop>
<Plus class="size-4" /> Feld hinzufügen
</PopoverTrigger>
<PopoverContent class="w-[22rem] p-3" @click.stop>
<div class="grid grid-cols-2 gap-2">
<button v-for="(label, type) in types" :key="type" type="button" class="flex items-center gap-2 rounded-md border px-2.5 py-2 text-left text-[13px] font-medium hover:border-brand-300 hover:bg-brand-soft/60" @click="add(type, state.fields.length)">
<component :is="fieldTypes[type].icon" class="size-4 shrink-0 text-brand-text" /> <span class="truncate">{{ label }}</span>
</button>
</div>
</PopoverContent>
</Popover>
<div class="mt-5 flex items-center gap-4 border-t pt-5">
<span class="inline-flex h-9 items-center rounded-md bg-brand px-4 text-sm font-medium text-brand-foreground opacity-80">Absenden</span>
<span class="text-xs text-muted-foreground">Beschriftung und Bestätigungstext unter „Einstellungen“</span>
</div>
</div>
</template>
<template v-else>
<h1 class="text-3xl font-semibold tracking-tight">{{ state.title }}</h1>
<p v-if="state.description" class="mt-3 leading-relaxed whitespace-pre-line text-muted-foreground">{{ state.description }}</p>
<div class="@container mt-8 rounded-lg border bg-card p-5 sm:p-8">
<FormRenderer :key="JSON.stringify(previewForm.fields)" :form="previewForm" preview />
</div>
<p class="mt-3 text-center text-xs text-muted-foreground">Vorschau: Bedingungen und Pflichtfelder funktionieren wie im Portal, gesendet wird nichts.</p>
</template>
</div>
</main>
<aside v-if="mode === 'edit'" class="hidden w-[340px] shrink-0 flex-col border-l bg-card lg:flex">
<div class="min-h-0 flex-1 overflow-y-auto p-4">
<FieldSettings v-if="selected" :key="selected._id" :field="selected" />
<template v-else>
<p class="mb-4 text-xs text-muted-foreground">Klicken fügt das Feld unter dem ausgewählten ein. Felder lassen sich auch an jede Stelle ziehen.</p>
<section v-for="[group, items] in palette" :key="group" class="mb-4">
<h3 class="mb-2 text-xs font-semibold tracking-wide text-muted-foreground uppercase">{{ group }}</h3>
<VueDraggable
:model-value="items"
:group="{ name: 'form-fields', pull: 'clone', put: false }"
:clone="(item) => createField(item.type)"
:sort="false"
class="grid grid-cols-2 gap-2"
>
<button
v-for="item in items"
:key="item.type"
type="button"
class="flex cursor-grab items-center gap-2 rounded-md border bg-card px-2.5 py-2 text-left text-[13px] font-medium hover:border-brand-300 hover:bg-brand-soft/60 active:cursor-grabbing"
@click="add(item.type)"
>
<component :is="item.icon" class="size-4 shrink-0 text-brand-text" />
<span class="truncate">{{ item.label }}</span>
</button>
</VueDraggable>
</section>
</template>
</div>
</aside>
</div>
</div>
<Toaster position="bottom-left" />
</template>