rob-revisited/ide/ui/js/symfony-forms-preview.js

284 lines
20 KiB
JavaScript

// The preview of a Symfony form without PHP (the Forms window, symfony-forms.js): the HTML Symfony's form themes would
// render for the FormType being built, from its fields and options: form_div_layout (the default), form_table_layout,
// bootstrap_5_layout and tailwind_2_layout (their classes, the error states with "Show errors": is-invalid +
// invalid-feedback, the red border...), with the ids and names Symfony gives (product_name, product[name]). Sub-forms
// are drawn from their own FormType when the window read it; collections show one entry and carry their prototype.
// The page around it is the project's (base.html.twig and its CSS, through twig-preview.js) with the theme's CSS.
import { blockPrefix, humanize, shortName, typeOf, constraintMessage, asMap, rendererOf } from './symfony-forms-model.js';
export const esc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
const CLASSES = {
div: { row: '', label: '', input: '', select: '', check: '', checkLabel: '', help: 'help-text', invalid: '', submit: '', button: '' },
table: { row: '', label: '', input: '', select: '', check: '', checkLabel: '', help: 'help-text', invalid: '', submit: '', button: '' },
bootstrap_5: { row: 'mb-3', label: 'form-label', input: 'form-control', select: 'form-select', check: 'form-check-input', checkLabel: 'form-check-label',
help: 'form-text mb-0 help-text', invalid: 'is-invalid', submit: 'btn-primary btn', button: 'btn-secondary btn' },
tailwind_2: { row: 'mb-6', label: 'block text-gray-800', input: 'mt-1 w-full', select: 'mt-1 w-full', check: 'mr-2', checkLabel: 'block text-gray-800',
help: 'mt-1 text-gray-600', invalid: 'border-2 border-red-700', submit: 'px-4 py-2 rounded bg-blue-600 text-white', button: 'px-4 py-2 rounded bg-gray-200' },
};
const CURRENCY = { EUR: '€', USD: '$', GBP: '£', JPY: '¥', CHF: 'CHF', CNY: '¥', INR: '₹' };
const SAMPLES = {
CountryType: ['France', 'Germany', 'Japan', 'Spain', 'United Kingdom'], LanguageType: ['English', 'French', 'German', 'Japanese', 'Spanish'],
LocaleType: ['en', 'en_GB', 'fr', 'fr_FR', 'ja'], CurrencyType: ['Euro', 'Japanese Yen', 'US Dollar'], TimezoneType: ['Europe / Paris', 'America / New York', 'Asia / Tokyo'],
};
const attrs = (map) => Object.entries(map).filter(([, v]) => v !== null && v !== undefined && v !== false && v !== '')
.map(([k, v]) => (v === true ? ` ${k}="${esc(k)}"` : ` ${k}="${esc(v)}"`)).join('');
const join = (...c) => c.filter(Boolean).join(' ').trim();
const scalar = (v) => (v === null || v === undefined || typeof v === 'object' ? '' : v);
/**
* The <form> Symfony would render for a FormType model.
* @param {object} model {class, fields: [{name, type, options}], defaults}
* @param {{theme?: string|string[], errors?: boolean, subforms?: object, enums?: object}} o
* theme: a form theme's file (or a renderer: div, table, bootstrap_5, tailwind_2); subforms: fqcn -> model of a project
* form type (sub-forms, collection entries); enums: fqcn -> case names
*/
export function formHtml(model, o = {}) {
const r = ['div', 'table', 'bootstrap_5', 'tailwind_2'].includes(o.theme) ? o.theme : rendererOf(o.theme);
const ctx = { r, c: CLASSES[r], errors: !!o.errors, subforms: o.subforms || {}, enums: o.enums || {}, depth: 0 };
const name = blockPrefix(model?.class || 'FormType');
const defaults = asMap(model?.defaults);
const body = children(ctx, model, name, name, defaults.csrf_protection !== false);
return `<form name="${esc(name)}" method="post"${hasFile(model) ? ' enctype="multipart/form-data"' : ''}>\n${body}</form>\n`;
}
function hasFile(model) {
return (model?.fields || []).some((f) => shortName(f.type) === 'FileType');
}
/** the rows of a compound form (the root or a sub-form) in its <div id> (form_table_layout: a <table>) */
function children(ctx, model, id, fullName, csrf) {
const rows = [];
for (const f of model?.fields || []) {
if (!f || !f.name || f.name === '?') continue;
rows.push(row(ctx, f, `${id}_${f.name}`, `${fullName}[${f.name}]`));
}
if (csrf) rows.push(`<input type="hidden" id="${esc(id)}__token" name="${esc(fullName)}[_token]" value="csrf-token">`);
const inner = rows.join('\n');
return ctx.r === 'table' ? `<table id="${esc(id)}">\n${inner}\n</table>\n` : `<div id="${esc(id)}">\n${inner}\n</div>\n`;
}
/** what the validator would say about a field (Show errors) */
function errorsOf(ctx, f) {
if (!ctx.errors) return [];
const opts = asMap(f.options);
const kind = shortName(f.type);
if (['SubmitType', 'ResetType', 'ButtonType', 'HiddenType'].includes(kind)) return [];
const constraints = Array.isArray(opts.constraints) ? opts.constraints.filter((c) => c && c['@new'] && !/\\Valid$/.test(c['@new'])) : [];
if (constraints.length) return [constraintMessage(constraints[0])];
if (kind === 'RepeatedType') return [typeof opts.invalid_message === 'string' ? opts.invalid_message : 'The values do not match.'];
if (opts.required !== false && kind !== 'CheckboxType' && kind !== 'CollectionType' && (typeOf(f.type) || !f.type)) return ['This value should not be blank.'];
return [];
}
function errorsHtml(ctx, list) {
if (!list.length) return '';
if (ctx.r === 'bootstrap_5') return list.map((m) => `<div class="invalid-feedback d-block">${esc(m)}</div>`).join('');
if (ctx.r === 'tailwind_2') return `<ul>${list.map((m) => `<li class="text-red-700">${esc(m)}</li>`).join('')}</ul>`;
return `<ul>${list.map((m) => `<li>${esc(m)}</li>`).join('')}</ul>`;
}
function labelText(f, opts) {
if (opts.label === false) return null;
return typeof opts.label === 'string' && opts.label !== '' ? opts.label : humanize(f.name);
}
function labelHtml(ctx, text, id, required, extra = '', labelAttr = {}) {
if (text === null) return '';
const tag = ctx.compoundLegend ? 'legend' : 'label';
const cls = join(asMap(labelAttr).class, ctx.compoundLegend && ctx.r === 'bootstrap_5' ? 'col-form-label' : ctx.c.label, extra, required ? 'required' : '');
return `<${tag}${tag === 'label' && id ? ` for="${esc(id)}"` : ''}${attrs({ ...asMap(labelAttr), class: cls })}>${esc(text)}</${tag}>`;
}
function helpHtml(ctx, id, help) {
if (typeof help !== 'string' || !help) return '';
return ctx.r === 'tailwind_2' ? `<p id="${esc(id)}_help" class="${ctx.c.help}">${esc(help)}</p>` : `<div id="${esc(id)}_help" class="${ctx.c.help}">${esc(help)}</div>`;
}
/** one field's row: label, widget, help, errors in the theme's order and markup */
function row(ctx, f, id, fullName) {
const opts = asMap(f.options);
const kind = typeOf(f.type)?.name || (f.type ? 'subform' : 'TextType');
const required = opts.required !== false && !['CheckboxType', 'RadioType'].includes(kind) ? true : opts.required === true;
const errors = errorsOf(ctx, f);
const help = helpHtml(ctx, id, opts.help);
const rowAttr = asMap(opts.row_attr);
const rowClass = (extra = '') => join(rowAttr.class, ctx.c.row, extra);
const label = labelText(f, opts);
if (kind === 'HiddenType') return widget(ctx, f, kind, id, fullName, required, errors.length > 0);
if (['SubmitType', 'ResetType', 'ButtonType'].includes(kind)) {
const type = kind === 'SubmitType' ? 'submit' : kind === 'ResetType' ? 'reset' : 'button';
const a = asMap(opts.attr);
const button = `<button type="${type}" id="${esc(id)}" name="${esc(fullName)}"${attrs({ ...a, class: join(a.class, kind === 'SubmitType' ? ctx.c.submit : ctx.c.button) })}>${esc(label ?? humanize(f.name))}</button>`;
if (ctx.r === 'table') return `<tr><td></td><td>${button}</td></tr>`;
return `<div${attrs({ ...rowAttr, class: rowClass() })}>${button}</div>`;
}
if (kind === 'RepeatedType') {
const inner = asMap(opts.type)['@class'] || 'Symfony\\Component\\Form\\Extension\\Core\\Type\\TextType';
const common = asMap(opts.options);
const first = { name: 'first', type: inner, options: { ...common, ...asMap(opts.first_options), required: opts.required, help: opts.help } };
const second = { name: 'second', type: inner, options: { ...common, ...asMap(opts.second_options), required: opts.required } };
const firstHtml = row({ ...ctx, errors: false }, first, `${id}_first`, `${fullName}[first]`);
const errHtml = errors.length && ctx.r !== 'table' ? errorsHtml(ctx, errors) : '';
return firstHtml.replace(/<\/div>$/, errHtml + '</div>') + '\n' + row({ ...ctx, errors: false }, second, `${id}_second`, `${fullName}[second]`);
}
if (kind === 'subform' || kind === 'CollectionType') {
const body = kind === 'CollectionType' ? collection(ctx, f, opts, id, fullName) : subform(ctx, f, id, fullName);
if (ctx.r === 'table') return `<tr><td>${labelHtml(ctx, label, null, required)}</td><td>${errorsHtml(ctx, errors)}${body}${help}</td></tr>`;
if (ctx.r === 'bootstrap_5') {
return `<fieldset${attrs({ ...rowAttr, class: rowClass() })}>${labelHtml({ ...ctx, compoundLegend: true }, label, null, required)}${body}${help}${errorsHtml(ctx, errors)}</fieldset>`;
}
return `<div${attrs({ ...rowAttr, class: rowClass() || undefined })}>${labelHtml(ctx, label, null, required)}${ctx.r === 'tailwind_2' ? '' : errorsHtml(ctx, errors)}${body}${help}${ctx.r === 'tailwind_2' ? errorsHtml(ctx, errors) : ''}</div>`;
}
const w = widget(ctx, f, kind, id, fullName, required, errors.length > 0);
const expanded = (kind === 'ChoiceType' || kind === 'EnumType' || kind === 'EntityType' || SAMPLES[kind]) && opts.expanded === true;
if (kind === 'CheckboxType' || kind === 'RadioType') {
const box = `${w}${labelHtml({ ...ctx, c: { ...ctx.c, label: ctx.c.checkLabel } }, label, id, required)}`;
if (ctx.r === 'bootstrap_5') return `<div${attrs({ ...rowAttr, class: rowClass() })}><div class="form-check">${box}${help}${errorsHtml(ctx, errors)}</div></div>`;
if (ctx.r === 'table') return `<tr><td></td><td>${errorsHtml(ctx, errors)}${box}${help}</td></tr>`;
if (ctx.r === 'tailwind_2') return `<div${attrs({ ...rowAttr, class: rowClass() })}>${box}${help}${errorsHtml(ctx, errors)}</div>`;
return `<div${attrs(rowAttr)}>${errorsHtml(ctx, errors)}${box}${help}</div>`;
}
const labelFor = expanded ? null : id;
if (ctx.r === 'table') return `<tr${attrs(rowAttr)}><td>${labelHtml(ctx, label, labelFor, required)}</td><td>${errorsHtml(ctx, errors)}${w}${help}</td></tr>`;
if (ctx.r === 'bootstrap_5' && expanded) {
return `<fieldset${attrs({ ...rowAttr, class: rowClass() })}>${labelHtml({ ...ctx, compoundLegend: true }, label, null, required)}${w}${help}${errorsHtml(ctx, errors)}</fieldset>`;
}
if (ctx.r === 'bootstrap_5' || ctx.r === 'tailwind_2') return `<div${attrs({ ...rowAttr, class: rowClass() })}>${labelHtml(ctx, label, labelFor, required, '', opts.label_attr)}${w}${help}${errorsHtml(ctx, errors)}</div>`;
return `<div${attrs(rowAttr)}>${labelHtml(ctx, label, labelFor, required, '', opts.label_attr)}${errorsHtml(ctx, errors)}${w}${help}</div>`;
}
/** an <input>, <select>, <textarea>... with the theme's classes and the field's attr */
function widget(ctx, f, kind, id, fullName, required, invalid) {
const opts = asMap(f.options);
const a = asMap(opts.attr);
const described = typeof opts.help === 'string' && opts.help ? `${id}_help` : null;
const base = (cls, more = {}) => attrs({ id, name: fullName, required: required ? 'required' : null, disabled: opts.disabled === true ? 'disabled' : null,
'aria-describedby': described, ...a, ...more, class: join(a.class, cls, invalid ? ctx.c.invalid : '') || null });
const value = scalar(opts.data);
const input = (type, more = {}) => `<input type="${type}"${base(type === 'checkbox' || type === 'radio' ? ctx.c.check : type === 'range' ? (ctx.r === 'bootstrap_5' ? 'form-range' : ctx.c.input) : ctx.c.input, more)}${value !== '' && type !== 'checkbox' ? ` value="${esc(value)}"` : ''}>`;
const html5 = opts.html5 !== false;
switch (kind) {
case 'TextareaType': return `<textarea${base(ctx.c.input)}>${esc(value)}</textarea>`;
case 'EmailType': return input('email');
case 'PasswordType': return input('password');
case 'UrlType': return input('text', { inputmode: 'url' });
case 'TelType': return input('tel');
case 'SearchType': return input('search');
case 'ColorType': return input(html5 ? 'color' : 'text');
case 'IntegerType': return input('number');
case 'NumberType': return input(opts.html5 === true ? 'number' : 'text', { inputmode: 'decimal' });
case 'RangeType': return input('range');
case 'UuidType': case 'UlidType': return input('text');
case 'FileType': return `<input type="file"${base(ctx.c.input, { name: fullName + (opts.multiple ? '[]' : ''), multiple: opts.multiple ? 'multiple' : null })}>`;
case 'HiddenType': return `<input type="hidden"${attrs({ id, name: fullName, ...a })}${value !== '' ? ` value="${esc(value)}"` : ''}>`;
case 'CheckboxType': return input('checkbox', { value: '1', checked: opts.data === true ? 'checked' : null, required: opts.required === true ? 'required' : null });
case 'RadioType': return input('radio', { value: '1' });
case 'MoneyType': {
const currency = typeof opts.currency === 'string' ? opts.currency : opts.currency === false ? '' : 'EUR';
const sign = CURRENCY[currency] || currency;
const field = input(opts.html5 === true ? 'number' : 'text', { inputmode: 'decimal' });
if (!sign) return field;
if (ctx.r === 'bootstrap_5') return `<div class="input-group${invalid ? ' has-validation' : ''}"><span class="input-group-text">${esc(sign)}</span>${field}</div>`;
return `${esc(sign)} ${field}`;
}
case 'PercentType': {
const field = input('text', { inputmode: 'decimal' });
const sign = opts.symbol === false ? '' : typeof opts.symbol === 'string' ? opts.symbol : '%';
if (!sign) return field;
return ctx.r === 'bootstrap_5' ? `<div class="input-group">${field}<span class="input-group-text">${esc(sign)}</span></div>` : `${field} ${esc(sign)}`;
}
case 'DateType': case 'BirthdayType': return dateWidget(ctx, opts, base, input, id, fullName, invalid, 'date');
case 'DateTimeType': return dateWidget(ctx, opts, base, input, id, fullName, invalid, 'datetime-local');
case 'TimeType': return dateWidget(ctx, opts, base, input, id, fullName, invalid, 'time');
case 'WeekType': return opts.widget === 'single_text' ? input('week') : dateWidget(ctx, opts, base, input, id, fullName, invalid, 'week');
case 'DateIntervalType': return `<div${attrs({ id })}>${['years', 'months', 'days'].map((p) => `<input type="number" id="${esc(id)}_${p}" name="${esc(fullName)}[${p}]" placeholder="${humanize(p)}"${attrs({ class: ctx.c.input || null })}>`).join(' ')}</div>`;
case 'ChoiceType': case 'EnumType': case 'EntityType': case 'CountryType': case 'LanguageType': case 'LocaleType': case 'CurrencyType': case 'TimezoneType':
return choiceWidget(ctx, f, kind, opts, base, id, fullName, required, invalid);
default: return input('text');
}
}
/** the choices of a choice field: [label, value] */
function choicesOf(ctx, f, kind, opts) {
if (kind === 'ChoiceType') {
const c = opts.choices;
if (Array.isArray(c)) return c.map((v) => [String(scalar(v)), String(scalar(v))]);
if (c && typeof c === 'object' && !c['@php']) return Object.entries(c).map(([k, v]) => [k, typeof v === 'object' ? k : String(v)]);
return [['…', '']];
}
if (kind === 'EnumType') {
const cls = asMap(opts.class)['@class'];
const cases = ctx.enums[cls] || ['…'];
return cases.map((n) => [n, n.toLowerCase()]);
}
if (kind === 'EntityType') {
const cls = shortName(asMap(opts.class)['@class'] || 'Entity');
const prop = typeof opts.choice_label === 'string' ? opts.choice_label : '';
return [1, 2, 3].map((n) => [`${cls} ${n}${prop ? ` (${prop})` : ''}`, String(n)]);
}
return (SAMPLES[kind] || []).map((n) => [n, n]);
}
function choiceWidget(ctx, f, kind, opts, base, id, fullName, required, invalid) {
const choices = choicesOf(ctx, f, kind, opts);
const multiple = opts.multiple === true;
if (opts.expanded === true) {
const type = multiple ? 'checkbox' : 'radio';
const items = choices.map(([label, value], i) => {
const cid = `${id}_${i}`;
const box = `<input type="${type}" id="${esc(cid)}" name="${esc(fullName)}${multiple ? '[]' : ''}"${attrs({ class: join(ctx.c.check, invalid ? ctx.c.invalid : '') || null, required: !multiple && required ? 'required' : null })} value="${esc(value)}">`;
const lab = `<label for="${esc(cid)}"${attrs({ class: join(ctx.c.checkLabel, required ? 'required' : '') || null })}>${esc(label)}</label>`;
return ctx.r === 'bootstrap_5' ? `<div class="form-check">${box}${lab}</div>` : `${box}${lab}`;
}).join(ctx.r === 'bootstrap_5' ? '' : '\n');
return `<div id="${esc(id)}">${items}</div>`;
}
const placeholder = typeof opts.placeholder === 'string' ? opts.placeholder : (!required && !multiple ? '' : null);
const options = (placeholder !== null && !multiple ? `<option value=""${required ? ' disabled selected' : ''}>${esc(placeholder)}</option>` : '')
+ choices.map(([label, value]) => `<option value="${esc(value)}">${esc(label)}</option>`).join('');
return `<select${base(ctx.c.select, { name: fullName + (multiple ? '[]' : ''), multiple: multiple ? 'multiple' : null })}>${options}</select>`;
}
function dateWidget(ctx, opts, base, input, id, fullName, invalid, html5Type) {
const widgetKind = opts.widget || 'single_text';
if (widgetKind === 'single_text') return input(opts.html5 === false ? 'text' : html5Type);
const parts = html5Type === 'time' ? ['hour', 'minute'] : html5Type === 'week' ? ['year', 'week'] : html5Type === 'date' ? ['year', 'month', 'day'] : ['year', 'month', 'day', 'hour', 'minute'];
const cls = ctx.r === 'bootstrap_5' ? 'form-select' : ctx.c.select;
const one = (p) => (widgetKind === 'text'
? `<input type="text" id="${esc(id)}_${p}" name="${esc(fullName)}[${p}]" size="${p === 'year' ? 4 : 2}"${attrs({ class: join(ctx.c.input, invalid ? ctx.c.invalid : '') || null })}>`
: `<select id="${esc(id)}_${p}" name="${esc(fullName)}[${p}]"${attrs({ class: join(cls, invalid ? ctx.c.invalid : '') || null })}><option>${p === 'year' ? '2026' : p === 'month' ? 'Nov' : '01'}</option></select>`);
const wrap = ctx.r === 'bootstrap_5' ? 'input-group' : '';
return `<div id="${esc(id)}"${wrap ? ` class="${wrap}"` : ''}>${parts.map(one).join(html5Type === 'time' ? ':' : '')}</div>`;
}
/** a sub-form: its own FormType's rows (when the window read it), else its class */
function subform(ctx, f, id, fullName) {
const model = ctx.subforms[String(f.type).replace(/^\\/, '')];
if (!model || ctx.depth > 3) return `<div id="${esc(id)}"><em>${esc(shortName(f.type))}</em></div>`;
return children({ ...ctx, depth: ctx.depth + 1 }, model, id, fullName, false);
}
/** a collection: one entry shown, the prototype (what "add" clones) in data-prototype */
function collection(ctx, f, opts, id, fullName) {
const entryType = asMap(opts.entry_type)['@class'] || 'Symfony\\Component\\Form\\Extension\\Core\\Type\\TextType';
const entryOptions = asMap(opts.entry_options);
const entry = (n) => row({ ...ctx, errors: false, depth: ctx.depth + 1 }, { name: n, type: entryType, options: { label: n, ...entryOptions } }, `${id}_${n}`, `${fullName}[${n}]`);
const protoName = typeof opts.prototype_name === 'string' ? opts.prototype_name : '__name__';
const proto = opts.prototype === false ? '' : ` data-prototype="${esc(entry(protoName).replace(new RegExp(`>${protoName}<`, 'g'), `>${protoName}label__<`))}"`;
return `<div id="${esc(id)}"${proto}>${entry('0')}</div>`;
}
/** the stylesheet a theme needs in the preview (the project's own copy when it has one, else a CDN) */
export function themeStylesheets(theme, localBootstrap = null) {
const r = ['div', 'table', 'bootstrap_5', 'tailwind_2'].includes(theme) ? theme : rendererOf(theme);
if (r === 'bootstrap_5') return [localBootstrap ? '/' + localBootstrap : 'https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css'];
if (r === 'tailwind_2') return ['https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css'];
return [];
}
/** a whole page around the form when the project has no layout of its own */
export function standalonePage(form, title, stylesheets = []) {
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${esc(title)}</title>`
+ stylesheets.map((h) => `<link rel="stylesheet" href="${esc(h)}">`).join('') + `</head><body><main style="max-width:720px;margin:24px auto;padding:0 16px">${form}</main></body></html>`;
}