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

696 lines
45 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The Symfony Forms window: the project's FormTypes (src/Form/*Type.php), and the form builder that edits one visually.
// - The window (right): the form types (from the PHP index), "New form type", the project's form themes (twig.yaml).
// - The builder (over the workbench): the fields (added, reordered by dragging, removed), each field's type (Symfony's
// types, the project's own form types) and its options edited by kind (label, required, help, attr, constraints with
// their options, choices, the target entity and query_builder of an EntityType, a CollectionType's entry_type and
// allow_add / allow_delete / by_reference / prototype, dates' widget / html5...), configureOptions (data_class,
// validation_groups, csrf...), form events (listener methods made) and data transformers (their class made).
// "Add fields from the class" proposes the properties of the data class with the types they suggest (Doctrine mapping,
// PHP types, relations -> EntityType).
// - The preview (right of the builder): the HTML the chosen theme renders (default, table, Bootstrap 5, Tailwind 2),
// "Show errors" for the error states, in the project's own layout (base.html.twig, its CSS) without PHP.
// - Save writes back only what changed (a diff shown first); Generate makes the controller action and its template.
// The PHP side: ide/src/Symfony/FormCommands.php (FormTypeParser, FormTypeWriter, FormFieldSuggester, FormCodeGenerator).
import { backend } from './backend.js';
import { el, clear, icon, notify, prefs, t, dialog, chooser, prompt, confirm, debounce } from './ui.js';
import { HtmlPreview, dataUrlOf } from './html-preview.js';
import { twigPreviewText } from './twig-preview.js';
import { TYPES, GROUPS, OPTIONS, PERCENT_TYPE, CONSTRAINT_TYPES, EVENTS, EVENT_HELP, THEMES, CORE, typeOf, optionsOf, constraintOf, shortName, humanize,
blockPrefix, listenerName, phpOf, asMap } from './symfony-forms-model.js';
import { formHtml, themeStylesheets, standalonePage } from './symfony-forms-preview.js';
document.head.append(el('link', { rel: 'stylesheet', href: new URL('../css/symfony-forms.css', import.meta.url).href }));
const clone = (v) => JSON.parse(JSON.stringify(v ?? null));
// the model as PHP wrote it (a JSON text: the desktop bridge would sort a JSON object's keys, choices included)
const modelOf = (r) => (r.modelJson ? JSON.parse(r.modelJson) : r.model);
/** an empty constraint's arguments arrive as [] */
const fixArgs = (v) => { if (Array.isArray(v)) v.forEach(fixArgs); else if (v && typeof v === 'object') { if (v['@new'] && Array.isArray(v.args) && !v.args.length) v.args = {}; Object.values(v).forEach(fixArgs); } return v; };
export class SymfonyFormsPanel {
constructor(app) {
this.app = app;
this.node = el('div.sff-view');
this.list = null;
this.error = null;
this.render();
}
title() { return 'Symfony Forms'; }
actions() {
return [
el('button', { title: t('New form type…'), onclick: () => this.newType() }, icon('plus')),
el('button', { title: t('Refresh'), onclick: () => this.load() }, icon('refresh')),
];
}
shown() { if (!this.list) this.load(); }
async load() {
try { this.list = await backend.invoke('forms.list', {}); this.error = null; } catch (e) { this.error = e.message; }
this.render();
return this.list;
}
render() {
clear(this.node);
if (this.error) { this.node.append(el('div.sff-hint', {}, this.error)); return; }
if (!this.list) { this.node.append(el('div.sff-hint', {}, t('Loading…'))); return; }
this.node.append(el('div.sff-toolbar', {}, el('button.btn.primary', { 'data-tour': 'forms-new-type', onclick: () => this.newType() }, icon('plus'), t('New form type…')),
el('button.btn', { onclick: () => this.openActive(), title: t('The FormType open in the editor') }, t('Open the current file'))));
this.node.append(el('div.sff-section', {}, t('Form types')));
if (!this.list.types.length) this.node.append(el('div.sff-hint', {}, t('No form type yet: make one with "New form type…".')));
for (const type of this.list.types) {
this.node.append(el('div.sff-row', { title: type.path, onclick: () => this.open(type.path), oncontextmenu: (e) => { e.preventDefault(); this.app.editors.open(type.path); } },
icon('design'), el('span.sff-name', {}, shortName(type.class)), el('span.sff-sub', {}, type.path.replace(/^src\//, ''))));
}
this.node.append(el('div.sff-section', {}, t('Form themes of the project')));
this.node.append(el('div.sff-hint', {}, this.list.themes.length ? this.list.themes.join(', ') : t('Symfony\'s default (form_div_layout)')),
el('div.sff-toolbar', {}, el('button.btn', { onclick: () => this.chooseThemes() }, t('Change the themes…'))));
}
/** the FormType open in the editor */
openActive() {
const path = this.app.editors.activePath();
if (!path || !/\.php$/.test(path)) { notify(t('Open a FormType (src/Form/…Type.php) in the editor first.'), 'info'); return; }
this.open(path);
}
async open(path) {
try {
const text = await this.app.editors.readProjectText(path);
const read = await backend.invoke('forms.read', { path, text });
new FormBuilder(this, path, modelOf(read));
} catch (e) { notify(e.message, 'error', { title: t('Form builder') }); }
}
async newType() {
if (!this.list) await this.load();
const name = await prompt(t('New form type'), { label: t('Its class (in src/Form): ProductType, Admin\\UserType…'), value: 'NewType' });
if (!name) return;
let cls = name.trim().replace(/^\\/, '').replace(/\.php$/, '');
if (!cls.includes('\\')) cls = 'App\\Form\\' + cls;
if (!/Type$/.test(cls)) cls += 'Type';
const model = { class: cls, fields: [], events: [], transformers: [], defaults: {}, methods: [] };
// the data class: an entity / a DTO of the same name, when there is one
const base = shortName(cls).replace(/Type$/, '');
const data = (this.list?.classes || []).find((c) => shortName(c.class) === base);
if (data) model.defaults.data_class = { '@class': data.class };
const builder = new FormBuilder(this, null, model);
if (data) builder.addFromClass();
}
/** twig.yaml's form_themes, chosen in a list, written after a diff */
async chooseThemes() {
const current = new Set(this.list?.themes || []);
const all = [...THEMES, ...(this.list?.projectThemes || [])];
const boxes = all.map((theme) => el('label.sff-check', {}, el('input', { type: 'checkbox', checked: current.has(theme), value: theme }), theme));
dialog({
title: t('Form themes of the project'),
body: el('div', {}, el('p.sff-hint', {}, t('config/packages/twig.yaml form_themes: how every form of the project is rendered (a form can still choose its own).')), ...boxes),
buttons: [{ label: 'Cancel' }, { label: 'Show the change…', primary: true, action: async () => {
const themes = boxes.map((b) => b.firstChild).filter((i) => i.checked).map((i) => i.value);
const r = await backend.invoke('forms.themes', { themes });
await showDiff(this.app, r.files, t('Form themes of the project'));
await this.load();
} }],
});
}
}
/** The form builder: a FormType's model edited, previewed, written back. */
class FormBuilder {
constructor(panel, path, model) {
this.panel = panel;
this.app = panel.app;
this.path = path;
this.model = this.normalize(model);
this.saved = JSON.stringify(this.model);
this.selected = this.model.fields.length ? { kind: 'field', index: 0 } : { kind: 'form' };
this.errors = !!prefs.get('sffErrors', false);
this.theme = prefs.get('sffTheme:' + this.model.class, '');
this.subforms = {};
this.node = el('div.sff-overlay');
this.onKey = (e) => { if (e.key === 'Escape' && !document.querySelector('.dialog')) this.close(); };
document.addEventListener('keydown', this.onKey);
document.body.append(this.node);
this.updatePreview = debounce(() => this.preview?.update(), 250);
window.jumphpFormBuilder = this;
this.render();
}
normalize(m) {
const model = fixArgs(clone(m));
model.fields = (model.fields || []).map((f) => ({ ...f, options: asMap(f.options) }));
model.events = model.events || [];
model.transformers = model.transformers || [];
model.defaults = asMap(model.defaults);
model.methods = model.methods || [];
return model;
}
dirty() { return JSON.stringify(this.model) !== this.saved; }
async close(force = false) {
if (!force && this.dirty() && !(await confirm(t('Close the form builder'), t('The changes are not written to the file. Close anyway?'), { ok: 'Close', danger: true }))) return;
document.removeEventListener('keydown', this.onKey);
this.preview?.destroy();
this.node.remove();
if (window.jumphpFormBuilder === this) window.jumphpFormBuilder = null;
}
changed(full = false) {
if (full) this.render(); else { this.renderList(); this.renderTitle(); }
this.updatePreview();
}
/** the project's form types (sub-forms, entry types) */
projectTypes() { return (this.panel.list?.types || []).map((x) => x.class).filter((c) => c !== this.model.class); }
render() {
clear(this.node);
this.titleNode = el('div.sff-title');
this.renderTitle();
const head = el('div.sff-head', {}, this.titleNode, el('span.grow'),
el('button.btn', { 'data-tour': 'forms-generate', onclick: () => this.generate(), title: t('The controller action that shows and handles this form, and its Twig template') }, icon('code'), t('Generate controller and template…')),
el('button.btn.primary', { 'data-tour': 'forms-save', onclick: () => this.save() }, icon('check'), t('Save…')),
el('button.btn', { onclick: () => this.close(), title: t('Close (Escape)') }, icon('close')));
this.listNode = el('div.sff-list');
this.inspector = el('div.sff-inspector');
this.previewHost = el('div.sff-preview-host');
const previewBar = el('div.sff-preview-bar', {},
el('label', {}, t('Theme'), this.themeSelect()),
el('label', {}, el('input', { type: 'checkbox', checked: this.errors, onchange: (e) => { this.errors = e.target.checked; prefs.set('sffErrors', this.errors); this.updatePreview(); } }), t('Show errors')));
this.node.append(head, el('div.sff-body', {}, this.listNode, this.inspector, el('div.sff-preview', {}, previewBar, this.previewHost)));
this.renderList();
this.renderInspector();
this.startPreview();
}
renderTitle() {
clear(this.titleNode);
this.titleNode.append(icon('design'), el('b', {}, shortName(this.model.class)), el('span.sff-sub', {}, this.path || t('new file')), ...(this.dirty() ? [el('span.sff-dirty', { title: t('Not written yet') }, '●')] : []));
}
themeSelect() {
const project = this.panel.list?.themes || [];
const s = el('select.input', { onchange: (e) => { this.theme = e.target.value; prefs.set('sffTheme:' + this.model.class, this.theme); this.updatePreview(); } },
el('option', { value: '' }, t('The project\'s ({themes})', { themes: project.length ? project.map((x) => x.replace(/\.html\.twig$/, '')).join(', ') : 'form_div_layout' })),
...[...THEMES, ...(this.panel.list?.projectThemes || [])].map((x) => el('option', { value: x }, x)));
s.value = this.theme;
return s;
}
// the list: fields, form options, events, transformers -----------------------------------------------------------
renderList() {
const box = this.listNode;
const scroll = box.scrollTop;
clear(box);
const isSel = (kind, index) => this.selected.kind === kind && this.selected.index === index;
box.append(el('div.sff-section', {}, t('Fields'), el('span.grow'),
el('button.sff-mini', { title: t('Add fields from the class…'), onclick: () => this.addFromClass() }, icon('download')),
el('button.sff-mini', { title: t('Add a field'), onclick: (e) => this.addField(e.currentTarget) }, icon('plus'))));
if (!this.model.fields.length) box.append(el('div.sff-hint', {}, t('No field yet.')));
this.model.fields.forEach((f, i) => {
const row = el(`div.sff-row.sff-field${isSel('field', i) ? '.sel' : ''}${f.locked ? '.locked' : ''}`, {
draggable: !f.locked, onclick: () => this.select('field', i),
ondragstart: (e) => { this.drag = i; e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', String(i)); },
ondragover: (e) => { if (this.drag !== undefined) { e.preventDefault(); row.classList.add('drop'); } },
ondragleave: () => row.classList.remove('drop'),
ondrop: (e) => { e.preventDefault(); row.classList.remove('drop'); this.move(this.drag, i); this.drag = undefined; },
}, el('span.sff-grip', {}, f.locked ? '🔒' : '⋮⋮'), el('span.sff-name', {}, f.name), el('span.sff-type', {}, f.type ? shortName(f.type) : t('guessed')),
f.locked ? null : el('span.sff-row-actions', {},
el('button.sff-mini', { title: t('Move up'), onclick: (e) => { e.stopPropagation(); this.move(i, i - 1); } }, '↑'),
el('button.sff-mini', { title: t('Move down'), onclick: (e) => { e.stopPropagation(); this.move(i, i + 1); } }, '↓'),
el('button.sff-mini', { title: t('Remove'), onclick: (e) => { e.stopPropagation(); this.removeField(i); } }, icon('trash'))));
box.append(row);
});
box.append(el('div.sff-section', {}, t('Form')));
box.append(el(`div.sff-row${this.selected.kind === 'form' ? '.sel' : ''}`, { onclick: () => this.select('form', 0) }, icon('settings'),
el('span.sff-name', {}, t('Options (configureOptions)')), el('span.sff-type', {}, shortName(asMap(this.model.defaults.data_class)['@class'] || ''))));
box.append(el('div.sff-section', {}, t('Events'), el('span.grow'), el('button.sff-mini', { title: t('Add an event listener'), onclick: () => this.addEvent() }, icon('plus'))));
this.model.events.forEach((ev, i) => box.append(el(`div.sff-row${isSel('event', i) ? '.sel' : ''}${ev.locked ? '.locked' : ''}`, { onclick: () => this.select('event', i) },
icon('bell'), el('span.sff-name', {}, ev.event), el('span.sff-type', {}, ev.method ? ev.method + '()' : t('closure')),
ev.locked ? null : el('span.sff-row-actions', {}, el('button.sff-mini', { title: t('Remove'), onclick: (e) => { e.stopPropagation(); this.model.events.splice(i, 1); this.select('form', 0); } }, icon('trash'))))));
box.append(el('div.sff-section', {}, t('Data transformers'), el('span.grow'), el('button.sff-mini', { title: t('Add a data transformer'), onclick: () => this.addTransformer() }, icon('plus'))));
this.model.transformers.forEach((tr, i) => box.append(el(`div.sff-row${isSel('transformer', i) ? '.sel' : ''}${tr.locked ? '.locked' : ''}`, { onclick: () => this.select('transformer', i) },
icon('zap'), el('span.sff-name', {}, tr.field), el('span.sff-type', {}, (tr.kind === 'view' ? 'view · ' : 'model · ') + (tr.class ? shortName(tr.class) : t('callback'))),
tr.locked ? null : el('span.sff-row-actions', {}, el('button.sff-mini', { title: t('Remove'), onclick: (e) => { e.stopPropagation(); this.model.transformers.splice(i, 1); this.select('form', 0); } }, icon('trash'))))));
box.scrollTop = scroll;
}
select(kind, index) {
this.selected = { kind, index };
this.renderList();
this.renderInspector();
this.updatePreview();
}
move(from, to) {
const f = this.model.fields;
if (from === undefined || to < 0 || to >= f.length || from === to || f[to]?.locked) return;
const [item] = f.splice(from, 1);
f.splice(to, 0, item);
if (this.selected.kind === 'field') this.selected.index = to;
this.changed();
this.renderInspector();
}
removeField(i) {
this.model.fields.splice(i, 1);
this.selected = this.model.fields.length ? { kind: 'field', index: Math.min(i, this.model.fields.length - 1) } : { kind: 'form' };
this.changed(true);
}
/** a type picked in a list grouped like Symfony's reference (and the project's own form types) */
pickType(at, done) {
const items = [];
for (const g of GROUPS) for (const type of TYPES.filter((x) => x.group === g)) items.push({ label: type.name, group: t(g), action: () => done(type.fqcn) });
for (const c of this.projectTypes()) items.push({ label: shortName(c), hint: c, group: t('The project\'s form types'), action: () => done(c) });
chooser(items, { at, placeholder: 'Type to filter' });
}
addField(at) {
this.pickType(at, async (type) => {
const base = shortName(type).replace(/Type$/, '');
const name = await prompt(t('The field\'s name'), { label: t('The property of the data it edits (or any name with mapped: false)'), value: base.charAt(0).toLowerCase() + base.slice(1) });
if (!name) return;
const options = typeOf(type)?.name === 'CollectionType' ? { entry_type: { '@class': CORE + 'TextType' }, allow_add: true, allow_delete: true, by_reference: false } : {};
this.model.fields.push({ name: name.trim(), type, options });
this.selected = { kind: 'field', index: this.model.fields.length - 1 };
this.changed(true);
});
}
/** the data class's properties, each with the type it suggests: checked ones added */
async addFromClass() {
let cls = asMap(this.model.defaults.data_class)['@class'];
if (!cls) {
const classes = this.panel.list?.classes || [];
cls = await new Promise((resolve) => chooser(classes.map((c) => ({ label: shortName(c.class), hint: c.entity ? t('entity') : c.path, action: () => resolve(c.class) })),
{ placeholder: 'The class the form edits (an entity, a DTO)' }));
if (!cls) return;
}
let r;
try { r = await backend.invoke('forms.suggest', { class: cls }); } catch (e) { notify(e.message, 'error', { title: t('Add fields from the class') }); return; }
const have = new Set(this.model.fields.map((f) => f.name));
const rows = (r.fieldsJson ? JSON.parse(r.fieldsJson) : r.fields).filter((f) => !have.has(f.name)).map((f) => ({ f, box: el('input', { type: 'checkbox', checked: f.checked && !!f.type }) }));
if (!rows.length) { notify(t('Every property of {class} is already a field.', { class: shortName(cls) }), 'info'); return; }
const body = el('div.sff-suggest', {}, el('p.sff-hint', {}, t('The properties of {class}, with the type each one suggests:', { class: r.class })),
...rows.map(({ f, box }) => el('label.sff-suggest-row', {}, box, el('span.sff-name', {}, f.name), el('span.sff-type', {}, f.type ? shortName(f.type) : t('guessed')),
el('span.sff-sub', {}, f.reason), el('span.sff-sub', {}, Object.keys(asMap(f.options)).length ? phpOf(asMap(f.options)) : ''))));
dialog({
title: t('Add fields from the class'), body, wide: true,
buttons: [{ label: 'Cancel' }, { label: 'Add the checked fields', primary: true, tour: 'forms-add-fields', action: () => {
for (const { f, box } of rows) if (box.checked) this.model.fields.push({ name: f.name, type: f.type, options: asMap(f.options) });
if (!this.model.defaults.data_class) this.model.defaults.data_class = { '@class': r.class };
this.selected = { kind: 'field', index: 0 };
this.changed(true);
} }],
});
}
addEvent() {
chooser(EVENTS.map((ev) => ({ label: ev, hint: t(EVENT_HELP[ev]), action: () => {
let method = listenerName(ev);
while (this.model.events.some((x) => x.method === method)) method += '2';
this.model.events.push({ event: ev, method, priority: null });
this.select('event', this.model.events.length - 1);
} })), { placeholder: 'Form event', width: 560 });
}
addTransformer() {
const fields = this.model.fields.filter((f) => !f.locked).map((f) => f.name);
if (!fields.length) { notify(t('Add a field first.'), 'info'); return; }
chooser(fields.map((name) => ({ label: name, action: () => {
const cls = 'App\\Form\\DataTransformer\\' + name.charAt(0).toUpperCase() + name.slice(1) + 'Transformer';
this.model.transformers.push({ field: name, kind: 'model', class: cls, args: [] });
this.select('transformer', this.model.transformers.length - 1);
} })), { placeholder: 'The field it transforms' });
}
// the inspector -------------------------------------------------------------------------------------------------
renderInspector() {
const box = this.inspector;
clear(box);
const s = this.selected;
if (s.kind === 'field' && this.model.fields[s.index]) this.fieldEditor(box, this.model.fields[s.index]);
else if (s.kind === 'event' && this.model.events[s.index]) this.eventEditor(box, this.model.events[s.index]);
else if (s.kind === 'transformer' && this.model.transformers[s.index]) this.transformerEditor(box, this.model.transformers[s.index]);
else this.formEditor(box);
}
lockedNote(box, item) {
box.append(el('div.sff-locked', {}, el('p', {}, t('Written in a way the builder does not change (in a condition, with closures…): edit it in the code.')), el('pre', {}, item.code || '')));
}
fieldEditor(box, f) {
box.append(el('div.sff-ins-head', {}, el('b', {}, f.name), el('span.sff-sub', {}, f.type || t('type guessed by Symfony'))));
if (f.locked) { this.lockedNote(box, f); return; }
box.append(this.row(t('Name'), el('input.input.mono', { value: f.name, oninput: (e) => { f.name = e.target.value.trim(); this.changed(); } })));
const type = el('select.input', { onchange: (e) => { f.type = e.target.value || null; this.changed(true); } }, el('option', { value: '' }, t('Guessed by Symfony (no type)')));
for (const g of GROUPS) type.append(el('optgroup', { label: t(g) }, ...TYPES.filter((x) => x.group === g).map((x) => el('option', { value: x.fqcn }, x.name))));
const own = this.projectTypes();
if (own.length) type.append(el('optgroup', { label: t('The project\'s form types') }, ...own.map((c) => el('option', { value: c }, shortName(c)))));
if (f.type && !typeOf(f.type) && !own.includes(f.type)) type.append(el('option', { value: f.type }, shortName(f.type)));
type.value = f.type || '';
box.append(this.row(t('Type'), type));
const known = optionsOf(f.type);
box.append(el('div.sff-ins-section', {}, t('Options')));
for (const name of known) {
const def = name === 'type' && typeOf(f.type)?.name === 'PercentType' ? PERCENT_TYPE : OPTIONS[name];
if (def) box.append(this.optionEditor(f.options, name, def, f));
}
const others = Object.keys(f.options).filter((k) => !known.includes(k));
if (others.length) {
box.append(el('div.sff-ins-section', {}, t('Other options (PHP)')));
for (const k of others) box.append(this.optionEditor(f.options, k, { kind: 'code' }, f));
}
box.append(el('div.sff-toolbar', {}, el('button.btn', { onclick: async () => {
const name = await prompt(t('Another option'), { label: t('Its name (see the type\'s reference in Symfony\'s documentation)') });
if (name && !(name in f.options)) { f.options[name] = null; this.changed(true); }
} }, icon('plus'), t('Another option…'))));
}
row(label, input, hint) {
return el('label.sff-field-row', {}, el('span.sff-label', {}, label), input, hint ? el('span.sff-help', {}, hint) : null);
}
/** one option's editor by its kind; an empty value takes the option out */
optionEditor(opts, name, def, field = null) {
const set = (v, full = false) => { if (v === undefined) delete opts[name]; else opts[name] = v; this.changed(full); };
const has = name in opts;
const value = opts[name];
const label = el('span.mono', {}, name);
const kind = def.kind;
if (kind === 'label') {
const off = value === false;
const input = el('input.input', { value: typeof value === 'string' ? value : '', placeholder: field ? humanize(field.name) : '', disabled: off,
oninput: (e) => set(e.target.value === '' ? undefined : e.target.value) });
return this.row(label, el('div.sff-inline', {}, input, el('label.sff-check', {}, el('input', { type: 'checkbox', checked: off, onchange: (e) => set(e.target.checked ? false : undefined, true) }), t('none'))));
}
if (kind === 'bool') {
const s = el('select.input', { onchange: (e) => set(e.target.value === '' ? undefined : e.target.value === 'true') },
el('option', { value: '' }, def.def === undefined ? t('not set') : t('default ({value})', { value: def.def ? t('yes') : t('no') })), el('option', { value: 'true' }, t('yes')), el('option', { value: 'false' }, t('no')));
s.value = has && typeof value === 'boolean' ? String(value) : '';
return this.row(label, s);
}
if (kind === 'text' || kind === 'int' || kind === 'number') {
const input = el('input.input', { value: has && value !== null && typeof value !== 'object' ? String(value) : '', placeholder: def.placeholder || '', type: kind === 'text' ? 'text' : 'number',
oninput: (e) => { const v = e.target.value; set(v === '' ? undefined : kind === 'int' ? parseInt(v, 10) : kind === 'number' ? Number(v) : v); } });
return this.row(label, input);
}
if (kind === 'select') {
const s = el('select.input', { onchange: (e) => set(e.target.value === '' ? undefined : e.target.value) }, el('option', { value: '' }, t('not set')), ...def.values.map((v) => el('option', { value: v }, v)));
s.value = has && typeof value === 'string' ? value : '';
return this.row(label, s);
}
if (kind === 'list') {
const input = el('input.input', { value: Array.isArray(value) ? value.join(', ') : '', placeholder: 'a, b, c',
oninput: (e) => { const v = e.target.value.split(',').map((x) => x.trim()).filter(Boolean); set(v.length ? v : undefined); } });
return this.row(label, input);
}
if (kind === 'class') {
const list = 'sff-classes-' + name;
const classes = name === 'class' && field && typeOf(field.type)?.name === 'EnumType' ? (this.panel.list?.enums || []) : (this.panel.list?.classes || []);
const input = el('input.input.mono', { value: asMap(value)['@class'] || '', list, placeholder: 'App\\Entity\\…',
oninput: (e) => set(e.target.value.trim() === '' ? undefined : { '@class': e.target.value.trim().replace(/^\\/, '') }) });
return this.row(label, el('div', {}, input, el('datalist', { id: list }, ...classes.map((c) => el('option', { value: c.class })))));
}
if (kind === 'type') {
const s = el('select.input', { onchange: (e) => set(e.target.value === '' ? undefined : { '@class': e.target.value }, true) }, el('option', { value: '' }, t('not set')));
for (const g of GROUPS.filter((x) => x !== 'Buttons')) s.append(el('optgroup', { label: t(g) }, ...TYPES.filter((x) => x.group === g).map((x) => el('option', { value: x.fqcn }, x.name))));
const own = this.projectTypes();
if (own.length) s.append(el('optgroup', { label: t('The project\'s form types') }, ...own.map((c) => el('option', { value: c }, shortName(c)))));
const cur = asMap(value)['@class'] || '';
if (cur && ![...s.options].some((o) => o.value === cur)) s.append(el('option', { value: cur }, shortName(cur)));
s.value = cur;
return this.row(label, s);
}
if (kind === 'map' || kind === 'choices') return this.mapEditor(label, opts, name, def, set);
if (kind === 'constraints') return this.constraintsEditor(label, opts, name, set);
// code: PHP kept as written
const text = has ? (value && typeof value === 'object' && typeof value['@php'] === 'string' ? value['@php'] : phpOf(value)) : '';
const area = el('textarea.input.mono', { rows: 2, value: text, placeholder: def.sample || 'PHP',
oninput: (e) => set(e.target.value.trim() === '' ? undefined : { '@php': e.target.value, ...(def.uses && def.sample && e.target.value.includes(def.uses[0].split('\\').pop()) ? { '@uses': def.uses } : {}) }) });
const sample = def.sample ? el('button.sff-mini', { title: t('Insert an example'), onclick: (e) => { e.preventDefault(); area.value = def.sample; area.dispatchEvent(new Event('input')); } }, '⤶') : null;
return this.row(label, el('div.sff-inline', {}, area, sample));
}
mapEditor(label, opts, name, def, set) {
const value = asMap(opts[name]);
const rows = Object.entries(value);
const box = el('div.sff-map');
const write = () => {
const out = {};
for (const r of box.querySelectorAll('.sff-map-row')) {
const [k, v] = r.querySelectorAll('input');
if (k.value !== '') out[k.value] = def.kind === 'map' && /^(true|false)$/.test(v.value) ? v.value === 'true' : def.kind === 'map' && v.value !== '' && /^-?\d+$/.test(v.value) && k.value !== 'placeholder' ? Number(v.value) : v.value;
}
set(Object.keys(out).length ? out : undefined);
};
const listId = 'sff-keys-' + name;
const add = (k = '', v = '') => box.insertBefore(el('div.sff-map-row', {},
el('input.input.mono', { value: k, placeholder: def.kind === 'choices' ? t('Label') : t('key'), list: def.keys ? listId : null, oninput: write }),
el('input.input', { value: typeof v === 'object' && v !== null ? phpOf(v) : String(v ?? ''), placeholder: def.kind === 'choices' ? t('value') : '', oninput: write }),
el('button.sff-mini', { title: t('Remove'), onclick: (e) => { e.preventDefault(); e.currentTarget.parentNode.remove(); write(); } }, '×')), addButton);
const addButton = el('button.sff-mini', { title: t('Add'), onclick: (e) => { e.preventDefault(); add(); } }, '+');
box.append(addButton);
if (def.keys) box.append(el('datalist', { id: listId }, ...def.keys.map((k) => el('option', { value: k }))));
for (const [k, v] of rows) add(k, v);
return this.row(label, box);
}
constraintsEditor(label, opts, name, set) {
const list = Array.isArray(opts[name]) ? opts[name] : [];
const box = el('div.sff-constraints');
const write = (full = false) => set(list.length ? list : undefined, full);
list.forEach((c, i) => {
const known = constraintOf(c?.['@new']);
const card = el('div.sff-constraint', {}, el('div.sff-constraint-head', {}, el('b', {}, shortName(c?.['@new'] || c?.['@php'] || '?')), el('span.grow'),
el('button.sff-mini', { title: t('Remove'), onclick: (e) => { e.preventDefault(); list.splice(i, 1); write(true); } }, '×')));
if (known && c.args && typeof c.args === 'object' && !Array.isArray(c.args) || (known && Array.isArray(c.args) && !c.args.length)) {
if (Array.isArray(c.args)) c.args = {};
for (const [opt, kind] of Object.entries(known.options)) {
const def = kind.startsWith('select:') ? { kind: 'select', values: kind.slice(7).split(',') } : { kind };
card.append(this.optionEditor(c.args, opt, def));
}
} else if (c?.['@php']) card.append(el('pre.mono', {}, c['@php']));
box.append(card);
});
box.append(el('button.btn', { onclick: (e) => {
e.preventDefault();
chooser(CONSTRAINT_TYPES.map((c) => ({ label: c.name, hint: c.message, action: () => { list.push({ '@new': c.fqcn, args: {} }); write(true); } })), { at: e.currentTarget, placeholder: 'Constraint', width: 520 });
} }, icon('plus'), t('Add a constraint…')));
return this.row(label, box);
}
formEditor(box) {
const d = this.model.defaults;
box.append(el('div.sff-ins-head', {}, el('b', {}, shortName(this.model.class)), el('span.sff-sub', {}, t('configureOptions(): the options of the whole form'))));
if (this.model.defaultsLocked) { box.append(el('div.sff-locked', {}, t('Written in a way the builder does not change: edit it in the code.'))); return; }
box.append(this.optionEditor(d, 'data_class', { kind: 'class' }), this.optionEditor(d, 'validation_groups', { kind: 'list' }),
this.optionEditor(d, 'csrf_protection', { kind: 'bool', def: true }), this.optionEditor(d, 'csrf_token_id', { kind: 'text' }),
this.optionEditor(d, 'allow_extra_fields', { kind: 'bool', def: false }), this.optionEditor(d, 'translation_domain', { kind: 'text' }),
this.optionEditor(d, 'attr', { kind: 'map', keys: ['novalidate', 'class', 'id'] }), this.optionEditor(d, 'method', { kind: 'text', placeholder: 'POST' }));
const known = ['data_class', 'validation_groups', 'csrf_protection', 'csrf_token_id', 'allow_extra_fields', 'translation_domain', 'attr', 'method'];
for (const k of Object.keys(d).filter((x) => !known.includes(x))) box.append(this.optionEditor(d, k, { kind: 'code' }));
box.append(el('div.sff-toolbar', {},
el('button.btn', { onclick: () => this.addFromClass() }, icon('download'), t('Add fields from the class…')),
el('button.btn', { onclick: async () => {
const name = await prompt(t('Another option'), { label: t('Its name (see the type\'s reference in Symfony\'s documentation)') });
if (name && !(name in d)) { d[name] = null; this.changed(true); }
} }, icon('plus'), t('Another option…'))));
box.append(el('div.sff-ins-section', {}, t('Form themes of the project')), el('div.sff-hint', {}, (this.panel.list?.themes || []).join(', ') || 'form_div_layout'),
el('div.sff-toolbar', {}, el('button.btn', { onclick: () => this.panel.chooseThemes().then(() => this.render()) }, t('Change the themes…'))));
}
eventEditor(box, ev) {
box.append(el('div.sff-ins-head', {}, el('b', {}, ev.event), el('span.sff-sub', {}, t('The constant FormEvents::{name}', { name: ev.event }))));
if (ev.locked) { this.lockedNote(box, ev); return; }
const s = el('select.input', { onchange: (e) => {
const was = listenerName(ev.event);
ev.event = e.target.value;
if (ev.method === was) ev.method = listenerName(ev.event);
this.changed(true);
} }, ...EVENTS.map((x) => el('option', { value: x }, x)));
s.value = ev.event;
box.append(this.row(t('Event'), s, t(EVENT_HELP[ev.event] || '')),
this.row(t('Method'), el('input.input.mono', { value: ev.method || '', oninput: (e) => { ev.method = e.target.value.trim(); this.changed(); } }),
(this.model.methods || []).includes(ev.method) ? t('The class has this method.') : t('Made in the class when written: public function {method}(FormEvent $event): void', { method: ev.method })),
this.row(t('Priority'), el('input.input', { type: 'number', value: ev.priority ?? '', oninput: (e) => { ev.priority = e.target.value === '' ? null : parseInt(e.target.value, 10); this.changed(); } })));
}
transformerEditor(box, tr) {
box.append(el('div.sff-ins-head', {}, el('b', {}, tr.field), el('span.sff-sub', {}, t('a data transformer'))));
if (tr.locked) { this.lockedNote(box, tr); return; }
const field = el('select.input', { onchange: (e) => { tr.field = e.target.value; this.changed(); } }, ...this.model.fields.map((f) => el('option', { value: f.name }, f.name)));
field.value = tr.field;
const kind = el('select.input', { onchange: (e) => { tr.kind = e.target.value; this.changed(); } },
el('option', { value: 'model' }, t('model (the object\'s value <-> the normalized one)')), el('option', { value: 'view' }, t('view (the normalized value <-> what the field shows)')));
kind.value = tr.kind || 'model';
box.append(this.row(t('Transformed field'), field), this.row(t('Kind'), kind),
this.row(t('Class'), el('input.input.mono', { value: tr.class || '', oninput: (e) => { tr.class = e.target.value.trim().replace(/^\\/, ''); this.changed(); } }),
t('A class implementing DataTransformerInterface: made in src/ when it does not exist yet.')));
}
// preview ---------------------------------------------------------------------------------------------------------
themes() { return this.theme ? [this.theme] : (this.panel.list?.themes?.length ? this.panel.list.themes : ['form_div_layout.html.twig']); }
/** the sub-forms' own models and the enums' cases, read once */
async previewData() {
const types = new Set();
for (const f of this.model.fields) {
if (f.type && !typeOf(f.type)) types.add(f.type);
const entry = asMap(asMap(f.options).entry_type)['@class'];
if (entry && !typeOf(entry)) types.add(entry);
}
for (const cls of types) {
if (this.subforms[cls] !== undefined) continue;
this.subforms[cls] = null;
try { const r = await backend.invoke('forms.model', { class: cls }); this.subforms[cls] = r ? this.normalize(modelOf(r)) : null; } catch { /* drawn as its class name */ }
}
const enums = {};
for (const e of this.panel.list?.enums || []) enums[e.class] = e.cases;
const subforms = {};
for (const [k, v] of Object.entries(this.subforms)) if (v) subforms[k] = v;
return { subforms, enums };
}
async pageHtml() {
const { subforms, enums } = await this.previewData();
const themes = this.themes();
const form = formHtml(this.model, { theme: themes, errors: this.errors, subforms, enums });
const links = themeStylesheets(themes, this.panel.list?.bootstrap || null);
const linkTags = links.map((h) => `<link rel="stylesheet" href="${h}">`).join('');
const title = humanize(blockPrefix(this.model.class));
if (!this.panel.list?.base) return standalonePage(form, title, links);
const readText = (p) => this.app.editors.readProjectText(p);
const twig = `{% extends 'base.html.twig' %}{% block title %}${title}{% endblock %}{% block body %}<div class="container" style="max-width:760px;margin:24px auto;padding:0 16px">${form}</div>{% endblock %}`;
const page = await twigPreviewText('templates/_form_preview.html.twig', twig, readText, true);
return /<\/head>/i.test(page) ? page.replace(/<\/head>/i, linkTags + '</head>') : linkTags + page;
}
startPreview() {
this.preview?.destroy();
this.preview = new HtmlPreview(this.previewHost, {
path: 'templates/_form_preview.html.twig', kind: 'html', prefix: 'sffPreview',
text: () => this.pageHtml(),
readText: (p) => this.app.editors.readProjectText(p),
readDataUrl: async (p) => {
const f = await backend.invoke('file.read', { path: p });
if (f.image || f.audio) return f.image || f.audio;
if (f.text) return 'data:text/plain;charset=utf-8,' + encodeURIComponent(f.content);
const r = await backend.invoke('file.bytes', { path: p, offset: 0, length: 1024 * 1024 });
return r.length < r.size ? null : dataUrlOf(p, r.base64);
},
});
}
// writing -------------------------------------------------------------------------------------------------------
async save() {
let r;
try {
const text = this.path ? await this.app.editors.readProjectText(this.path) : null;
r = await backend.invoke('forms.write', { path: this.path || '', modelJson: JSON.stringify(this.model), ...(typeof text === 'string' ? { text } : {}) });
} catch (e) { notify(e.message, 'error', { title: t('Form builder') }); return; }
const main = r.files[0];
if (main.before === main.after && r.files.length === 1) { notify(t('Nothing changed.'), 'info'); return; }
if (!(await showDiff(this.app, r.files, t('Save {class}', { class: shortName(this.model.class) })))) return;
this.path = main.path;
const read = await backend.invoke('forms.read', { path: main.path, text: main.after });
this.model = this.normalize(modelOf(read));
this.saved = JSON.stringify(this.model);
this.panel.load();
this.render();
}
/** the controller action and the template, chosen in a form, shown as diffs */
async generate() {
const list = this.panel.list || {};
const prefix = blockPrefix(this.model.class);
const base = shortName(this.model.class).replace(/Type$/, '');
const controllers = list.controllers || [];
const field = (lab, input, hint) => el('label.sff-field-row', {}, el('span.sff-label', {}, lab), input, hint ? el('span.sff-help', {}, hint) : null);
const ctl = el('select.input', {}, el('option', { value: '' }, t('A new controller')), ...controllers.map((c) => el('option', { value: c.class }, shortName(c.class))));
const newCtl = el('input.input.mono', { value: `App\\Controller\\${base}Controller` });
ctl.onchange = () => { newCtl.parentNode.style.display = ctl.value ? 'none' : ''; action.value = ctl.value ? 'new' + base : 'new'; };
const action = el('input.input.mono', { value: 'new' });
const route = el('input.input.mono', { value: `/${prefix.replace(/_/g, '-')}/new` });
const routeName = el('input.input.mono', { value: `app_${prefix}_new` });
const template = el('input.input.mono', { value: `${prefix}/new.html.twig` });
const mode = el('select.input', {}, el('option', { value: 'auto' }, t('From the data class (entity: persisted, else an object filled)')),
el('option', { value: 'entity' }, t('An entity: persist and flush')), el('option', { value: 'dto' }, t('An object (DTO): use it')), el('option', { value: 'array' }, t('No class: $form->getData()')));
const flash = el('input.input', { value: t('Saved.') });
const title = el('input.input', { value: humanize(prefix) });
const rows = el('select.input', {}, el('option', { value: '1' }, t('A form_row() per field')), el('option', { value: '' }, t('form_widget(form): every field')));
const theme = el('select.input', {}, el('option', { value: '' }, t('The project\'s')), ...[...THEMES, ...(list.projectThemes || [])].map((x) => el('option', { value: x }, x)));
theme.value = this.theme || '';
const body = el('div.sff-generate', {}, field(t('Controller'), ctl), field(t('New controller class'), newCtl), field(t('Action (method)'), action),
field(t('Route'), route), field(t('Route name'), routeName), field(t('Template'), template, t('In templates/')), field(t('Data'), mode),
field(t('Flash message'), flash, t('Empty: none')), field(t('Page title'), title), field(t('Template body'), rows), field(t('Form theme of this form'), theme, t('{% form_theme %} in the template: only this form')));
dialog({
title: t('Generate controller and template'), body, wide: true,
buttons: [{ label: 'Cancel' }, { label: 'Show the code…', primary: true, action: async () => {
const options = { controller: ctl.value || newCtl.value.trim(), action: action.value.trim(), route: route.value.trim(), routeName: routeName.value.trim(),
template: template.value.trim(), mode: mode.value, flash: flash.value.trim(), title: title.value.trim(), rows: !!rows.value, theme: theme.value };
const r = await backend.invoke('forms.generate', { modelJson: JSON.stringify(this.model), options });
await showDiff(this.app, r.files, t('Generate controller and template'));
this.panel.load();
} }],
});
}
}
/** The files' changes side by side (a tab per file); Apply writes them. Resolves true when applied. */
export function showDiff(app, files, title) {
return new Promise((resolve) => {
const monaco = window.monaco;
const tabs = el('div.sff-diff-tabs');
const host = el('div.sff-diff');
let editor = null;
let models = [];
const show = (i) => {
for (const [n, b] of [...tabs.children].entries()) b.classList.toggle('on', n === i);
editor?.dispose();
for (const m of models) m.dispose();
const f = files[i];
if (!monaco) { clear(host); host.append(el('pre.mono', {}, f.after)); return; }
const lang = /\.php$/.test(f.path) ? 'php' : /\.twig$/.test(f.path) ? 'twig' : /\.ya?ml$/.test(f.path) ? 'yaml' : 'plaintext';
models = [monaco.editor.createModel(f.before, lang), monaco.editor.createModel(f.after, lang)];
editor = monaco.editor.createDiffEditor(host, { readOnly: true, originalEditable: false, automaticLayout: true, renderSideBySide: true, minimap: { enabled: false },
scrollBeyondLastLine: false, hideUnchangedRegions: { enabled: true, contextLineCount: 3 } });
editor.setModel({ original: models[0], modified: models[1] });
// the first change in sight
const sub = editor.onDidUpdateDiff(() => { sub.dispose(); const c = editor.getLineChanges()?.[0]; if (c) editor.getModifiedEditor().revealLineNearTop(Math.max(1, c.modifiedStartLineNumber - 3)); });
};
files.forEach((f, i) => tabs.append(el('button', { onclick: () => show(i) }, f.created ? '+ ' : '', f.path)));
let done = false;
dialog({
title, wide: true, body: el('div.sff-diff-box', {}, el('p.sff-hint', {}, t('What will be written (unchanged parts stay as they are):')), tabs, host),
buttons: [{ label: 'Cancel' }, { label: 'Apply', primary: true, tour: 'change-apply', action: async () => { await applyFiles(app, files); done = true; resolve(true); } }],
onClose: () => { editor?.dispose(); for (const m of models) m.dispose(); if (!done) resolve(false); },
});
setTimeout(() => show(0), 0);
});
}
/** written through the editor when the file is open there (one undo step), else to the disk */
async function applyFiles(app, files) {
for (const f of files) {
const open = app.editors.files.get(f.path);
if (open?.model && !open.readOnly) {
open.model.pushEditOperations([], [{ range: open.model.getFullModelRange(), text: f.after }], () => null);
await app.editors.save(f.path);
} else {
await backend.invoke('file.write', { path: f.path, content: f.after });
}
}
app.tree?.refresh();
notify(files.length === 1 ? t('{path} written.', { path: files[0].path }) : t('{n} files written.', { n: files.length }), 'success');
}