rob-revisited/ide/ui/js/controller-panel-model.js

94 lines
4.8 KiB
JavaScript

// The model of the controller panel (controller-panel.js), no DOM: what to ask the PHP side and when (a controller open in the
// editor, its text changing as the user types), the URL of a route with its placeholders filled, the HTTP Client request
// made from a route and the words of its security line.
/** a file worth asking about (cheap, before any round trip): the PHP side decides for real */
export function looksLikeController(path, text = '') {
if (!/\.php$/i.test(path || '')) return false;
return /Controller/.test(path) || /#\[\s*(?:\\?[\w\\]*\\)?Route\b|\bextends\s+(?:\\?[\w\\]*\\)?AbstractController\b/.test(text);
}
/** the placeholders of a route's URL ({id}, {slug}) in order */
export const placeholders = (url) => [...new Set([...String(url).matchAll(/\{(\w+)\}/g)].map((m) => m[1]))];
/** a plausible value for a placeholder: the first default, 1 for numbers, else a word */
export function sampleValue(route, name) {
const def = route.defaults?.[name];
if (def !== undefined && def !== '') return String(def);
const req = route.requirements?.[name] || '';
if (/\\d|\[0-9\]/.test(req)) return '1';
if (/^\w+(\|\w+)+$/.test(req)) return req.split('|')[0];
return req === '' && /(^id|Id|_id|^page)$/.test(name) ? '1' : 'example';
}
/** the URL path with its placeholders replaced by values (a missing one keeps its sample) */
export function fillUrl(route, values = {}) {
return route.url.replace(/\{(\w+)\}/g, (_, name) => encodeURIComponent(values[name] ?? sampleValue(route, name)));
}
/** site + path, no double slash */
export const joinUrl = (site, path) => String(site).replace(/\/+$/, '') + '/' + String(path).replace(/^\/+/, '');
/** the request the HTTP Client gets for a route: {{baseUrl}} + the path (placeholders given samples), a JSON body when the action reads a payload */
export function requestFor(route, values = {}) {
const method = route.methods?.[0] || 'GET';
const payload = (route.params || []).some((p) => p.kind === 'payload');
return {
name: `${method} ${route.name}`,
method,
url: '{{baseUrl}}' + fillUrl(route, values),
headers: payload ? [{ name: 'Content-Type', value: 'application/json', enabled: true }] : [],
body: payload ? '{\n \n}' : '',
description: route.action ? `${route.name} (${route.action})` : route.name,
};
}
/** what the security line says: the grants, the access_control rule and whether the route is public */
export function securityOf(route) {
const grants = (route.grants || []).map((g) => ({ text: g.attribute + (g.subject ? ` ← ${g.subject}` : ''), level: g.level, line: g.line }));
const rule = route.access ? { index: route.access.index, path: route.access.path, roles: route.access.roles || [], expression: route.access.expression || '' } : null;
return { grants, rule, open: grants.length === 0 && !rule };
}
/** a short text of the parameters' kind (a key of the panel's t() table) */
export const KIND_LABEL = { route: 'route value', entity: 'entity', payload: 'request payload', query: 'query string', queryParam: 'query parameter',
upload: 'upload', header: 'header', user: 'current user', request: 'request', service: 'service', resolver: 'resolver', value: 'value' };
/** the arguments worth a chip: services are what every controller has, shown only when they matter */
export const interesting = (p) => p.kind !== 'service' && p.kind !== 'request';
/** header summary: {routes, prefix} */
export function summary(info) {
return { routes: (info?.routes || []).length, prefix: info?.prefix?.path || '', namePrefix: info?.prefix?.name || '' };
}
/** A default path for a new action: "showPost" -> "/show-post" */
export const pathOfAction = (name) => '/' + String(name).replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
/** A default route name for a new action: "showPost" -> "show_post" */
export const routeNameOfAction = (name, prefix = '') => prefix + String(name).replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase();
/**
* Asks the PHP side about the open file when its text changes. A text already answered is not sent again; an answer
* that comes after a newer question is dropped (typing faster than the round trip). ask(path, text) -> promise of the info.
*/
export function createRefresher(ask) {
let lastText = null;
let lastPath = null;
let last = null;
let seq = 0;
return {
async refresh(path, text) {
if (text === lastText && path === lastPath && last) return { info: last, stale: false, cached: true };
const mine = ++seq;
const info = await ask(path, text);
if (mine !== seq) return { info: last, stale: true, cached: false };
lastText = text;
lastPath = path;
last = info;
return { info, stale: false, cached: false };
},
reset() { lastText = lastPath = last = null; seq++; },
get last() { return last; },
};
}