rob-revisited/ide/ui/js/flame.js

238 lines
10 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.

// Flame graph and memory chart of the Profiler (profiler.js): the pure parts (layout of the call tree, colours by
// namespace, search, the range of a run, formats; tested by flame.test.mjs) and two small canvas drawers.
/** Where a function belongs (the same rule as ProfileBuilder::space in PHP): app, engine, vendor, php. */
export function nodeSpace(name, file = '') {
if (name.startsWith('php::') || file === 'php:internal') return 'php';
const n = name.replace(/^\{/, '');
if (n.startsWith('JumPHP\\') || n.startsWith('closure:JumPHP')) return 'engine';
if (n.startsWith('App\\')) return 'app';
if (file.includes('/engine/src/') || file.includes('/jumphp/engine/')) return 'engine';
if (file.includes('/vendor/')) return 'vendor';
if (name === '(root)') return 'root';
if (!name.includes('\\') && file === '' && !name.startsWith('{')) return 'php';
return 'app';
}
/** hsl colours by namespace; a little variation per name so neighbours differ */
export const SPACE_HUE = { app: 18, engine: 212, vendor: 276, php: 140, root: 0 };
export function colorOf(node, dark = true) {
const space = nodeSpace(node.n, node.f || '');
let h = 0;
for (let i = 0; i < node.n.length; i++) h = (h * 31 + node.n.charCodeAt(i)) | 0;
const v = Math.abs(h) % 24;
if (space === 'root') return dark ? '#4a4d52' : '#c9ccd1';
return dark ? `hsl(${SPACE_HUE[space] + (v % 8) - 4} ${52 + (v % 3) * 6}% ${34 + (v % 5) * 3}%)` : `hsl(${SPACE_HUE[space] + (v % 8) - 4} ${62 + (v % 3) * 6}% ${62 + (v % 5) * 3}%)`;
}
/** The value of a node by metric: 'v' (time, ms) or 'm' (memory, bytes; a node that freed more than it took is 0). */
export const valueOf = (node, metric) => (metric === 'm' ? Math.max(0, node.m || 0) : node.v || 0);
/**
* The rectangles of a flame graph: one per node, x0..x1 in 0..1 of the root's width (the focused node when zoomed), depth = row.
* A child never exceeds its parent: children are laid left to right, largest first (as given), scaled when they add up to more.
* @param {object} root a node {n, f, l, v, m, c, ch}
* @param {{metric?: 'v'|'m', focus?: number[], minWidth?: number}} opts focus: indexes of ch from the root; minWidth: fraction below which nodes are dropped
*/
export function layoutFlame(root, { metric = 'v', focus = [], minWidth = 0.0005 } = {}) {
let top = root;
const path = [root];
for (const i of focus) {
const next = top.ch?.[i];
if (!next) break;
top = next;
path.push(top);
}
const total = valueOf(top, metric) || 1e-12;
const rects = [];
const walk = (node, x0, x1, depth, indexPath) => {
rects.push({ node, x0, x1, depth, path: indexPath });
const kids = node.ch || [];
if (!kids.length) return;
const sum = kids.reduce((s, k) => s + valueOf(k, metric), 0);
const scale = sum > valueOf(node, metric) && sum > 0 ? valueOf(node, metric) / sum : 1;
let x = x0;
const width = x1 - x0;
const nodeValue = valueOf(node, metric) || 1e-12;
kids.forEach((k, i) => {
const w = (valueOf(k, metric) * scale / nodeValue) * width;
if (w / (1) >= minWidth) walk(k, x, x + w, depth + 1, [...indexPath, i]);
x += w;
});
};
walk(top, 0, 1, 0, [...focus.slice(0, path.length - 1)]);
return { rects, total, top, path, maxDepth: rects.reduce((m, r) => Math.max(m, r.depth), 0) };
}
/** The rectangle under a point (px, py in CSS pixels of a canvas of w x h with rows of rowH); inverted = icicle (row 0 on top). */
export function hitTest(layout, px, py, w, h, rowH, inverted) {
const row = inverted ? Math.floor(py / rowH) : Math.floor((h - py) / rowH);
const x = px / w;
for (const r of layout.rects) {
if (r.depth === row && x >= r.x0 && x < r.x1) return r;
}
return null;
}
/** The nodes whose function name (or file) contains the query: a Set of nodes (empty query: null). */
export function searchNodes(root, query) {
const q = String(query || '').trim().toLowerCase();
if (!q) return null;
const found = new Set();
const walk = (n) => {
if (n.n.toLowerCase().includes(q) || (n.f || '').toLowerCase().includes(q)) found.add(n);
(n.ch || []).forEach(walk);
};
walk(root);
return found;
}
/** Hot spots of a part of the run: sums the slices from..to (inclusive) of a profile's `slices`. */
export function rangeTotals(slices, from, to, n = 10) {
if (!slices) return null;
const last = slices.count - 1;
const a = Math.max(0, Math.min(from, to));
const b = Math.min(last, Math.max(from, to));
const t = new Array(slices.names.length).fill(0);
const m = new Array(slices.names.length).fill(0);
for (let i = a; i <= b; i++) {
(slices.t[i] || []).forEach((v, k) => { t[k] += v; });
(slices.m[i] || []).forEach((v, k) => { m[k] += v; });
}
const rows = slices.names.map((name, k) => ({ n: name, ms: t[k], bytes: m[k] }));
return {
time: rows.filter((r) => r.ms > 0 && r.n !== '(other)').sort((x, y) => y.ms - x.ms).slice(0, n),
memory: rows.filter((r) => r.bytes > 0 && r.n !== '(other)').sort((x, y) => Math.abs(y.bytes) - Math.abs(x.bytes)).slice(0, n),
ms: t.reduce((s, v) => s + v, 0), bytes: m.reduce((s, v) => s + v, 0),
};
}
/** The slices a brush from x0 to x1 (0..1 of the chart's width) covers. */
export function brushSlices(x0, x1, count = 100) {
const a = Math.max(0, Math.min(x0, x1));
const b = Math.min(1, Math.max(x0, x1));
return [Math.min(count - 1, Math.floor(a * count)), Math.min(count - 1, Math.max(Math.floor(a * count), Math.ceil(b * count) - 1))];
}
export function formatMs(ms) {
if (ms === null || ms === undefined || Number.isNaN(ms)) return '–';
const a = Math.abs(ms);
if (a >= 60000) return `${(ms / 60000).toFixed(1)} min`;
if (a >= 1000) return `${(ms / 1000).toFixed(2)} s`;
if (a >= 10) return `${ms.toFixed(1)} ms`;
if (a >= 0.1) return `${ms.toFixed(2)} ms`;
return `${(ms * 1000).toFixed(0)} µs`;
}
export function formatBytes(b) {
if (b === null || b === undefined || Number.isNaN(b)) return '–';
const sign = b < 0 ? '-' : '';
let v = Math.abs(b);
for (const unit of ['B', 'KB', 'MB', 'GB']) {
if (v < 1024 || unit === 'GB') return `${sign}${unit === 'B' ? Math.round(v) : v.toFixed(v < 10 ? 2 : 1)} ${unit}`;
v /= 1024;
}
return '';
}
export const formatCount = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e4 ? `${(n / 1e3).toFixed(0)}k` : String(n));
export const shortName = (name) => name.replace(/^.*\\([^\\]+(?:->|::))/, '$1').replace(/^JumPHP\\|^App\\/, '');
// --- drawing ---------------------------------------------------------------------------------------------------
const cssVar = (name, fallback) => (typeof getComputedStyle === 'function' ? getComputedStyle(document.documentElement).getPropertyValue(name).trim() || fallback : fallback);
/** Draws a flame graph into a canvas (CSS size w x h). Returns what the pointer needs: {layout, rowH, inverted}. */
export function drawFlame(canvas, root, { metric = 'v', focus = [], inverted = false, search = null, hover = null, dark = true, rowH = 18 } = {}) {
const dpr = window.devicePixelRatio || 1;
const w = canvas.clientWidth;
const layout = layoutFlame(root, { metric, focus, minWidth: 0.6 / Math.max(1, w) });
const h = Math.max(60, (layout.maxDepth + 1) * rowH + 2);
canvas.style.height = `${h}px`;
canvas.width = Math.round(w * dpr);
canvas.height = Math.round(h * dpr);
const g = canvas.getContext('2d');
g.scale(dpr, dpr);
g.clearRect(0, 0, w, h);
g.font = '11px ' + (cssVar('--font', 'system-ui'));
g.textBaseline = 'middle';
const text = cssVar('--text', '#ddd');
for (const r of layout.rects) {
const x = r.x0 * w;
const bw = (r.x1 - r.x0) * w;
if (bw < 0.5) continue;
const y = inverted ? r.depth * rowH : h - (r.depth + 1) * rowH;
const dim = search && !search.has(r.node);
g.globalAlpha = dim ? 0.25 : 1;
g.fillStyle = colorOf(r.node, dark);
g.fillRect(x, y, Math.max(0.5, bw - 1), rowH - 1);
if (hover && hover.node === r.node) { g.strokeStyle = text; g.lineWidth = 1.5; g.strokeRect(x + 0.5, y + 0.5, Math.max(1, bw - 2), rowH - 2); }
if (search && !dim) { g.strokeStyle = '#ffd24a'; g.lineWidth = 1.5; g.strokeRect(x + 0.5, y + 0.5, Math.max(1, bw - 2), rowH - 2); }
if (bw > 28) {
g.fillStyle = dark ? '#fff' : '#111';
g.save();
g.beginPath();
g.rect(x + 2, y, bw - 4, rowH);
g.clip();
g.fillText(shortName(r.node.n), x + 4, y + rowH / 2);
g.restore();
}
}
g.globalAlpha = 1;
return { layout, rowH, inverted, w, h };
}
/** The memory chart: an area of usage over time, the peak marked, a brush (x0..x1 in 0..1) shaded. */
export function drawMemory(canvas, timeline, { brush = null, dark = true } = {}) {
const dpr = window.devicePixelRatio || 1;
const w = canvas.clientWidth;
const h = canvas.clientHeight || 90;
canvas.width = Math.round(w * dpr);
canvas.height = Math.round(h * dpr);
const g = canvas.getContext('2d');
g.scale(dpr, dpr);
g.clearRect(0, 0, w, h);
const ys = timeline.m;
const max = Math.max(1, ...ys);
const min = Math.min(...ys);
const lo = Math.max(0, min - (max - min) * 0.15);
const n = ys.length;
const X = (i) => (i / Math.max(1, n - 1)) * w;
const Y = (v) => h - 14 - ((v - lo) / Math.max(1, max - lo)) * (h - 26);
const accent = cssVar('--accent', '#3574f0');
g.beginPath();
g.moveTo(0, h - 14);
ys.forEach((v, i) => g.lineTo(X(i), Y(v)));
g.lineTo(w, h - 14);
g.closePath();
g.fillStyle = dark ? 'rgba(84,138,247,0.28)' : 'rgba(53,116,240,0.22)';
g.fill();
g.beginPath();
ys.forEach((v, i) => (i ? g.lineTo(X(i), Y(v)) : g.moveTo(X(i), Y(v))));
g.strokeStyle = accent;
g.lineWidth = 1.5;
g.stroke();
const pk = ys.indexOf(max);
g.fillStyle = cssVar('--red', '#e06c6c');
g.beginPath();
g.arc(X(pk), Y(max), 3, 0, Math.PI * 2);
g.fill();
g.font = '10px ' + cssVar('--font', 'system-ui');
g.fillStyle = cssVar('--text-2', '#999');
g.textBaseline = 'alphabetic';
g.textAlign = pk > n * 0.7 ? 'right' : 'left';
g.fillText(formatBytes(max), X(pk) + (pk > n * 0.7 ? -6 : 6), Math.max(10, Y(max) - 4));
g.textAlign = 'left';
g.fillText('0', 2, h - 3);
g.textAlign = 'right';
g.fillText(`${(timeline.duration).toFixed(timeline.duration < 10 ? 2 : 1)} s`, w - 2, h - 3);
if (brush) {
const a = Math.min(brush[0], brush[1]) * w;
const b = Math.max(brush[0], brush[1]) * w;
g.fillStyle = 'rgba(255,210,74,0.18)';
g.fillRect(a, 0, Math.max(1, b - a), h - 14);
g.strokeStyle = '#ffd24a';
g.lineWidth = 1;
g.strokeRect(a + 0.5, 0.5, Math.max(1, b - a), h - 15);
}
}