520 lines
33 KiB
JavaScript
520 lines
33 KiB
JavaScript
// The command wizards: a Symfony console command or a Castor task made from a form, an existing one read back (php-parser)
|
|
// and edited, every change shown as a diff before it is written, and a form generated from its arguments / options to run it
|
|
// (through the Console window's runner, or the Scripts window's). PHP side: ide/src/Wizard (wizard.* commands).
|
|
import { backend } from './backend.js';
|
|
import { el, clear, icon, dialog, notify, t, copyText, debounce } from './ui.js';
|
|
import { monaco } from './editor.js';
|
|
|
|
const SYMFONY_STEPS = ['title', 'section', 'text', 'ask', 'confirm', 'choice', 'progress', 'table', 'success', 'note', 'warning', 'error', 'code'];
|
|
const CASTOR_STEPS = ['run', 'capture', 'title', 'section', 'writeln', 'success', 'note', 'warning', 'error', 'ask', 'confirm', 'fs', 'http', 'watch', 'notify', 'variable', 'code'];
|
|
const FS_OPS = ['mkdir', 'remove', 'touch', 'exists', 'copy', 'rename', 'mirror', 'dumpFile', 'appendToFile'];
|
|
|
|
function stepLabel(type) {
|
|
return {
|
|
title: t('Title'), section: t('Section title'), text: t('Text to write'), writeln: t('Line of text'), ask: t('Question'), confirm: t('Yes / no question'), choice: t('Choice'),
|
|
progress: t('Progress bar'), table: t('Table'), success: t('Success message'), note: t('Note'), warning: t('Warning'), error: t('Error message'), code: t('PHP code'),
|
|
run: t('Run a command'), capture: t('Capture the output'), fs: t('Files (fs)'), http: t('HTTP request'), watch: t('Watch files'), notify: t('Desktop notification'),
|
|
variable: t('Variable'),
|
|
}[type] || type;
|
|
}
|
|
|
|
/** a field: label + input bound to obj[key] */
|
|
function field(label, obj, key, { type = 'text', placeholder = '', options = null, rows = 0, onchange = null, title = '', cls = '', tour = undefined } = {}) {
|
|
const set = (v) => { obj[key] = v; onchange?.(); };
|
|
let input;
|
|
if (type === 'checkbox') {
|
|
input = el('input', { type: 'checkbox', checked: !!obj[key], onchange: (e) => set(e.target.checked) });
|
|
return el('label.cwz-check' + cls, { title }, input, el('span', {}, label));
|
|
}
|
|
if (options) {
|
|
input = el('select.input', { onchange: (e) => set(e.target.value) }, ...options.map(([v, text]) => el('option', { value: v, selected: String(obj[key] ?? '') === v }, text)));
|
|
} else if (rows) {
|
|
input = el('textarea.input', { rows, placeholder, spellcheck: false, value: obj[key] ?? '', oninput: (e) => set(e.target.value) });
|
|
} else {
|
|
input = el('input.input', { type, placeholder, spellcheck: false, 'data-tour': tour, value: obj[key] ?? '', oninput: (e) => set(type === 'number' ? Number(e.target.value) : e.target.value) });
|
|
}
|
|
return el('label.cwz-field' + cls, { title }, el('span', {}, label), input);
|
|
}
|
|
|
|
const envText = (env) => (env && typeof env === 'object' && !Array.isArray(env) ? Object.entries(env).map(([k, v]) => `${k}=${v}`).join('\n') : env || '');
|
|
|
|
class Wizard {
|
|
/**
|
|
* @param kind 'symfony' | 'castor'
|
|
* @param edit null for a new one, else {file, function?}: the existing command / task being edited
|
|
*/
|
|
constructor(app, kind, info, model, edit) {
|
|
this.app = app;
|
|
this.kind = kind;
|
|
this.info = info;
|
|
this.model = model;
|
|
this.edit = edit;
|
|
this.changes = null;
|
|
this.error = null;
|
|
this.refresh = debounce(() => this.preview(), 250);
|
|
}
|
|
|
|
open() {
|
|
this.form = el('div.cwz-form');
|
|
this.code = el('div.cwz-code');
|
|
this.status = el('div.cwz-status');
|
|
const symfony = this.kind === 'symfony';
|
|
const title = symfony
|
|
? (this.edit ? t('Edit the Command {name}', { name: this.model.name }) : t('New Symfony Command'))
|
|
: (this.edit ? t('Edit the Castor Task {name}', { name: this.fullName() }) : t('New Castor Task'));
|
|
this.dialog = dialog({
|
|
title, wide: true, sticky: true,
|
|
body: el('div.cwz', {}, this.form, el('div.cwz-right', {}, el('div.cwz-right-head', {}, icon('diff'), el('span', {}, this.edit ? t('The changes') : t('The new code'))), this.code, this.status)),
|
|
buttons: [
|
|
{ label: t('Cancel') },
|
|
{ label: t('Run…'), action: () => { openRunForm(this.app, this.kind, this.model); return false; } },
|
|
{ label: this.edit ? t('Apply the Changes') : t('Write the File'), primary: true, tour: 'cmd-write', action: () => this.apply() },
|
|
],
|
|
onClose: () => this.dispose(),
|
|
});
|
|
this.dialog.box.classList.add('cwz-dialog');
|
|
this.render();
|
|
this.preview();
|
|
return this;
|
|
}
|
|
|
|
dispose() { this.diff?.dispose(); this.models?.forEach((m) => m.dispose()); }
|
|
|
|
fullName() { return (this.model.namespace ? this.model.namespace + ':' : '') + (this.model.name || ''); }
|
|
|
|
changed(structure = false) {
|
|
if (structure) this.render();
|
|
this.refresh();
|
|
}
|
|
|
|
render() {
|
|
const scroll = this.form.scrollTop;
|
|
clear(this.form);
|
|
if (this.kind === 'symfony') this.renderSymfony(); else this.renderCastor();
|
|
this.form.scrollTop = scroll;
|
|
}
|
|
|
|
section(title, ...children) { return el('div.cwz-section', {}, el('h4', {}, title), ...children); }
|
|
|
|
// Symfony ------------------------------------------------------------------------------------------------------
|
|
|
|
renderSymfony() {
|
|
const m = this.model;
|
|
const s = this.info.symfony || {};
|
|
const on = () => this.changed();
|
|
this.form.append(this.section(t('Command'),
|
|
el('div.cwz-row', {},
|
|
field(t('Name'), m, 'name', { placeholder: 'app:send-report', onchange: on, tour: 'cmd-name' }),
|
|
field(t('Style'), m, 'style', { onchange: on, options: [['attributes', t('Attributes (Symfony 7.3+)')], ['classic', t('Classic (configure / execute)')]],
|
|
title: s.version ? `symfony/console ${s.version}` : '' })),
|
|
el('div.cwz-row', {},
|
|
field(t('Description'), m, 'description', { onchange: on }),
|
|
field(t('Aliases'), m, 'aliases', { placeholder: 'report, rep', onchange: on })),
|
|
el('div.cwz-row', {},
|
|
this.edit ? null : field(t('Class'), m, 'class', { placeholder: classOf(m.name), onchange: on }),
|
|
field(t('Hidden'), m, 'hidden', { type: 'checkbox', onchange: on })),
|
|
field(t('Help'), m, 'help', { rows: 2, onchange: on }),
|
|
s.version ? el('p.pub-faint.cwz-note', {}, t('symfony/console {version} in composer.lock: {style} style by default.', { version: s.version, style: s.invokable ? t('attributes') : t('classic') })) : null));
|
|
this.form.append(this.section(t('Arguments'), ...m.arguments.map((a, i) => this.argumentRow(a, i)),
|
|
el('button.btn.small', { 'data-tour': 'cmd-add-argument', onclick: () => { m.arguments.push({ name: '', mode: 'required', array: false, type: 'string', default: '', description: '' }); this.changed(true); } }, icon('plus'), t('Argument'))));
|
|
this.form.append(this.section(t('Options'), ...m.options.map((o, i) => this.optionRow(o, i, 'symfony')),
|
|
el('button.btn.small', { onclick: () => { m.options.push({ name: '', shortcut: '', mode: 'none', type: 'string', default: '', description: '' }); this.changed(true); } }, icon('plus'), t('Option'))));
|
|
this.form.append(this.servicesSection());
|
|
if (this.edit) {
|
|
this.form.append(el('p.pub-faint.cwz-note', {}, t('The body of the command is left as it is: edit it in the editor.')));
|
|
} else {
|
|
this.form.append(this.bodySection(SYMFONY_STEPS),
|
|
this.section(t('Result'), field(t('It returns'), m, 'result', { onchange: on, options: [['SUCCESS', 'Command::SUCCESS'], ['FAILURE', 'Command::FAILURE'], ['INVALID', 'Command::INVALID']] })));
|
|
}
|
|
}
|
|
|
|
remove(list, i) { list.splice(i, 1); this.changed(true); }
|
|
|
|
argumentRow(a, i) {
|
|
const on = () => this.changed();
|
|
return el('div.cwz-item', {},
|
|
field(t('Name'), a, 'name', { placeholder: 'user', onchange: on, tour: 'cmd-arg-name' }),
|
|
field(t('Mode'), a, 'mode', { onchange: () => this.changed(true), options: [['required', t('required')], ['optional', t('optional')]] }),
|
|
field(t('Type'), a, 'type', { onchange: on, options: [['string', 'string'], ['int', 'int'], ['float', 'float']] }),
|
|
field(t('Several'), a, 'array', { type: 'checkbox', onchange: on, title: t('An array: several values') }),
|
|
a.mode === 'optional' ? field(t('Default'), a, 'default', { onchange: on, placeholder: a.array ? 'a, b' : '' }) : null,
|
|
field(t('Description'), a, 'description', { onchange: on, cls: '.grow' }),
|
|
el('button.cwz-del', { title: t('Remove'), onclick: () => this.remove(this.model.arguments, i) }, icon('trash')));
|
|
}
|
|
|
|
optionRow(o, i, kind) {
|
|
const on = () => this.changed();
|
|
const list = kind === 'symfony' ? this.model.options : this.model.params;
|
|
const modes = [['none', t('flag (no value)')], ['required', t('value required')], ['optional', t('value optional')], ['array', t('several values')], ['negatable', t('--x / --no-x')]];
|
|
const withValue = !['none', 'negatable'].includes(o.mode);
|
|
return el('div.cwz-item', {},
|
|
field(t('Name'), o, 'name', { placeholder: 'dry-run', onchange: on }),
|
|
field(t('Shortcut'), o, 'shortcut', { placeholder: 'f', onchange: on, cls: '.short' }),
|
|
field(t('Mode'), o, 'mode', { onchange: () => this.changed(true), options: modes }),
|
|
withValue && o.mode !== 'array' ? field(t('Type'), o, 'type', { onchange: on, options: [['string', 'string'], ['int', 'int'], ['float', 'float']] }) : null,
|
|
withValue && o.mode !== 'optional' ? field(t('Default'), o, 'default', { onchange: on }) : null,
|
|
field(t('Description'), o, 'description', { onchange: on, cls: '.grow' }),
|
|
el('button.cwz-del', { title: t('Remove'), onclick: () => this.remove(list, i) }, icon('trash')));
|
|
}
|
|
|
|
/** constructor injection: a class of the project (the PHP index), its variable */
|
|
servicesSection() {
|
|
const m = this.model;
|
|
const id = 'cwz-classes-' + Math.random().toString(36).slice(2);
|
|
const list = el('datalist', { id });
|
|
const input = el('input.input', { type: 'text', placeholder: t('A class or an interface, e.g. LoggerInterface'), spellcheck: false });
|
|
input.setAttribute('list', id);
|
|
const fill = debounce(async () => {
|
|
const q = input.value.trim();
|
|
if (q.length < 2) return;
|
|
const found = await backend.invoke('php.classes', { query: q, limit: 40 }).catch(() => []);
|
|
clear(list);
|
|
for (const c of found) list.append(el('option', { value: c.name }));
|
|
}, 150);
|
|
input.addEventListener('input', fill);
|
|
const add = () => {
|
|
const cls = input.value.trim().replace(/^\\/, '');
|
|
if (!cls) return;
|
|
const short = cls.split('\\').pop().replace(/Interface$/, '') || 'service';
|
|
m.services.push({ class: cls, name: short.charAt(0).toLowerCase() + short.slice(1) });
|
|
this.changed(true);
|
|
};
|
|
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); add(); } });
|
|
const known = new Set((this.original?.services || []).map((s) => s.name));
|
|
return this.section(t('Injected services'),
|
|
...m.services.map((s, i) => el('div.cwz-item', {},
|
|
el('code.cwz-class', {}, s.class),
|
|
field(t('Variable'), s, 'name', { onchange: () => this.changed(), cls: '.short' }),
|
|
this.edit && known.has(s.name) ? el('span.pub-faint', {}, t('in the constructor')) : el('button.cwz-del', { title: t('Remove'), onclick: () => this.remove(m.services, i) }, icon('trash')))),
|
|
el('div.cwz-add', {}, input, list, el('button.btn.small', { onclick: add }, icon('plus'), t('Inject'))));
|
|
}
|
|
|
|
// the body: steps picked in a palette --------------------------------------------------------------------------
|
|
|
|
bodySection(types) {
|
|
const steps = this.model.body;
|
|
const palette = el('div.cwz-palette', {}, ...types.map((type) => el('button.btn.small', { 'data-tour': 'cmd-step-' + type, title: t('Add a step: {name}', { name: stepLabel(type) }),
|
|
onclick: () => { steps.push(newStep(type)); this.changed(true); } }, stepLabel(type))));
|
|
return this.section(t('Body'), el('p.pub-faint.cwz-note', {}, t('Click a step to add it; the code is written in this order.')), palette,
|
|
...steps.map((s, i) => this.stepRow(s, i)));
|
|
}
|
|
|
|
stepRow(s, i) {
|
|
const steps = this.model.body;
|
|
const on = () => this.changed();
|
|
const fields = {
|
|
ask: () => [field(t('Variable'), s, 'var', { onchange: on, cls: '.short' }), field(t('Question'), s, 'question', { onchange: on, cls: '.grow' }), field(t('Default'), s, 'default', { onchange: on })],
|
|
confirm: () => [field(t('Variable'), s, 'var', { onchange: on, cls: '.short' }), field(t('Question'), s, 'question', { onchange: on, cls: '.grow' }), field(t('Yes by default'), s, 'default', { type: 'checkbox', onchange: on })],
|
|
choice: () => [field(t('Variable'), s, 'var', { onchange: on, cls: '.short' }), field(t('Question'), s, 'question', { onchange: on, cls: '.grow' }),
|
|
field(t('Choices'), s, 'choices', { placeholder: 'dev, prod', onchange: on }), field(t('Default'), s, 'default', { onchange: on })],
|
|
progress: () => [field(t('Steps'), s, 'count', { type: 'number', onchange: on, cls: '.short' })],
|
|
table: () => [field(t('Headers'), s, 'headers', { placeholder: 'Id, Name', onchange: on }), field(t('Rows (one per line)'), s, 'rows', { rows: 2, placeholder: '1, Ada', onchange: on, cls: '.grow' })],
|
|
run: () => runFields(s, on),
|
|
capture: () => [field(t('Variable'), s, 'var', { onchange: on, cls: '.short' }), ...runFields(s, on)],
|
|
fs: () => [field(t('Operation'), s, 'op', { onchange: () => this.changed(true), options: FS_OPS.map((o) => [o, `fs()->${o}()`]) }), field(t('Path'), s, 'path', { onchange: on, cls: '.grow' }),
|
|
['copy', 'rename', 'mirror'].includes(s.op) ? field(t('Target'), s, 'target', { onchange: on }) : null,
|
|
['dumpFile', 'appendToFile'].includes(s.op) ? field(t('Content'), s, 'content', { onchange: on }) : null],
|
|
http: () => [field(t('Method'), s, 'method', { onchange: on, options: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].map((v) => [v, v]) }),
|
|
field('URL', s, 'url', { placeholder: 'https://', onchange: on, cls: '.grow' }), field(t('Variable'), s, 'var', { onchange: on, cls: '.short' })],
|
|
watch: () => [field(t('Path'), s, 'path', { placeholder: 'src/...', onchange: on }), field(t('Command on change'), s, 'command', { onchange: on, cls: '.grow' })],
|
|
variable: () => [field(t('Variable'), s, 'var', { onchange: on, cls: '.short' }), field(t('Key'), s, 'key', { onchange: on }), field(t('Default'), s, 'default', { onchange: on })],
|
|
code: () => [field(t('PHP code'), s, 'code', { rows: 3, onchange: on, cls: '.grow' })],
|
|
}[s.type] || (() => [field(t('Text to write'), s, 'text', { onchange: on, cls: '.grow' })]);
|
|
const move = (d) => { const j = i + d; if (j < 0 || j >= steps.length) return; [steps[i], steps[j]] = [steps[j], steps[i]]; this.changed(true); };
|
|
return el('div.cwz-step', {},
|
|
el('div.cwz-step-head', {}, el('b', {}, stepLabel(s.type)), el('span.cwz-grow'),
|
|
el('button.cwz-del', { title: t('Move up'), onclick: () => move(-1) }, '↑'), el('button.cwz-del', { title: t('Move down'), onclick: () => move(1) }, '↓'),
|
|
el('button.cwz-del', { title: t('Remove'), onclick: () => this.remove(steps, i) }, icon('trash'))),
|
|
el('div.cwz-item', {}, ...fields().filter(Boolean)));
|
|
}
|
|
|
|
// Castor -------------------------------------------------------------------------------------------------------
|
|
|
|
renderCastor() {
|
|
const m = this.model;
|
|
const on = () => this.changed();
|
|
const files = this.info.castor?.files || [];
|
|
if (!this.edit) {
|
|
const choices = [['', files[0] ? files[0] : 'castor.php'], ...files.slice(1).map((f) => [f, f]), ['new', t('A new file in .castor/…')]];
|
|
const fileField = el('div.cwz-row', {},
|
|
field(t('Kind'), m, 'kind', { onchange: () => this.changed(true), options: [['task', t('Task (#[AsTask])')], ['context', t('Context (#[AsContext])')], ['listener', t('Listener (#[AsListener])')]] }),
|
|
field(t('Written into'), m, 'fileChoice', { onchange: () => { m.file = m.fileChoice === 'new' ? '.castor/tasks.php' : m.fileChoice; this.changed(true); }, options: choices }),
|
|
m.fileChoice === 'new' ? field(t('File'), m, 'file', { placeholder: '.castor/deploy.php', onchange: on }) : null);
|
|
this.form.append(this.section(t('Where'), fileField));
|
|
}
|
|
if (m.kind === 'context') {
|
|
const c = m.context;
|
|
this.form.append(this.section(t('Context'),
|
|
el('div.cwz-row', {}, field(t('Name'), c, 'name', { placeholder: 'production', onchange: on }), field(t('Function'), m, 'function', { placeholder: (c.name || 'my') + 'Context', onchange: on }),
|
|
field(t('Default context'), c, 'default', { type: 'checkbox', onchange: on })),
|
|
el('div.cwz-row', {}, field(t('Working folder'), c, 'workingDirectory', { onchange: on }), field(t('Time limit (s)'), c, 'timeout', { type: 'number', onchange: on, cls: '.short' })),
|
|
el('div.cwz-row', {}, field(t('Environment (NAME=value lines)'), c, 'env', { rows: 2, onchange: on }), field(t('Data (name=value lines)'), c, 'data', { rows: 2, onchange: on })),
|
|
el('div.cwz-row', {}, field('TTY', c, 'tty', { type: 'checkbox', onchange: on }), field(t('Allow failure'), c, 'allowFailure', { type: 'checkbox', onchange: on }),
|
|
field(t('Quiet'), c, 'quiet', { type: 'checkbox', onchange: on }))));
|
|
return;
|
|
}
|
|
if (m.kind === 'listener') {
|
|
const l = m.listener;
|
|
this.form.append(this.section(t('Listener'),
|
|
el('div.cwz-row', {}, field(t('Event'), l, 'event', { onchange: on, options: (this.info.castor?.events || ['BeforeExecuteTaskEvent']).map((e) => [e, e]) }),
|
|
field(t('Priority'), l, 'priority', { type: 'number', onchange: on, cls: '.short' }), field(t('Function'), m, 'function', { placeholder: 'on' + l.event.replace(/Event$/, ''), onchange: on }))),
|
|
this.bodySection(CASTOR_STEPS));
|
|
return;
|
|
}
|
|
this.form.append(this.section(t('Task'),
|
|
el('div.cwz-row', {}, field(t('Name'), m, 'name', { placeholder: 'reset', onchange: on }), field(t('Namespace'), m, 'namespace', { placeholder: 'db', onchange: on }),
|
|
field(t('Function'), m, 'function', { placeholder: functionOf(m), onchange: on })),
|
|
el('div.cwz-row', {}, field(t('Description'), m, 'description', { onchange: on }), field(t('Aliases'), m, 'aliases', { onchange: on }),
|
|
field(t('Default task'), m, 'default', { type: 'checkbox', onchange: on, title: t('Run by castor alone') }))));
|
|
this.form.append(this.section(t('Arguments and options'), ...m.params.map((p, i) => (p.kind === 'option' ? this.castorOption(p, i) : this.castorArgument(p, i))),
|
|
el('div.cwz-add', {},
|
|
el('button.btn.small', { onclick: () => { m.params.push({ kind: 'argument', name: '', mode: 'required', type: 'string', default: '', description: '' }); this.changed(true); } }, icon('plus'), t('Argument')),
|
|
el('button.btn.small', { onclick: () => { m.params.push({ kind: 'option', name: '', mode: 'auto', type: 'bool', default: '', description: '', shortcut: '' }); this.changed(true); } }, icon('plus'), t('Option')))));
|
|
if (this.edit) this.form.append(el('p.pub-faint.cwz-note', {}, t('The body of the task is left as it is: edit it in the editor.')));
|
|
else this.form.append(this.bodySection(CASTOR_STEPS));
|
|
}
|
|
|
|
castorArgument(p, i) {
|
|
const on = () => this.changed();
|
|
return el('div.cwz-item', {}, el('span.cwz-badge', {}, t('argument')),
|
|
field(t('Name'), p, 'name', { onchange: on }),
|
|
field(t('Mode'), p, 'mode', { onchange: () => this.changed(true), options: [['required', t('required')], ['optional', t('optional')]] }),
|
|
field(t('Type'), p, 'type', { onchange: on, options: [['string', 'string'], ['int', 'int'], ['float', 'float'], ['array', 'array']] }),
|
|
p.mode === 'optional' ? field(t('Default'), p, 'default', { onchange: on }) : null,
|
|
field(t('Description'), p, 'description', { onchange: on, cls: '.grow' }),
|
|
el('button.cwz-del', { title: t('Remove'), onclick: () => this.remove(this.model.params, i) }, icon('trash')));
|
|
}
|
|
|
|
castorOption(p, i) {
|
|
const on = () => this.changed();
|
|
const flag = ['none', 'negatable'].includes(p.mode) || (p.mode === 'auto' && p.type === 'bool');
|
|
return el('div.cwz-item', {}, el('span.cwz-badge', {}, t('option')),
|
|
field(t('Name'), p, 'name', { onchange: on }),
|
|
field(t('Shortcut'), p, 'shortcut', { onchange: on, cls: '.short' }),
|
|
field(t('Type'), p, 'type', { onchange: () => this.changed(true), options: [['bool', t('flag (bool)')], ['string', 'string'], ['int', 'int'], ['float', 'float'], ['array', 'array']] }),
|
|
field(t('Mode'), p, 'mode', { onchange: () => this.changed(true), options: [['auto', t('as Castor guesses')], ['none', t('flag (no value)')], ['required', t('value required')], ['optional', t('value optional')], ['array', t('several values')], ['negatable', t('--x / --no-x')]] }),
|
|
flag ? null : field(t('Default'), p, 'default', { onchange: on }),
|
|
field(t('Description'), p, 'description', { onchange: on, cls: '.grow' }),
|
|
el('button.cwz-del', { title: t('Remove'), onclick: () => this.remove(this.model.params, i) }, icon('trash')));
|
|
}
|
|
|
|
// preview, diff, write -----------------------------------------------------------------------------------------
|
|
|
|
payload() {
|
|
const m = structuredClone(this.model);
|
|
if (this.kind === 'castor') {
|
|
delete m.fileChoice;
|
|
return this.edit ? { model: m, edit: this.edit } : { model: m };
|
|
}
|
|
return this.edit ? { model: m, file: this.edit.file } : { model: m };
|
|
}
|
|
|
|
async preview() {
|
|
try {
|
|
const r = await backend.invoke(this.kind === 'symfony' ? 'wizard.symfonyPreview' : 'wizard.castorPreview', this.payload());
|
|
this.changes = r.changes;
|
|
this.error = null;
|
|
} catch (e) {
|
|
this.error = String(e.message || e);
|
|
}
|
|
this.showChanges();
|
|
}
|
|
|
|
/** the changes as a diff (Monaco's, inline), the files they touch */
|
|
showChanges() {
|
|
clear(this.status);
|
|
if (this.error) { this.status.append(el('div.cwz-error', {}, this.error)); return; }
|
|
const changes = this.changes || [];
|
|
const same = changes.every((c) => c.before === c.after);
|
|
// the files it touches (a new .castor/ file and the root file importing it): a click shows one
|
|
this.current = Math.min(this.current || 0, Math.max(0, changes.length - 1));
|
|
this.status.append(same ? el('div.pub-faint', {}, t('Nothing changes.')) : el('div.cwz-files', {}, ...changes.map((c, i) => el('button.cwz-file' + (i === this.current ? '.on' : ''),
|
|
{ onclick: () => { this.current = i; this.showChanges(); } }, c.before === null ? t('{file} (new)', { file: c.file }) : c.file))));
|
|
const main = changes[this.current];
|
|
if (!main) return;
|
|
if (!monaco) {
|
|
clear(this.code);
|
|
this.code.append(el('pre.cwz-pre', {}, main.after));
|
|
return;
|
|
}
|
|
if (!this.diff) {
|
|
this.diff = monaco.editor.createDiffEditor(this.code, { readOnly: true, originalEditable: false, renderSideBySide: false, automaticLayout: true, minimap: { enabled: false },
|
|
scrollBeyondLastLine: false, fontSize: 12, renderOverviewRuler: false, ignoreTrimWhitespace: false,
|
|
theme: document.documentElement.dataset.theme === 'light' ? 'jumphp-light' : 'jumphp-dark' });
|
|
this.models = [monaco.editor.createModel('', 'php'), monaco.editor.createModel('', 'php')];
|
|
this.diff.setModel({ original: this.models[0], modified: this.models[1] });
|
|
}
|
|
this.models[0].setValue(main.before ?? '');
|
|
this.models[1].setValue(main.after);
|
|
// the first change in view
|
|
setTimeout(() => { const c = this.diff.getLineChanges?.(); if (c?.length) this.diff.getModifiedEditor().revealLineInCenter(c[0].modifiedStartLineNumber || 1); }, 120);
|
|
}
|
|
|
|
async apply() {
|
|
await this.preview();
|
|
if (this.error) return false;
|
|
const changes = this.changes.filter((c) => c.before !== c.after);
|
|
if (!changes.length) { notify(t('Nothing changes.'), 'info'); return false; }
|
|
const r = await backend.invoke('wizard.apply', { changes });
|
|
notify(t('Written: {files}', { files: r.files.join(', ') }), 'success', { title: this.kind === 'symfony' ? 'Symfony' : 'Castor' });
|
|
this.app.editors?.open?.(r.files[0]);
|
|
if (this.kind === 'symfony') this.app.symfonyConsole?.load?.(true);
|
|
else {
|
|
const scripts = this.app.scripts;
|
|
await scripts?.load?.(true);
|
|
// the task needs the castor program (it also writes .castor.stub.php, what makes AsTask / run() known to the editor)
|
|
if (scripts?.data?.castor && !scripts.data.castor.installed && scripts.data.castor.installable) {
|
|
await scripts.installCastor();
|
|
await scripts.load(true);
|
|
}
|
|
this.app.reindex?.();
|
|
}
|
|
return true;
|
|
}
|
|
}
|
|
|
|
function runFields(s, on) {
|
|
if (typeof s.env !== 'string') s.env = envText(s.env);
|
|
return [field(t('Command'), s, 'command', { placeholder: 'bin/console cache:clear', onchange: on, cls: '.grow' }),
|
|
field(t('Working folder'), s, 'cwd', { onchange: on, cls: '.short' }),
|
|
field(t('Environment (NAME=value lines)'), s, 'env', { rows: 1, onchange: on }),
|
|
field(t('Time limit (s)'), s, 'timeout', { type: 'number', onchange: on, cls: '.short' }),
|
|
field('TTY', s, 'tty', { type: 'checkbox', onchange: on }), field(t('Allow failure'), s, 'allowFailure', { type: 'checkbox', onchange: on }),
|
|
field(t('Quiet'), s, 'quiet', { type: 'checkbox', onchange: on })];
|
|
}
|
|
|
|
const STEP_DEFAULTS = {
|
|
ask: { var: 'answer', question: '', default: '' }, confirm: { var: 'confirmed', question: '', default: true },
|
|
choice: { var: 'choice', question: '', choices: '', default: '' }, progress: { count: 10 }, table: { headers: '', rows: '' },
|
|
run: { command: '', cwd: '', env: '', timeout: 0, tty: false, allowFailure: false, quiet: false }, capture: { var: 'output', command: '', cwd: '', env: '' },
|
|
fs: { op: 'mkdir', path: '' }, http: { method: 'GET', url: '', var: 'response' }, watch: { path: '', command: '' }, variable: { var: 'value', key: '', default: '' },
|
|
code: { code: '' },
|
|
};
|
|
function newStep(type) { return { type, ...structuredClone(STEP_DEFAULTS[type] || { text: '' }) }; }
|
|
|
|
const classOf = (name) => {
|
|
const last = String(name || '').replace(/^.*:/, '');
|
|
const words = last.split(/[^A-Za-z0-9]+/).filter(Boolean);
|
|
return (words.length ? words.map((w) => w[0].toUpperCase() + w.slice(1)).join('') : 'My') + 'Command';
|
|
};
|
|
const functionOf = (m) => {
|
|
const words = `${m.namespace || ''} ${m.name || ''}`.split(/[^A-Za-z0-9]+/).filter(Boolean);
|
|
return words.map((w, i) => (i ? w[0].toUpperCase() + w.slice(1) : w.toLowerCase())).join('') || 'myTask';
|
|
};
|
|
|
|
function emptySymfony(info) {
|
|
return { style: info.symfony?.style || 'attributes', name: 'app:', class: '', description: '', aliases: '', hidden: false, help: '',
|
|
arguments: [], options: [], services: [], body: [{ type: 'title', text: '' }, { type: 'success', text: 'Done.' }], result: 'SUCCESS' };
|
|
}
|
|
|
|
function emptyCastor() {
|
|
return { kind: 'task', fileChoice: '', file: '', name: '', namespace: '', function: '', description: '', aliases: '', default: false, params: [],
|
|
body: [{ type: 'run', command: '', cwd: '', env: '', timeout: 0, tty: false, allowFailure: false, quiet: false }],
|
|
context: { name: '', default: false, workingDirectory: '', env: '', data: '', tty: false, timeout: 0, allowFailure: false, quiet: false },
|
|
listener: { event: 'BeforeExecuteTaskEvent', priority: 0 } };
|
|
}
|
|
|
|
/** The Symfony command wizard: a new command, or an existing one by its name or its file (read back and edited). */
|
|
export async function openSymfonyWizard(app, { name = null, file = null } = {}) {
|
|
try {
|
|
const info = await backend.invoke('wizard.info', {});
|
|
if (!name && !file) return new Wizard(app, 'symfony', info, emptySymfony(info), null).open();
|
|
const r = await backend.invoke('wizard.symfonyRead', file ? { file } : { name });
|
|
const model = { ...r.model, aliases: r.model.aliases.join(', ') };
|
|
const w = new Wizard(app, 'symfony', info, model, { file: r.file });
|
|
w.original = structuredClone(r.model);
|
|
return w.open();
|
|
} catch (e) {
|
|
notify(e.message, 'error', { title: t('Symfony command wizard') });
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** The Castor task wizard: a new task / context / listener, or an existing task by its name (read back and edited). */
|
|
export async function openCastorWizard(app, { name = null, file = null, fn = null } = {}) {
|
|
try {
|
|
const info = await backend.invoke('wizard.info', {});
|
|
if (!name && !fn) return new Wizard(app, 'castor', info, emptyCastor(), null).open();
|
|
const r = await backend.invoke('wizard.castorRead', { file, function: fn || name });
|
|
const model = { ...r.model, aliases: r.model.aliases.join(', ') };
|
|
return new Wizard(app, 'castor', info, model, { file: r.file, function: r.model.function }).open();
|
|
} catch (e) {
|
|
notify(e.message, 'error', { title: t('Castor task wizard') });
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The run form: a field per argument and option, the command line it makes, run through the Console window's runner
|
|
* (a Symfony command) or the Scripts window's (a Castor task).
|
|
*/
|
|
export function openRunForm(app, kind, model) {
|
|
const values = { arguments: {}, options: {} };
|
|
const symfony = kind === 'symfony';
|
|
const args = symfony ? model.arguments : (model.params || []).filter((p) => p.kind === 'argument');
|
|
const opts = symfony ? model.options : (model.params || []).filter((p) => p.kind === 'option');
|
|
const isFlag = (o) => ['none', 'negatable'].includes(o.mode) || (!symfony && o.type === 'bool');
|
|
const line = el('code.cwz-line', {}, '…');
|
|
const name = symfony ? model.name : (model.namespace ? model.namespace + ':' : '') + model.name;
|
|
let argv = null;
|
|
const update = debounce(async () => {
|
|
try {
|
|
const r = await backend.invoke(symfony ? 'wizard.symfonyArgv' : 'wizard.castorArgv', { model, values });
|
|
argv = r.argv;
|
|
line.textContent = r.line;
|
|
line.classList.remove('bad');
|
|
} catch (e) { line.textContent = String(e.message || e); line.classList.add('bad'); }
|
|
}, 80);
|
|
const body = el('div.cwz-run', {},
|
|
args.length ? el('h4', {}, t('Arguments')) : null,
|
|
...args.map((a) => field(a.name + (a.mode === 'required' ? ' *' : ''), values.arguments, a.name, { placeholder: a.default || (a.array || a.type === 'array' ? t('several: separated by spaces') : ''), onchange: update, title: a.description })),
|
|
opts.length ? el('h4', {}, t('Options')) : null,
|
|
...opts.map((o) => (isFlag(o)
|
|
? field(`--${o.name}` + (o.shortcut ? ` (-${o.shortcut})` : ''), values.options, o.name, { type: 'checkbox', onchange: update, title: o.description })
|
|
: field(`--${o.name}` + (o.shortcut ? ` (-${o.shortcut})` : ''), values.options, o.name, { placeholder: o.default || '', onchange: update, title: o.description }))),
|
|
!args.length && !opts.length ? el('p.pub-faint', {}, t('No arguments nor options.')) : null,
|
|
el('div.cwz-line-row', {}, line, el('button.btn', { title: t('Copy the command line'), onclick: () => copyText(line.textContent) }, icon('copy'))),
|
|
el('p.pub-faint.cwz-note', {}, symfony ? t('Run through the Console window (the site\'s PHP container, or the local PHP it is set to).') : t('Run through the Scripts window (castor of this project).')));
|
|
update();
|
|
const run = async (here) => {
|
|
// the values as they are now (the preview may still be waiting)
|
|
argv = (await backend.invoke(symfony ? 'wizard.symfonyArgv' : 'wizard.castorArgv', { model, values })).argv;
|
|
if (symfony) {
|
|
const panel = app.symfonyConsole;
|
|
if (!panel) { notify(t('This project has no Symfony console.'), 'error'); return false; }
|
|
app.showTool?.('console', true);
|
|
if (here) panel.runHere({ argv, command: name }, name); else panel.runInTerminal({ argv }, name);
|
|
return true;
|
|
}
|
|
if (!app.scripts) { notify(t('The Scripts window is not available here.'), 'error'); return false; }
|
|
await app.scripts.load(true);
|
|
return (await app.scripts.run(`castor:${name}`, { args: argv.slice(1) })) !== false;
|
|
};
|
|
dialog({
|
|
title: t('Run {name}', { name }), body, sticky: true,
|
|
buttons: symfony
|
|
? [{ label: t('Cancel') }, { label: t('Run here'), action: () => run(true) }, { label: t('Run'), primary: true, action: () => run(false) }]
|
|
: [{ label: t('Cancel') }, { label: t('Run'), primary: true, action: () => run(false) }],
|
|
}).box.classList.add('cwz-run-dialog');
|
|
}
|
|
|
|
/** The Console window's links: "New command…" in its tool bar, "Edit in the wizard" on a command. */
|
|
export function consoleWizardButton(app) {
|
|
return el('button', { title: t('New command… (the Symfony command wizard)'), onclick: () => openSymfonyWizard(app) }, icon('plus'));
|
|
}
|
|
export function consoleEditButton(app, name) {
|
|
return el('button.btn.small.cwz-edit-link', { title: t('Edit in the wizard'), onclick: () => openSymfonyWizard(app, { name }) }, icon('edit'), t('Edit in the wizard'));
|
|
}
|
|
|
|
/** The Scripts window's menu of a Castor task: edit it in the wizard, run it from a form. */
|
|
export function castorMenuItems(app, name) {
|
|
return [
|
|
{ label: t('Edit in the Wizard…'), icon: 'edit', action: () => openCastorWizard(app, { name }) },
|
|
{ label: t('Run with Arguments…'), icon: 'play', action: async () => {
|
|
try {
|
|
const r = await backend.invoke('wizard.castorRead', { name });
|
|
openRunForm(app, 'castor', r.model);
|
|
} catch (e) { notify(e.message, 'error', { title: t('Castor task wizard') }); }
|
|
} },
|
|
];
|
|
}
|