rob-revisited/ide/ui/js/scripts.js

575 lines
33 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 Scripts window: the project's own scripts (a shell body with variables, kept in .jumphp/scripts.json, or
// .jumphp/scripts.local.json for "this computer only") and the tasks its runners already have (Makefile targets, Castor
// tasks, composer.json / package.json scripts, justfile recipes, Taskfile tasks). Each one runs in a Terminal tab, the
// Run window or in the background, and can be pinned to the tool bar, given a shortcut (an action: Search Everywhere,
// the Tools menu), be a run configuration, and run by itself on save of matching files, when the project opens or
// before a run configuration — the last three only once the project is trusted (workspace trust, asked once).
// The PHP side: ide/src/Scripts (ScriptCommands, TaskDetector, ScriptShell, ScriptStore, ScriptTrust, Castor).
import { backend } from './backend.js';
import { el, clear, icon, menu, dialog, confirm, notify, prompt, prefs, t, kbd } from './ui.js';
import { monaco } from './editor.js';
import { openCastorWizard, castorMenuItems } from './command-wizard.js';
const ICONS = ['zap', 'play', 'test', 'debug', 'bug', 'terminal', 'console', 'refresh', 'check', 'package', 'download', 'upload', 'container', 'database', 'server',
'globe', 'code', 'design', 'game', 'disk', 'trash', 'settings', 'star', 'snowflake', 'profile', 'board', 'plugin', 'search', 'file', 'folder', 'history', 'camera', 'bell', 'eye', 'log', 'branch', 'push', 'pull'];
const EMOJI = ['🚀', '🧪', '🧹', '🔨', '📦', '🐘', '🐳', '🔥', '✨', '📝', '🔄', '⚙️', '🗄️', '🌐', '🧰', '🎨', '🔒', '📊'];
const RUNNER_ICONS = { make: 'settings', castor: 'zap', composer: 'package', npm: 'package', just: 'play', task: 'check' };
const VARIABLES = ['${file}', '${dir}', '${project}', '${selection}', '${line}', '${fileName}', '${relativeFile}', '${input:Label}'];
/** An icon of the IDE (by name) or an emoji. */
export function scriptIcon(name) {
return /^[a-z][A-Za-z]*$/.test(name || '') ? icon(name) : el('span.scr-emoji', {}, name || '⚡');
}
/** 'Ctrl+Alt+M' -> 'ctrl+alt+m', as the IDE's key handler writes keys (app.js bindKeys). */
export function keyOf(text) {
const parts = String(text || '').toLowerCase().split('+').map((p) => p.trim()).filter(Boolean);
const key = parts.filter((p) => !['ctrl', 'cmd', 'alt', 'shift'].includes(p)).pop();
if (!key) return null;
return [parts.includes('ctrl') || parts.includes('cmd') ? 'ctrl' : '', parts.includes('alt') ? 'alt' : '', parts.includes('shift') ? 'shift' : '', key].filter(Boolean).join('+');
}
/** A key press as 'Ctrl+Shift+B' (null: a modifier alone). */
function keyText(e) {
if (['Control', 'Shift', 'Alt', 'Meta'].includes(e.key)) return null;
const key = e.key.length === 1 ? e.key.toUpperCase() : e.key;
return [e.ctrlKey || e.metaKey ? 'Ctrl' : '', e.altKey ? 'Alt' : '', e.shiftKey ? 'Shift' : '', key].filter(Boolean).join('+');
}
/** The ${input:Label} of a command, each once. */
export function inputLabels(command) {
return [...new Set([...String(command || '').matchAll(/\$\{input:([^}]+)\}/g)].map((m) => m[1].trim()))];
}
/** A glob of the "on save" event against a project path (same rules as ScriptStore::globMatches). */
export function globMatches(glob, path) {
return String(glob || '').split(/\s*[,;]\s*/).filter(Boolean).some((one) => {
let re = '';
for (let i = 0; i < one.length; i++) {
const c = one[i];
if (c === '*' && one[i + 1] === '*') { if (one[i + 2] === '/') { re += '(?:.*/)?'; i += 2; } else { re += '.*'; i += 1; } }
else if (c === '*') re += '[^/]*';
else if (c === '?') re += '[^/]';
else re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
}
return new RegExp('^' + re + '$').test(one.includes('/') ? path : path.split('/').pop());
});
}
export class ScriptsPanel {
constructor(app) {
this.app = app;
this.node = el('div.scr-view');
this.data = null;
this.error = null;
this.filter = '';
this.closed = new Set(prefs.get(`scripts:closed:${app.projectKey}`, []));
this.actionIds = [];
this.boundKeys = [];
this.running = new Set(); // scripts started by an event, not started again until they end
this.openDone = false;
app.editors?.on('saved', (path) => this.onSaved(path));
this.render();
this.load();
}
title() { return 'Scripts'; }
actions() {
return [
el('button', { title: t('New Script…'), onclick: () => this.edit(null) }, icon('plus')),
el('button', { title: t('Refresh'), onclick: () => this.load(true) }, icon('refresh')),
el('button', { title: t('More'), onclick: (e) => this.moreMenu(e.currentTarget) }, icon('more')),
];
}
moreMenu(at) {
const d = this.data || {};
menu([
{ label: t('New Script…'), icon: 'plus', action: () => this.edit(null) },
{ label: t('New Castor Task…'), icon: 'zap', action: () => this.newCastorTask() },
...(d.castor?.present && !d.castor?.installed && d.castor?.installable ? [{ label: t('Install Castor…'), icon: 'download', action: () => this.installCastor() }] : []),
'-',
d.trusted ? { label: t('Stop Trusting This Project'), icon: 'close', action: () => this.setTrust(false) }
: { label: t('Trust This Project…'), icon: 'check', action: () => this.askTrust() },
], at);
}
async load(refresh = false) {
try {
this.data = await backend.invoke('scripts.list', { refresh });
this.error = null;
} catch (e) {
this.error = String(e.message || e);
}
this.render();
this.sync();
if (!this.openDone && this.data) {
this.openDone = true;
this.onOpen();
}
}
// what there is ------------------------------------------------------------------------------------------------
/** every script and task, as one list of {ref, name, help, icon, command, runIn, kind, binding, script, task, runner} */
items() {
const d = this.data;
if (!d) return [];
const out = d.scripts.map((s) => ({ ref: `script:${s.id}`, name: s.name, help: s.command.split('\n')[0], icon: s.icon, command: s.command, runIn: s.runIn,
key: s.key, pin: s.pin, events: s.events, script: s, kind: 'script' }));
for (const g of d.groups) {
for (const task of g.tasks) {
const b = d.bindings[task.ref] || {};
out.push({ ref: task.ref, name: task.name, help: task.help, icon: b.icon || RUNNER_ICONS[g.id] || 'zap', command: task.command, runIn: b.runIn || 'run',
key: b.key || '', pin: !!b.pin, events: b.events || { save: '', open: false, before: [] }, binding: b, task, runner: g.id, kind: 'task' });
}
}
return out;
}
item(ref) { return this.items().find((i) => i.ref === ref) || null; }
/** Actions (Search Everywhere, Tools menu, shortcuts), tool bar buttons and run configurations follow the list. */
sync() {
const a = this.app.actions;
const map = this.app.keyMap;
for (const id of this.actionIds) a?.items.delete(id);
for (const k of this.boundKeys) if (map && String(map[k] || '').startsWith('scripts.')) delete map[k];
this.actionIds = [];
this.boundKeys = [];
const configs = [];
for (const i of this.items()) {
if (i.kind !== 'script' && !i.key && !i.pin) continue;
const id = `scripts.${i.ref}`;
a?.add(id, t('Run Script: {name}', { name: i.name }), () => this.run(i.ref), { kbd: i.key || undefined, icon: /^[a-z]/.test(i.icon) ? i.icon : 'zap' });
this.actionIds.push(id);
const k = i.key && keyOf(i.key);
if (k && map && !map[k]) { map[k] = id; this.boundKeys.push(k); }
configs.push({ id, label: i.name, group: t('Scripts'), icon: /^[a-z]/.test(i.icon) ? i.icon : 'zap', kind: 'script', script: i.ref, command: [i.command] });
}
const runner = this.app.runner;
if (runner) {
runner.configs = [...runner.configs.filter((c) => !c.script), ...configs];
if (!runner.config() && runner.configs.length) runner.selected = runner.configs[0].id;
this.app.updateRunWidget?.();
}
if (configs.length) document.getElementById('runWidget')?.removeAttribute('hidden');
this.renderToolbar();
}
renderToolbar() {
const box = document.getElementById('scriptButtons');
if (!box) return;
clear(box);
const pinned = this.items().filter((i) => i.pin);
box.hidden = !pinned.length;
for (const i of pinned) {
box.append(el('button.hbtn.scr-pin', { title: i.name + (i.key ? ` (${kbd(i.key)})` : ''), dataset: { ref: i.ref },
onclick: () => this.run(i.ref), oncontextmenu: (e) => { e.preventDefault(); this.itemMenu(i, e.currentTarget); } }, scriptIcon(i.icon)));
}
}
// drawing ---------------------------------------------------------------------------------------------------
render() {
const scroll = this.node.querySelector('.scr-list')?.scrollTop || 0;
clear(this.node);
const d = this.data;
if (this.error) {
this.node.append(el('div.prof-empty', {}, el('div.prof-empty-title', {}, t('The scripts could not be listed')), el('pre.sfc-error', {}, this.error),
el('button.btn', { onclick: () => this.load(true) }, t('Try again'))));
return;
}
if (!d) { this.node.append(el('div.prof-empty', {}, el('p', {}, t('Looking for scripts…')))); return; }
if (d.needsTrust && !d.trusted) {
this.node.append(el('div.scr-trust', {}, icon('warning'),
el('span', {}, t('Some scripts of this project run by themselves (on save, on open, before a run). They stay off until you trust this project.')),
el('button.btn.small.primary', { onclick: () => this.askTrust() }, t('Trust…'))));
}
const filter = el('input.sfc-filter', { type: 'search', placeholder: t('Filter scripts'), value: this.filter, spellcheck: false });
const list = el('div.scr-list');
filter.addEventListener('input', () => { this.filter = filter.value; this.fill(list); });
this.node.append(el('div.scr-bar', {}, filter,
el('button.btn.small', { title: t('A shell script of this project, with variables, an icon and a shortcut'), onclick: () => this.edit(null) }, icon('plus'), t('New Script…'))), list);
this.fill(list);
list.scrollTop = scroll;
}
fill(list) {
clear(list);
const d = this.data;
const q = this.filter.toLowerCase();
const match = (i) => !q || i.name.toLowerCase().includes(q) || String(i.help || '').toLowerCase().includes(q);
const section = (id, title, file, items, extra = null) => {
const shown = items.filter(match);
if (!shown.length && !extra && id !== 'own') return;
const open = q !== '' || !this.closed.has(id);
list.append(el('div.sfc-group' + (open ? '.open' : ''), { onclick: () => {
open ? this.closed.add(id) : this.closed.delete(id);
prefs.set(`scripts:closed:${this.app.projectKey}`, [...this.closed]);
this.fill(list);
} }, el('span.sfc-caret', {}, open ? '▾' : '▸'), el('span', {}, title), file ? el('span.scr-file', {}, file) : null, el('span.sfc-count', {}, String(shown.length))));
if (!open) return;
if (extra) list.append(extra);
list.append(...shown.map((i) => this.row(i)));
if (id === 'own' && !items.length) list.append(el('p.pub-faint.scr-none', {}, t('No script yet: + makes one (a shell script with ${file}, ${selection}…, an icon, a shortcut).')));
};
const all = this.items();
section('own', t('Project scripts'), '.jumphp/scripts.json', all.filter((i) => i.kind === 'script'));
for (const g of d.groups) {
let extra = null;
if (g.id === 'castor' && !d.castor.installed) {
extra = el('div.scr-note', {}, t('Castor is not installed: its tasks are read from {file} and run with castor.', { file: g.file }),
d.castor.installable ? el('button.btn.small', { onclick: () => this.installCastor() }, icon('download'), t('Install Castor…')) : null);
} else if (g.id === 'castor' && !g.listed && d.castor.error) {
extra = el('div.scr-note', { title: d.castor.error }, t('castor list failed: the tasks are read from {file}.', { file: g.file }));
} else if (g.id === 'castor' && !d.trusted) {
extra = el('div.scr-note', {}, t('Read from {file} without running it: trust the project to ask castor itself.', { file: g.file }));
}
section(g.id, g.label, g.file, all.filter((i) => i.kind === 'task' && i.runner === g.id), extra);
}
if (!d.groups.length) list.append(el('p.pub-faint.scr-none', {}, t('No Makefile, castor.php, composer.json scripts, package.json scripts, justfile nor Taskfile here.')));
}
row(i) {
const events = i.events || {};
const auto = [events.save ? t('on save of {glob}', { glob: events.save }) : '', events.open ? t('on open') : '', events.before?.length ? t('before {n} run configuration(s)', { n: events.before.length }) : ''].filter(Boolean);
return el('div.scr-row', { title: i.command, ondblclick: () => this.run(i.ref), oncontextmenu: (e) => { e.preventDefault(); this.itemMenu(i, e); } },
el('span.scr-icon', {}, scriptIcon(i.icon)),
el('span.scr-main', {},
el('span.scr-name', {}, i.name,
i.script?.local ? el('span.scr-badge', { title: t('On this computer only (.jumphp/scripts.local.json)') }, t('Local')) : null,
i.script?.docker ? el('span.scr-badge', { title: t('Runs in the site\'s PHP container') }, 'docker') : null,
i.key ? el('span.scr-badge.key', {}, kbd(i.key)) : null,
auto.length ? el('span.scr-badge.auto' + (this.data.trusted ? '' : '.off'), { title: this.data.trusted ? '' : t('Off until the project is trusted') }, auto.join(' · ')) : null),
i.help ? el('span.scr-help', {}, i.help) : null),
el('button.scr-btn' + (i.pin ? '.on' : ''), { title: i.pin ? t('Unpin from the tool bar') : t('Pin to the tool bar'), onclick: (e) => { e.stopPropagation(); this.togglePin(i); } }, icon('star')),
i.kind === 'script' ? el('button.scr-btn', { title: t('Edit'), onclick: (e) => { e.stopPropagation(); this.edit(i.script); } }, icon('edit')) : null,
el('button.scr-btn.run', { title: t('Run'), onclick: (e) => { e.stopPropagation(); this.run(i.ref); } }, icon('play')));
}
itemMenu(i, at) {
const where = (runIn) => this.run(i.ref, { runIn });
menu([
{ head: i.name },
{ label: t('Run'), icon: 'play', kbd: i.key ? kbd(i.key) : '', action: () => this.run(i.ref) },
{ label: t('Run in a Terminal Tab'), icon: 'terminal', action: () => where('terminal') },
{ label: t('Run in the Run Window'), icon: 'play', action: () => where('run') },
{ label: t('Run in the Background'), icon: 'zap', action: () => where('background') },
'-',
{ label: i.pin ? t('Unpin from the tool bar') : t('Pin to the tool bar'), icon: 'star', action: () => this.togglePin(i) },
{ label: t('Shortcut, Icon and Events…'), icon: 'settings', action: () => (i.kind === 'script' ? this.edit(i.script) : this.editBinding(i)) },
...(i.kind === 'script' ? [{ label: t('Edit…'), icon: 'edit', action: () => this.edit(i.script) },
{ label: t('Delete'), icon: 'trash', action: () => this.remove(i.script) }]
: [{ label: t('Make a Script from It…'), icon: 'plus', action: () => this.edit({ name: i.name, icon: i.icon, command: i.command, runIn: i.runIn }) },
...(i.task?.runner === 'make' || i.runner === 'make' ? [{ label: t('Open the Makefile'), icon: 'file', action: () => this.openFile(i.runner) }] : []),
...(i.runner === 'castor' ? [{ label: t('Open castor.php'), icon: 'file', action: () => this.openFile(i.runner) }, ...castorMenuItems(this.app, i.name)] : [])]),
], at instanceof Event ? { x: at.clientX, y: at.clientY } : at);
}
openFile(runner) {
const g = this.data.groups.find((x) => x.id === runner);
if (g) this.app.editors.open(g.file);
}
// running ---------------------------------------------------------------------------------------------------
/** What the editor shows: the file (relative to the project), the line, the selection. */
context() {
const path = this.app.editors?.activePath?.();
const editor = this.app.editors?.editor?.();
const sel = editor?.getSelection?.();
return {
file: path && !path.startsWith('/') && !path.includes('://') ? path : null,
line: editor?.getPosition?.()?.lineNumber ?? null,
selection: sel && !sel.isEmpty() ? editor.getModel().getValueInRange(sel) : '',
};
}
/**
* Runs a script or a task. event: 'save' | 'open' | 'before' (only in a trusted project). Resolves with true when it
* ended well (or was started in a terminal / the Run window), false when it failed or was not run.
*/
async run(ref, { event = null, runIn = null, wait = false, args = null } = {}) {
const item = this.item(ref);
if (!item) { notify(t('No script {name} in this project.', { name: ref }), 'error'); return false; }
if (event && !this.data?.trusted) return false;
const inputs = {};
for (const label of inputLabels(item.command)) {
const value = await prompt(t('Run {name}', { name: item.name }), { label });
if (value === null) return false;
inputs[label] = value;
}
const payload = { ref, context: this.context(), inputs, event, runIn: runIn || undefined, args: args || undefined };
let prepared;
try {
prepared = await backend.invoke('scripts.prepare', payload);
} catch (e) {
notify(e.message, 'error', { title: t('Cannot run {name}', { name: item.name }) });
return false;
}
if (prepared.confirm && !(await confirm(t('Run {name}?', { name: item.name }), el('pre.scr-confirm', {}, prepared.command), { ok: t('Run') }))) return false;
let mode = runIn || prepared.runIn;
if (wait && mode === 'terminal') mode = 'background'; // a terminal cannot be waited for (before a run)
if (mode === 'terminal' && this.app.terminal) {
if (!event) await this.app.editors.saveAll(true);
const started = this.app.terminal.run(prepared.line, prepared.label);
this.app.showTool('terminal');
await started;
return true;
}
if (mode === 'background') {
const task = this.app.task?.(t('Running {name}…', { name: prepared.label }));
try {
const r = await backend.invoke('scripts.background', payload);
const ok = r.code === 0;
if (!ok || !event) {
notify(r.output ? r.output.split('\n').slice(-6).join('\n') : t('Exit code {code} · {seconds} s', { code: r.code, seconds: r.seconds }), ok ? 'success' : 'error',
{ title: ok ? t('{name}: done in {seconds} s', { name: r.label, seconds: r.seconds }) : t('{name} ended with code {code}', { name: r.label, code: r.code }) });
}
return ok;
} catch (e) {
notify(e.message, 'error', { title: t('Cannot run {name}', { name: item.name }) });
return false;
} finally { task?.(); }
}
const config = { id: 'adhoc', kind: 'tool', label: prepared.label, command: prepared.argv };
if (wait) {
const end = await this.app.runner.startAndWait(config);
return !!end && end.code === 0;
}
return (await this.app.runner.start(config)) !== null;
}
/** On save: the scripts whose glob matches the file (one at a time per script). */
onSaved(path) {
if (!this.data?.trusted || !path || path.startsWith('/') || path.startsWith('.jumphp/')) return;
for (const i of this.items()) {
if (!i.events?.save || !globMatches(i.events.save, path) || this.running.has(i.ref)) continue;
this.running.add(i.ref);
this.run(i.ref, { event: 'save' }).finally(() => this.running.delete(i.ref));
}
}
onOpen() {
if (!this.data?.trusted) return;
for (const i of this.items()) if (i.events?.open) this.run(i.ref, { event: 'open' });
}
/** Before a run configuration: its "before launch" scripts, in order; false stops the run. */
async beforeLaunch(config) {
const before = this.items().filter((i) => i.events?.before?.includes(config.id));
if (!before.length) return true;
if (!this.data?.trusted) {
notify(t('The scripts before {name} did not run: this project is not trusted.', { name: config.label }), 'warning', { actions: [{ label: t('Trust…'), action: () => this.askTrust() }] });
return true;
}
for (const i of before) {
if (!(await this.run(i.ref, { event: 'before', wait: true }))) {
notify(t('{script} failed: {name} was not started.', { script: i.name, name: config.label }), 'error', { title: t('Before launch') });
return false;
}
}
return true;
}
// trust -----------------------------------------------------------------------------------------------------
async askTrust() {
const yes = await confirm(t('Trust this project?'), el('div', {},
el('p', {}, t('A trusted project runs its scripts by themselves: on save of matching files, when it opens and before run configurations, and castor list reads its castor.php by running it.')),
el('p', {}, t('Trust it only if you trust where it comes from: scripts committed in .jumphp/scripts.json are shell commands of whoever wrote them.')),
el('p.pub-faint', {}, this.app.project?.root || '')), { ok: t('Trust the Project') });
if (yes) await this.setTrust(true);
return yes;
}
async setTrust(on) {
try { await backend.invoke('scripts.trust', { on }); } catch (e) { notify(e.message, 'error'); return; }
await this.load(true);
}
// editing ---------------------------------------------------------------------------------------------------
async togglePin(i) {
try {
if (i.kind === 'script') await backend.invoke('scripts.save', { script: { ...i.script, pin: !i.pin } });
else await backend.invoke('scripts.bind', { ref: i.ref, binding: { ...(i.binding || {}), pin: !i.pin } });
} catch (e) { notify(e.message, 'error'); return; }
await this.load();
}
async remove(script) {
if (!(await confirm(t('Delete the script {name}?', { name: script.name }), script.command, { ok: t('Delete'), danger: true }))) return;
try { await backend.invoke('scripts.remove', { id: script.id }); } catch (e) { notify(e.message, 'error'); return; }
await this.load();
}
/** The icon chooser: the IDE's icons, emoji, or any emoji typed. */
iconPicker(value, onChange) {
const current = el('button.btn.scr-icon-btn', { type: 'button', title: t('Icon') }, scriptIcon(value));
const grid = el('div.scr-icons');
const set = (v) => { value = v; current.replaceChildren(scriptIcon(v)); onChange(v); for (const b of grid.children) b.classList.toggle('on', b.dataset.v === v); };
for (const v of [...ICONS, ...EMOJI]) grid.append(el('button.scr-icon-choice' + (v === value ? '.on' : ''), { type: 'button', title: v, dataset: { v }, onclick: () => set(v) }, scriptIcon(v)));
const custom = el('input.input.scr-emoji-input', { placeholder: t('or an emoji'), maxLength: 8, oninput: (e) => { if (e.target.value.trim()) set(e.target.value.trim()); } });
return el('div.scr-iconpick', {}, current, grid, custom);
}
/** A field that records a key press as a shortcut. */
shortcutField(value, onChange) {
const input = el('input.input.scr-key', { value: value || '', placeholder: t('Press keys, e.g. Ctrl+Alt+B'), readOnly: true });
input.addEventListener('keydown', (e) => {
if (e.key === 'Tab') return;
e.preventDefault(); e.stopPropagation();
if ((e.key === 'Backspace' || e.key === 'Delete') && !e.ctrlKey && !e.altKey) { input.value = ''; onChange(''); return; }
const k = keyText(e);
if (!k) return;
input.value = k;
onChange(k);
const taken = this.app.keyMap?.[keyOf(k)];
input.title = taken && !String(taken).startsWith('scripts.') ? t('Already used by the IDE ({action}): the IDE keeps it.', { action: taken }) : '';
input.classList.toggle('warn', !!input.title);
});
return el('div.scr-keyrow', {}, input, el('button.btn.small', { type: 'button', onclick: () => { input.value = ''; onChange(''); } }, t('Clear')));
}
/** The events: on save of a glob, on open, before run configurations. */
eventsFields(events, onChange) {
const ev = { save: events?.save || '', open: !!events?.open, before: [...(events?.before || [])] };
const configs = (this.app.runner?.configs || []).filter((c) => !c.script);
const emit = () => onChange(ev);
return el('div.scr-events', {},
el('label.field', {}, el('span', {}, t('Run when a file matching this glob is saved (e.g. *.scss, src/**/*.php)')),
el('input.input', { value: ev.save, placeholder: '*.scss', spellcheck: false, oninput: (e) => { ev.save = e.target.value; emit(); } })),
el('label.scr-check', {}, el('input', { type: 'checkbox', checked: ev.open, onchange: (e) => { ev.open = e.target.checked; emit(); } }), t('Run when the project opens')),
configs.length ? el('details.scr-before' + (ev.before.length ? '' : ''), { open: ev.before.length > 0 }, el('summary', {}, t('Run before these run configurations (it must succeed)')),
...configs.map((c) => el('label.scr-check', {}, el('input', { type: 'checkbox', checked: ev.before.includes(c.id), onchange: (e) => {
ev.before = e.target.checked ? [...ev.before, c.id] : ev.before.filter((x) => x !== c.id); emit();
} }), c.group ? `${c.group} › ${c.label}` : c.label))) : null,
this.data?.trusted ? null : el('p.pub-faint.scr-warn', {}, icon('warning'), t('This project is not trusted: events stay off until you trust it.')));
}
/** A Monaco editor in a dialog (shell or PHP), a textarea when Monaco is not there. */
codeEditor(host, value, language) {
if (!monaco) {
const area = el('textarea.input.scr-code-fallback', { value, spellcheck: false, rows: 8 });
host.append(area);
return { getValue: () => area.value, dispose: () => null };
}
const model = monaco.editor.createModel(value, language);
const editor = monaco.editor.create(host, {
model, minimap: { enabled: false }, lineNumbers: 'on', glyphMargin: false, folding: false, scrollBeyondLastLine: false, automaticLayout: true, fontSize: 13,
renderLineHighlight: 'none', overviewRulerLanes: 0, tabSize: 2,
theme: document.documentElement.dataset.theme === 'light' ? 'jumphp-light' : 'jumphp-dark',
});
return { getValue: () => model.getValue(), dispose: () => { editor.dispose(); model.dispose(); }, editor };
}
/** The editor of a script (new: null, or a prefilled object without id). */
edit(script) {
const s = { name: '', icon: 'zap', command: '', runIn: 'terminal', cwd: '', env: {}, docker: false, confirm: false, local: false, pin: false, key: '', events: { save: '', open: false, before: [] }, ...(script || {}) };
const isNew = !s.id;
const name = el('input.input', { value: s.name, placeholder: t('e.g. Build the assets'), oninput: (e) => { s.name = e.target.value; } });
const codeHost = el('div.scr-code');
const envText = el('textarea.input.scr-env', { rows: 3, spellcheck: false, placeholder: 'APP_ENV=dev', value: Object.entries(s.env || {}).map(([k, v]) => `${k}=${v}`).join('\n') });
const select = el('select.input', { onchange: (e) => { s.runIn = e.target.value; } },
...[['terminal', t('A Terminal tab (interactive)')], ['run', t('The Run window')], ['background', t('In the background, with a notification')]]
.map(([v, label]) => el('option', { value: v, selected: s.runIn === v }, label)));
const check = (key, label, title = '') => el('label.scr-check', { title }, el('input', { type: 'checkbox', checked: !!s[key], onchange: (e) => { s[key] = e.target.checked; } }), label);
const body = el('div.scr-edit', {},
el('div.scr-edit-top', {}, el('label.field.scr-grow', {}, el('span', {}, t('Script name')), name), el('div.field', {}, el('span', {}, t('Icon')), this.iconPicker(s.icon, (v) => { s.icon = v; }))),
el('div.field', {}, el('span', {}, t('Commands (a shell script, several lines)')), codeHost,
el('span.scr-vars', {}, t('Variables you can use:'), ' ', ...VARIABLES.map((v) => el('code', { title: t('Click to insert'), onclick: () => this.insert(editor, v) }, v)))),
el('div.scr-edit-grid', {},
el('label.field', {}, el('span', {}, t('Where it runs')), select),
el('label.field', {}, el('span', {}, t('Working folder (in the project)')), el('input.input', { value: s.cwd, placeholder: '.', spellcheck: false, oninput: (e) => { s.cwd = e.target.value; } }))),
el('label.field', {}, el('span', {}, t('Environment (NAME=value, one per line)')), envText),
el('div.scr-checks', {},
this.data?.site ? check('docker', t('Run in the site\'s PHP container (docker exec)'), t('The site must be running (Serve the site); paths become /app/...')) : null,
check('confirm', t('Ask before running')),
check('local', t('On this computer only (not committed)'), '.jumphp/scripts.local.json'),
check('pin', t('Pin to the tool bar'))),
el('details.scr-section', { open: !!(s.key || s.events.save || s.events.open || s.events.before.length) }, el('summary', {}, t('Shortcut and events')),
el('div.field', {}, el('span', {}, t('Keyboard shortcut')), this.shortcutField(s.key, (k) => { s.key = k; })),
this.eventsFields(s.events, (ev) => { s.events = ev; })));
let editor = null;
const collect = () => {
s.command = editor.getValue();
s.env = Object.fromEntries(envText.value.split('\n').map((l) => l.trim()).filter((l) => l && l.includes('=')).map((l) => [l.slice(0, l.indexOf('=')).trim(), l.slice(l.indexOf('=') + 1)]));
return s;
};
const save = async () => {
const script = collect();
const auto = script.events.save || script.events.open || script.events.before.length;
if (auto && !this.data?.trusted) await this.askTrust();
const saved = await backend.invoke('scripts.save', { script });
Object.assign(s, saved);
await this.load();
return saved;
};
const d = dialog({
title: isNew ? t('New Script') : t('Edit the Script {name}', { name: s.name }), wide: true, sticky: true,
body,
buttons: [
...(isNew ? [] : [{ label: t('Delete'), danger: true, action: async () => { await this.remove(s); } }]),
{ label: t('Run Now'), action: async () => { const saved = await save(); this.run(`script:${saved.id}`); return false; } },
{ label: t('Cancel') },
{ label: t('Save'), primary: true, action: async () => { await save(); } },
],
onClose: () => editor?.dispose(),
});
d.box.classList.add('scr-dialog');
editor = this.codeEditor(codeHost, s.command || (isNew ? '# ${file} is the file open in the editor, ${input:Message} asks a value\necho "Hello from ${project}"\n' : ''), 'shell');
return d;
}
insert(editor, text) {
const e = editor?.editor;
if (!e) return;
e.executeEdits('scripts', [{ range: e.getSelection(), text, forceMoveMarkers: true }]);
e.focus();
}
/** A detected task: its icon, where it runs, pin, shortcut and events (kept on this computer). */
editBinding(i) {
const b = { pin: !!i.pin, key: i.key || '', icon: i.binding?.icon || '', runIn: i.binding?.runIn || '', events: i.events };
const select = el('select.input', { onchange: (e) => { b.runIn = e.target.value; } },
...[['', t('The Run window')], ['terminal', t('A Terminal tab (interactive)')], ['background', t('In the background, with a notification')]]
.map(([v, label]) => el('option', { value: v, selected: b.runIn === v }, label)));
const body = el('div.scr-edit', {},
el('p.pub-faint', {}, el('code', {}, i.command)),
el('div.field', {}, el('span', {}, t('Icon')), this.iconPicker(i.icon, (v) => { b.icon = v; })),
el('label.field', {}, el('span', {}, t('Where it runs')), select),
el('label.scr-check', {}, el('input', { type: 'checkbox', checked: b.pin, onchange: (e) => { b.pin = e.target.checked; } }), t('Pin to the tool bar')),
el('div.field', {}, el('span', {}, t('Keyboard shortcut')), this.shortcutField(b.key, (k) => { b.key = k; })),
this.eventsFields(b.events, (ev) => { b.events = ev; }),
el('p.pub-faint', {}, t('Kept on this computer only (.jumphp/scripts.local.json).')));
dialog({
title: t('{name}: Shortcut, Icon and Events', { name: i.name }), body,
buttons: [{ label: t('Cancel') }, { label: t('Save'), primary: true, action: async () => {
if ((b.events.save || b.events.open || b.events.before.length) && !this.data?.trusted) await this.askTrust();
await backend.invoke('scripts.bind', { ref: i.ref, binding: b });
await this.load();
} }],
});
}
/** A new Castor task, context or listener: the wizard (ide/ui/js/command-wizard.js). */
newCastorTask() { return openCastorWizard(this.app); }
async installCastor() {
const yes = await confirm(t('Install Castor?'), el('div', {},
el('p', {}, t('The IDE downloads the static castor program of its newest release (github.com/jolicode/castor), checks it against the release\'s SHA256SUMS, and puts it in ~/.jumphp/bin.')),
el('p.pub-faint', {}, 'https://castor.jolicode.com')), { ok: t('Download and Install') });
if (!yes) return;
const task = this.app.task?.(t('Installing Castor…'));
try {
const r = await backend.invoke('scripts.castorInstall', {});
notify(t('Castor is installed: {path}', { path: r.path }), 'success', { title: 'Castor' });
await this.load(true);
} catch (e) {
notify(e.message, 'error', { title: 'Castor' });
} finally { task?.(); }
}
}