280 lines
17 KiB
JavaScript
280 lines
17 KiB
JavaScript
// The fixtures form: Doctrine fixtures made visually. An entity picked, a value generator per field (fixed value, Faker formatter with its
|
|
// preview, sequence, number / date between, enum case, a reference to another entity's fixture), how many objects, groups; the class
|
|
// (DoctrineFixturesBundle + Faker, or a Foundry Factory + Story) shown as a diff before it is written, an existing one read back and
|
|
// edited (only the form's regions change), and the load (doctrine:fixtures:load) with its guards. PHP side: ide/src/Fixtures (fixtures.*).
|
|
// The model's flows are in fixtures-model.js (tested without a DOM).
|
|
import { backend } from './backend.js';
|
|
import { el, clear, icon, dialog, confirm, notify, t, debounce } from './ui.js';
|
|
import { diffPane, writeChanges, installNotice } from './wizard-preview.js';
|
|
import { TYPES, TYPE_LABELS, typesFor, defaultGenerator, sample, sampleRows, newModel, cleanModel, coerce, argText, dependencies, loadLine } from './fixtures-model.js';
|
|
|
|
const short = (cls) => String(cls || '').split('\\').pop();
|
|
|
|
function input(obj, key, { type = 'text', placeholder = '', on, cls = '', title = '' } = {}) {
|
|
return el('input.input' + cls, { type, value: obj[key] ?? '', placeholder, title, spellcheck: false, oninput: (e) => { obj[key] = type === 'number' ? e.target.value : e.target.value; on?.(); } });
|
|
}
|
|
|
|
function check(label, obj, key, on) {
|
|
return el('label.wg-check', {}, el('input', { type: 'checkbox', checked: !!obj[key], onchange: (e) => { obj[key] = e.target.checked; on?.(); } }), el('span', {}, label));
|
|
}
|
|
|
|
function select(options, value, onchange, cls = '') {
|
|
return el('select.input' + cls, { onchange: (e) => onchange(e.target.value) }, ...options.map(([v, text]) => el('option', { value: v, selected: String(value ?? '') === String(v) }, text)));
|
|
}
|
|
|
|
class FixturesForm {
|
|
constructor(app, info, model, edit) {
|
|
this.app = app;
|
|
this.info = info;
|
|
this.model = model;
|
|
this.edit = edit;
|
|
this.changes = null;
|
|
this.missing = [];
|
|
this.rows = null;
|
|
this.refresh = debounce(() => this.preview(), 250);
|
|
}
|
|
|
|
open() {
|
|
this.top = el('div.wg-top');
|
|
this.grid = el('div.wg-grid');
|
|
this.note = el('div.wg-deps');
|
|
this.pane = diffPane();
|
|
this.sampleBox = el('div.wg-rows', { hidden: true });
|
|
this.tab = 'code';
|
|
this.tabs = el('div.wg-tabs');
|
|
this.dialog = dialog({
|
|
title: this.edit ? t('Edit the fixtures {name}', { name: this.model.class }) : t('New fixtures'), wide: true, sticky: true,
|
|
body: el('div.wg', {}, el('div.wg-left', {}, this.top, this.grid, this.note), el('div.wg-right', {}, this.tabs, this.pane.node, this.sampleBox)),
|
|
buttons: [
|
|
{ label: t('Close') },
|
|
{ label: t('Load fixtures…'), tour: 'fixtures-load', action: () => { openFixtureLoad(this.app, this.info); return false; } },
|
|
{ label: this.edit ? t('Apply the Changes') : t('Write the files'), primary: true, tour: 'fixtures-write', action: () => this.apply() },
|
|
],
|
|
onClose: () => this.pane.dispose(),
|
|
});
|
|
this.dialog.box.classList.add('wg-dialog');
|
|
this.render();
|
|
this.preview();
|
|
return this;
|
|
}
|
|
|
|
/** the top: packages, which fixture, the entity and the options of the whole class */
|
|
renderTop() {
|
|
clear(this.top);
|
|
const m = this.model;
|
|
const inst = this.info.install;
|
|
const missing = [inst.bundle, inst.faker].filter((p) => !p.installed);
|
|
if (missing.length) {
|
|
this.top.append(installNotice(this.app, t('Fixtures need these packages'), missing, async () => { this.info = await backend.invoke('fixtures.info', {}); this.render(); }));
|
|
}
|
|
const existing = (this.info.fixtures || []).filter((f) => f.generated);
|
|
const entities = this.info.entities.map((e) => [e.class, e.name]);
|
|
this.top.append(el('div.wg-row', {},
|
|
existing.length ? el('label.wg-field', {}, el('span', {}, t('Fixtures')), select([['', t('New fixtures…')], ...existing.map((f) => [f.file, short(f.class)])], this.edit?.file || '', (v) => this.pick(v))) : null,
|
|
el('label.wg-field', {}, el('span', {}, t('Entity')), this.edit ? el('input.input', { value: short(m.entity), disabled: true }) : select(entities, m.entity, (v) => { this.model = newModel(this.info, v, m.kind); this.model.class = `${short(v)}Fixtures`; this.render(); this.preview(); })),
|
|
el('label.wg-field', {}, el('span', {}, t('Class')), input(m, 'class', { on: this.refresh, cls: '.wg-w' })),
|
|
el('label.wg-field', {}, el('span', {}, t('Kind')), select([['faker', t('Faker (DoctrineFixturesBundle)')], ['foundry', t('Foundry (Factory + Story)')]], m.kind, (v) => { m.kind = v; this.render(); this.preview(); })),
|
|
));
|
|
this.top.append(el('div.wg-row', {},
|
|
el('label.wg-field', {}, el('span', {}, t('How many')), input(m, 'count', { type: 'number', on: this.refresh, cls: '.wg-s' })),
|
|
el('label.wg-field', {}, el('span', {}, t('Groups (comma separated)')), input(m, 'groups', { on: this.refresh, cls: '.wg-w', placeholder: 'dev, demo' })),
|
|
el('label.wg-field', {}, el('span', {}, t('Seed (optional)')), input(m, 'seed', { type: 'number', on: this.refresh, cls: '.wg-s' })),
|
|
el('label.wg-field', {}, el('span', {}, t('Faker locale')), input(m, 'locale', { on: this.refresh, cls: '.wg-s' })),
|
|
));
|
|
if (m.kind === 'foundry' && !inst.foundry.installed) {
|
|
this.top.append(installNotice(this.app, t('Foundry is not installed in this project'), [inst.foundry], async () => { this.info = await backend.invoke('fixtures.info', {}); this.render(); }));
|
|
}
|
|
}
|
|
|
|
async pick(file) {
|
|
if (!file) { this.edit = null; this.model = newModel(this.info, this.model.entity, this.model.kind); this.render(); this.preview(); return; }
|
|
try {
|
|
const r = await backend.invoke('fixtures.read', { file });
|
|
this.edit = { file };
|
|
this.model = { ...r.model, groups: (r.model.groups || []).join(', '), seed: r.model.seed ?? '' };
|
|
this.render();
|
|
this.preview();
|
|
} catch (e) { notify(e.message || String(e), 'error', { title: t('Fixtures') }); }
|
|
}
|
|
|
|
render() {
|
|
this.renderTop();
|
|
this.renderGrid();
|
|
this.renderTabs();
|
|
this.renderNote();
|
|
}
|
|
|
|
renderTabs() {
|
|
clear(this.tabs);
|
|
for (const [id, label] of [['code', t('The code')], ['rows', t('Rows')]]) {
|
|
this.tabs.append(el('button.wg-tab' + (this.tab === id ? '.on' : ''), { onclick: () => { this.tab = id; this.renderTabs(); } }, label));
|
|
}
|
|
this.pane.node.hidden = this.tab !== 'code';
|
|
this.sampleBox.hidden = this.tab !== 'rows';
|
|
if (this.tab === 'rows') this.renderRows();
|
|
}
|
|
|
|
renderGrid() {
|
|
clear(this.grid);
|
|
const info = this.info;
|
|
this.grid.append(el('div.wg-head', {}, el('span', {}, t('Field')), el('span', {}, t('Value')), el('span', {}, t('Parameters')), el('span', {}, t('Sample'))));
|
|
const entity = info.entities.find((e) => e.class === this.model.entity);
|
|
for (const f of this.model.fields) {
|
|
const meta = entity?.fields.find((x) => x.name === f.name) || { name: f.name, type: '' };
|
|
const g = f.generator;
|
|
const sampleCell = el('span.wg-sample', {}, sample(g, info));
|
|
const on = () => { sampleCell.textContent = sample(g, info); this.renderNote(); this.refresh(); if (this.tab === 'rows') this.renderRows(); };
|
|
const types = typesFor(meta);
|
|
if (!types.includes(g.type)) types.unshift(g.type);
|
|
this.grid.append(el('div.wg-field-row' + (g.type === 'skip' ? '.off' : ''), {},
|
|
el('span.wg-name', { title: meta.type }, f.name, el('small', {}, meta.type || '')),
|
|
select(types.map((ty) => [ty, t(TYPE_LABELS[ty])]), g.type, (ty) => { f.generator = defaultGenerator(ty, meta, info); this.renderGrid(); this.renderNote(); this.refresh(); }),
|
|
el('span.wg-params', {}, ...this.params(f, g, meta, on)),
|
|
sampleCell));
|
|
}
|
|
}
|
|
|
|
/** the inputs of one generator */
|
|
params(f, g, meta, on) {
|
|
const info = this.info;
|
|
switch (g.type) {
|
|
case 'faker': {
|
|
const groups = {};
|
|
for (const c of info.catalog) (groups[c.group] ||= []).push(c);
|
|
const pick = el('select.input', { onchange: (e) => { const c = info.catalog.find((x) => x.name === e.target.value); g.formatter = c.name; g.args = c.args.map((a) => a.default); this.renderGrid(); this.refresh(); } },
|
|
...Object.entries(groups).map(([name, list]) => el('optgroup', { label: t(name) }, ...list.map((c) => el('option', { value: c.name, selected: c.name === g.formatter }, c.name)))));
|
|
const spec = info.catalog.find((c) => c.name === g.formatter);
|
|
return [pick, ...(spec?.args || []).map((a, i) => el('label.wg-mini', { title: a.name }, el('span', {}, a.name), el('input.input.wg-s', { value: argText(g.args?.[i] ?? a.default), spellcheck: false,
|
|
oninput: (e) => { g.args ||= []; g.args[i] = coerce(e.target.value); on(); } }))),
|
|
check(t('unique'), g, 'unique', on)];
|
|
}
|
|
case 'fixed': return [el('input.input', { value: g.value === undefined ? '' : (typeof g.value === 'string' ? g.value : JSON.stringify(g.value)), spellcheck: false,
|
|
oninput: (e) => { g.value = ['string', 'text'].includes(meta.type) || !meta.type ? e.target.value : coerce(e.target.value); on(); } })];
|
|
case 'sequence': return [input(g, 'pattern', { on, placeholder: 'Item {n}', title: t('{n} is the number of the object') }), el('label.wg-mini', {}, el('span', {}, t('from')), input(g, 'start', { type: 'number', on, cls: '.wg-s' }))];
|
|
case 'between': return [input(g, 'min', { type: 'number', on, cls: '.wg-s' }), el('span', {}, '…'), input(g, 'max', { type: 'number', on, cls: '.wg-s' }), check(t('decimals'), g, 'float', on)];
|
|
case 'dateBetween': return [input(g, 'from', { on, cls: '.wg-s' }), el('span', {}, '…'), input(g, 'to', { on, cls: '.wg-s' }), check(t('immutable'), g, 'immutable', on)];
|
|
case 'boolean': return [el('label.wg-mini', {}, el('span', {}, t('% true')), input(g, 'chance', { type: 'number', on, cls: '.wg-s' }))];
|
|
case 'enum': {
|
|
const cases = info.enums?.[g.class] || [];
|
|
return [el('code', {}, short(g.class)), select([['random', t('random case')], ['case', t('a case')]], g.mode, (v) => { g.mode = v; g.case ||= cases[0]?.name || ''; this.renderGrid(); this.refresh(); }),
|
|
g.mode === 'case' ? select(cases.map((c) => [c.name, c.name]), g.case, (v) => { g.case = v; on(); }) : null];
|
|
}
|
|
case 'ref': return [el('code', {}, short(g.target)), select([['random', t('random one')], ['index', t('a given one (number)')]], g.mode, (v) => { g.mode = v; this.renderGrid(); this.refresh(); }),
|
|
g.mode === 'index' ? input(g, 'index', { type: 'number', on, cls: '.wg-s' }) : null];
|
|
case 'refs': return [el('code', {}, short(g.target)), input(g, 'min', { type: 'number', on, cls: '.wg-s' }), el('span', {}, '…'), input(g, 'max', { type: 'number', on, cls: '.wg-s' })];
|
|
default: return [];
|
|
}
|
|
}
|
|
|
|
/** the load order: who this one waits for */
|
|
renderNote() {
|
|
clear(this.note);
|
|
const deps = dependencies(this.model, this.info);
|
|
const order = this.info.order?.order || [];
|
|
this.note.append(el('div', {}, icon('hierarchy'), el('span', {}, deps.length ? t('Loaded after: {names}', { names: deps.map(short).join(', ') }) : t('No dependency: loaded first.'))));
|
|
const missing = deps.filter((d) => !(this.info.fixtures || []).some((f) => f.class === d));
|
|
if (missing.length) this.note.append(el('div.wg-warn', {}, t('Fixtures still to make for the relations: {names}', { names: missing.map(short).join(', ') })));
|
|
if (order.length) this.note.append(el('div.pub-faint', {}, t('Order of the project: {names}', { names: order.map(short).join(' → ') })));
|
|
if (this.info.order?.cycles?.length) this.note.append(el('div.wg-warn', {}, t('Fixtures that wait for each other: {names}', { names: this.info.order.cycles.map(short).join(', ') })));
|
|
}
|
|
|
|
renderRows() {
|
|
clear(this.sampleBox);
|
|
const rows = this.rows?.ok ? this.rows.rows : sampleRows(cleanModel(this.model), this.info, 5);
|
|
const real = !!this.rows?.ok;
|
|
const cols = rows.length ? Object.keys(rows[0]) : [];
|
|
this.sampleBox.append(el('div.wg-rows-head', {}, el('span.pub-faint', {}, real ? t("Rows made by the project's own Faker") : t('Samples (not run)')),
|
|
el('button.btn.small', { onclick: () => this.runRows() }, icon('play'), t('Run with the project\'s Faker'))));
|
|
if (this.rows && !this.rows.ok) this.sampleBox.append(el('pre.wg-log', {}, this.rows.output || t('No answer.')));
|
|
this.sampleBox.append(el('table.wg-table', {}, el('thead', {}, el('tr', {}, ...cols.map((c) => el('th', {}, c)))),
|
|
el('tbody', {}, ...rows.map((r) => el('tr', {}, ...cols.map((c) => el('td', {}, String(r[c] ?? ''))))))));
|
|
}
|
|
|
|
async runRows() {
|
|
this.sampleBox.classList.add('busy');
|
|
try { this.rows = await backend.invoke('fixtures.rows', { model: cleanModel(this.model), rows: 5 }); } catch (e) { this.rows = { ok: false, output: e.message || String(e) }; }
|
|
this.sampleBox.classList.remove('busy');
|
|
this.renderRows();
|
|
}
|
|
|
|
async preview() {
|
|
try {
|
|
const r = await backend.invoke('fixtures.preview', { model: cleanModel(this.model) });
|
|
this.changes = r.changes;
|
|
this.missing = r.missing || [];
|
|
this.pane.show(r.changes);
|
|
} catch (e) {
|
|
this.changes = null;
|
|
this.pane.show([], String(e.message || e));
|
|
}
|
|
}
|
|
|
|
async apply() {
|
|
await this.preview();
|
|
if (!this.changes) return false;
|
|
const files = await writeChanges(this.app, this.changes);
|
|
if (!files.length) return false;
|
|
notify(t('Written: {files}', { files: files.join(', ') }), 'success', { title: t('Fixtures') });
|
|
this.app.editors?.open?.(files[files.length - 1]);
|
|
this.info = await backend.invoke('fixtures.info', {});
|
|
return true;
|
|
}
|
|
}
|
|
|
|
/** The fixtures form: a new one (optionally for an entity), or an existing one made by the form (its file) read back and edited. */
|
|
export async function openFixtures(app, { file = null, entity = null } = {}) {
|
|
try {
|
|
const info = await backend.invoke('fixtures.info', {});
|
|
if (!info.entities.length) { notify(t('No entity in this project: create one first (New Entity).'), 'info', { title: t('Fixtures') }); return null; }
|
|
if (file) {
|
|
const r = await backend.invoke('fixtures.read', { file });
|
|
return new FixturesForm(app, info, { ...r.model, groups: (r.model.groups || []).join(', '), seed: r.model.seed ?? '' }, { file }).open();
|
|
}
|
|
return new FixturesForm(app, info, { ...newModel(info, entity, info.kind), groups: 'dev' }, null).open();
|
|
} catch (e) {
|
|
notify(e.message || String(e), 'error', { title: t('Fixtures') });
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Loading the fixtures: append (the rows stay) or purge (the tables are emptied first, after a confirmation), all or by group, the command
|
|
* line shown, refused with a reason on a production environment or a connection flagged production (the PHP side checks again).
|
|
*/
|
|
export async function openFixtureLoad(app, info = null, { group = '' } = {}) {
|
|
try {
|
|
info ||= await backend.invoke('fixtures.info', {});
|
|
const state = { mode: 'append', groups: group ? [group] : [] };
|
|
const line = el('code.wg-line');
|
|
const out = el('pre.wg-log', { hidden: true });
|
|
const guard = info.guard;
|
|
const refresh = () => { line.textContent = loadLine(state); };
|
|
refresh();
|
|
const groups = info.groups || [];
|
|
const body = el('div.wg-load', {},
|
|
guard.blocked ? el('div.wg-error', {}, guard.reason) : el('div.pub-faint', {}, t('Environment: {env}', { env: guard.env })),
|
|
el('label.wg-check', {}, el('input', { type: 'radio', name: 'fxmode', checked: true, onchange: () => { state.mode = 'append'; refresh(); } }), el('span', {}, t('Add to the data already there (--append)'))),
|
|
el('label.wg-check', {}, el('input', { type: 'radio', name: 'fxmode', onchange: () => { state.mode = 'purge'; refresh(); } }), el('span', {}, t('Empty the tables first (purge)'))),
|
|
groups.length ? el('div.wg-groups', {}, el('strong', {}, t('Groups')), ...groups.map((g) => el('label.wg-check', {}, el('input', { type: 'checkbox', checked: state.groups.includes(g),
|
|
onchange: (e) => { state.groups = e.target.checked ? [...state.groups, g] : state.groups.filter((x) => x !== g); refresh(); } }), el('span', {}, g)))) : null,
|
|
line, out);
|
|
dialog({
|
|
title: t('Load fixtures'), body,
|
|
buttons: [{ label: t('Close') }, { label: t('Load'), primary: true, tour: 'fixtures-load-run', action: async () => {
|
|
if (guard.blocked) return false;
|
|
if (state.mode === 'purge' && !await confirm(t('Empty the tables?'), t('The tables of the fixtures are emptied before the load. Their data is lost.'), { ok: t('Purge and load'), danger: true })) return false;
|
|
out.hidden = false;
|
|
out.textContent = t('Loading…');
|
|
const r = await backend.invoke('fixtures.load', { mode: state.mode, groups: state.groups, confirmPurge: state.mode === 'purge' });
|
|
out.textContent = (r.output || '').replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').trim() || (r.ok ? t('Done.') : t('Failed.'));
|
|
out.classList.toggle('bad', !r.ok);
|
|
notify(r.ok ? t('Fixtures loaded.') : t('The load failed: see the output.'), r.ok ? 'success' : 'error', { title: t('Fixtures') });
|
|
return false;
|
|
} }],
|
|
});
|
|
} catch (e) {
|
|
notify(e.message || String(e), 'error', { title: t('Fixtures') });
|
|
}
|
|
}
|
|
|
|
export { TYPES };
|