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

402 lines
22 KiB
JavaScript

// The Console window: the commands of a Symfony application (bin/console) or a Laravel one (artisan), for the web sites of
// bin/jumphp web:* (docs/web.md) and any project that has one. `list --format=json` run in the site's PHP container (or a
// temporary one of the same image when the site is not running) gives the commands: grouped by namespace, filtered, each one
// a form made from its definition (arguments, options), its help and the command line it makes. Run types it into a Terminal
// tab attached to the container (docker exec -it: the questions of make:entity work); "Run here" runs it without questions
// and shows its output. A free command line with completion and history; favourite commands pinned (prefs).
// The header chooses where it runs (remembered in .jumphp/web.json): Docker, on the project's PHP (bin/jumphp web:php: the
// same PHP for web:serve, web:composer and the console; changing it rebuilds what is needed in the Run window), or Local PHP
// (the computer's php, from the PATH or a chosen program). Composer's platform check ("your dependencies require PHP >= 8.5")
// is read: one click uses that PHP for the project.
// The PHP side: ide/src/Symfony/ConsoleCommands.php. Claude: symfony_commands / symfony_run at the end.
import { backend } from './backend.js';
import { el, clear, icon, notify, prefs, t, copyText, debounce } from './ui.js';
import { consoleWizardButton, consoleEditButton } from './command-wizard.js';
const GROUP_LABEL = (id) => (id === '_global' ? t('General') : id);
export class SymfonyConsolePanel {
constructor(app) {
this.app = app;
this.tool = app.project.capabilities?.console || 'bin/console';
this.node = el('div.sfc-view');
this.list = null; // console.list: {application, groups, globals, count, running}
this.status = null; // console.status: {running, container, image}
this.error = null;
this.busy = false;
this.filter = '';
this.selected = prefs.get(this.key('selected'), null);
this.values = { arguments: {}, options: {} };
this.output = null; // the last "Run here": {name, code, output, seconds}
this.preview = '';
this.historyAt = -1;
this.open = new Set(prefs.get(this.key('open'), []));
this.updatePreview = debounce(() => this.refreshPreview(), 80);
this.render();
}
key(name) { return `sfc:${name}:${this.app.projectKey}`; }
favorites() { return prefs.get(this.key('favs'), []); }
history() { return prefs.get(this.key('history'), []); }
title() { return this.tool === 'artisan' ? 'Laravel Artisan' : 'Symfony Console'; }
actions() {
return [
consoleWizardButton(this.app),
el('button', { title: t('Refresh the list of commands'), onclick: () => this.load(true) }, icon('refresh')),
];
}
shown() { if (!this.list && !this.busy) this.load(false); }
async load(refresh) {
this.busy = true; this.error = null; this.platform = null; this.render();
try {
this.status = await backend.invoke('console.status', {});
const list = await backend.invoke('console.list', { refresh });
if (list.error) { this.error = list.error; this.platform = list.platform || null; this.list = null; }
else this.list = list;
} catch (e) {
this.error = String(e.message || e);
}
this.busy = false;
this.render();
}
/** the project's PHP changed (bin/jumphp web:php in the Run window: it may build an image), then the commands again */
async setPhp(version) {
let r;
try { r = await backend.invoke('web.setPhp', { version }); } catch (e) { notify(e.message, 'error', { title: t('PHP version') }); return; }
this.busy = true; this.render();
this.app.showTool?.('run');
await new Promise((resolve) => { const off = backend.on('run.exit', (p) => { if (p.id === r.id) { off?.(); resolve(p); } }); });
this.load(true);
}
/** Docker / Local PHP (and the local php program), remembered for the project */
async setRunner(runner, binary) {
try {
this.status = await backend.invoke('console.setRunner', binary === undefined ? { runner } : { runner, binary });
} catch (e) { notify(e.message, 'error', { title: t('Local PHP') }); return; }
this.list = null;
this.load(true);
}
/** what Composer's platform check said: the PHP the dependencies need, and the button that uses it */
renderPlatform(platform) {
if (!platform) return null;
const local = this.status?.runner === 'local';
return el('div.sfc-platform', {},
el('p', {}, t('The dependencies need PHP {need}; the console ran PHP {running}.', { need: platform.need, running: platform.running })),
platform.version ? el('button.btn.primary', { onclick: async () => {
if (local) await backend.invoke('console.setRunner', { runner: 'docker' }).catch(() => null);
this.setPhp(platform.version);
} }, local ? t('Run it in Docker with PHP {version}', { version: platform.version }) : t('Use PHP {version} for this project', { version: platform.version }))
: el('p.pub-faint', {}, t('No PHP version offered fits: change the requirements in composer.json.')));
}
/** every command, by name */
commands() { return (this.list?.groups || []).flatMap((g) => g.commands); }
command(name = this.selected) { return this.commands().find((c) => c.name === name) || null; }
select(name) {
this.selected = name;
prefs.set(this.key('selected'), name);
this.values = { arguments: {}, options: {} };
this.output = null;
this.render();
this.refreshPreview();
}
toggleFavorite(name) {
const favs = this.favorites();
prefs.set(this.key('favs'), favs.includes(name) ? favs.filter((n) => n !== name) : [...favs, name].sort());
this.render();
}
startSite() {
const config = this.app.runner?.configs.find((c) => c.id === 'web:serve');
if (!config) { notify(t('This project has no "Serve the site" run configuration: start its containers yourself.'), 'info'); return; }
this.app.runner.start(config);
// the list again once the site's container answers (2 minutes at most)
clearInterval(this.waiting);
const begun = Date.now();
this.waiting = setInterval(async () => {
const s = await backend.invoke('console.status', {}).catch(() => null);
if (s?.running || Date.now() - begun > 120000) {
clearInterval(this.waiting);
if (s?.running) { this.status = s; this.load(true); }
}
}, 3000);
}
// drawing ---------------------------------------------------------------------------------------------------
render() {
const scroll = this.node.querySelector('.sfc-list')?.scrollTop || 0;
clear(this.node);
this.node.append(this.renderStatus(), this.renderFree());
if (this.error) {
this.node.append(el('div.prof-empty', {},
el('div.prof-empty-title', {}, t('The commands could not be listed')),
el('pre.sfc-error', {}, this.error),
this.renderPlatform(this.platform),
this.status && !this.status.running && this.status.runner !== 'local' && !this.platform ? el('button.btn.primary', { onclick: () => this.startSite() }, t('Start the site')) : null,
el('button.btn', { onclick: () => this.load(true) }, t('Try again'))));
return;
}
if (!this.list) {
this.node.append(el('div.prof-empty', {}, el('p', {}, this.busy ? t('Listing the commands…') : t('No commands yet.'))));
return;
}
const side = this.renderList();
this.node.append(el('div.sfc-main', {}, side, this.renderForm()));
side.querySelector('.sfc-list').scrollTop = scroll;
}
renderStatus() {
const s = this.status;
const app = this.list?.application;
const local = s?.runner === 'local';
const where = !s ? t('Looking for the site…')
: local ? (s.error ? s.error : t('Commands run with the PHP of this computer ({binary}).', { binary: s.binary }))
: s.error && !s.php ? t('{error}: the commands cannot run (Docker runs them).', { error: s.error })
: s.running ? t('The site is running: commands run in its PHP container ({name}).', { name: s.container })
: t('The site is not running: commands run in a temporary container, without its database.');
return el('div.sfc-status' + (s?.running || (local && s.php) ? '.on' : ''), {},
el('span.sfc-dot'),
el('span.sfc-where', {}, where),
s ? this.renderRunner(s) : null,
app ? el('span.sfc-app', {}, `${app.name} ${app.version}`.trim()) : null,
s && !s.running && !local ? el('button.btn.small', { onclick: () => this.startSite() }, t('Start the site')) : null,
this.busy ? el('span.sfc-busy', {}, '…') : null);
}
/** where the console runs: Docker (the project's PHP version) or Local PHP (the program, its version) */
renderRunner(s) {
const local = s.runner === 'local';
const runner = el('select.input.sfc-select', { title: t('Where the commands run'), onchange: (e) => this.setRunner(e.target.value) },
el('option', { value: 'docker', selected: !local }, 'Docker'),
el('option', { value: 'local', selected: local }, t('Local PHP')));
if (local) {
const binary = el('input.input.sfc-binary', { type: 'text', value: s.localPhp || '', placeholder: t('php of the PATH'), spellcheck: false,
title: t('The php program (empty: the one of the PATH)') });
binary.addEventListener('change', () => this.setRunner('local', binary.value.trim()));
return el('span.sfc-runner', {}, runner, binary, s.php ? el('span.sfc-php', { title: s.binary }, `PHP ${s.php}`) : null);
}
const versions = s.available || [];
const why = s.source ? t('PHP of this project: {source}', { source: s.source }) : '';
const php = el('select.input.sfc-select', { title: why, disabled: !versions.length || s.setup === 'compose' && !s.php,
onchange: (e) => this.setPhp(e.target.value) },
el('option', { value: 'auto', selected: !s.setting }, s.setting ? t('Auto (what Composer needs)') : t('PHP {version} (auto)', { version: s.php || '?' })),
...versions.map((v) => el('option', { value: v, selected: s.setting === v }, `PHP ${v}`)));
const setups = { jumphp: t('JumPHP stack'), dunglas: 'symfony-docker', compose: t('service {name}', { name: s.service || 'php' }) };
return el('span.sfc-runner', {}, runner, php,
s.setup ? el('button.btn.small', { title: t('Change the Docker setup (Docker window, Compose tab)'),
onclick: () => { this.app.dockerPanel?.setTab?.('compose'); this.app.showTool?.('docker'); } }, setups[s.setup] || s.setup) : null);
}
/** the free command line: completion of the names, ↑ / ↓ through the history */
renderFree() {
const id = 'sfc-names-' + Math.random().toString(36).slice(2);
const input = el('input.sfc-free', { 'data-tour': 'console-free', type: 'text', placeholder: t('A command, e.g. {example}', { example: this.tool === 'artisan' ? 'migrate --pretend' : 'debug:router' }), list: id, spellcheck: false });
input.setAttribute('list', id);
const names = el('datalist', { id }, ...[...new Set([...this.history(), ...this.commands().map((c) => c.name)])].slice(0, 400).map((n) => el('option', { value: n })));
const go = (here) => {
const line = input.value.trim();
if (!line) return;
prefs.set(this.key('history'), [line, ...this.history().filter((h) => h !== line)].slice(0, 30));
this.historyAt = -1;
input.value = '';
here ? this.runHere({ line }, line) : this.runInTerminal({ line }, line);
};
input.addEventListener('keydown', (e) => {
const h = this.history();
if (e.key === 'Enter') { e.preventDefault(); go(e.ctrlKey || e.metaKey); }
else if (e.key === 'ArrowUp' && h.length) { e.preventDefault(); this.historyAt = Math.min(h.length - 1, this.historyAt + 1); input.value = h[this.historyAt]; }
else if (e.key === 'ArrowDown' && this.historyAt >= 0) { e.preventDefault(); this.historyAt--; input.value = this.historyAt >= 0 ? h[this.historyAt] : ''; }
});
return el('div.sfc-freebar', {},
el('span.sfc-prompt', {}, `php ${this.tool}`), input, names,
el('button.btn.primary', { 'data-tour': 'console-free-run', title: t('Run in a Terminal tab (Enter)'), onclick: () => go(false) }, icon('play'), t('Run')),
el('button.btn', { title: t('Run without questions and show the output here (Ctrl+Enter)'), onclick: () => go(true) }, t('Run here')));
}
renderList() {
const filter = el('input.sfc-filter', { 'data-tour': 'console-filter', type: 'search', placeholder: t('Filter commands'), value: this.filter, spellcheck: false });
const body = el('div.sfc-list');
filter.addEventListener('input', () => { this.filter = filter.value; this.fillList(body); });
this.fillList(body);
return el('div.sfc-side', {}, filter, body);
}
fillList(box) {
clear(box);
const q = this.filter.toLowerCase();
const match = (c) => !q || c.name.toLowerCase().includes(q) || c.description.toLowerCase().includes(q) || c.aliases.some((a) => a.toLowerCase().includes(q));
const row = (c) => {
const fav = this.favorites().includes(c.name);
return el('div.sfc-cmd' + (c.name === this.selected ? '.on' : ''), { 'data-tour': 'console-cmd-' + c.name, title: c.description, onclick: () => this.select(c.name),
ondblclick: () => this.runInTerminal({ command: c.name, ...this.values }, c.name) },
el('button.sfc-star' + (fav ? '.on' : ''), { title: fav ? t('Remove from favorites') : t('Add to favorites'), onclick: (e) => { e.stopPropagation(); this.toggleFavorite(c.name); } }, icon('star')),
el('span.sfc-name', {}, c.name),
el('span.sfc-desc', {}, c.description));
};
const favs = this.favorites().map((n) => this.command(n)).filter((c) => c && match(c));
if (favs.length) box.append(el('div.sfc-group-title', {}, icon('star'), t('Favorites')), ...favs.map(row));
let shown = 0;
for (const g of this.list.groups) {
const commands = g.commands.filter(match);
if (!commands.length) continue;
shown += commands.length;
const open = q !== '' || this.open.has(g.id);
box.append(el('div.sfc-group' + (open ? '.open' : ''), { onclick: () => {
open ? this.open.delete(g.id) : this.open.add(g.id);
prefs.set(this.key('open'), [...this.open]);
this.fillList(box);
} }, el('span.sfc-caret', {}, open ? '▾' : '▸'), el('span', {}, GROUP_LABEL(g.id)), el('span.sfc-count', {}, String(commands.length))));
if (open) box.append(...commands.map(row));
}
if (!shown) box.append(el('p.pub-faint.sfc-none', {}, t('No command matches.')));
}
renderForm() {
const c = this.command();
const box = el('div.sfc-form');
if (!c) {
box.append(el('div.prof-empty', {}, el('p', {}, t('{count} commands. Choose one to see its arguments, its options and its help.', { count: this.list.count }))));
return box;
}
const v = this.values;
const changed = () => this.updatePreview();
const fav = this.favorites().includes(c.name);
box.append(...[el('div.sfc-head', {},
el('h3', {}, c.name),
el('button.sfc-star' + (fav ? '.on' : ''), { title: fav ? t('Remove from favorites') : t('Add to favorites'), onclick: () => this.toggleFavorite(c.name) }, icon('star')),
this.tool === 'bin/console' ? consoleEditButton(this.app, c.name) : null),
c.description ? el('p.sfc-description', {}, c.description) : null,
c.aliases.length ? el('p.pub-faint', {}, t('Aliases: {list}', { list: c.aliases.join(', ') })) : null].filter(Boolean));
if (c.arguments.length) {
box.append(el('h4', {}, t('Arguments')));
for (const a of c.arguments) {
const input = el('input', { 'data-tour': 'console-arg-' + a.name, type: 'text', value: v.arguments[a.name] ?? '', placeholder: a.default || (a.array ? t('several: separated by spaces') : ''), spellcheck: false,
oninput: (e) => { v.arguments[a.name] = e.target.value; changed(); } });
box.append(el('label.sfc-field', {},
el('span.sfc-label', {}, a.name, a.required ? el('b.sfc-req', { title: t('Required') }, ' *') : null, a.array ? el('span.sfc-tag', {}, '…') : null),
input, a.description ? el('span.sfc-hint', {}, a.description) : null));
}
}
const optionField = (o) => {
const name = `--${o.name}` + (o.shortcut ? ` (${o.shortcut})` : '');
if (!o.value) {
return el('label.sfc-check', { title: o.description },
el('input', { type: 'checkbox', checked: !!v.options[o.name], onchange: (e) => { v.options[o.name] = e.target.checked; changed(); } }),
el('span.sfc-label', {}, name), el('span.sfc-hint', {}, o.description));
}
return el('label.sfc-field', {},
el('span.sfc-label', {}, name, o.multiple ? el('span.sfc-tag', {}, '…') : null),
el('input', { type: 'text', value: v.options[o.name] ?? '', spellcheck: false,
placeholder: o.default || (o.multiple ? t('several: separated by spaces') : (o.valueRequired ? '' : t('optional value'))),
oninput: (e) => { v.options[o.name] = e.target.value; changed(); } }),
o.description ? el('span.sfc-hint', {}, o.description) : null);
};
if (c.options.length) box.append(el('h4', {}, t('Options')), ...c.options.map(optionField));
const globals = (this.list.globals || []).filter((o) => o.name !== 'help' && o.name !== 'version');
if (globals.length) {
const d = el('details.sfc-globals', {}, el('summary', {}, t('Global options')), ...globals.map(optionField));
if (globals.some((o) => v.options[o.name])) d.open = true;
box.append(d);
}
this.previewNode = el('code.sfc-preview', {}, this.preview || `php ${this.tool} ${c.name}`);
box.append(el('div.sfc-run', {},
this.previewNode,
el('button.btn', { title: t('Copy the command line'), onclick: () => copyText(this.previewNode.textContent) }, icon('copy')),
el('button.btn.primary', { 'data-tour': 'console-run', title: t('Run in a Terminal tab: interactive commands can ask their questions'), onclick: () => this.runInTerminal({ command: c.name, ...v }, c.name) }, icon('play'), t('Run')),
el('button.btn', { 'data-tour': 'console-run-here', title: t('Run without questions (--no-interaction) and show the output here'), onclick: () => this.runHere({ command: c.name, ...v }, c.name) }, t('Run here'))));
if (this.output && this.output.name === c.name) box.append(this.renderOutput());
if (c.help) box.append(el('h4', {}, t('Help')), el('pre.sfc-help', {}, c.help.replaceAll('%command.name%', c.name).replaceAll('%command.full_name%', `${this.tool} ${c.name}`)));
if (c.usage.length) box.append(el('h4', {}, t('Usage')), el('pre.sfc-help', {}, c.usage.join('\n')));
return box;
}
renderOutput() {
const o = this.output;
if (o.busy) return el('div.sfc-output', {}, el('p.pub-faint', {}, t('Running…')));
return el('div.sfc-output', {},
el('div.sfc-output-head' + (o.code === 0 ? '.ok' : '.ko'), {}, o.error || t('Exit code {code} · {seconds} s', { code: o.code, seconds: o.seconds })),
this.renderPlatform(o.platform),
o.output ? el('pre', {}, o.output) : null);
}
async refreshPreview() {
const c = this.command();
if (!c || !this.previewNode) return;
try {
this.preview = (await backend.invoke('console.preview', { command: c.name, ...this.values })).line;
this.previewNode.textContent = this.preview;
} catch { /* the next change */ }
}
// running ---------------------------------------------------------------------------------------------------
/** In a Terminal tab (docker exec -it in the site's container): the user answers the questions there. */
async runInTerminal(payload, label) {
let r;
try { r = await backend.invoke('console.terminalLine', payload); } catch (e) { notify(e.message, 'error', { title: t('Cannot run {name}', { name: label }) }); return; }
if (!this.app.terminal) { this.runHere(payload, label); return; }
await this.app.docker?.();
const started = this.app.terminal.run(r.line, `${this.tool === 'artisan' ? 'artisan' : 'console'} ${label.split(' ')[0]}`);
this.app.showTool('terminal');
await started;
}
/** Without a terminal (no questions): the output in the window. */
async runHere(payload, label) {
const name = payload.command || this.selected;
this.output = { name, busy: true };
if (payload.line) this.selected = this.command(payload.line.split(/\s+/)[0])?.name || this.selected;
this.output.name = this.selected;
this.render();
try {
const r = await backend.invoke('console.run', payload);
this.output = { name: this.output.name, ...r };
} catch (e) {
this.output = { name: this.output.name, code: -1, error: String(e.message || e) };
}
if (!this.selected) notify(this.output.output || this.output.error || '', this.output.code === 0 ? 'info' : 'error', { title: label });
this.render();
}
}
// Claude's tools (agent.js): the commands of the site and a run without questions
export const consoleAgentTools = {
symfonyConsole() {
if (!this.app.symfonyConsole) throw new Error('no Console window here: the project has no bin/console nor artisan (or the IDE does not run it on this computer)');
return this.app.symfonyConsole;
},
async tool_symfony_commands(args) {
const panel = this.symfonyConsole();
const list = await backend.invoke('console.list', { refresh: !!args.refresh });
panel.list = list; panel.render();
if (args.command) {
const c = list.groups.flatMap((g) => g.commands).find((x) => x.name === args.command || x.aliases.includes(args.command));
if (!c) throw new Error(`no command ${args.command}`);
panel.select(c.name);
return c;
}
const q = String(args.filter || '').toLowerCase();
return {
application: list.application, running: list.running,
commands: list.groups.flatMap((g) => g.commands)
.filter((c) => !q || c.name.toLowerCase().includes(q) || c.description.toLowerCase().includes(q))
.map((c) => ({ name: c.name, description: c.description })),
};
},
async tool_symfony_run(args) {
this.symfonyConsole();
const payload = Array.isArray(args.args) ? { argv: [String(args.command || ''), ...args.args.map(String)].filter((a, i) => i > 0 || a) } : { line: String(args.command || '') };
return backend.invoke('console.run', payload);
},
};