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

367 lines
22 KiB
JavaScript

// The Events window (Symfony): listen to an event without remembering its name, its constant or its event class. The picker lists
// the framework's events (kernel, security, forms, console, Messenger workers, Mailer, Doctrine lifecycle; only those of the
// installed packages) and the project's own (event classes of src/ and what src/ dispatches), searchable. For the event chosen:
// who listens to it, where it is dispatched, and a form that writes an EventSubscriber, an #[AsEventListener] listener, a Doctrine
// #[AsDoctrineListener] / #[AsEntityListener] listener, or adds a method to an existing class (several events in one new class).
// "New event": the event class (properties), the dispatch call inserted in a method (EventDispatcherInterface injected), a listener.
// The "Listeners" tab: who listens to what in which order, from the code (priorities editable, a subscription removed) or from
// the application (debug:event-dispatcher --format=json through the Console window's runner: vendors included); a click opens it.
// Every change is a diff first (php-parser, format-preserving), written on "Write the files".
// The PHP side: ide/src/Symfony/EventCommands.php (EventCatalog, EventListeners, EventCode).
import { backend } from './backend.js';
import { el, clear, icon, notify, prefs, t } from './ui.js';
/** the window's own stylesheet (ide/ui/css/symfony-events.css), shared with the Messenger window */
export function symfonyStyles() {
if (document.getElementById('symfony-events-css')) return;
document.head.append(el('link', { id: 'symfony-events-css', rel: 'stylesheet', href: 'css/symfony-events.css' }));
}
const short = (cls) => String(cls || '').split('\\').pop();
/**
* The files a tool proposes to write, as a list: each one's diff in an editor tab, then "Write the files" (the backend checks
* that they did not change since).
*/
export class ChangesView {
constructor(app, applyCommand, onWritten) { this.app = app; this.applyCommand = applyCommand; this.onWritten = onWritten; this.changes = null; this.node = el('div'); }
show(changes) {
this.changes = changes;
this.render();
if (changes.length) this.diff(changes[0]);
}
hide() { this.changes = null; this.render(); }
diff(c) {
this.app.editors.openDiff(c.path, { original: c.before, modified: c.after, readOnly: true, title: `${c.path} (${c.create ? t('new file') : t('changes')})` }).catch((e) => notify(e.message, 'error'));
}
async write() {
try {
const r = await backend.invoke(this.applyCommand, { changes: this.changes });
notify(t('{n} files written', { n: r.written.length }), 'info');
this.changes = null;
this.render();
this.app.editors.reloadFromDisk?.();
this.app.tree?.refresh?.();
if (r.written[0]) this.app.editors.open(r.written[0]).catch(() => null);
this.onWritten?.(r);
} catch (e) { notify(e.message, 'error'); }
}
render() {
clear(this.node);
if (!this.changes) return;
this.node.append(el('div.sft-changes', {},
el('div.sft-changes-title', {}, t('Changes')),
...this.changes.map((c) => el('div.sft-change', {},
el('span.sft-badge' + (c.create ? '.new' : ''), {}, c.create ? t('new file') : t('edit')),
el('span.sft-path', {}, c.path),
el('button.btn.small', { onclick: () => this.diff(c) }, icon('diff'), t('Diff')))),
el('div.sft-row', {},
el('button.btn.primary', { onclick: () => this.write() }, t('Write the files')),
el('button.btn', { onclick: () => this.hide() }, t('Cancel')))));
}
}
/** a link that opens a file of the project at a line */
export function fileLink(app, file, line, text) {
return el('a.sft-link', { href: '#', title: `${file}:${line || 1}`, onclick: (e) => { e.preventDefault(); app.editors.open(file, line ? { line } : {}).catch((err) => notify(err.message, 'error')); } }, text);
}
const KINDS = [
['subscriber', 'New EventSubscriber'],
['listener', 'New listener (#[AsEventListener] on methods)'],
['listener-class', 'New listener (#[AsEventListener] on the class)'],
['add', 'Add to an existing class'],
];
const DOCTRINE_KINDS = [['doctrine', 'New Doctrine listener (#[AsDoctrineListener])'], ['entity', 'New entity listener (#[AsEntityListener])'], ['add', 'Add to an existing class']];
export class EventsPanel {
constructor(app) {
this.app = app;
this.node = el('div.sfc-view.sft-view');
this.tab = prefs.get('sfEventsTab', 'events');
this.catalog = null;
this.listeners = null; // from the code
this.real = null; // from debug:event-dispatcher
this.source = 'code';
this.filter = '';
this.selected = null; // an event's name
this.mode = 'event'; // event | new-event
this.subs = []; // the subscriptions of the class being written
this.form = { kind: 'subscriber', className: '', method: '', priority: 0, target: '', entity: '', connection: '' };
this.newEvent = { className: 'App\\Event\\', name: '', properties: [{ name: '', type: '' }], dispatchClass: '', dispatchMethod: '', listenerKind: '', listenerClass: '' };
this.classes = null;
this.busy = false;
this.changes = new ChangesView(app, 'events.apply', () => this.load());
symfonyStyles();
this.render();
}
title() { return t('Events'); }
actions() {
return [el('button', { title: t('Refresh'), onclick: () => this.load() }, icon('refresh'))];
}
shown() { if (!this.catalog && !this.busy) this.load(); }
async load() {
this.busy = true; this.render();
try {
[this.catalog, this.listeners] = await Promise.all([backend.invoke('events.catalog', {}), backend.invoke('events.listeners', {})]);
} catch (e) { notify(e.message, 'error', { title: t('Events') }); }
this.busy = false;
this.render();
}
async loadReal() {
this.busy = true; this.source = 'app'; this.render();
try { this.real = await backend.invoke('events.debug', {}); } catch (e) { notify(e.message, 'error', { title: 'debug:event-dispatcher' }); this.source = 'code'; }
this.busy = false;
this.render();
}
events() { return [...(this.catalog?.project || []), ...(this.catalog?.framework || [])]; }
event(name = this.selected) { return this.events().find((e) => e.name === name) || null; }
listenersOf(name) { return (this.listeners?.events || []).find((g) => g.event === name)?.listeners || []; }
/** the classes that already listen (subscribers, listeners): where a subscription can be added */
targets() {
const seen = new Map();
for (const g of this.listeners?.events || []) for (const l of g.listeners) if (!seen.has(l.class)) seen.set(l.class, l);
return [...seen.values()];
}
setTab(tab) { this.tab = tab; prefs.set('sfEventsTab', tab); this.render(); }
select(name) {
const e = this.event(name);
this.selected = name;
this.mode = 'event';
const doctrine = e?.kind === 'doctrine';
if (!this.subs.length) {
const base = short(e?.class || '').replace(/(Event|EventArgs)$/, '') || 'App';
this.form.kind = doctrine ? 'doctrine' : (this.form.kind === 'doctrine' || this.form.kind === 'entity' ? 'subscriber' : this.form.kind);
this.form.className = doctrine ? `App\\EventListener\\${base[0].toUpperCase()}${base.slice(1)}Listener` : `App\\EventSubscriber\\${base}Subscriber`;
}
this.form.method = '';
this.render();
}
// the code ----------------------------------------------------------------------------------------------------
sub(e = this.event()) {
return { event: e, method: this.form.method.trim(), priority: Number(this.form.priority) || 0 };
}
async preview(payload, command = 'events.preview') {
try {
const r = await backend.invoke(command, payload);
if (!r.changes.length) { notify(t('Nothing to change'), 'info'); return; }
this.changes.show(r.changes);
this.render();
} catch (e) { notify(e.message, 'error'); }
}
previewListen() {
const f = this.form;
if (f.kind === 'add') {
const target = this.targets().find((l) => l.class === f.target);
if (!target) { notify(t('Choose a class'), 'error'); return; }
this.preview({ action: 'add', file: target.file, class: target.class, kind: target.kind === 'subscriber' ? 'subscriber' : 'listener', sub: this.sub() });
return;
}
const subs = this.subs.length ? this.subs : [this.sub()];
this.preview({ action: 'new', kind: f.kind, class: f.className, subs, entity: f.entity, connection: f.connection });
}
async setPriority(l, priority) {
this.preview({ action: 'priority', file: l.file, class: l.class, event: l.event, method: l.method, priority: Number(priority) || 0 });
}
async loadClasses() {
if (this.classes) return;
try { this.classes = (await backend.invoke('events.classes', {})).classes; } catch { this.classes = []; }
this.render();
}
// drawing ------------------------------------------------------------------------------------------------------
render() {
const scroll = this.node.querySelector('.sfc-list')?.scrollTop || 0;
clear(this.node);
this.node.append(el('div.cryo-tabs', {},
el('button' + (this.tab === 'events' ? '.on' : ''), { onclick: () => this.setTab('events') }, t('Events')),
el('button' + (this.tab === 'listeners' ? '.on' : ''), { onclick: () => this.setTab('listeners') }, t('Listeners')),
this.busy ? el('span.sfc-busy', {}, '…') : null));
if (!this.catalog) {
this.node.append(el('div.prof-empty', {}, el('p', {}, this.busy ? t('Reading the project…') : '')));
return;
}
if (this.tab === 'listeners') { this.node.append(this.renderListeners()); return; }
const side = this.renderPicker();
this.node.append(el('div.sfc-main', {}, side, el('div.sfc-form', {}, this.mode === 'new-event' ? this.renderNewEvent() : this.renderEvent(), this.changes.node)));
side.querySelector('.sfc-list').scrollTop = scroll;
}
renderPicker() {
const q = this.filter.toLowerCase();
const match = (e) => !q || [e.name, e.class, e.const || '', e.group].some((s) => s.toLowerCase().includes(q));
const groups = new Map();
for (const e of this.events()) if (match(e)) { if (!groups.has(e.group)) groups.set(e.group, []); groups.get(e.group).push(e); }
const input = el('input.input.sfc-filter', { type: 'search', value: this.filter, placeholder: t('Search an event (name, class, constant)'), spellcheck: false });
input.addEventListener('input', () => { this.filter = input.value; this.render(); const i = this.node.querySelector('.sfc-filter'); i.focus(); i.setSelectionRange(i.value.length, i.value.length); });
const list = el('div.sfc-list');
for (const [group, events] of groups) {
list.append(el('div.sfc-group-title', {}, group === 'Project' ? t('This project') : group, el('span.sfc-count', {}, String(events.length))));
for (const e of events) {
const n = this.listenersOf(e.name).length;
list.append(el('div.sfc-cmd.sft-event' + (e.name === this.selected && this.mode === 'event' ? '.on' : ''), { title: e.class, onclick: () => this.select(e.name) },
el('span.sfc-name', {}, e.const || (e.name.includes('\\') ? short(e.name) : e.name)),
el('span.sfc-desc', {}, e.const ? e.name : ''),
n ? el('span.sft-pill', { title: t('{n} listeners in the code', { n }) }, String(n)) : null));
}
}
if (!groups.size) list.append(el('div.sfc-none.pub-faint', {}, t('Nothing found')));
return el('div.sfc-side', {},
el('div.sft-row.sft-pad', {}, input,
el('button.btn.small', { title: t('A new event of the project'), onclick: () => { this.mode = 'new-event'; this.loadClasses(); this.render(); } }, icon('plus'), t('New event'))),
list);
}
renderEvent() {
const e = this.event();
if (!e) return el('div.prof-empty', {}, el('p', {}, t('Choose an event on the left: who listens to it, and a listener written for it.')));
const listeners = this.listenersOf(e.name);
const doctrine = e.kind === 'doctrine';
const f = this.form;
const kinds = doctrine ? DOCTRINE_KINDS : KINDS;
const field = (label, input, hint) => el('label.sfc-field', {}, el('span.sfc-label', {}, label), input, hint ? el('span.sfc-hint', {}, hint) : null);
const input = (key, attrs = {}) => {
const i = el('input.input', { type: 'text', value: f[key] ?? '', spellcheck: false, ...attrs });
i.addEventListener('input', () => { f[key] = i.value; });
return i;
};
const kind = el('select.input', { onchange: (ev) => { f.kind = ev.target.value; this.render(); } }, ...kinds.map(([v, label]) => el('option', { value: v, selected: f.kind === v }, t(label))));
const box = el('div', {},
el('div.sfc-head', {}, el('h3', {}, e.const || e.name)),
el('p.sfc-description', {}, e.const ? e.name + ' — ' : '', el('span.sfc-name', {}, e.class)),
e.project && e.file ? el('p', {}, fileLink(this.app, e.file, e.line, t('Open the event class'))) : null);
if (e.dispatches?.length) {
box.append(el('h4', {}, t('Dispatched in')), ...e.dispatches.map((d) => el('div.sft-line', {}, fileLink(this.app, d.file, d.line, `${d.in || d.file}:${d.line}`))));
}
box.append(el('h4', {}, t('Listeners in the code (in the order they are called)')));
if (!listeners.length) box.append(el('p.pub-faint', {}, t('Nobody listens to it in src/.')));
for (const l of listeners) box.append(this.renderListener(l, true));
box.append(el('h4', {}, t('Listen to this event')));
box.append(field(t('Kind'), kind));
if (f.kind === 'add') {
const targets = this.targets();
if (!f.target && targets[0]) f.target = targets[0].class;
box.append(field(t('Class'), el('select.input', { onchange: (ev) => { f.target = ev.target.value; } },
...targets.map((l) => el('option', { value: l.class, selected: f.target === l.class }, `${short(l.class)} (${l.kind})`))), targets.length ? null : t('No subscriber or listener in src/ yet.')));
} else {
box.append(field(t('Class'), input('className')));
}
if (f.kind === 'entity') box.append(field(t('Entity'), input('entity', { placeholder: 'App\\Entity\\User' })));
if (f.kind === 'doctrine') box.append(field(t('Connection'), input('connection', { placeholder: 'default' }), t('optional')));
if (f.kind !== 'doctrine') box.append(field(t('Method'), input('method', { placeholder: this.defaultMethod(e) })));
box.append(field(t('Priority'), input('priority', { type: 'number', step: 1 }), t('Higher first; Symfony\'s own listeners use -255 to 255.')));
if (this.subs.length) {
box.append(el('div.sft-subs', {}, el('span.sfc-hint', {}, t('This class will listen to:')),
...this.subs.map((s, i) => el('span.sft-chip', {}, `${s.event.const || short(s.event.name)} → ${s.method || this.defaultMethod(s.event)}${s.priority ? ` (${s.priority})` : ''}`,
el('button.sfc-star', { title: t('Remove'), onclick: () => { this.subs.splice(i, 1); this.render(); } }, icon('close'))))));
}
box.append(el('div.sfc-run', {},
el('button.btn.primary', { onclick: () => this.previewListen() }, t('Preview the code')),
f.kind !== 'add' ? el('button.btn', { title: t('Add this event to the class being written, then choose another event'),
onclick: () => { if (!this.subs.some((s) => s.event.name === e.name && s.method === f.method)) this.subs.push(this.sub(e)); this.render(); } }, icon('plus'), t('One more event in this class')) : null));
return box;
}
defaultMethod(e) {
if (e.kind === 'doctrine') return e.name;
const n = e.name.includes('\\') ? short(e.name).replace(/Event$/, '') : e.name;
return 'on' + n.replace(/(?:^|[._\s-])([a-z])/gi, (m, c) => c.toUpperCase()).replace(/[^A-Za-z0-9]/g, '').replace(/^./, (c) => c.toUpperCase());
}
/** a listener: priority (editable when it comes from the code), class::method (opens it), its kind */
renderListener(l, editable) {
const prio = editable && l.file ? el('input.input.sft-prio', { type: 'number', value: l.priority, title: t('Priority (Enter: preview the change)') }) : el('span.sft-prio', {}, String(l.priority));
if (prio.tagName === 'INPUT') prio.addEventListener('change', () => this.setPriority(l, prio.value));
const name = `${short(l.class)}::${l.method}()`;
return el('div.sft-listener.' + (l.kind || 'vendor'), { title: l.class },
prio,
l.file ? fileLink(this.app, l.file, l.line, name) : el('span.sfc-name', {}, name),
el('span.sft-kind', {}, l.kind || ''),
l.entity ? el('span.sfc-hint', {}, short(l.entity)) : null,
editable && l.file && ['subscriber', 'listener', 'doctrine', 'entity'].includes(l.kind)
? el('button.sfc-star', { title: t('Remove this subscription (the method stays)'), onclick: () => this.preview({ action: 'remove', file: l.file, class: l.class, event: l.event, method: l.method }) }, icon('trash')) : null);
}
renderNewEvent() {
const n = this.newEvent;
const field = (label, input, hint) => el('label.sfc-field', {}, el('span.sfc-label', {}, label), input, hint ? el('span.sfc-hint', {}, hint) : null);
const input = (obj, key, attrs = {}) => {
const i = el('input.input', { type: 'text', value: obj[key] ?? '', spellcheck: false, ...attrs });
i.addEventListener('input', () => { obj[key] = i.value; });
return i;
};
const classes = this.classes || [];
const target = classes.find((c) => c.class === n.dispatchClass);
const props = el('div.sft-props', {}, ...n.properties.map((p, i) => el('div.sft-row', {},
input(p, 'name', { placeholder: t('name') }), input(p, 'type', { placeholder: t('type (int, string, App\\Entity\\Order…)') }),
el('button.sfc-star', { title: t('Remove'), onclick: () => { n.properties.splice(i, 1); this.render(); } }, icon('close')))),
el('button.btn.small', { onclick: () => { n.properties.push({ name: '', type: '' }); this.render(); } }, icon('plus'), t('Property')));
return el('div', {},
el('div.sfc-head', {}, el('h3', {}, t('New event'))),
field(t('Class'), input(n, 'className')),
field(t('Name'), input(n, 'name', { placeholder: 'order.placed' }), t('optional: a NAME constant, dispatched under that name (else the class is the name)')),
el('h4', {}, t('Properties')), props,
el('h4', {}, t('Dispatch it')),
field(t('In the class'), el('select.input', { onchange: (ev) => { n.dispatchClass = ev.target.value; n.dispatchMethod = ''; this.render(); } },
el('option', { value: '' }, t('(nowhere for now)')), ...classes.map((c) => el('option', { value: c.class, selected: c.class === n.dispatchClass }, c.class)))),
target ? field(t('At the end of'), el('select.input', { onchange: (ev) => { n.dispatchMethod = ev.target.value; } },
el('option', { value: '' }, '—'), ...target.methods.filter((m) => m !== '__construct').map((m) => el('option', { value: m, selected: m === n.dispatchMethod }, `${m}()`))),
t('EventDispatcherInterface is injected in the constructor if the class has none.')) : null,
el('h4', {}, t('Listen to it')),
field(t('Kind'), el('select.input', { onchange: (ev) => { n.listenerKind = ev.target.value; this.render(); } },
el('option', { value: '' }, t('(no listener)')), ...KINDS.filter(([k]) => k !== 'add').map(([k, label]) => el('option', { value: k, selected: n.listenerKind === k }, t(label))))),
n.listenerKind ? field(t('Class'), input(n, 'listenerClass', { placeholder: 'App\\EventListener\\OrderPlacedListener' })) : null,
el('div.sfc-run', {}, el('button.btn.primary', { onclick: () => this.previewNewEvent() }, t('Preview the code'))));
}
previewNewEvent() {
const n = this.newEvent;
const target = (this.classes || []).find((c) => c.class === n.dispatchClass);
this.preview({ action: 'event', class: n.className, name: n.name, properties: n.properties.filter((p) => p.name.trim()),
dispatch: target && n.dispatchMethod ? { file: target.file, class: target.class, method: n.dispatchMethod } : null,
listener: n.listenerKind && n.listenerClass ? { kind: n.listenerKind, class: n.listenerClass } : null });
}
renderListeners() {
const data = this.source === 'app' && this.real ? this.real : this.listeners;
const q = this.filter.toLowerCase();
const input = el('input.input.sfc-filter', { type: 'search', value: this.filter, placeholder: t('Filter: event, class, method'), spellcheck: false });
input.addEventListener('input', () => { this.filter = input.value; this.render(); const i = this.node.querySelector('.sfc-filter'); i.focus(); i.setSelectionRange(i.value.length, i.value.length); });
const list = el('div.sfc-list.sft-order');
for (const g of data?.events || []) {
const ls = g.listeners.filter((l) => !q || [g.event, l.class, l.method].some((s) => String(s).toLowerCase().includes(q)));
if (!ls.length) continue;
const e = this.event(g.event);
list.append(el('div.sfc-group-title', { title: g.event }, e?.const || g.event, e?.const ? el('span.sfc-desc', {}, g.event) : null, el('span.sfc-count', {}, String(ls.length))));
for (const l of ls) list.append(this.renderListener(l, this.source === 'code'));
}
if (!list.children.length) list.append(el('div.sfc-none.pub-faint', {}, this.source === 'code' ? t('No listener in src/.') : t('Nothing found')));
return el('div.sft-listeners', {},
el('div.sft-row.sft-pad', {},
el('button.btn.small' + (this.source === 'code' ? '.primary' : ''), { onclick: () => { this.source = 'code'; this.render(); } }, t('From the code')),
el('button.btn.small' + (this.source === 'app' ? '.primary' : ''), { title: 'bin/console debug:event-dispatcher --format=json', onclick: () => this.loadReal() }, icon('console'), t('From the application (vendors too)')),
input),
this.changes.node,
list);
}
}