import { createEffect, createMemo, createSignal, For, onSettled, Show, type Component, } from "solid-js"; import { saveAuditReport } from "../lib/auditexport"; import { auditLength, audits, hideAudit, showAudit, stepAudit, type AuditCategory, type AuditDetail, type AuditSpan, type LoadAudit, } from "../lib/loadaudit"; import { count } from "../lib/print"; /** * The load flamegraph: one track's load, drawn on one axis. * * `:timeaudit` raises it. It answers the question the console trace cannot — not *what is this * load waiting on* but **where did the time go** — and that answer needs the overlaps kept, so it * needs a picture rather than a list. The fetch is a long bar; the codec is a short one inside it; * the waveform fold is thirty thin bars after the decode; the cover's palette is a bar that began * before the press and lands after the first sample; the detector's search sits on a lane of its * own because it is not on this thread. * * **Lanes, not a strict pyramid.** A flame graph normally assumes every interval lies inside its * parent, and half of this load does not: the accent effect, the fold's pump and the worker's * search are children of the *track* and siblings of the fetch, running alongside it. So a span is * placed in the first lane below its parent that its time does not collide with, and its own * children start below that. Nothing overlaps and nothing is flattened away, and two things that * genuinely run at once read as running at once rather than one inside the other — which is the * difference between a chart of this player and a chart of a loader with one sequential await. * * Three things it deliberately does not do: * * - **It does not sample.** Every bar is an interval some function opened and closed around its * own wait (`lib/loadaudit.ts`). Nothing is inferred here, so a gap in the picture is a stretch * of the load no code claimed — a finding, not a missing sample. * - **It does not hand the keyboard to the page behind it.** Like the artwork overlay it binds on * the window in the capture phase and swallows what it uses (Tab and the modifiers are left * alone — one is the browser's route out, the others are the browser's). This overlay exists to * be read, and the keys behind it would change what is being read while it is being read. * - **It does not pretend a load is over.** While a span is open the axis keeps growing and the * header names what is still running. But it grows in *steps*: a graph that relaid itself out * every millisecond would spend more on being redrawn than the load spends loading, and the * measurement it is watching would be the worse for being watched. */ /** Pixels per lane, and the hairline gap that keeps two lanes readable as two. */ const LANE_H = 17; /** Below this a bar is a hairline rather than a bar, and it is folded into its parent's count. */ const MIN_PX = 0.6; /** Lanes drawn before the graph stops growing rather than becoming unreadable. */ const MAX_LANES = 26; /** Mono at 10px: enough to size a label to its bar without measuring text. */ const CHAR_PX = 6.05; /** How tall one row of mark labels is, in the band reserved for them under the lanes. */ const MARK_ROW = 11; /** Chart a mark's label wants beside the one to its left before the two may share a row. */ const MARK_GAP = 7; /** Rows of mark labels to make room for, and no more: past this the marks are a wall, not a story. */ const MARK_ROWS_MAX = 4; /** How often the axis is re-asked how far the load has got, while something is still open. */ const TICK_MS = 140; /** The chart's width until the observer says otherwise: wide enough that a four-second load is * still a picture rather than a thumb, and the number a test without layout is measured against. */ const WIDTH = 960; const CATEGORIES: AuditCategory[] = [ "network", "disk", "decode", "audio", "analysis", "waveform", "accent", "wait", "main", ]; /** A bar as it will be drawn: where, how wide, which lane, and what it hides. */ interface Row { uid: string; span: AuditSpan; x: number; w: number; lane: number; /** Direct children — the `+n` a narrow parent advertises so a thin bar can be read as a deep one. */ kids: number; /** Time inside this span that is not inside one of its children, ms. */ self: number; } /** A mark's line where it belongs, and its label where there is room for it. */ interface MarkLabel { key: number; name: string; /** The moment itself, in chart px. Never moved: this is the measurement. */ at: number; /** Where the label is drawn, which is not the same place — see `marks`. */ x: number; row: number; } interface Layout { rows: Row[]; lanes: number; /** Self time per category over *every* span, drawn or not: the answer to "where did it go". */ totals: Record; hidden: number; } /** Milliseconds, at the precision that matches their size. */ const fmt = (ms: number): string => ms < 1 ? `${ms.toFixed(2)}ms` : ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(2)}s`; /** * The ladder the axis and the ruler snap to. * * A decade of 1/1.2/1.5/2/2.5/3/4/5/6/8 rather than the usual 1/2/5, for a reason specific to this * chart: the axis is *also* the amount of picture that is not the load. On a 1/2/5 ladder a * 1.1-second load is drawn across half of a 2-second axis, and the empty right half of a * flamegraph reads as a load that stopped rather than as rounding. Stepping is still the point — a * live load relayouts the whole chart whenever the axis changes, so the ladder has to be coarse * enough that it changes a handful of times per load and not per span. */ const STEPS: number[] = []; for (let decade = 0.1; decade <= 600_000; decade *= 10) { for (const m of [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8]) { STEPS.push(Math.round(decade * m * 100) / 100); } } const niceCeil = (ms: number): number => { for (const s of STEPS) if (ms <= s) return s; return Math.ceil(ms / 600_000) * 600_000; }; const niceStep = (ms: number): number => { for (const s of STEPS) if (ms <= s) return s; return 600_000; }; /** * A detail record as a list of rows with a stable field to key on. * * `Object.entries` hands back a fresh tuple per pass, and a `` over those is the * `UNSTABLE_LIST_IDENTITY` diagnostic waiting to happen; `{k, v}` objects with `k` as the key are * the same information in a shape the list can hold on to. */ const factsOf = (detail: AuditDetail | undefined): { k: string; v: string }[] => Object.entries(detail ?? {}).map(([k, v]) => ({ k, v: String(v) })); /** * The end a span reaches: its own, or — while it is still open — as far as the load has actually * got, never further than the window being drawn. * * The distinction matters because the axis is rounded *up* to a step: extend an open span to the * axis edge and every still-running wait is drawn as though it had reached the end of the ruler, * which is a bar that overstates by whatever the rounding added. The frontier is the truth; the * axis is the paper it is drawn on. */ const endOf = (s: AuditSpan, live: number, to: number): number => s.end ?? Math.min(to, Math.max(s.start, live)); /** * Place every span in a lane, depth-first from the roots. * * The lane a span takes is the first one below its parent's that its time does not collide with, * which is what lets concurrent top-level spans (stream, cover, fold, detector) share the picture * without pretending to nest. Occupancy is tracked per lane across the whole chart — a lane is a * row of pixels, and two bars in it at the same moment would be one unreadable bar. */ function layoutSpans( audit: LoadAudit, from: number, to: number, width: number, live: number, ): Layout { const spans = audit.raw(); const known = new Set(); for (const s of spans) known.add(s.key); const kidsOf = new Map(); for (const s of spans) { // A parent that never made it into the buffer (dropped by the cap) must not take its children // down with it: orphaned, they become top-level bars, which is what they look like. const parent = s.parent !== null && known.has(s.parent) ? s.parent : null; const bucket = kidsOf.get(parent) ?? []; bucket.push(s); kidsOf.set(parent, bucket); } for (const list of kidsOf.values()) list.sort((a, b) => a.start - b.start); const scale = width / Math.max(1e-6, to - from); const totals = Object.fromEntries(CATEGORIES.map((c) => [c, 0])) as Record; const laneEnd: number[] = []; const rows: Row[] = []; let hidden = 0; let lanes = 0; const place = (span: AuditSpan, minLane: number): void => { const start = span.start; const end = Math.max(start, endOf(span, live, to)); let lane = Math.max(0, minLane); while (lane < laneEnd.length && laneEnd[lane]! > start) lane += 1; laneEnd[lane] = end; lanes = Math.max(lanes, lane + 1); const kids = kidsOf.get(span.key) ?? []; const spanMs = end - start; let childMs = 0; for (const k of kids) childMs += Math.max(0, endOf(k, live, to) - k.start); const x = (start - from) * scale; const w = spanMs * scale; if (lane < MAX_LANES && w >= MIN_PX && x + w > 0 && x < width) { rows.push({ uid: `${audit.seq}:${span.key}`, span, x: Math.max(0, x), w: Math.min(width - Math.max(0, x), w), lane, kids: kids.length, self: Math.max(0, spanMs - childMs), }); } else { // Folded away, but still counted: a thin bar with nothing in it and a thin bar with the // whole waveform fold in it are different diagnoses, and the count is what tells them apart. hidden += 1; } // Self time is counted for folded spans too — the totals are a fact about the load, not about // what happened to fit on screen. totals[span.category] += Math.max(0, spanMs - childMs); for (const k of kids) place(k, lane + 1); }; for (const root of kidsOf.get(null) ?? []) place(root, 0); return { rows, lanes: Math.max(1, lanes), totals, hidden }; } interface Props { /** The timeline being drawn. The graph follows it: `←`/`→` swap it for another load. */ audit: LoadAudit; } export const TimeAuditModal: Component = (props) => { let backdrop: HTMLDivElement | undefined; let host: HTMLDivElement | undefined; /** Zoomed window into the load, or null for all of it. */ const [view, setView] = createSignal<{ from: number; to: number } | null>(null, { name: "audit-view", }); const [selected, setSelected] = createSignal(null, { name: "audit-selected" }); const [hovered, setHovered] = createSignal(null, { name: "audit-hovered" }); /** The chart's width in CSS pixels — the fallback the observer has not yet corrected. */ const [width, setWidth] = createSignal(WIDTH, { name: "audit-width" }); /** The heartbeat, written only while something is still open. */ const [beat, setBeat] = createSignal(0, { name: "audit-beat" }); const spans = createMemo(() => props.audit.raw(), { name: "audit-spans" }); const openSpans = createMemo(() => spans().filter((s) => s.end === null), { name: "audit-open", }); /** * How far the load has reached: the last recorded end, or the current moment for anything still * open — which is what makes the picture grow while a load runs instead of appearing all at once * when it finishes. */ const reached = createMemo( () => { spans(); // any span opened or closed moves the frontier beat(); // ...and so does the heartbeat, but only while a span is open return auditLength(props.audit); }, { name: "audit-reached" }, ); /** * The axis, rounded up to a step. * * The rounding is not decoration: this is the value that decides whether every bar in the graph * has to move. Without it a live load relayouts the whole chart every heartbeat, and the cost of * watching the load lands on the load. With it the graph grows in visible steps — cheaper to * draw, and easier to read than something that creeps. */ const axis = createMemo(() => Math.max(10, niceCeil(reached())), { name: "audit-axis" }); const range = createMemo(() => view() ?? { from: 0, to: axis() }, { name: "audit-window" }); const layout = createMemo( () => layoutSpans(props.audit, range().from, range().to, width(), reached()), { name: "audit-layout" }, ); const byUid = createMemo(() => new Map(layout().rows.map((r) => [r.uid, r])), { name: "audit-by-uid", }); /** What the readout is about: what the pointer is on, else what was last clicked. */ const focusUid = createMemo(() => hovered() ?? selected(), { name: "audit-focus-uid" }); const focus = createMemo(() => (focusUid() ? (byUid().get(focusUid()!) ?? null) : null), { name: "audit-focus-row", }); const px = createMemo(() => width() / Math.max(1e-6, range().to - range().from), { name: "audit-px-per-ms", }); /** * Where the marks' labels go — which is *not* where the marks are. * * The marks of a real load arrive in pairs: the press and the moment the bytes were asked for are * one millisecond apart, and the first sample and the row's first report are close enough that * neither label has the chart to itself. Drawn at their own x, in one row, those labels sit on top * of each other and read as one smear of overstruck letters — which is worse than not drawing * them, because it looks like a bug in the drawing. * * So the labels are packed left to right into rows: each goes to the first row whose last label * has finished before this one starts, the way a ruler's tick labels are packed. The rows get a * band of their own under the lanes, so a stack of labels never sits on a stack of bars. * * Only the *label* moves. The line stays at the instant, always, even when the label has been * pushed a row down or pulled inside the right edge — that asymmetry is the point: the position is * the measurement, and the text is its caption. Past `MARK_ROWS_MAX` rows the marks have stopped * being a story, and a label shares a row with its neighbour rather than pushing the picture taller. */ const marks = createMemo( () => { const out: MarkLabel[] = []; const edge: number[] = []; // where each row's last label ended const list = [...props.audit.marks()].sort((a, b) => a.at - b.at); for (const m of list) { const at = (m.at - range().from) * px(); if (at < -2 || at > width() + 2) continue; // outside the drawn window, so there is no line to caption const w = m.name.length * CHAR_PX + 6; const x = Math.max(0, Math.min(width() - w, at + 4)); let row = edge.findIndex((right) => x >= right + MARK_GAP); if (row < 0) row = Math.min(edge.length, MARK_ROWS_MAX - 1); edge[row] = Math.max(edge[row] ?? 0, x + w); out.push({ key: m.key, name: m.name, at, x, row }); } return { out, rows: Math.max(1, edge.length) }; }, { name: "audit-marks" }, ); /** Where the lanes end, which is where the marks' band begins. */ const lanesBottom = createMemo(() => Math.min(MAX_LANES, layout().lanes) * LANE_H + 14, { name: "audit-lanes-bottom", }); const height = createMemo( () => lanesBottom() + (marks().out.length ? marks().rows * MARK_ROW + 3 : 0), { name: "audit-height" }, ); /** Ruler ticks, in ms, at a step that leaves the axis legible at this width. */ const ticks = createMemo( () => { const { from, to } = range(); const step = niceStep(Math.max(0.1, (to - from) / 8)); const out: number[] = []; for (let t = Math.ceil(from / step) * step; t <= to + 1e-6 && out.length < 40; t += step) out.push(Math.round(t * 100) / 100); return out; }, { name: "audit-ticks" }, ); /** * A fresh timeline is a fresh subject. * * The zoom, the selection and the hover all belong to the load they were made on, and carrying * them onto another track's graph would be a comparison nobody asked for that nothing on screen * would distinguish from an honest one. */ createEffect( () => props.audit.seq, () => { setView(null); setSelected(null); setHovered(null); }, { name: "audit-reset" }, ); /** * Keep the axis honest while something is still running. * * Bound on the open-span count rather than always on: once a load has settled there is nothing * left to grow, and a timer that redraws a finished graph is a chart animating its own staleness. */ /** * Keep the axis honest while something is still running. * * Bound on the open-span count rather than always on: once a load has settled there is nothing * left to grow, and a timer that redraws a finished graph is a chart animating its own staleness. * The teardown is *returned* rather than handed to `onCleanup`, which is the `library-sync` idiom * and the one this codebase's diagnostics accept from an effect phase. */ createEffect( () => openSpans().length, (live) => { if (live === 0) return; const beat = setInterval(() => setBeat((n) => n + 1), TICK_MS); return () => clearInterval(beat); }, { name: "audit-tick" }, ); /** * The panel's width, the pointer's keys, and the focus — all once, once the node is in the * document. * * `onSettled` is the 2.0 replacement for `onMount` + `onCleanup` (see VirtualList.tsx): it cannot * host `onCleanup()`, so the teardown is *returned*, and reads inside it are untracked by design, * which is what is wanted — one observer and one listener per mount, however often the timeline * being drawn changes underneath them. * * Three things live here because each one is only true after the settle: * * - **Focus.** Not from a `ref`: a ref runs while the element is still detached, and focus on a * detached element is simply refused. The backdrop takes it — the keyboard belongs to the * overlay as a whole, and no bar inside it wants to be a tab stop. * - **The width.** The axis is pixels-per-millisecond, so a guessed width is a wrong ruler. The * observer is asked rather than the layout read directly: reading `clientWidth` here would * force a synchronous reflow immediately after the chart was built, and ResizeObserver reports * the size in a callback the browser runs when layout is already clean. Where there is no * observer at all (jsdom), the signal keeps the fallback it was created with. * - **The keyboard**, bound in the capture phase for the reason the artwork overlay gives: the * library view binds `j`/`k`/`g`/`/`/Escape on the window in the bubble phase, and a capture * listener on the same target runs first — so a key that belongs to the graph cannot also move * a cursor behind it or arm a search field nobody can see. `←`/`→` walk the recorded loads * rather than the list's cursor, `z` (with Backspace and `c`) undoes a zoom, and Escape leaves. * Tab goes to the browser: a dialog you cannot leave is worse than one whose keys leak. */ onSettled(() => { backdrop?.focus(); let teardown: (() => void) | undefined; const el = host; if (el && typeof ResizeObserver !== "undefined") { const ro = new ResizeObserver(() => setWidth(Math.max(320, el.clientWidth || WIDTH))); ro.observe(el); teardown = () => ro.disconnect(); } const onKey = (e: KeyboardEvent) => { if (e.key === "Tab" || e.metaKey || e.ctrlKey || e.altKey) return; if (e.key === "Escape" || e.key === "ArrowLeft" || e.key === "ArrowRight") { e.preventDefault(); e.stopImmediatePropagation(); if (e.key === "Escape") hideAudit(); else stepAudit(e.key === "ArrowLeft" ? -1 : 1); return; } if ( e.key === "z" || e.key === "Z" || e.key === "c" || e.key === "C" || e.key === "Backspace" ) { e.preventDefault(); e.stopImmediatePropagation(); setView(null); setSelected(null); } if (e.key === "e" || e.key === "E") { e.preventDefault(); e.stopImmediatePropagation(); exportReport(); } }; window.addEventListener("keydown", onKey, true); return () => { teardown?.(); clearTimeout(savedTimer); window.removeEventListener("keydown", onKey, true); }; }); /** * Handing the records out, from the graph. * * `e` for the keyboard and a chip in the footer for everything else — the phone that asked for * this measurement has no keyboard in front of it half the time, and the person holding it is the * one who wants to send it to somebody else. The line says what actually happened, including the * case where the browser refused to produce a file: a silent button is a button nobody trusts. */ const [saved, setSaved] = createSignal(null); let savedTimer: ReturnType | undefined; const exportReport = (): void => { const name = saveAuditReport(); setSaved(name ?? "this browser will not hand out a file"); clearTimeout(savedTimer); // Quiet again after a while: the footer is a record of the load, and a stale "saved" reads as // belonging to the load now on screen. savedTimer = setTimeout(() => setSaved(null), 6000); }; const zoomTo = (r: Row): void => { const dur = Math.max(1, (r.span.end ?? r.span.start) - r.span.start); const pad = dur * 0.1; setView({ from: Math.max(0, r.span.start - pad), to: r.span.start + dur + pad }); setSelected(r.uid); }; /** Truncate a label to its bar rather than let it wander over its neighbours. */ const label = (r: Row): string => { const room = Math.floor((r.w - 8) / CHAR_PX); if (room < 4) return ""; const dur = fmt(Math.max(0, (r.span.end ?? r.span.start) - r.span.start)); const name = r.kids > 0 && room < 14 ? `${r.span.name}+${r.kids}` : r.span.name; const both = `${name} ${dur}`; const text = both.length <= room ? both : name; return text.length <= room ? text : `${text.slice(0, Math.max(1, room - 1))}…`; }; const totals = createMemo( () => { const t = layout().totals; const sum = CATEGORIES.reduce((a, c) => a + t[c], 0); return { sum, rows: CATEGORIES.filter((c) => t[c] > 0.05).map((c) => ({ c, ms: t[c] })) }; }, { name: "audit-totals" }, ); return (
{ backdrop = el; }} class="audit-modal" role="dialog" aria-modal="true" aria-label="Where the time went loading this track" tabindex={-1} onMouseDown={(e) => { if (e.target === backdrop) hideAudit(); // No text selection dragged out of a chart. e.preventDefault(); }} >
{props.audit.title || "untitled"} {props.audit.artist || "unknown"} {props.audit.album ? ` · ${props.audit.album}` : ""}
{props.audit.reason} {/* The load's own length, not the axis's: the two differ by whatever the ladder rounded up, and the number worth reading beside a track's name is the one the listener felt. */} {fmt(Math.min(axis(), reached()))} {count(spans().length, "span")} {count(layout().lanes, "lane")} 0}> · {layout().hidden} folded {props.audit.trackId}
0}>
still running:{" "} {openSpans() .map((s) => s.name) .join(", ")}
{ host = el; }} class="ta-chart" > {/* Every `` in here is `keyed` by a stable field. A layout pass hands back a fresh `Row` for every bar — a row is a position, and positions move when the axis does — and identity-keying those is the `UNSTABLE_LIST_IDENTITY` diagnostic: field-for-field the same bars, brand-new objects, and every `` thrown away and rebuilt on each zoom, each tick, each span that closes. The bars are hidden from the accessibility tree because they are `` elements you can only reach with a mouse, and the tree they draw is available as text — `hackermusic.timeAudit("show")` prints this same load, one line per span, which is also the version worth pasting into a bug report. */}
click a bar to zoom into it · ← → other loads · z whole load · esc close } > {(row) => { const facts = createMemo(() => factsOf(row().span.detail), { name: "audit-facts" }); return ( <> {row().span.name} {row().span.category} at {fmt(row().span.start)} {fmt(Math.max(0, (row().span.end ?? row().span.start) - row().span.start))} {axis() > 0 ? `${Math.round((100 * Math.max(0, (row().span.end ?? row().span.start) - row().span.start)) / axis())}% of load` : ""} self {fmt(row().self)} on the worker still open f.k}> {(f) => ( {f().k} {f().v} )} ); }}
t.c}> {(chip) => { // The share is read from the layout rather than carried on the item, so a relayout // updates a chip's width without rebuilding the chip. const ms = createMemo(() => layout().totals[chip().c]); return ( 0 ? (100 * ms()) / totals().sum : 0}%` }} /> {chip().c} {fmt(ms())} ); }} {(why) => {why()}} f.k}> {(f) => ( {f().k} {f().v} )}
); };