201 lines
11 KiB
JavaScript
201 lines
11 KiB
JavaScript
// The controller panel: under the code of a Symfony controller open in the editor (inside its editor group), a collapsible
|
|
// bar and the list of the controller's routes: methods, path, name, the action (click: its line), parameters against the
|
|
// arguments, security (#[IsGranted] and the access_control rule), the templates it renders, the routes it redirects to, the forms
|
|
// and the JSON it answers; per route: open in the browser, send a request from the HTTP Client, copy the URL or the name.
|
|
// It follows the typing (a debounced question to the PHP side, controller.routes, an unchanged text is not asked again) and
|
|
// stays hidden for any other file. ide/src/Symfony/ControllerRoutes.php reads the code.
|
|
import { backend } from './backend.js';
|
|
import { el, icon, notify, prompt, t, prefs, debounce } from './ui.js';
|
|
import { looksLikeController, fillUrl, joinUrl, placeholders, requestFor, sampleValue, securityOf, KIND_LABEL, interesting, summary,
|
|
pathOfAction, routeNameOfAction, createRefresher } from './controller-panel-model.js';
|
|
|
|
const copy = async (text) => {
|
|
try { await navigator.clipboard.writeText(text); notify(t('Copied'), 'info', { timeout: 1500 }); } catch (e) { notify(e.message, 'error'); }
|
|
};
|
|
|
|
export class ControllerPanel {
|
|
/** @param {{app: object, editors: object, group: object, tab: object, file: object}} o */
|
|
constructor({ app, editors, group, tab, file }) {
|
|
Object.assign(this, { app, editors, group, tab, file });
|
|
this.open = prefs.get('controllerPanel', true);
|
|
this.info = null;
|
|
this.error = null;
|
|
this.refresher = createRefresher((path, text) => backend.invoke('controller.routes', { path, text }));
|
|
this.head = el('div.cp-head', { onclick: (e) => { if (!e.target.closest('button')) this.toggle(); } });
|
|
this.body = el('div.cp-body');
|
|
this.node = el('div.cp', { 'data-tour': 'controller-panel', style: { display: 'none' } }, this.head, this.body);
|
|
group.node.insertBefore(this.node, group.crumbs);
|
|
this.sub = file.model.onDidChangeContent(debounce(() => this.refresh(), 350));
|
|
this.refresh();
|
|
}
|
|
|
|
destroy() {
|
|
this.sub?.dispose();
|
|
this.node.remove();
|
|
this.dead = true;
|
|
}
|
|
|
|
toggle() {
|
|
this.open = !this.open;
|
|
prefs.set('controllerPanel', this.open);
|
|
this.render();
|
|
this.editors.layout();
|
|
}
|
|
|
|
async refresh() {
|
|
if (this.dead) return;
|
|
const text = this.file.model.getValue();
|
|
if (!looksLikeController(this.tab.path, text)) { this.apply({ controller: false }); return; }
|
|
try {
|
|
const { info, stale } = await this.refresher.refresh(this.tab.path, text);
|
|
if (!stale && !this.dead) this.apply(info);
|
|
} catch (e) {
|
|
// a PHP side that cannot answer: keep what was shown
|
|
this.error = e.message;
|
|
this.render();
|
|
}
|
|
}
|
|
|
|
apply(info) {
|
|
if (!info?.controller) { this.info = null; this.node.style.display = 'none'; this.editors.layout(); return; }
|
|
if (info.error) { this.error = info.error; } else { this.info = info; this.error = null; }
|
|
this.node.style.display = '';
|
|
this.render();
|
|
this.editors.layout();
|
|
}
|
|
|
|
// drawing ----------------------------------------------------------------------------------------------
|
|
|
|
render() {
|
|
const info = this.info;
|
|
const s = summary(info);
|
|
this.node.classList.toggle('collapsed', !this.open);
|
|
this.head.replaceChildren(...[
|
|
el('span.cp-caret', {}, this.open ? '▾' : '▸'),
|
|
el('span.cp-title', {}, t('Controller routes')),
|
|
el('span.cp-count', { 'data-tour': 'controller-routes' }, t('{n} routes', { n: s.routes })),
|
|
s.prefix ? el('span.cp-prefix', { title: t('Prefix: {path}', { path: s.prefix }) }, s.prefix) : null,
|
|
this.error ? el('span.cp-error', { title: this.error }, t('The code has an error: {message}', { message: this.error.slice(0, 80) })) : null,
|
|
el('span.cp-grow'),
|
|
el('button.cp-btn', { title: t('Add an action to this controller'), onclick: () => this.addAction() }, '+ ', t('Add action')),
|
|
].filter(Boolean));
|
|
this.body.replaceChildren();
|
|
this.body.style.display = this.open ? '' : 'none';
|
|
if (!this.open || !info) return;
|
|
if (!info.routes.length) { this.body.append(el('div.cp-empty', {}, t('No route in this controller'))); return; }
|
|
for (const route of info.routes) this.body.append(this.row(route, info));
|
|
}
|
|
|
|
row(route, info) {
|
|
const url = el('span.cp-path', {}, ...route.url.split(/(\{[^}]+\})/).map((p) => (p.startsWith('{') ? el('span.cp-ph', {}, p) : p)));
|
|
const reqs = Object.entries(route.requirements || {}).map(([k, v]) => el('span.cp-chip.req', { title: t('Requirement') }, `${k}: ${v}`));
|
|
const defs = Object.entries(route.defaults || {}).map(([k, v]) => el('span.cp-chip.def', { title: t('Default value') }, `${k} = ${v}`));
|
|
const top = el('div.cp-line',
|
|
el('span.cp-methods', {}, ...(route.methods.length ? route.methods : ['ANY']).map((m) => el(`span.cp-m.m-${m}`, {}, m))),
|
|
url,
|
|
el('span.cp-name', { title: t('Route name') }, route.name),
|
|
el('a.cp-action', { href: '#', title: t('Go to the line'), onclick: (e) => { e.preventDefault(); this.go(route.line); } }, `${route.action}()`),
|
|
el('span.cp-grow'),
|
|
el('button.cp-act', { title: t('Open in browser'), onclick: () => this.browse(route, info) }, icon('globe'), t('Open in browser')),
|
|
el('button.cp-act', { title: t('Send request'), onclick: () => this.send(route) }, icon('play'), t('Send request')),
|
|
el('button.cp-act', { title: t('Copy URL'), onclick: () => copy(joinUrl(info.site, fillUrl(route))) }, icon('copy'), t('Copy URL')),
|
|
el('button.cp-act', { title: t('Copy route name'), onclick: () => copy(route.name) }, icon('copy'), t('Copy route name')),
|
|
);
|
|
const chips = el('div.cp-line.cp-chips', {}, ...reqs, ...defs, ...this.paramChips(route), ...this.securityChips(route), ...this.flowChips(route));
|
|
return el('div.cp-row', {}, top, chips.childNodes.length ? chips : null);
|
|
}
|
|
|
|
paramChips(route) {
|
|
return (route.params || []).filter((p) => interesting(p) || p.placeholder).map((p) => {
|
|
const how = p.via ? `#[${p.via}] ` : '';
|
|
const label = p.unused ? t('not used by the action') : t(KIND_LABEL[p.kind] || p.kind);
|
|
return el(`span.cp-chip.param.k-${p.kind}`, { title: `${how}${p.type || ''} $${p.name}` }, `$${p.name}`, el('em', {}, ` ${p.type ? p.type.replace(/^\?/, '?') + ' · ' : ''}${label}`));
|
|
});
|
|
}
|
|
|
|
securityChips(route) {
|
|
const sec = securityOf(route);
|
|
const out = sec.grants.map((g) => el('a.cp-chip.sec', { href: '#', title: t('Security'), onclick: (e) => { e.preventDefault(); this.go(g.line); } }, g.text));
|
|
if (sec.rule) {
|
|
out.push(el('span.cp-chip.sec.rule', { title: t('Rule {n}: {path}', { n: sec.rule.index + 1, path: sec.rule.path }) },
|
|
t('Rule {n}: {path}', { n: sec.rule.index + 1, path: sec.rule.path }) + (sec.rule.roles.length ? ' → ' + sec.rule.roles.join(', ') : sec.rule.expression ? ' → ' + sec.rule.expression : '')));
|
|
} else if (route.firewall) {
|
|
out.push(el('span.cp-chip.sec.none', { title: t('No access_control rule') }, t('No access_control rule')));
|
|
}
|
|
return out;
|
|
}
|
|
|
|
flowChips(route) {
|
|
const out = [];
|
|
for (const tpl of route.templates || []) {
|
|
out.push(el(`a.cp-chip.tpl${tpl.file ? '' : '.missing'}`, { href: '#', title: tpl.file ? t('Open the template') : t('Template not found'),
|
|
onclick: (e) => { e.preventDefault(); if (tpl.file) this.editors.open(tpl.file); else this.go(tpl.line); } }, icon('file'), tpl.name));
|
|
}
|
|
for (const r of route.redirects || []) {
|
|
out.push(el('a.cp-chip.redir', { href: '#', title: t('Go to this route'), onclick: (e) => { e.preventDefault(); this.goRoute(r.route); } }, '→ ', r.route));
|
|
}
|
|
for (const f of route.forms || []) {
|
|
out.push(el(`a.cp-chip.form${f.file ? '' : '.missing'}`, { href: '#', title: f.class, onclick: (e) => { e.preventDefault(); if (f.file) this.editors.open(f.file); else this.go(f.line); } }, icon('file'), f.short));
|
|
}
|
|
for (const r of (route.responses || []).filter((x) => x.type === 'json')) {
|
|
out.push(el('a.cp-chip.json', { href: '#', title: t('JSON response'), onclick: (e) => { e.preventDefault(); this.go(r.line); } }, 'JSON', r.keys?.length ? el('em', {}, ' { ' + r.keys.slice(0, 5).join(', ') + (r.keys.length > 5 ? ', …' : '') + ' }') : null));
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// actions ----------------------------------------------------------------------------------------------
|
|
|
|
go(line) { this.editors.reveal(this.group, { line, focus: true }); }
|
|
|
|
async goRoute(name) {
|
|
const own = this.info?.routes.find((r) => r.name === name);
|
|
if (own) return this.go(own.line);
|
|
const found = await backend.invoke('controller.route.find', { name }).catch(() => null);
|
|
if (found?.file) this.editors.open(found.file, { line: found.line });
|
|
else notify(t('No route named {name}', { name }), 'info');
|
|
}
|
|
|
|
/** the values of the placeholders, asked one by one (the sample is the proposal) */
|
|
async values(route) {
|
|
const values = {};
|
|
for (const name of placeholders(route.url)) {
|
|
const v = await prompt(t('Value of {name}', { name: `{${name}}` }), { value: sampleValue(route, name), label: route.path });
|
|
if (v === null || v === undefined) return null;
|
|
values[name] = v;
|
|
}
|
|
return values;
|
|
}
|
|
|
|
async browse(route, info) {
|
|
const values = await this.values(route);
|
|
if (!values) return;
|
|
this.app.openUrl(joinUrl(info.site, fillUrl(route, values)));
|
|
}
|
|
|
|
async send(route) {
|
|
const values = await this.values(route);
|
|
if (!values) return;
|
|
try {
|
|
const data = await backend.invoke('http.list');
|
|
let collection = data.collections?.[0]?.id;
|
|
if (!collection) collection = (await backend.invoke('http.collection.create', { name: 'API' })).id;
|
|
const { path } = await backend.invoke('http.request.add', { collection, folder: '', request: requestFor(route, values) });
|
|
this.app.showTool?.('httpClient');
|
|
const client = await this.app.httpClient?.ready();
|
|
await client?.load?.();
|
|
await client?.openRequest?.(collection, path);
|
|
} catch (e) { notify(e.message, 'error', { title: t('Send request') }); }
|
|
}
|
|
|
|
async addAction() {
|
|
const name = await prompt(t('Action name (camelCase)'), { value: 'index', label: this.info?.prefix?.path ? t('Prefix: {path}', { path: this.info.prefix.path }) : '' });
|
|
if (!name) return;
|
|
try {
|
|
const prefix = this.info?.prefix?.name || '';
|
|
const r = await backend.invoke('controller.addAction', { path: this.tab.path, text: this.file.model.getValue(), name,
|
|
route: pathOfAction(name), methods: ['GET'], routeName: routeNameOfAction(name, prefix) });
|
|
const { reviewChanges } = await import('./symfony-diff.js');
|
|
if (await reviewChanges(this.app, r.files, { title: t('Add action') })) this.refresh();
|
|
} catch (e) { notify(e.message, 'error', { title: t('Add action') }); }
|
|
}
|
|
}
|