Files
laraundfelix/resources/js/inquiry-form.js
T
LarsandClaude Sonnet 5.5 c6a8167601 Baue die Verwaltung Kommunikation, die öffentliche Anfrageschnittstelle und das CMS-Widget Anfrage
Anliegen, Feldkatalog, Feldgruppen, Anfragevorlagen mit Fassungen, Anfrage-Einstiege, Posteingang mit
Status und Notizen, Einstellungen mit Empfängern. Das Widget speichert nur die Kennung eines veröffentlichten
Einstiegs; Formular, Bedingungen und Annahme kommen zur Laufzeit vom Server (Kompaktformular und
mehrstufiger Dialog aus derselben Beschreibung).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 17:41:55 +01:00

943 lines
35 KiB
JavaScript

/*
* Anfrageformular (ADR-60). Das Formular wird aus der Beschreibung gebaut, die der Server liefert (Texte, Schritte, Felder,
* Auswahlwerte). Welche Fragen sichtbar oder Pflicht sind, entscheidet allein der Server: nach jeder Änderung einer
* steuernden Auswahl wird der Zustand abgefragt. Kompaktformular und mehrstufiger Dialog sind nur zwei Darstellungen
* derselben Beschreibung. Eingaben ausgeblendeter Fragen bleiben im Browser erhalten, werden aber nie gesendet.
*/
let counter = 0;
function h(tag, attrs = {}, ...children) {
const el = document.createElement(tag);
for (const [key, value] of Object.entries(attrs)) {
if (value === false || value === null || value === undefined) {
continue;
}
if (key === 'class') {
el.className = value;
} else if (key === 'text') {
el.textContent = value;
} else if (key.startsWith('on')) {
el.addEventListener(key.slice(2), value);
} else if (value === true) {
el.setAttribute(key, '');
} else {
el.setAttribute(key, String(value));
}
}
for (const child of children.flat()) {
if (child === null || child === undefined || child === false) {
continue;
}
el.append(child.nodeType ? child : document.createTextNode(String(child)));
}
return el;
}
const REQUIRED_MESSAGE = 'Bitte füllen Sie dieses Feld aus.';
class InquiryForm {
constructor(root) {
this.root = root;
this.id = 'inq' + ++counter;
this.preview = root.dataset.preview === '1';
this.values = {};
this.touched = new Set();
this.state = null;
this.def = null;
this.current = 0;
this.sequence = 0;
this.pending = Promise.resolve();
this.submitting = false;
this.finished = false;
}
async start() {
try {
const response = await fetch(this.root.dataset.definitionUrl, { headers: { Accept: 'application/json' }, credentials: 'same-origin' });
if (!response.ok) {
this.root.replaceChildren();
this.root.hidden = true;
return;
}
this.def = await response.json();
} catch {
this.root.replaceChildren(h('p', { class: 'inquiry-note', role: 'alert', text: 'Das Anfrageformular konnte nicht geladen werden. Bitte laden Sie die Seite neu.' }));
return;
}
this.token = this.def.token;
this.csrf = this.def.csrf;
this.state = this.def.state;
this.values = { ...(this.def.defaults || {}) };
this.wizard = this.def.mode === 'wizard';
this.render();
}
/* ------------------------------------------------------------------ Aufbau */
render() {
const def = this.def;
const open = def.open === 'button';
this.panel = h('div', { class: 'inquiry-panel', id: this.id + '-panel', hidden: open });
this.status = h('p', { class: 'inquiry-sr', 'aria-live': 'polite', role: 'status' });
this.formEl = h('form', { class: 'inquiry-form', novalidate: true, 'aria-labelledby': this.id + '-heading', onsubmit: (event) => event.preventDefault() });
this.heading = h('h2', { class: 'inquiry-heading', id: this.id + '-heading', tabindex: '-1', text: def.texts.heading });
const intro = def.texts.intro ? h('p', { class: 'inquiry-intro', text: def.texts.intro }) : null;
this.progress = this.wizard ? h('ol', { class: 'inquiry-progress', 'aria-label': 'Fortschritt' }) : null;
this.summaryBox = h('div', { class: 'inquiry-errors', role: 'alert', tabindex: '-1', hidden: true });
this.stepEls = new Map();
this.fieldEls = new Map();
this.groupEls = new Map();
const steps = def.steps.map((step) => this.buildStep(step));
this.summaryEl = this.wizard ? this.buildSummary() : null;
this.actions = h('div', { class: 'inquiry-actions' });
this.privacy = def.texts.privacy_note ? h('p', { class: 'inquiry-privacy', text: def.texts.privacy_note }) : null;
this.honeypot = h('div', { class: 'inquiry-hp', 'aria-hidden': 'true' }, h('label', {}, 'Bitte leer lassen', h('input', { type: 'text', name: 'inq_hp', tabindex: '-1', autocomplete: 'off' })));
this.formEl.append(
...[this.progress, this.summaryBox, ...steps, this.summaryEl, this.privacy, this.honeypot, this.actions].filter(Boolean),
);
this.panel.append(...[this.heading, intro, h('p', { class: 'inquiry-legend', text: 'Mit * markierte Angaben sind Pflichtangaben.' }), this.formEl, this.status].filter(Boolean));
this.root.replaceChildren();
if (open) {
this.opener = h('button', {
type: 'button',
class: 'button inquiry-opener',
'aria-expanded': 'false',
'aria-controls': this.id + '-panel',
text: def.texts.open_label,
onclick: () => this.openPanel(),
});
this.root.append(this.opener);
}
this.root.append(this.panel);
this.syncValues();
this.applyState();
this.renderActions();
}
openPanel() {
this.panel.hidden = false;
this.opener.setAttribute('aria-expanded', 'true');
this.opener.hidden = true;
this.heading.focus();
}
buildStep(step) {
const el = h('section', { class: 'inquiry-step', 'data-step': step.key, 'aria-labelledby': this.id + '-s-' + step.key });
const showTitle = this.wizard || this.def.steps.length > 1;
el.append(h('h3', { class: 'inquiry-step-title', id: this.id + '-s-' + step.key, tabindex: '-1', text: step.title, hidden: !showTitle }));
if (step.intro) {
el.append(h('p', { class: 'inquiry-step-intro', text: step.intro }));
}
for (const item of step.items) {
if (item.kind === 'issue') {
el.append(this.buildIssues());
} else {
el.append(this.buildGroup(item));
}
}
this.stepEls.set(step.key, el);
return el;
}
buildGroup(group) {
const el = h(group.label ? 'fieldset' : 'div', { class: 'inquiry-group', 'data-group': group.key || null });
if (group.label) {
el.append(h('legend', { text: group.label }));
}
if (group.description) {
el.append(h('p', { class: 'inquiry-help', text: group.description }));
}
for (const row of group.fields) {
el.append(this.buildField(this.def.fields[row.field]));
}
if (group.key) {
this.groupEls.set(group.key, el);
}
return el;
}
buildIssues() {
const wrap = h('div', { class: 'inquiry-issues' });
this.issueEl = this.choiceField('anliegen', this.def.texts.issue_question, this.def.issues.map((issue) => ({ key: issue.key, label: issue.label, description: issue.description })));
this.subissueEl = h('div', { class: 'inquiry-field', 'data-field': 'unteranliegen', hidden: true });
this.fieldEls.set('unteranliegen', this.subissueEl);
wrap.append(this.issueEl, this.subissueEl);
return wrap;
}
/** Auswahl des Anliegens: große Optionen mit Beschreibung. */
choiceField(key, legend, options) {
const el = h('fieldset', { class: 'inquiry-field inquiry-choice', 'data-field': key });
el.append(h('legend', {}, legend, h('span', { class: 'inquiry-req', 'aria-hidden': 'true', text: ' *' })));
const list = h('div', { class: 'inquiry-options' });
for (const option of options) {
const id = `${this.id}-${key}-${option.key}`;
const input = h('input', { type: 'radio', name: `${this.id}-${key}`, id, value: option.key, onchange: () => this.onIssueChange(key, option.key) });
input.checked = this.values[key] === option.key;
list.append(h('div', { class: 'inquiry-option' }, input, h('label', { for: id }, h('span', { class: 'inquiry-option-label', text: option.label }), option.description ? h('span', { class: 'inquiry-option-desc', text: option.description }) : null)));
}
el.append(list, h('p', { class: 'inquiry-error', id: `${this.id}-${key}-err`, 'aria-live': 'polite' }));
this.fieldEls.set(key, el);
return el;
}
renderSubissues() {
const parent = this.def.issues.find((issue) => issue.key === this.state.issue);
const children = parent ? parent.children : [];
if (!children.some((child) => child.key === this.values.unteranliegen)) {
delete this.values.unteranliegen;
}
const fresh = this.choiceField('unteranliegen', 'Worum geht es genauer?', children.map((child) => ({ key: child.key, label: child.label, description: child.description })));
this.subissueEl.replaceWith(fresh);
this.subissueEl = fresh;
}
buildField(field) {
const id = `${this.id}-${field.key}`;
const wrap = h('div', { class: 'inquiry-field', 'data-field': field.key, 'data-type': field.type });
const describedBy = [field.help ? id + '-help' : null, id + '-err'].filter(Boolean).join(' ');
const requiredMark = () => h('span', { class: 'inquiry-req', 'aria-hidden': 'true', text: ' *' });
const label = (text, forId) => h('label', { for: forId, class: 'inquiry-label' }, text, requiredMark());
const legend = (text) => h('legend', { class: 'inquiry-label' }, text, requiredMark());
const help = field.help ? h('p', { class: 'inquiry-help', id: id + '-help', text: field.help }) : null;
const error = h('p', { class: 'inquiry-error', id: id + '-err', 'aria-live': 'polite' });
const control = (input) => {
input.addEventListener('input', () => this.onInput(field, input));
input.addEventListener('change', () => this.onInput(field, input));
return input;
};
const value = this.values[field.key];
const options = field.type === 'boolean' ? [{ key: 'ja', label: 'Ja' }, { key: 'nein', label: 'Nein' }] : field.options || [];
const dropdown = field.type === 'select' && options.length > 6;
const grouped = ['boolean', 'multiselect', 'period'].includes(field.type) || (field.type === 'select' && !dropdown);
const box = grouped ? h('fieldset', { class: 'inquiry-fieldset' }) : wrap;
const choice = (kind, option) => {
const oid = `${id}-${option.key}`;
const input = control(h('input', { type: kind, id: oid, value: option.key, name: kind === 'radio' ? id : null, 'aria-describedby': describedBy }));
input.checked = kind === 'radio' ? value === option.key : Array.isArray(value) && value.includes(option.key);
return h('div', { class: 'inquiry-option' }, input, h('label', { for: oid }, h('span', { class: 'inquiry-option-label', text: option.label })));
};
let parts;
if (field.type === 'textarea') {
parts = [label(field.label, id), help, control(h('textarea', { id, name: field.key, rows: 5, maxlength: field.max_length || 4000, 'aria-describedby': describedBy }, value || '')), error];
} else if (dropdown) {
const select = h('select', { id, name: field.key, 'aria-describedby': describedBy }, h('option', { value: '', text: 'Bitte wählen' }), options.map((option) => h('option', { value: option.key, text: option.label })));
select.value = value || '';
parts = [label(field.label, id), help, control(select), error];
} else if (field.type === 'select' || field.type === 'boolean') {
parts = [legend(field.label), help, h('div', { class: 'inquiry-options' }, options.map((option) => choice('radio', option))), error];
} else if (field.type === 'multiselect') {
parts = [legend(field.label), help, h('div', { class: 'inquiry-options' }, options.map((option) => choice('checkbox', option))), error];
} else if (field.type === 'period') {
const range = value || {};
const part = (name, text) => h('div', {}, h('label', { for: `${id}-${name}`, class: 'inquiry-sublabel', text }), control(h('input', { type: 'date', id: `${id}-${name}`, 'data-part': name, value: range[name] || '', 'aria-describedby': describedBy })));
parts = [legend(field.label), help, h('div', { class: 'inquiry-period' }, part('von', 'Von'), part('bis', 'Bis')), error];
} else {
const attrs = { id, name: field.key, type: { email: 'email', phone: 'tel', date: 'date' }[field.type] || 'text', value: value || '', 'aria-describedby': describedBy };
if (field.type === 'email') {
attrs.autocomplete = 'email';
attrs.inputmode = 'email';
} else if (field.type === 'phone') {
attrs.autocomplete = 'tel';
} else if (field.type === 'number') {
attrs.inputmode = 'decimal';
} else if (field.type === 'text') {
attrs.maxlength = field.max_length || 200;
}
parts = [label(field.label, id), help, control(h('input', attrs)), error];
}
if (grouped) {
wrap.append(box);
}
box.append(...parts.filter(Boolean));
this.fieldEls.set(field.key, wrap);
return wrap;
}
buildSummary() {
this.summaryList = h('dl', { class: 'inquiry-summary-list' });
return h('section', { class: 'inquiry-step inquiry-summary', 'data-step': '_summary', 'aria-labelledby': this.id + '-sum', hidden: true },
h('h3', { class: 'inquiry-step-title', id: this.id + '-sum', tabindex: '-1', text: this.def.texts.summary_title }),
this.summaryList,
);
}
/* ------------------------------------------------------------------ Eingaben */
onIssueChange(key, value) {
this.values[key] = value;
this.touched.add(key);
if (key === 'anliegen') {
delete this.values.unteranliegen;
}
this.refresh();
}
onInput(field, input) {
const type = field.type;
const wrap = this.fieldEls.get(field.key);
if (type === 'multiselect') {
this.values[field.key] = [...wrap.querySelectorAll('input[type=checkbox]:checked')].map((box) => box.value);
} else if (type === 'period') {
this.values[field.key] = { von: wrap.querySelector('[data-part=von]').value, bis: wrap.querySelector('[data-part=bis]').value };
} else if (input.type === 'radio') {
this.values[field.key] = input.value;
} else {
this.values[field.key] = input.value;
}
this.touched.add(field.key);
this.setError(field.key, '');
if ((this.def.controls || []).includes(field.key)) {
this.refresh();
}
}
/** Überträgt die Werte in die Steuerelemente (nach Vorbelegung durch den Server). */
syncValues() {
for (const [key, el] of this.fieldEls) {
const value = this.values[key];
if (key === 'anliegen' || key === 'unteranliegen') {
el.querySelectorAll('input[type=radio]').forEach((radio) => { radio.checked = radio.value === value; });
continue;
}
const field = this.def.fields[key];
if (!field) {
continue;
}
if (field.type === 'multiselect') {
el.querySelectorAll('input[type=checkbox]').forEach((box) => { box.checked = Array.isArray(value) && value.includes(box.value); });
} else if (field.type === 'period') {
el.querySelector('[data-part=von]').value = value?.von || '';
el.querySelector('[data-part=bis]').value = value?.bis || '';
} else if (field.type === 'select' || field.type === 'boolean') {
const radios = el.querySelectorAll('input[type=radio]');
if (radios.length) {
radios.forEach((radio) => { radio.checked = radio.value === value; });
} else {
el.querySelector('select').value = value || '';
}
} else {
el.querySelector('input, textarea').value = value || '';
}
}
}
/* ------------------------------------------------------------------ Zustand */
refresh() {
const run = ++this.sequence;
this.pending = this.pending.then(async () => {
if (run !== this.sequence) {
return;
}
try {
const response = await fetch(this.root.dataset.stateUrl, {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRF-TOKEN': this.csrf },
body: JSON.stringify({ values: this.allValues() }),
});
if (!response.ok || run !== this.sequence) {
return;
}
const before = this.visibleKeys();
this.state = await response.json();
this.applyPresets();
this.applyState();
this.announce(before);
} catch {
// Der letzte bekannte Zustand bleibt; beim Absenden prüft der Server ohnehin alles.
}
});
return this.pending;
}
applyPresets() {
let changed = false;
for (const [key, value] of Object.entries(this.state.presets || {})) {
if (!this.touched.has(key) && (this.values[key] === undefined || this.values[key] === '') && this.values[key] !== value) {
this.values[key] = value;
changed = true;
}
}
if (changed) {
this.syncValues();
this.refresh();
}
}
visibleKeys() {
return Object.entries(this.state?.fields || {}).filter(([, visible]) => visible).map(([key]) => key);
}
announce(before) {
const now = this.visibleKeys();
const added = now.filter((key) => !before.includes(key));
const removed = before.filter((key) => !now.includes(key));
if (added.length) {
this.status.textContent = 'Weitere Fragen wurden eingeblendet.';
} else if (removed.length) {
this.status.textContent = 'Einige Fragen sind entfallen.';
}
}
/** Alle erfassten Werte für die Abfrage des Zustands; der Server entscheidet, welche davon zählen. */
allValues() {
const out = {};
for (const [key, value] of Object.entries(this.values)) {
if (value !== undefined && value !== '') {
out[key] = value;
}
}
return out;
}
/** Nur Werte sichtbarer Fragen: Das Gesendete entspricht dem, was der Besucher sieht. */
visibleValues() {
const out = {};
for (const [key, value] of Object.entries(this.values)) {
if (this.state?.fields?.[key] && value !== undefined && value !== '') {
out[key] = value;
}
}
return out;
}
applyState() {
const state = this.state;
if (this.issueEl && (this.subissueEl.dataset.parent === undefined || this.subissueEl.dataset.parent !== (state.issue || ''))) {
this.renderSubissues();
this.subissueEl.dataset.parent = state.issue || '';
}
for (const [key, el] of this.groupEls) {
el.hidden = state.groups[key] === false;
}
for (const [key, el] of this.fieldEls) {
const visible = !!state.fields[key];
el.hidden = !visible;
el.classList.toggle('is-required', !!state.required[key]);
el.querySelectorAll('input, select, textarea').forEach((input) => {
input.disabled = !visible;
if (state.required[key]) {
input.setAttribute('aria-required', 'true');
} else {
input.removeAttribute('aria-required');
}
});
}
this.syncSteps();
}
/* ------------------------------------------------------------------ Schritte */
stepHasContent(step) {
if (!this.state.steps[step.key]) {
return false;
}
return step.items.some((item) => (item.kind === 'issue'
? this.state.fields.anliegen || this.state.fields.unteranliegen
: item.fields.some((row) => this.state.fields[row.field])));
}
visibleSteps() {
return this.def.steps.filter((step) => this.stepHasContent(step));
}
/** Anzeige der Schritte: im Dialog nur der aktuelle, im Kompaktformular alle sichtbaren. */
syncSteps() {
const steps = this.visibleSteps();
if (!this.wizard) {
for (const step of this.def.steps) {
this.stepEls.get(step.key).hidden = !steps.includes(step);
}
this.renderActions();
return;
}
const total = steps.length + 1;
this.current = Math.max(0, Math.min(this.current, total - 1));
const onSummary = this.current === steps.length;
for (const step of this.def.steps) {
this.stepEls.get(step.key).hidden = onSummary || steps[this.current] !== step;
}
this.summaryEl.hidden = !onSummary;
this.progress.replaceChildren(...[...steps.map((step) => step.title), this.def.texts.summary_title].map((title, index) => h('li', {
class: 'inquiry-progress-item' + (index === this.current ? ' is-current' : '') + (index < this.current ? ' is-done' : ''),
'aria-current': index === this.current ? 'step' : null,
}, h('span', { class: 'inquiry-progress-nr', text: String(index + 1) }), h('span', { class: 'inquiry-progress-title', text: title }))));
if (onSummary) {
this.fillSummary(steps);
}
this.renderActions();
}
goTo(index, focusHeading = true) {
this.current = index;
this.syncSteps();
if (focusHeading) {
const steps = this.visibleSteps();
const target = this.current === steps.length ? this.summaryEl.querySelector('h3') : this.stepEls.get(steps[this.current].key).querySelector('h3');
target.focus({ preventScroll: false });
target.scrollIntoView({ block: 'start', behavior: 'smooth' });
}
}
renderActions() {
const texts = this.def.texts;
this.actions.replaceChildren();
if (!this.wizard) {
this.actions.append(this.submitButton());
return;
}
const steps = this.visibleSteps();
const last = this.current >= steps.length;
if (this.current > 0) {
this.actions.append(h('button', { type: 'button', class: 'button button-secondary', text: texts.back_label, onclick: () => this.goTo(this.current - 1) }));
}
this.actions.append(last ? this.submitButton() : h('button', { type: 'button', class: 'button', text: texts.next_label, onclick: () => this.next() }));
}
submitButton() {
this.submitEl = h('button', { type: 'button', class: 'button', text: this.def.texts.submit_label, onclick: () => this.submit() });
return this.submitEl;
}
async next() {
await this.pending;
const steps = this.visibleSteps();
const errors = this.validateStep(steps[this.current]);
if (errors.length) {
this.showErrors(errors);
return;
}
this.hideSummary();
this.goTo(this.current + 1);
}
fillSummary(steps) {
const rows = [];
for (const step of steps) {
const index = steps.indexOf(step);
for (const item of step.items) {
const entries = item.kind === 'issue'
? this.issueRows()
: item.fields.filter((row) => this.state.fields[row.field]).map((row) => this.fieldRow(this.def.fields[row.field]));
for (const entry of entries.filter(Boolean)) {
rows.push({ ...entry, index, step });
}
}
}
this.summaryList.replaceChildren();
let last = null;
for (const row of rows) {
if (last !== row.step) {
this.summaryList.append(h('div', { class: 'inquiry-summary-step' }, h('dt', { class: 'inquiry-summary-heading', text: row.step.title }), h('dd', {}, h('button', { type: 'button', class: 'inquiry-link', text: this.def.texts.edit_label, 'aria-label': `${this.def.texts.edit_label}: ${row.step.title}`, onclick: () => this.goTo(row.index) }))));
last = row.step;
}
this.summaryList.append(h('div', { class: 'inquiry-summary-row' }, h('dt', { text: row.label }), h('dd', { text: row.text })));
}
if (!rows.length) {
this.summaryList.append(h('p', { text: 'Sie haben noch keine Angaben gemacht.' }));
}
}
issueRows() {
const rows = [];
const parent = this.def.issues.find((issue) => issue.key === this.state.issue);
if (parent && this.state.fields.anliegen) {
rows.push({ label: 'Anliegen', text: parent.label });
}
const child = parent?.children.find((item) => item.key === this.state.subissue);
if (child && this.state.fields.unteranliegen) {
rows.push({ label: 'Genauer', text: child.label });
}
return rows;
}
fieldRow(field) {
const text = this.displayValue(field, this.values[field.key]);
return text === '' ? null : { label: field.label, text };
}
displayValue(field, value) {
if (value === undefined || value === null || value === '' || (Array.isArray(value) && !value.length)) {
return '';
}
const label = (key) => (field.options || []).find((option) => option.key === key)?.label || key;
const date = (iso) => iso ? iso.split('-').reverse().join('.') : '';
switch (field.type) {
case 'select': return label(value);
case 'multiselect': return value.map(label).join(', ');
case 'boolean': return value === 'ja' ? 'Ja' : 'Nein';
case 'date': return date(value);
case 'period': return [date(value.von), date(value.bis)].filter(Boolean).join(' bis ');
default: return String(value);
}
}
/* ------------------------------------------------------------------ Prüfung und Senden */
/** Prüfung der Pflichtangaben zur Bedienung; maßgeblich ist die Prüfung des Servers. */
validateStep(step) {
const errors = [];
const keys = [];
for (const item of step.items) {
if (item.kind === 'issue') {
keys.push('anliegen', 'unteranliegen');
} else {
item.fields.forEach((row) => keys.push(row.field));
}
}
for (const key of keys) {
if (!this.state.fields[key]) {
continue;
}
const message = this.checkField(key);
this.setError(key, message);
if (message) {
errors.push({ key, message, label: this.labelOf(key) });
}
}
return errors;
}
labelOf(key) {
if (key === 'anliegen') {
return this.def.texts.issue_question;
}
return key === 'unteranliegen' ? 'Worum geht es genauer?' : this.def.fields[key]?.label || key;
}
checkField(key) {
const value = this.values[key];
const empty = value === undefined || value === null || value === '' || (Array.isArray(value) && !value.length)
|| (typeof value === 'object' && !Array.isArray(value) && !value.von && !value.bis);
if (empty) {
return this.state.required[key] ? (key === 'anliegen' || key === 'unteranliegen' ? 'Bitte treffen Sie eine Auswahl.' : REQUIRED_MESSAGE) : '';
}
const field = this.def.fields[key];
if (field?.type === 'email' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(value))) {
return 'Bitte geben Sie eine gültige E-Mail-Adresse ein.';
}
if (field?.type === 'period' && this.state.required[key] && !(value.von && value.bis)) {
return 'Bitte geben Sie Beginn und Ende an.';
}
return '';
}
setError(key, message) {
const wrap = this.fieldEls.get(key);
if (!wrap) {
return;
}
wrap.classList.toggle('is-invalid', !!message);
wrap.querySelectorAll('input, select, textarea').forEach((input) => {
if (message) {
input.setAttribute('aria-invalid', 'true');
} else {
input.removeAttribute('aria-invalid');
}
});
const slot = wrap.querySelector('.inquiry-error');
if (slot) {
slot.textContent = message;
}
}
hideSummary() {
this.summaryBox.hidden = true;
this.summaryBox.replaceChildren();
}
showErrors(errors, intro = 'Bitte prüfen Sie Ihre Angaben:') {
const list = h('ul', {}, errors.map((error) => h('li', {}, h('a', { href: '#', text: `${error.label}: ${error.message}`, onclick: (event) => { event.preventDefault(); this.focusField(error.key); } }))));
this.summaryBox.replaceChildren(h('p', { class: 'inquiry-errors-title', text: intro }), list);
this.summaryBox.hidden = false;
this.summaryBox.focus();
this.summaryBox.scrollIntoView({ block: 'center', behavior: 'smooth' });
}
focusField(key) {
const wrap = this.fieldEls.get(key);
const input = wrap?.querySelector('input:not([disabled]), select, textarea');
if (input) {
input.focus();
}
}
async submit() {
if (this.submitting || this.finished) {
return;
}
await this.pending;
const steps = this.visibleSteps();
const errors = steps.flatMap((step) => this.validateStep(step));
if (errors.length) {
if (this.wizard) {
const first = steps.findIndex((step) => this.validateStep(step).length);
this.goTo(first, false);
this.validateStep(steps[first]);
}
this.showErrors(errors);
return;
}
this.hideSummary();
if (this.preview) {
this.success('Vorschau');
return;
}
this.submitting = true;
this.submitEl.disabled = true;
this.submitEl.setAttribute('aria-busy', 'true');
this.formEl.setAttribute('aria-busy', 'true');
try {
const response = await this.post();
const data = await response.json().catch(() => ({}));
if (response.status === 201) {
this.success(data.reference);
return;
}
this.failure(response.status, data);
} catch {
this.failure(0, {});
} finally {
this.submitting = false;
this.formEl.removeAttribute('aria-busy');
if (this.submitEl && !this.finished) {
this.submitEl.disabled = false;
this.submitEl.removeAttribute('aria-busy');
}
}
}
async post(retry = true) {
const response = await fetch(this.root.dataset.submitUrl, {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRF-TOKEN': this.csrf },
body: JSON.stringify({
values: this.visibleValues(),
token: this.token,
website: this.honeypot.querySelector('input').value,
source: location.pathname,
}),
});
// Abgelaufenes Formular oder Sitzung: neues Token holen und einmal erneut senden. Die Eingaben bleiben erhalten.
if (response.status === 419 && retry) {
const fresh = await fetch(this.root.dataset.definitionUrl, { headers: { Accept: 'application/json' }, credentials: 'same-origin' });
if (fresh.ok) {
const data = await fresh.json();
this.token = data.token;
this.csrf = data.csrf;
return this.post(false);
}
}
return response;
}
failure(status, data) {
const fields = data.fields || {};
const errors = Object.entries(fields).map(([key, message]) => ({ key, message, label: this.labelOf(key) }));
if (errors.length) {
errors.forEach((error) => this.setError(error.key, error.message));
if (this.wizard) {
const steps = this.visibleSteps();
const first = steps.findIndex((step) => step.items.some((item) => (item.kind === 'issue' ? errors.some((e) => e.key.endsWith('anliegen')) : item.fields.some((row) => fields[row.field]))));
this.goTo(first === -1 ? 0 : first, false);
}
this.showErrors(errors);
return;
}
let message;
if (status === 429 && data.fields === undefined) {
message = 'Es wurden in kurzer Zeit zu viele Anfragen gesendet. Bitte warten Sie einen Moment und versuchen Sie es dann noch einmal.';
} else if ([410, 419, 422, 429].includes(status) && data.message) {
message = data.message;
} else {
message = this.def.texts.error_text;
}
this.showMessage(message);
}
showMessage(text) {
this.summaryBox.replaceChildren(h('p', { class: 'inquiry-errors-title', text }));
this.summaryBox.hidden = false;
this.summaryBox.focus();
this.summaryBox.scrollIntoView({ block: 'center', behavior: 'smooth' });
}
success(reference) {
this.finished = true;
const preview = reference === 'Vorschau';
const box = h('div', { class: 'inquiry-success', role: 'status', tabindex: '-1' },
h('h3', { text: this.def.texts.success_title }),
h('p', { text: this.def.texts.success_text }),
preview
? h('p', { class: 'inquiry-note', text: 'Vorschau: Es wurde nichts gesendet.' })
: h('p', { class: 'inquiry-reference' }, 'Ihr Kennzeichen: ', h('strong', { text: reference })),
);
this.formEl.replaceWith(box);
this.heading.hidden = false;
box.focus();
box.scrollIntoView({ block: 'center', behavior: 'smooth' });
}
}
export function initInquiryForms(root = document) {
root.querySelectorAll('[data-inquiry]').forEach((el) => {
if (el.dataset.inquiryReady === '1') {
return;
}
el.dataset.inquiryReady = '1';
new InquiryForm(el).start();
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => initInquiryForms());
} else {
initInquiryForms();
}