rob-revisited/ide/ui/js/var-model.js

126 lines
5.7 KiB
JavaScript

// The data side of the debugger's variable tree (no DOM: tested by var-model.test.mjs): paging of big arrays, reading a whole value
// through the debugger, and its text forms (plain text, JSON, PHP code like var_export) for the Copy buttons.
// A variable is what Debugger.php property() gives: {name, fullname, type, class, value, children, size, page, pagesize, facet, length, full, items}.
const SCALARS = ['int', 'float', 'string', 'bool', 'null'];
export const isScalar = (v) => SCALARS.includes(v?.type);
/** Can the user give it a new value? A scalar the debugger can name (fullname, or the expression it was read from). */
export const isEditable = (v) => isScalar(v) && !!(v.fullname || v.expression);
/**
* Paging of a big array / object: the debugger sends `pagesize` children at a time (property_get with p=<page>).
* loaded: how many are shown; size: how many there are. -> {left, page}: how many are still to load and the page to ask for next
* (null when the page size is not known).
*/
export function pagePlan(loaded, size, pagesize) {
const left = Math.max(0, (size || 0) - loaded);
return { left, page: left > 0 && pagesize > 0 ? Math.floor(loaded / pagesize) : null };
}
/** A PHP single-quoted string literal. */
export function phpString(s) {
return `'${String(s).replace(/\\/g, '\\\\').replace(/'/g, '\\\'')}'`;
}
/** What to type to edit a scalar: a PHP literal of its current value. */
export function editText(v) {
if (v.type === 'string') return phpString(v.full ?? v.value ?? '');
if (v.type === 'null') return 'null';
return String(v.value ?? '');
}
/** The value as the row shows it (a string with its quotes). */
export function valueText(v) {
if (v.type === 'string') return JSON.stringify(v.value ?? '');
return String(v.value ?? '');
}
/** The value as plain text: a string without quotes, whole when the debugger kept it. */
export function plainText(v) {
if (v.type === 'string') return String(v.full ?? v.value ?? '');
return String(v.value ?? '');
}
/** Loads the children of a variable page by page. fetchChildren(v, page) -> {items, size, pagesize}|null. */
async function loadAll(fetchChildren, v, budget, maxNodes) {
const first = v.items ? { items: v.items, size: v.size, pagesize: v.pagesize } : await fetchChildren(v, 0);
const items = [...(first?.items || [])];
const size = v.size ?? first?.size ?? items.length;
const pagesize = v.pagesize || first?.pagesize || items.length;
while (items.length < size && budget.n + items.length < maxNodes) {
const { page } = pagePlan(items.length, size, pagesize);
if (page === null) break;
const more = await fetchChildren(v, page);
if (!more?.items?.length) break;
items.push(...more.items);
}
return { items, size };
}
/**
* A variable with all its children read (to copy it): {tree, cut}. cut: some part was left out (too deep, or more than maxNodes entries).
* fetchChildren(v, page) -> {items, size, pagesize}.
*/
export async function fetchTree(fetchChildren, v, { maxDepth = 8, maxNodes = 500 } = {}) {
const budget = { n: 0, cut: false };
const walk = async (node, depth) => {
const out = { ...node, items: [] };
if (!node.children) return out;
if (depth >= maxDepth) { budget.cut = true; return out; }
const { items, size } = await loadAll(fetchChildren, node, budget, maxNodes);
if (items.length < size) budget.cut = true;
for (const child of items) {
if (budget.n >= maxNodes) { budget.cut = true; break; }
budget.n++;
out.items.push(await walk(child, depth + 1));
}
return out;
};
return { tree: await walk(v, 0), cut: budget.cut };
}
/** The plain JS value of a read tree (for JSON). */
export function toData(node) {
switch (node.type) {
case 'null': case 'uninitialized': return null;
case 'bool': return node.value === true || node.value === 'true' || node.value === '1';
case 'int': case 'float': { const n = Number(node.value); return Number.isFinite(n) ? n : String(node.value); }
case 'string': return plainText(node);
case 'array': {
const items = node.items || [];
if (items.every((c, i) => String(c.name) === String(i))) return items.map(toData);
return Object.fromEntries(items.map((c) => [String(c.name), toData(c)]));
}
case 'object': return Object.fromEntries((node.items || []).map((c) => [String(c.name), toData(c)]));
default: return String(node.value ?? '');
}
}
export const toJson = (node) => JSON.stringify(toData(node), null, 2);
/** PHP code that rebuilds the value, like var_export (short array syntax; an object as \Class::__set_state([...])). */
export function toPhp(node, indent = '') {
const inner = `${indent} `;
const key = (c) => (/^-?(0|[1-9]\d*)$/.test(String(c.name)) ? String(c.name) : phpString(c.name));
switch (node.type) {
case 'null': case 'uninitialized': return 'null';
case 'bool': return node.value === true || node.value === 'true' ? 'true' : 'false';
case 'int': case 'float': return String(node.value);
case 'string': return phpString(plainText(node));
case 'array': {
const items = node.items || [];
if (!items.length) return '[]';
const list = items.every((c, i) => String(c.name) === String(i));
return `[\n${items.map((c) => `${inner}${list ? '' : `${key(c)} => `}${toPhp(c, inner)},\n`).join('')}${indent}]`;
}
case 'object': {
const items = node.items || [];
const cls = `\\${String(node.class || 'stdClass').replace(/^\\/, '')}`;
if (!items.length) return `${cls}::__set_state([])`;
return `${cls}::__set_state([\n${items.map((c) => `${inner}${phpString(c.name)} => ${toPhp(c, inner)},\n`).join('')}${indent}])`;
}
default: return `null /* ${node.type || 'unknown'} */`;
}
}