rob-revisited/ide/ui/js/api-platform.js

590 lines
40 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 API Platform window (desktop IDE, bottom; projects that require api-platform/core): the #[ApiResource] attributes of the
// project's classes read from the sources by ide/src/ApiPlatform, edited in forms, every change shown as a diff before it is written.
// - Resources: the classes (entities, DTOs), #[ApiResource] on / off, its options (short name, operations with their own options,
// subresources with uriTemplate + uriVariables, formats, pagination, order, security, validation / serialization groups, state classes).
// - Properties: a grid, one row per property: the serialization groups (#[Groups]) as read / write checkboxes, #[ApiProperty], #[ApiFilter].
// - State: the State Providers / Processors, new ones from templates, wired to a resource or an operation.
// - Routes: every route worked out from the code, compared with the console's debug:router; the OpenAPI export.
// - Requests: the HTTP Client collections of the resources (one request per operation, example bodies, filters), refreshed when the
// class changes without ever overwriting a request somebody edited.
import { backend } from './backend.js';
import { el, clear, icon, notify, prefs, t, confirm, prompt, dialog, menu, chooser, copyText } from './ui.js';
const cssHref = new URL('../css/api-platform.css', import.meta.url).href;
if (![...document.querySelectorAll('link[rel=stylesheet]')].some((l) => l.href === cssHref)) document.head.append(el('link', { rel: 'stylesheet', href: cssHref }));
import { CTX, FIELD, RES_SECTIONS, OP_FIELDS, isExpr, clone, same, readField, writeField, modelOf, changed } from './api-platform-model.js';
const short = (c) => String(c || '').split('\\').pop();
const OPS = ['Get', 'GetCollection', 'Post', 'Put', 'Patch', 'Delete'];
const FORMATS = ['jsonld', 'json', 'jsonapi', 'hal', 'xml', 'csv', 'html'];
export class ApiPlatformPanel {
constructor(app) {
this.app = app;
this.node = el('div.ap-view');
this.tab = prefs.get('apiTab', 'resources');
this.meta = null;
this.cls = null; // the class being edited: apiplatform.class
this.selected = prefs.get('apiClass:' + app.projectKey, null);
this.ri = 0; // its #[ApiResource] being edited
this.res = null; // the form of that resource: {model, ops, opsDirty}
this.grid = null; // the form of the property grid
this.filter = '';
this.allClasses = prefs.get('apiAllClasses', false);
this.routes = null; // the routes from the code
this.router = null; // the console's routes
this.plan = null; // the requests' plan
this.datalists = el('div', { hidden: true });
}
title() { return 'API Platform'; }
actions() {
return [
el('button', { title: t('Refresh'), onclick: () => this.load(true) }, icon('refresh')),
el('button', { title: t('Bigger: the whole window (Escape: back)'), onclick: () => this.maximize() }, icon('expand')),
];
}
shown() { if (!this.meta) this.load(); }
maximize(on = !this.node.classList.contains('ap-max')) {
this.node.classList.toggle('ap-max', on);
if (on) {
this.escape = (e) => { if (e.key === 'Escape') this.maximize(false); };
document.addEventListener('keydown', this.escape);
} else if (this.escape) document.removeEventListener('keydown', this.escape);
}
/** the window opened on a class (the Doctrine window's entity editor, the diagram's menu) */
async show(cls, tab = 'resources') {
this.app.showTool('apiplatform', true);
this.tab = tab;
if (cls) { this.selected = cls; prefs.set('apiClass:' + this.app.projectKey, cls); }
if (!this.meta) await this.load(); else { await this.loadClass(); this.render(); }
}
async load(refresh = false) {
try {
this.meta = await backend.invoke('apiplatform.classes', {});
if (!this.meta.classes.some((c) => c.class === this.selected)) this.selected = (this.meta.classes.find((c) => c.api) || this.meta.classes[0])?.class || null;
this.fillLists();
if (refresh) { this.routes = null; this.router = null; this.plan = null; }
await this.loadClass();
} catch (e) { notify(e.message, 'error', { title: 'API Platform' }); this.meta = { classes: [], groups: [], filters: [], prefix: '/api' }; }
this.render();
}
async loadClass() {
this.cls = null;
this.res = null;
this.grid = null;
if (!this.selected) return;
try {
this.cls = await backend.invoke('apiplatform.class', { class: this.selected });
this.ri = Math.min(this.ri, Math.max(0, this.cls.resources.length - 1));
this.buildResource();
this.buildGrid();
} catch (e) { notify(e.message, 'error', { title: 'API Platform' }); }
}
fillLists() {
clear(this.datalists);
this.datalists.append(el('datalist', { id: 'ap-classes' }, ...this.meta.classes.map((c) => el('option', { value: c.class }))),
el('datalist', { id: 'ap-groups' }, ...this.meta.groups.map((g) => el('option', { value: g }))));
}
get resource() { return this.cls?.resources[this.ri] || null; }
// the forms' models ----------------------------------------------------------------------------------------------
buildResource() {
const r = this.resource;
if (!r) { this.res = null; return; }
const keys = RES_SECTIONS.flatMap(([, ks]) => ks);
const model = modelOf(r.args, keys);
const explicit = r.hasOperations;
const ops = explicit ? r.operations.map((o) => ({ index: o.index, type: o.type, ...modelOf(o.args, OP_FIELDS), initType: o.type, open: false, expr: o.expr || null })) : [];
this.res = { model, ops, explicit, dirtyOps: false, keys };
}
buildGrid() {
const r = this.resource;
const norm = readField(r?.args || {}, 'normalizationGroups').value || [];
const denorm = readField(r?.args || {}, 'denormalizationGroups').value || [];
const cols = [...new Set([...norm, ...denorm, ...this.cls.properties.flatMap((p) => p.groups || [])])];
const rows = {};
for (const p of this.cls.properties) {
const api = p.apiProperty || {};
rows[p.name] = { groups: new Set(p.groups || []), initGroups: p.groups, readable: api.readable !== false, writable: api.writable !== false, identifier: api.identifier === true,
description: typeof api.description === 'string' ? api.description : '', example: api.example === undefined || isExpr(api.example) ? '' : String(api.example),
filters: p.filters.map((f) => ({ index: f.index, filter: f.key || f.class, label: f.key ? f.key + (f.strategy ? ':' + f.strategy : '') : short(f.class), strategy: f.strategy || '', known: !!f.key })), init: null };
rows[p.name].init = this.rowState(rows[p.name]);
}
this.grid = { cols, norm: new Set(norm), denorm: new Set(denorm), initNorm: [...norm], initDenorm: [...denorm], rows };
}
rowState(r) { return JSON.stringify([[...r.groups].sort(), r.readable, r.writable, r.identifier, r.description, r.example, r.filters.map((f) => [f.index, f.filter, f.strategy])]); }
// render ---------------------------------------------------------------------------------------------------------
render() {
const scroll = this.node.querySelector('.ap-body')?.scrollTop || 0;
clear(this.node);
const tabs = [['resources', t('Resources'), 'structure'], ['properties', t('Properties'), 'design'], ['state', t('State'), 'plugin'], ['routes', t('Routes'), 'globe'], ['requests', t('Requests'), 'play']];
this.node.append(this.datalists, el('div.ap-tabs', {}, ...tabs.map(([id, label, ico]) => el('button.ap-tab' + (this.tab === id ? '.on' : ''), {
onclick: () => { this.tab = id; prefs.set('apiTab', id); this.render(); if (id === 'routes' && !this.routes) this.loadRoutes(); if (id === 'requests' && !this.plan) this.loadPlan(); },
}, icon(ico), label)), el('span.ap-spacer'), this.meta?.version ? el('span.ap-ver', {}, 'api-platform/core ' + this.meta.version) : null));
const body = el('div.ap-body');
this.node.append(body);
if (!this.meta) { body.append(el('div.ap-hint', {}, t('Loading…'))); return; }
({ resources: () => this.renderResources(body), properties: () => this.renderProperties(body), state: () => this.renderState(body),
routes: () => this.renderRoutes(body), requests: () => this.renderRequests(body) })[this.tab]();
body.scrollTop = scroll;
}
/** the list of the project's classes, on the left of the resources and properties tabs */
classList() {
const list = el('div.ap-classes');
const input = el('input.input.ap-filter', { value: this.filter, placeholder: t('Filter: class, short name'), oninput: () => { this.filter = input.value; this.fillClasses(list); } });
this.fillClasses(list);
return el('div.ap-side', {}, input, el('label.ap-filter-all', {}, el('input', { type: 'checkbox', checked: this.allClasses, onchange: (e) => { this.allClasses = e.target.checked; prefs.set('apiAllClasses', this.allClasses); this.fillClasses(list); } }), t('All classes')), list);
}
fillClasses(list) {
clear(list);
const q = this.filter.toLowerCase();
for (const c of this.meta.classes.filter((x) => (x.kind !== 'other' || x.api || this.allClasses) && (!q || x.class.toLowerCase().includes(q) || (x.shortName || '').toLowerCase().includes(q)))) {
list.append(el('div.ap-class' + (c.class === this.selected ? '.on' : ''), { 'data-tour': 'api-class-' + c.name, title: c.class, onclick: async () => { this.selected = c.class; this.ri = 0; prefs.set('apiClass:' + this.app.projectKey, c.class); await this.loadClass(); this.render(); } },
el('span.ap-badge' + (c.api ? '.on' : ''), {}, 'API'), el('span.ap-cname', {}, c.name), c.shortName ? el('span.ap-sub', {}, c.shortName) : null, el('span.ap-kind', {}, c.kind)));
}
}
// the resources tab ----------------------------------------------------------------------------------------------
renderResources(body) {
const c = this.cls;
const main = el('div.ap-main');
body.append(el('div.ap-cols', {}, this.classList(), main));
if (!c) { main.append(el('div.ap-hint', {}, t('No PHP class here yet.'))); return; }
const info = this.meta.classes.find((x) => x.class === c.class);
main.append(el('div.ap-head', {}, el('b', {}, c.name), el('span.ap-sub', {}, c.class), el('span.ap-spacer'),
el('button.btn.small', { onclick: () => this.app.editors.open(c.file, { line: c.line }) }, icon('code'), t('Open the PHP file'))));
if (!c.resources.length) {
main.append(el('div.ap-empty', {}, el('p', {}, t('This class is not an API resource.')),
el('button.btn.primary', { 'data-tour': 'api-expose', onclick: () => this.toggleResource() }, t('Expose it with #[ApiResource]'))));
return;
}
const r = this.resource;
main.append(el('div.ap-resbar', {}, ...c.resources.map((x, i) => el('button.ap-chip' + (i === this.ri ? '.on' : ''), { onclick: () => { this.ri = i; this.buildResource(); this.buildGrid(); this.render(); } },
'#[ApiResource] ' + (c.resources.length > 1 ? (x.args.uriTemplate && !isExpr(x.args.uriTemplate) ? x.args.uriTemplate : '#' + (i + 1)) : ''))),
el('button.btn.small', { onclick: () => this.addResource() }, icon('plus'), t('Subresource')),
el('span.ap-spacer'), el('button.btn.small', { onclick: () => this.toggleResource() }, icon('trash'), t('Remove #[ApiResource]'))));
for (const [title, keys] of RES_SECTIONS) {
main.append(el('div.ap-section', {}, t(title)), el('div.ap-form', {}, ...keys.map((k) => this.control(this.res.model, k))));
}
// operations
main.append(el('div.ap-section', {}, t('Operations'), el('span.ap-sub', {}, this.res.explicit ? '' : t('none listed: API Platform makes its default ones'))));
const ops = el('div.ap-ops');
main.append(ops);
this.renderOps(ops);
main.append(el('div.ap-actions', {}, el('button.btn.primary', { onclick: () => this.saveResource() }, t('Preview and save…')),
el('button.btn', { onclick: async () => { this.buildResource(); this.render(); } }, t('Reset'))));
void info;
}
renderOps(box) {
clear(box);
const res = this.res;
if (!res.explicit) {
const defaults = this.cls.routes.filter((x) => x.resource === this.ri);
for (const d of defaults) box.append(el('div.ap-op.dflt', {}, el('span.ap-method.m-' + d.method, {}, d.method), el('code', {}, d.path), el('span.ap-sub', {}, d.type)));
box.append(el('button.btn.small', { onclick: () => { res.explicit = true; res.dirtyOps = true; res.ops = defaults.map((d) => ({ index: null, type: d.type, ...modelOf({}, OP_FIELDS), initType: d.type, open: false, expr: null })); this.renderOps(box); } },
t('Make them explicit to edit them')));
return;
}
for (const [i, op] of res.ops.entries()) {
const route = this.cls.routes.find((x) => x.resource === this.ri && x.operation === op.index && op.index !== null);
const head = el('div.ap-ophead', {},
el('button.ap-fold', { onclick: () => { op.open = !op.open; this.renderOps(box); } }, icon(op.open ? 'collapse' : 'expand')),
op.expr ? el('code', {}, op.expr) : el('select.input.ap-type', { onchange: (e) => { op.type = e.target.value; res.dirtyOps = true; } }, ...[...new Set([...OPS, op.type])].map((x) => el('option', { value: x, selected: x === op.type }, x))),
route ? el('span.ap-method.m-' + route.method, {}, route.method) : null, route ? el('code', {}, route.path) : null,
op.m?.security ? el('span.ap-lock', { title: op.m.security }, icon('eye')) : null, el('span.ap-spacer'),
el('button.ap-x', { title: t('Remove'), onclick: () => { res.ops.splice(i, 1); res.dirtyOps = true; this.renderOps(box); } }, icon('trash')));
box.append(el('div.ap-op', {}, head, op.open && !op.expr ? el('div.ap-form', {}, ...OP_FIELDS.map((k) => this.control(op, k, () => { res.dirtyOps = true; }))) : null));
}
box.append(el('button.btn.small', { onclick: (e) => menu(OPS.map((x) => ({ label: x, action: () => { res.ops.push({ index: null, type: x, ...modelOf({}, OP_FIELDS), initType: x, open: true, expr: null }); res.dirtyOps = true; this.renderOps(box); } })), e.currentTarget) },
icon('plus'), t('Add an operation')));
}
/** one field of a form model, as the control of its kind */
control(model, k, onchange = () => {}) {
const [label, kind] = FIELD[k];
if (k in model.locked) return el('div.ap-f', {}, el('span.ap-fl', {}, t(label)), el('code.ap-expr', { title: t('An expression in the code: edit it there') }, String(model.locked[k])));
const m = model.m;
let ctl;
const set = (v) => { m[k] = v; onchange(); };
switch (kind) {
case 'tri':
ctl = el('select.input', { onchange: (e) => set(e.target.value) }, el('option', { value: '', selected: m[k] === '' }, t('default')), el('option', { value: 'true', selected: m[k] === 'true' }, t('yes')), el('option', { value: 'false', selected: m[k] === 'false' }, t('no')));
break;
case 'int': ctl = el('input.input', { type: 'number', min: 0, value: m[k], oninput: (e) => set(e.target.value) }); break;
case 'class': ctl = el('input.input', { list: 'ap-classes', value: m[k], placeholder: k === 'processor' || k === 'provider' ? 'App\\State\\…' : '', oninput: (e) => set(e.target.value.trim()) }); break;
case 'groups': ctl = this.chips(m[k], set, 'ap-groups'); break;
case 'formats':
ctl = el('div.ap-checks', {}, ...FORMATS.map((f) => el('label.ap-check', {}, el('input', { type: 'checkbox', checked: m[k].includes(f), onchange: (e) => set(e.target.checked ? [...m[k], f] : m[k].filter((x) => x !== f)) }), f)));
break;
case 'order': ctl = this.rows(m[k], set, (row, up) => [
el('input.input', { list: 'ap-props', value: row[0], placeholder: t('property'), oninput: (e) => { row[0] = e.target.value; up(); } }),
el('select.input', { onchange: (e) => { row[1] = e.target.value; up(); } }, ...['ASC', 'DESC'].map((d) => el('option', { value: d, selected: String(row[1]).toUpperCase() === d }, d)))], ['', 'ASC']); break;
case 'links': ctl = this.rows(m[k], set, (row, up) => [
el('input.input', { value: row[0], placeholder: 'authorId', oninput: (e) => { row[0] = e.target.value; up(); } }),
el('input.input', { list: 'ap-classes', value: row[1], placeholder: 'fromClass', oninput: (e) => { row[1] = e.target.value; up(); } }),
el('input.input', { value: row[2], placeholder: 'fromProperty', oninput: (e) => { row[2] = e.target.value; up(); } }),
el('input.input', { value: row[3], placeholder: 'toProperty', oninput: (e) => { row[3] = e.target.value; up(); } })], ['', '', '', '']); break;
default: ctl = el('input.input', { value: m[k], oninput: (e) => set(e.target.value) });
}
if (kind === 'order' && !this.datalists.querySelector('#ap-props')) this.datalists.append(el('datalist', { id: 'ap-props' }, ...(this.cls?.properties || []).map((p) => el('option', { value: p.name }))));
return el('div.ap-f' + (kind === 'order' || kind === 'links' || kind === 'formats' ? '.wide' : ''), {}, el('span.ap-fl', {}, t(label)), ctl);
}
/** a list of words as chips with an input to add one (Enter or a comma) */
chips(list, set, datalist) {
const box = el('div.ap-chips');
const draw = () => {
clear(box);
for (const g of list) box.append(el('span.ap-tag', {}, g, el('button', { onclick: () => { list = list.filter((x) => x !== g); set(list); draw(); } }, '×')));
const input = el('input.ap-add', { list: datalist, placeholder: '+', onkeydown: (e) => {
if ((e.key === 'Enter' || e.key === ',') && input.value.trim()) { e.preventDefault(); const v = input.value.trim().replace(/,$/, ''); if (!list.includes(v)) { list = [...list, v]; set(list); } draw(); box.querySelector('input')?.focus(); }
}, onchange: () => { const v = input.value.trim(); if (v && !list.includes(v)) { list = [...list, v]; set(list); draw(); } } });
box.append(input);
};
draw();
return box;
}
/** rows of inputs (order, links) with add and remove */
rows(list, set, cells, blank) {
const box = el('div.ap-rows');
const draw = () => {
clear(box);
for (const [i, row] of list.entries()) box.append(el('div.ap-row', {}, ...cells(row, () => set(list)), el('button.ap-x', { onclick: () => { list.splice(i, 1); set(list); draw(); } }, icon('trash'))));
box.append(el('button.btn.small', { onclick: () => { list.push([...blank]); set(list); draw(); } }, icon('plus'), t('Add')));
};
draw();
return box;
}
// saving the resource --------------------------------------------------------------------------------------------
async saveResource() {
const r = this.res;
const spec = { index: this.ri, args: changed(r.model, r.keys) };
if (r.dirtyOps || r.ops.some((o) => o.type !== o.initType || !same(o.m, o.init))) {
spec.operations = r.ops.filter((o) => !o.expr || o.index !== null).map((o) => ({ index: o.index, type: o.type,
args: o.index === null ? changed(o, OP_FIELDS, true) : changed(o, OP_FIELDS) }));
}
await this.change('apiplatform.resource.update', { class: this.selected, spec }, this.cls.name);
}
async toggleResource() {
if (!this.cls.resources.length) return this.change('apiplatform.resource.update', { class: this.selected, spec: { index: null, args: {} } }, this.cls.name);
if (!await confirm(t('Remove #[ApiResource]'), t('Remove the #[ApiResource] attribute of {name}?', { name: this.cls.name }), { ok: t('Preview…') })) return;
return this.change('apiplatform.resource.update', { class: this.selected, spec: { index: this.ri, remove: true } }, this.cls.name);
}
async addResource() {
const uri = await prompt(t('Subresource'), { label: t('URI template'), value: '/' + (this.meta.classes.find((c) => c.class === this.selected)?.name || '').toLowerCase() + 's/{id}/…', ok: t('Preview…') });
if (!uri) return;
await this.change('apiplatform.resource.update', { class: this.selected, spec: { index: null, args: { uriTemplate: uri }, operations: [{ type: 'GetCollection', args: {} }] } }, this.cls.name);
}
/** a change computed by the backend, shown as a diff, written on Apply */
async change(command, payload, title, { apply = 'apiplatform.apply', after = null } = {}) {
try {
const r = await backend.invoke(command, payload);
this.preview(r.changes, { title, apply, after });
} catch (e) { notify(e.message, 'error', { title: 'API Platform' }); }
}
preview(changes, { title, apply = 'apiplatform.apply', after = null, payload = null } = {}) {
if (!changes?.length) { notify(t('Nothing to change.'), 'info', { title: 'API Platform' }); return; }
const monaco = window.monaco;
const host = el('div.ap-diff');
let diff = null;
const list = el('div.ap-files');
const showFile = (i) => {
list.querySelectorAll('.ap-file').forEach((n, j) => n.classList.toggle('on', j === i));
const c = changes[i];
const lang = c.path.endsWith('.json') ? 'json' : c.path.endsWith('.http') || c.path.includes('.http') ? 'plaintext' : 'php';
if (monaco) {
if (!diff) diff = monaco.editor.createDiffEditor(host, { readOnly: true, renderSideBySide: false, automaticLayout: true, minimap: { enabled: false }, fontSize: 12.5, scrollBeyondLastLine: false });
diff.setModel({ original: monaco.editor.createModel(c.before, lang), modified: monaco.editor.createModel(c.after, lang) });
const once = diff.onDidUpdateDiff(() => { once.dispose(); const first = diff.getLineChanges()?.[0]; if (first) diff.getModifiedEditor().revealLineInCenter(Math.max(1, first.modifiedStartLineNumber)); });
} else { clear(host); host.append(el('pre', {}, c.after)); }
};
const label = { create: t('new'), update: t('changed'), conflict: t('kept, new one beside it'), delete: t('removed'), settings: t('new'), env: t('changed') };
for (const [i, c] of changes.entries()) {
list.append(el('div.ap-file', { onclick: () => showFile(i) }, el('span.ap-tag2' + (c.new ? '.new' : ''), {}, c.action ? label[c.action] || c.action : c.new ? t('new') : t('changed')), el('span', {}, c.path)));
}
dialog({
title, wide: true, body: el('div.ap-preview', {}, el('div.ap-side2', {}, list), host),
onClose: () => { const m = diff?.getModel(); diff?.dispose(); m?.original?.dispose(); m?.modified?.dispose(); },
buttons: [{ label: t('Cancel') }, { label: t('Apply ({n} files)', { n: changes.length }), primary: true, tour: 'change-apply', action: async () => {
const r = await backend.invoke(apply, payload || { changes });
notify(t('{n} files written.', { n: r.written.length }), 'success', { title: 'API Platform' });
for (const p of r.written) this.app.editors?.changed?.(p);
this.plan = null;
await this.load();
after?.(r);
} }],
}).box.classList.add('ap-dialog');
showFile(0);
}
// the properties tab ---------------------------------------------------------------------------------------------
renderProperties(body) {
const main = el('div.ap-main');
body.append(el('div.ap-cols', {}, this.classList(), main));
const c = this.cls;
if (!c) { main.append(el('div.ap-hint', {}, t('No PHP class here yet.'))); return; }
const g = this.grid;
main.append(el('div.ap-head', {}, el('b', {}, c.name), el('span.ap-sub', {}, c.resources.length ? '#[ApiResource] ' + (this.ri + 1) : t('This class is not an API resource.')), el('span.ap-spacer'),
el('button.btn.small', { onclick: () => this.addGroup() }, icon('plus'), t('Group')),
el('button.btn.primary.small', { onclick: () => this.saveGrid() }, t('Preview and save…'))));
const table = el('table.ap-grid');
const head = el('tr', {}, el('th', {}, t('Property')), el('th', {}, t('Type')),
...g.cols.map((col) => el('th.ap-gh', {}, el('div', {}, col),
el('div.ap-rw', {}, el('button' + (g.norm.has(col) ? '.on' : ''), { onclick: () => { g.norm.has(col) ? g.norm.delete(col) : g.norm.add(col); this.render(); } }, 'R'),
el('button' + (g.denorm.has(col) ? '.on' : ''), { onclick: () => { g.denorm.has(col) ? g.denorm.delete(col) : g.denorm.add(col); this.render(); } }, 'W')))),
el('th', {}, t('Readable')), el('th', {}, t('Writable')), el('th', {}, t('Identifier')), el('th', {}, t('Filters')), el('th', {}, t('Description')), el('th', {}, t('Example')));
table.append(el('thead', {}, head));
const tbody = el('tbody');
for (const p of c.properties) {
const row = g.rows[p.name];
const orm = p.orm ? (p.orm.kind === 'relation' ? p.orm.relation + ' → ' + short(p.orm.target) : p.orm.type) : (p.phpType || '');
tbody.append(el('tr', {}, el('td.ap-pn', { title: t('Open the PHP file'), onclick: () => this.app.editors.open(c.file, { line: p.line }) }, p.id ? icon('star') : null, p.name), el('td.ap-pt', {}, orm),
...g.cols.map((col) => el('td.ap-c', {}, el('input', { type: 'checkbox', checked: row.groups.has(col), onchange: (e) => { e.target.checked ? row.groups.add(col) : row.groups.delete(col); } }))),
el('td.ap-c', {}, el('input', { type: 'checkbox', checked: row.readable, onchange: (e) => { row.readable = e.target.checked; } })),
el('td.ap-c', {}, el('input', { type: 'checkbox', checked: row.writable, onchange: (e) => { row.writable = e.target.checked; } })),
el('td.ap-c', {}, el('input', { type: 'checkbox', checked: row.identifier, onchange: (e) => { row.identifier = e.target.checked; } })),
el('td.ap-filters', {}, this.filterCell(row)),
el('td', {}, el('input.input.ap-cell', { value: row.description, oninput: (e) => { row.description = e.target.value; } })),
el('td', {}, el('input.input.ap-cell.narrow', { value: row.example, oninput: (e) => { row.example = e.target.value; } }))));
}
table.append(tbody);
main.append(el('div.ap-gridbox', {}, table));
if (c.classFilters.length) {
main.append(el('div.ap-section', {}, t('Filters declared on the class')), el('div.ap-hint', {}, c.classFilters.map((f) => (f.key || short(f.class)) + (f.properties ? ' ' + JSON.stringify(f.properties) : '')).join(' · ')));
}
}
filterCell(row) {
const box = el('div.ap-chips');
const draw = () => {
clear(box);
for (const f of row.filters) box.append(el('span.ap-tag.f', { title: f.known ? '' : f.filter }, f.label, el('button', { onclick: () => { row.filters = row.filters.filter((x) => x !== f); draw(); } }, '×')));
box.append(el('button.ap-addf', { title: t('Add a filter'), onclick: (e) => {
const items = [];
for (const f of this.meta.filters) {
if (f.strategies.length) for (const s of f.strategies) items.push({ label: `${f.key}: ${s}`, action: () => { row.filters.push({ index: null, filter: f.key, strategy: s, label: `${f.key}:${s}`, known: true }); draw(); } });
else items.push({ label: f.key, action: () => { row.filters.push({ index: null, filter: f.key, strategy: '', label: f.key, known: true }); draw(); } });
}
menu(items, e.currentTarget);
} }, '+'));
};
draw();
return box;
}
addGroup() {
const model = { name: '', read: true, write: true };
const name = el('input.input', { list: 'ap-groups', placeholder: 'book:read', oninput: (e) => { model.name = e.target.value.trim(); } });
const body = el('div.ap-form.col', {}, el('div.ap-f', {}, el('span.ap-fl', {}, t('Serialization group name')), name),
el('label.ap-check', {}, el('input', { type: 'checkbox', checked: true, onchange: (e) => { model.read = e.target.checked; } }), t('Read (normalization)')),
el('label.ap-check', {}, el('input', { type: 'checkbox', checked: true, onchange: (e) => { model.write = e.target.checked; } }), t('Write (denormalization)')));
dialog({ title: t('Group'), body, buttons: [{ label: t('Cancel') }, { label: t('Add'), primary: true, action: () => {
if (!model.name) return false;
const g = this.grid;
if (!g.cols.includes(model.name)) g.cols.push(model.name);
if (model.read) g.norm.add(model.name);
if (model.write) g.denorm.add(model.name);
this.render();
} }] });
}
async saveGrid() {
const g = this.grid;
const properties = {};
for (const p of this.cls.properties) {
const row = g.rows[p.name];
if (this.rowState(row) === row.init) continue;
const spec = {};
const groups = [...(p.groups || []).filter((x) => row.groups.has(x)), ...[...row.groups].filter((x) => !(p.groups || []).includes(x))];
if (!same([...groups].sort(), [...(p.groups || [])].sort())) spec.groups = groups;
const api = p.apiProperty || {};
const a = {};
const flag = (key, now, was) => { if (now !== was) a[key] = now === (key === 'identifier' ? false : true) ? null : now; };
flag('readable', row.readable, api.readable !== false);
flag('writable', row.writable, api.writable !== false);
flag('identifier', row.identifier, api.identifier === true);
const was = (v) => (typeof v === 'string' ? v : v === undefined || isExpr(v) ? '' : String(v));
if (row.description !== was(api.description)) a.description = row.description || null;
if (row.example !== was(api.example)) a.example = row.example || null;
if (Object.keys(a).length) spec.apiProperty = a;
if (!same(row.filters.map((f) => [f.index, f.filter, f.strategy]), p.filters.map((f) => [f.index, f.key || f.class, f.strategy || '']))) {
spec.filters = row.filters.map((f) => ({ index: f.index, filter: f.filter, strategy: f.strategy || null }));
}
if (Object.keys(spec).length) properties[p.name] = spec;
}
const payload = { class: this.selected, properties };
const norm = [...g.initNorm.filter((x) => g.norm.has(x)), ...[...g.norm].filter((x) => !g.initNorm.includes(x))];
const denorm = [...g.initDenorm.filter((x) => g.denorm.has(x)), ...[...g.denorm].filter((x) => !g.initDenorm.includes(x))];
const args = {};
if (!same([...norm].sort(), [...g.initNorm].sort())) args.normalizationGroups = norm.length ? norm : null;
if (!same([...denorm].sort(), [...g.initDenorm].sort())) args.denormalizationGroups = denorm.length ? denorm : null;
if (Object.keys(args).length && this.resource) payload.resource = { index: this.ri, args };
await this.change('apiplatform.properties.update', payload, this.cls.name);
}
// the state tab --------------------------------------------------------------------------------------------------
renderState(body) {
const main = el('div.ap-main.full');
body.append(main);
const state = this.meta.classes.filter((c) => c.implements.some((i) => /\\State\\(Provider|Processor)Interface$/.test(i)));
main.append(el('div.ap-head', {}, el('b', {}, t('State Providers and Processors')), el('span.ap-spacer'),
el('button.btn.small', { onclick: () => this.newState('provider') }, icon('plus'), t('New provider…')), el('button.btn.small', { onclick: () => this.newState('processor') }, icon('plus'), t('New processor…'))));
if (!state.length) { main.append(el('div.ap-hint', {}, t('No State Provider or Processor in this project yet.'))); return; }
const uses = {};
for (const c of this.meta.classes) for (const [cls, where] of c.uses || []) (uses[cls] ||= []).push(`${c.name} (${where})`);
for (const s of state) {
const kinds = s.implements.map((i) => (/ProviderInterface$/.test(i) ? 'provider' : 'processor'));
main.append(el('div.ap-state', {}, el('span.ap-badge.on', {}, [...new Set(kinds)].join(' + ')), el('a', { onclick: () => this.app.editors.open(s.file, { line: s.line }) }, s.class),
el('span.ap-sub', {}, uses[s.class] ? t('used by {list}', { list: uses[s.class].join(', ') }) : t('not wired yet')),
el('span.ap-spacer'), el('button.btn.small', { onclick: () => this.wire(s, kinds[0]) }, t('Wire…'))));
}
}
wire(s, kind) {
const apis = this.meta.classes.filter((c) => c.api);
if (!apis.length) { notify(t('No API resource to wire it to.'), 'info', { title: 'API Platform' }); return; }
chooser(apis.map((c) => ({ label: c.name, hint: c.class, action: () => this.change('apiplatform.resource.update', { class: c.class, spec: { index: 0, args: { [kind]: s.class } } },
t('Wire {state} to {name}', { state: s.name, name: c.name })) })), { placeholder: 'Resource…' });
}
async newState(kind) {
const apis = this.meta.classes.filter((c) => c.api);
const model = { name: '', resource: this.selected && apis.some((a) => a.class === this.selected) ? this.selected : apis[0]?.class || '', scope: 'resource', decorate: false };
const name = el('input.input', { placeholder: kind === 'provider' ? 'BookProvider' : 'BookProcessor', oninput: (e) => { model.name = e.target.value; } });
const resource = el('select.input', { onchange: (e) => { model.resource = e.target.value; } }, el('option', { value: '' }, t('(not wired)')), ...apis.map((c) => el('option', { value: c.class, selected: c.class === model.resource }, c.name)));
const deco = el('label.ap-check', {}, el('input', { type: 'checkbox', onchange: (e) => { model.decorate = e.target.checked; } }), kind === 'provider' ? t('Decorate the Doctrine provider') : t('Decorate the Doctrine persist processor'));
const body = el('div.ap-form.col', {}, el('div.ap-f', {}, el('span.ap-fl', {}, t('Class name')), name), el('div.ap-f', {}, el('span.ap-fl', {}, t('Wire it to')), resource), deco);
dialog({ title: kind === 'provider' ? t('New provider…') : t('New processor…'), body, buttons: [{ label: t('Cancel') }, { label: t('Preview…'), primary: true, action: async () => {
if (!model.name.trim()) return false;
await this.change('apiplatform.state.new', { kind, name: model.name.trim(), resource: model.resource, decorate: model.decorate, wire: model.resource ? { resource: 0 } : null },
kind === 'provider' ? t('New provider…') : t('New processor…'));
} }] });
}
// the routes tab -------------------------------------------------------------------------------------------------
async loadRoutes() {
try { this.routes = (await backend.invoke('apiplatform.overview', {})).routes; } catch (e) { this.routes = []; notify(e.message, 'error', { title: 'API Platform' }); }
if (this.tab === 'routes') this.render();
}
async compare() {
try {
const r = await backend.invoke('apiplatform.routes', {});
if (!r.ok) { notify(r.output || t('The console did not answer.'), 'warning', { title: 'debug:router' }); return; }
this.router = r.routes;
this.render();
} catch (e) { notify(e.message, 'error', { title: 'debug:router' }); }
}
renderRoutes(body) {
const main = el('div.ap-main.full');
body.append(main);
if (!this.routes) { main.append(el('div.ap-hint', {}, t('Loading…'))); return; }
const norm = (r) => `${r.method.replace(/\|HEAD$/, '')} ${r.path.replace(/\.\{_format\}$/, '')}`;
const real = this.router ? new Set(this.router.map(norm)) : null;
main.append(el('div.ap-head', {}, el('b', {}, t('{n} routes', { n: this.routes.length })), el('span.ap-spacer'),
this.meta.console ? el('button.btn.small', { onclick: () => this.compare() }, icon('console'), t('Compare with debug:router')) : null,
this.meta.console ? el('button.btn.small', { onclick: () => this.openapi() }, icon('code'), t('OpenAPI export')) : null));
const table = el('table.ap-grid.routes');
table.append(el('thead', {}, el('tr', {}, el('th', {}, ''), el('th', {}, t('Method')), el('th', {}, t('Path')), el('th', {}, t('Resource')), el('th', {}, t('Operation')), el('th', {}, t('Security')), el('th', {}, t('Route name')))));
const tbody = el('tbody');
for (const r of this.routes) {
const status = real ? (real.has(`${r.method} ${r.path}`) ? el('span.ap-ok', {}, '✓') : el('span.ap-ko', {}, '✗')) : '';
tbody.append(el('tr.ap-route', { onclick: () => this.show(r.class, 'resources') }, el('td', {}, status), el('td', {}, el('span.ap-method.m-' + r.method, {}, r.method)), el('td', {}, el('code', {}, r.path)),
el('td', {}, r.shortName), el('td', {}, r.type + (r.custom ? ' *' : '')), el('td.ap-sub', {}, r.security || ''), el('td.ap-sub', {}, r.name || '')));
}
table.append(tbody);
main.append(el('div.ap-gridbox', {}, table));
if (this.router) {
const known = new Set(this.routes.map((r) => `${r.method} ${r.path}`));
const extra = this.router.filter((r) => !known.has(norm(r)) && !/\/(docs|contexts|errors|validation_errors|\.well-known)/.test(r.path) && r.class);
if (extra.length) main.append(el('div.ap-section', {}, t('In debug:router, not found in the code')), el('div.ap-hint', {}, extra.map((r) => `${r.method} ${r.path.replace(/\.\{_format\}$/, '')} (${short(r.class)})`).join(' · ')));
}
}
async openapi() {
try {
const r = await backend.invoke('apiplatform.openapi', {});
dialog({ title: 'api:openapi:export', wide: true, body: el('textarea.input.ap-out', { readonly: true, value: r.output }), buttons: [{ label: t('Copy'), action: () => { copyText(r.output); return false; } }, { label: t('Close') }] });
} catch (e) { notify(e.message, 'error', { title: 'api:openapi:export' }); }
}
// the requests tab -----------------------------------------------------------------------------------------------
async loadPlan() {
try { this.plan = await backend.invoke('apiplatform.requests.plan', {}); } catch (e) { this.plan = { plan: [], changes: [] }; notify(e.message, 'error', { title: 'API Platform' }); }
if (this.tab === 'requests') this.render();
}
renderRequests(body) {
const main = el('div.ap-main.full');
body.append(main);
main.append(el('div.ap-head', {}, el('b', {}, t('HTTP Client requests')), el('span.ap-spacer'),
el('button.btn.small', { onclick: () => this.generate(this.selected ? [this.selected] : null) }, icon('play'), t('Generate for {name}', { name: short(this.selected) })),
el('button.btn.primary.small', { onclick: () => this.generate(null) }, icon('play'), t('Generate for all resources')),
el('button.btn.small', { onclick: () => this.openHttpClient() }, icon('globe'), t('Open the HTTP Client'))));
if (!this.plan) { main.append(el('div.ap-hint', {}, t('Loading…'))); return; }
const label = { create: t('new'), update: t('will be refreshed'), unchanged: t('up to date'), keep: t('yours: kept'), conflict: t('yours: the new one goes beside it'), delete: t('removed from the class: deleted'), forget: t('yours: kept, no longer followed'), settings: t('collection settings'), env: t('environment variables') };
const by = {};
for (const p of this.plan.plan) (by[p.collection] ||= []).push(p);
if (!Object.keys(by).length) main.append(el('div.ap-hint', {}, t('No API resource yet.')));
for (const [collection, items] of Object.entries(by)) {
main.append(el('div.ap-section', {}, collection, el('span.ap-sub', {}, `http-requests/${collection}/`)));
for (const p of items) {
const m = /^(GET|POST|PUT|PATCH|DELETE)\s+(\S+)/m.exec(p.after || p.before || '');
main.append(el('div.ap-req.a-' + p.action, {}, el('span.ap-tag2.' + p.action, {}, label[p.action] || p.action), m ? el('span.ap-method.m-' + m[1], {}, m[1]) : null, el('code', {}, p.path),
m ? el('span.ap-sub', {}, m[2]) : null));
}
}
main.append(el('div.ap-hint', {}, t('A request you edited in the HTTP Client is never overwritten: the tool keeps it and writes its new version beside it as name.theirs.http.')));
}
/** the HTTP Client window (loaded the first time), its collections read again */
async openHttpClient(show = true) {
if (show) this.app.showTool('httpClient', true);
const hc = await this.app.httpClient?.ready?.();
await hc?.load();
return hc;
}
async generate(classes) {
try {
const r = await backend.invoke('apiplatform.requests.plan', classes ? { classes } : {});
this.preview(r.changes, { title: t('HTTP Client requests'), apply: 'apiplatform.requests.apply', payload: classes ? { classes } : {}, after: () => this.openHttpClient(false) });
} catch (e) { notify(e.message, 'error', { title: 'API Platform' }); }
}
registerActions(a) {
a.add('apiPlatformTool', 'API Platform', () => this.show(null), { icon: 'structure' });
a.add('apiPlatformRequests', 'API Platform: Generate the HTTP Client Requests', () => { this.tab = 'requests'; prefs.set('apiTab', 'requests'); this.show(null, 'requests'); this.loadPlan(); }, { icon: 'play' });
a.add('apiPlatformRoutes', 'API Platform: Routes', () => { this.show(null, 'routes'); this.loadRoutes(); }, { icon: 'globe' });
}
}