rob-revisited/ide/ui/js/page-preview-model.js

154 lines
7.3 KiB
JavaScript

// The model of the Twig preview's "real page" mode (html-preview.js): the route selector's groups and labels, which route is
// chosen, what its parameters need, the redirects followed from the local site (and a login among them), the stylesheet of a
// fetched page put inside it, the SQL that suggests ids. Pure: no DOM, no backend (tested by page-preview-model.test.mjs).
export const STATIC = ''; // the selector's value for "Static (no PHP)"
/** the routes in the order of the selector: those that render the template, the other GET routes, the rest */
export function groupRoutes(routes) {
const list = Array.isArray(routes) ? routes : [];
return {
renders: list.filter((r) => r.renders),
get: list.filter((r) => !r.renders && r.get),
other: list.filter((r) => !r.renders && !r.get),
};
}
/** "app_home · GET /book/{id}" (no method listed: any) */
export const routeLabel = (r) => `${r.name} · ${r.methods?.length ? r.methods.join('|') : 'ANY'} ${r.path}`;
/**
* The route to show first. `saved` = what was chosen for this template ({route, values, static}); a template nobody chose a route for
* starts on the first route that renders it, else (no controller renders it) on the static preview.
* @returns {string} a route name, or STATIC
*/
export function pickRoute(routes, saved) {
const list = Array.isArray(routes) ? routes : [];
if (saved?.static) return STATIC;
if (saved?.route && list.some((r) => r.name === saved.route)) return saved.route;
return list.find((r) => r.renders)?.name ?? STATIC;
}
export const findRoute = (routes, name) => (routes || []).find((r) => r.name === name) || null;
/** the inputs of a route's parameters, each with what was typed last time for this route */
export function inputsOf(route, savedValues = {}) {
return (route?.params || []).map((p) => ({
name: p.name,
value: typeof savedValues[p.name] === 'string' ? savedValues[p.name] : '',
placeholder: p.default !== null && p.default !== undefined ? String(p.default) : (p.requirement || (p.optional ? '' : p.name)),
required: !p.optional,
entity: p.entity || '',
table: p.table || '',
column: p.column || '',
}));
}
/** the required parameters nothing was typed in */
export const missingValues = (inputs) => inputs.filter((i) => i.required && !String(i.value).trim()).map((i) => i.name);
/** the SQL asking the first ids of an entity's table (the Database window's connection) */
export function suggestSql(input, limit = 8) {
const ident = /^[A-Za-z_][A-Za-z0-9_]*$/;
if (!input.table || !ident.test(input.table) || !ident.test(input.column || 'id')) return '';
return `SELECT ${input.column || 'id'} FROM ${input.table} ORDER BY 1 LIMIT ${limit}`;
}
/** the values of the first column of a db.run result ({results: [{result, columns, rows}]} or a page) */
export function firstColumn(answer) {
const rows = answer?.results?.[0]?.rows ?? answer?.rows ?? [];
const values = [];
for (const row of rows) {
const v = Array.isArray(row) ? row[0] : row && typeof row === 'object' ? Object.values(row)[0] : row;
if (v !== null && v !== undefined && String(v) !== '') values.push(String(v));
}
return values.slice(0, 20);
}
/** a path that looks like a sign-in page */
export const loginLike = (url) => {
let path = String(url || '');
try { path = new URL(url, 'http://x').pathname; } catch { /* as it is */ }
return /(^|\/)(login|log-in|signin|sign-in|connexion|auth|authenticate)(\/|$|_check)/i.test(path);
};
/** a redirect's Location against the address it came from */
export function resolveUrl(from, location) {
try { return new URL(location, from).href; } catch { return ''; }
}
/**
* The page of a route, redirects followed (a few, the site's own address only): `first()` fetches the route, `next(url)` an address.
* A redirect to a sign-in page is reported (`login`), the page it leads to is the one shown.
* @returns {Promise<{response: object, chain: {status: number, url: string, to: string}[], login: boolean, loop: boolean}>}
*/
export async function followRedirects(first, next, max = 5) {
let response = await first();
const chain = [];
let login = false;
while (response && !response.missing && response.status >= 300 && response.status < 400 && response.location) {
const to = resolveUrl(response.url, response.location);
chain.push({ status: response.status, url: response.url, to });
if (loginLike(to)) login = true;
if (!to || chain.length >= max) return { response, chain, login, loop: true };
response = await next(to);
}
return { response, chain, login, loop: false };
}
/** the status line under the bar: what was fetched and how it went */
export function statusOf(result) {
const r = result?.response;
if (!r) return { kind: 'none', text: '' };
if (r.missing) return { kind: 'missing', text: r.missing.join(', ') };
const kind = r.status >= 500 ? 'error' : r.status >= 400 ? 'warn' : r.status >= 300 ? 'redirect' : 'ok';
return { kind, text: `${r.status} ${r.reason || ''}`.trim(), url: r.url, time: r.time, hops: result.chain.length, login: !!result.login };
}
/** an absolute address of the site (what a page's href / src / url() means), '' for data:, #anchors, other sites */
export function absoluteOf(base, url, origin) {
const u = String(url || '').trim();
if (!u || /^(data:|#|javascript:|about:)/i.test(u)) return '';
try {
const a = new URL(u, base);
if (!/^https?:$/.test(a.protocol)) return '';
a.hash = '';
return origin && a.origin !== origin ? '' : a.href;
} catch { return ''; }
}
/**
* A stylesheet of the real page with its @import and url(...) of the site put inside it (pictures and fonts as data: URLs).
* `io` = {text(url): Promise<?string>, dataUrl(url): Promise<?string>}; `origin`: the site's, other addresses stay as they are.
*/
export async function inlineCss(css, base, io, origin, seen = new Set()) {
let out = String(css || '');
for (const m of [...out.matchAll(/@import\s+(?:url\(\s*)?(['"]?)([^'")\s;]+)\1\s*\)?([^;]*);/gi)]) {
const url = absoluteOf(base, m[2], origin);
if (!url || seen.has(url)) continue;
seen.add(url);
const inner = await io.text(url);
const media = m[3].trim();
const body = inner === null || inner === undefined ? `/* ${url}: not found */` : await inlineCss(inner, url, io, origin, seen);
out = out.replace(m[0], media ? `@media ${media} {\n${body}\n}` : body);
}
for (const m of [...out.matchAll(/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi)]) {
const url = absoluteOf(base, m[2], origin);
if (!url) continue;
const data = await io.dataUrl(url);
if (data) out = out.split(m[0]).join(`url("${data}")`);
}
return out;
}
/** the key under which the choice for a template is remembered */
export const choiceKey = (prefix, path) => `${prefix}Route:${path}`;
/** what is remembered of a choice: the route, the values typed, the session switch */
export const choiceOf = (route, values, session) => ({ route, values, session: !!session, static: route === STATIC });
/** an HTML page shown instead of the site's when it cannot be reached, with the way out */
export function offlinePage(message) {
const text = String(message || '').replace(/[<&]/g, (c) => (c === '<' ? '&lt;' : '&amp;'));
return `<!doctype html><meta charset="utf-8"><body style="font:14px system-ui;margin:2em;color:#666"><p>${text}</p></body>`;
}