Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | 5x 5x 5x 5x 232x 260x 5x 12x 9x 8x 8x 12x 8x 1x 5x 18x 14x 12x 5x 4x 46x 116x 41x 39x 39x 38x 5x 14x 5x 37x 292x 282x 36x 36x 36x 180x 36x 7x 5x 46x 46x 4x 4x 46x 23x 2x 2x 1x 5x 24x 5x 4x 4x 4x 3x 34x 34x 32x 32x 34x 34x 34x 226x 34x 34x 34x 34x 256x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 128x 128x 128x 4x 4x 124x 80x 80x 80x 80x 80x 80x 80x 34x 34x 2x 2x 11x 34x 34x 34x 13x 13x 34x 6x 6x 4x 4x 34x 34x 2x 34x 34x 34x 34x 1x 1x 1x 1x 32x 12x 5x 5x 5x 5x 32x 32x | import { escape } from "../core/escape.js";
import { createPlayer, type Player, type PlayerState } from "../core/player.js";
import type { Trace, Vars, View } from "../core/trace.js";
import { fitTo, largest, svgSize } from "./fit.js";
import { ICONS } from "./icons.js";
/** Text for the controls and panels, for screen readers and tooltips. Translate them with `labels`. */
export interface Labels {
first: string;
prev: string;
play: string;
pause: string;
next: string;
last: string;
step: string;
code: string;
variables: string;
speed: string;
}
export const LABELS: Labels = {
first: "First step",
prev: "Previous step",
play: "Play",
pause: "Pause",
next: "Next step",
last: "Last step",
step: "Step",
code: "Code",
variables: "Variables",
speed: "Speed",
};
export interface RenderOptions<S> {
/** Overrides the trace's own view. Required when the trace has none. */
view?: View<S>;
intervalMs?: number;
/** Source code to show under the figure. Steps tagged with `t.at(line)` highlight that line. */
code?: string;
labels?: Partial<Labels>;
/**
* Keeps the step in the page URL as `#<element id>=<step>`, so a link can open the figure at that step.
* Needs the element to have an id. Written when the reader moves, not during playback.
*/
link?: boolean;
}
export interface RenderedFigure extends Player {
/** Stops playback and removes the figure's listeners and observer. Leaves the markup in place. */
destroy(): void;
}
type Action = "first" | "prev" | "toggle" | "next" | "last" | "speed";
const KEYS: Record<string, Action> = {
Home: "first",
ArrowLeft: "prev",
" ": "toggle",
ArrowRight: "next",
End: "last",
};
// Action, icon, label, key for aria-keyshortcuts, key as shown in the tooltip.
const BUTTONS: [Action, keyof typeof ICONS, keyof Labels, string, string][] = [
["first", "first", "first", "Home", "Home"],
["prev", "prev", "prev", "ArrowLeft", "←"],
["toggle", "play", "play", "Space", "Space"],
["next", "next", "next", "ArrowRight", "→"],
["last", "last", "last", "End", "End"],
];
const SPEEDS = [0.5, 1, 2, 4];
const speedText = (speed: number) => `${speed}×`;
const withKey = (label: string, key: string) => `${label} (${key})`;
// Markup pieces shared by render() and toHTML(), so the static and live figure are the same.
/** A value as the reader would write it. Never throws: watched values can be cyclic or not JSON at all. */
const show = (v: unknown): string => {
if (typeof v === "number") return String(v); // JSON would print NaN and Infinity as null
if (typeof v === "bigint") return `${v}n`;
try {
const json = JSON.stringify(v, (_, x) =>
typeof x === "bigint" ? `${x}n` : x instanceof Map ? Object.fromEntries(x) : x instanceof Set ? [...x] : x);
return json ?? String(v);
} catch {
return "[circular]";
}
};
const varsItems = (vars: Vars | undefined) =>
Object.entries(vars ?? {})
.filter(([, v]) => v !== undefined)
.map(([name, v]) => `<div><dt>${escape(name)}</dt><dd>${escape(show(v))}</dd></div>`)
.join("");
const codeLines = (code: string) =>
code
.replace(/\n$/, "")
.split("\n")
.map((text, i) => `<span class="stepthru-line" data-line="${i + 1}">${escape(text)}</span>`)
.join("");
const counterText = (index: number, length: number) => `${index + 1} / ${length}`;
function prepare<S>(trace: Trace<S>, { view = trace.view, labels, code }: RenderOptions<S>) {
if (!view) throw new TypeError("render needs a view: pass options.view or use a structure tracer");
const { steps } = trace;
if (steps.length === 0) throw new RangeError("the trace has no steps");
if (code !== undefined) {
const count = code.replace(/\n$/, "").split("\n").length;
const bad = steps.find((step) => step.line !== undefined && step.line > count);
if (bad) throw new RangeError(`a step is tagged with line ${bad.line}, but the code has ${count} lines`);
}
return {
steps,
// Draws a step on demand. Keeping every step's markup would hold megabytes for long traces.
draw: (index: number) => view(steps[index].state),
text: { ...LABELS, ...labels },
code,
hasVars: steps.some((step) => step.vars),
};
}
function figureHTML({ steps, draw, text, code, hasVars }: ReturnType<typeof prepare>, controlsHidden: boolean) {
const [first] = steps;
const last = steps.length - 1;
const buttons = BUTTONS.map(
([action, icon, label, key, keyText]) =>
`<button type="button" data-action="${action}" aria-label="${escape(text[label])}" aria-keyshortcuts="${key}"`
+ ` title="${escape(withKey(text[label], keyText))}">${ICONS[icon]}</button>`,
).join("");
return `<div class="stepthru-figure">${draw(0)}</div>`
+ (hasVars ? `<dl class="stepthru-vars" aria-label="${escape(text.variables)}">${varsItems(first.vars)}</dl>` : "")
+ `<p class="stepthru-caption" aria-live="polite">${escape(first.caption)}</p>`
+ `<div class="stepthru-controls"${controlsHidden ? " hidden" : ""}>${buttons}`
+ `<input class="stepthru-scrub" type="range" min="0" max="${last}" value="0" aria-label="${escape(text.step)}">`
+ `<span class="stepthru-counter">${counterText(0, steps.length)}</span>`
+ `<button type="button" class="stepthru-speed" data-action="speed" aria-label="${escape(`${text.speed} ${speedText(1)}`)}"`
+ ` title="${escape(text.speed)}">${speedText(1)}</button></div>`
+ (code ? `<pre class="stepthru-code" aria-label="${escape(text.code)}"><code>${codeLines(code)}</code></pre>` : "");
}
/**
* The figure's first step as an HTML string, for server or build-time rendering. Put it inside an
* element with class `stepthru`; the controls stay hidden until `render` runs on that element.
*/
export function toHTML<S>(trace: Trace<S>, options: RenderOptions<S> = {}): string {
return figureHTML(prepare(trace, options), true);
}
// Views key shapes that can move between steps with data-key and place them with a translate.
const TRANSLATE = /translate\(\s*([-\d.e]+)[\s,]+([-\d.e]+)\s*\)/;
/** Each keyed shape's place, as a CSS transform, by key. */
function places(root: Element): Map<string, [Element, string]> {
const found = new Map<string, [Element, string]>();
for (const shape of root.querySelectorAll("[data-key]")) {
const m = TRANSLATE.exec(shape.getAttribute("transform") ?? "");
Eif (m) found.set(shape.getAttribute("data-key")!, [shape, `translate(${m[1]}px, ${m[2]}px)`]);
}
return found;
}
/** Slides every keyed shape that changed place from where it was in `before`. */
function slide(root: Element, before: Map<string, [Element, string]>, ms: number) {
for (const [key, [shape, to]] of places(root)) {
const from = before.get(key)?.[1];
if (from && from !== to && typeof shape.animate === "function") {
shape.animate([{ transform: from }, { transform: to }], { duration: ms, easing: "ease-in-out" });
}
}
}
const reducedMotion = () =>
typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
// The figure mounted on each element, so rendering again into it first tears down the old one.
const mounted = new WeakMap<HTMLElement, RenderedFigure>();
/** Keeps `line` in view by scrolling `box` only, never the page. */
function scrollWithin(box: HTMLElement, line: HTMLElement) {
const top = line.offsetTop;
const bottom = top + line.offsetHeight;
if (top < box.scrollTop) box.scrollTop = top;
else if (bottom > box.scrollTop + box.clientHeight) box.scrollTop = bottom - box.clientHeight;
}
/** Mounts a playable figure for `trace` into `el` and returns its player. Replaces what `el` holds. */
export function render<S>(trace: Trace<S>, el: HTMLElement, options: RenderOptions<S> = {}): RenderedFigure {
const prepared = prepare(trace, options);
if (options.link && !el.id) throw new TypeError("link needs the figure's element to have an id");
const hashKey = `#${encodeURIComponent(el.id)}=`;
mounted.get(el)?.destroy();
const { steps, draw, text } = prepared;
const last = steps.length - 1;
// Size every step once up front, so the figure can keep the size of its largest step. A tracer's own `size` is
// much cheaper than drawing, but it only describes the tracer's own view.
const measure = trace.size && !options.view ? trace.size.bind(trace) : null;
const sizes = steps.map((step, i) => (measure ? measure(step.state) : svgSize(draw(i))));
const box = largest(sizes);
el.classList.add("stepthru");
el.tabIndex = 0;
el.innerHTML = figureHTML(prepared, false);
const part = <T extends Element>(selector: string) => el.querySelector<T>(selector);
const figure = part<HTMLElement>(".stepthru-figure")!;
const caption = part<HTMLElement>(".stepthru-caption")!;
const scrub = part<HTMLInputElement>(".stepthru-scrub")!;
const counter = part<HTMLElement>(".stepthru-counter")!;
const toggle = part<HTMLButtonElement>('[data-action="toggle"]')!;
const speedButton = part<HTMLButtonElement>(".stepthru-speed")!;
const vars = part<HTMLElement>(".stepthru-vars");
const codeBox = part<HTMLElement>(".stepthru-code");
const lines = [...el.querySelectorAll<HTMLElement>(".stepthru-line")];
let shown = 0;
let linking = false;
const update = ({ index, playing, speed }: PlayerState) => {
const step = steps[index];
// Slide only between neighboring steps; a jump across many steps would only smear.
const before = Math.abs(index - shown) === 1 && !reducedMotion() ? places(figure) : null;
figure.innerHTML = draw(index);
if (box) fitTo(figure.querySelector("svg")!, sizes[index]!, box);
if (before) slide(figure, before, 250 / Math.max(speed, 1));
shown = index;
// replaceState, so stepping does not fill the back button's history. Skipped for the first draw, so mounting writes nothing.
if (options.link && linking && !playing) history.replaceState(history.state, "", `${hashKey}${index + 1}`);
// Announce only steps the reader moves to; during playback a caption every interval is noise.
caption.setAttribute("aria-live", playing ? "off" : "polite");
caption.textContent = step.caption;
if (vars) vars.innerHTML = varsItems(step.vars);
for (const line of lines) {
const current = Number(line.dataset.line) === step.line;
line.classList.toggle("is-current", current);
if (current) {
line.setAttribute("aria-current", "step");
Eif (codeBox) scrollWithin(codeBox, line);
} else line.removeAttribute("aria-current");
}
scrub.value = String(index);
counter.textContent = counterText(index, steps.length);
toggle.innerHTML = playing ? ICONS.pause : ICONS.play;
toggle.setAttribute("aria-label", playing ? text.pause : text.play);
toggle.title = withKey(playing ? text.pause : text.play, "Space");
speedButton.textContent = speedText(speed);
speedButton.setAttribute("aria-label", `${text.speed} ${speedText(speed)}`);
};
const player = createPlayer(steps.length, update, options.intervalMs);
const actions: Record<Action, () => void> = {
first: () => player.seek(0),
prev: player.prev,
toggle: player.toggle,
next: player.next,
last: () => player.seek(last),
speed: () => player.setSpeed(SPEEDS.find((s) => s > player.state.speed) ?? SPEEDS[0]),
};
const listeners = new AbortController();
const { signal } = listeners;
el.addEventListener("click", (e) => {
const action = (e.target as Element).closest<HTMLElement>("[data-action]")?.dataset.action;
Eif (action) actions[action as Action]();
}, { signal });
el.addEventListener("keydown", (e) => {
// The slider handles its own arrows, Home and End; a focused button handles its own space.
const onButton = e.target instanceof HTMLButtonElement && e.key !== " ";
if ((e.target !== el && !onButton) || !(e.key in KEYS)) return;
e.preventDefault();
actions[KEYS[e.key]]();
}, { signal });
scrub.addEventListener("input", () => player.seek(Number(scrub.value)), { signal });
// Pause when the figure scrolls out of view, so it does not run where nobody can see it.
const observer = typeof IntersectionObserver === "undefined"
? null
: new IntersectionObserver(([entry]) => {
if (!entry.isIntersecting && player.state.playing) player.pause();
});
observer?.observe(el);
update(player.state);
linking = true;
if (options.link && location.hash.startsWith(hashKey)) {
const step = Number(location.hash.slice(hashKey.length));
Eif (Number.isInteger(step) && step >= 1) {
player.seek(step - 1);
el.scrollIntoView({ block: "center" });
}
}
const figureApi: RenderedFigure = {
...player,
get state() {
return player.state;
},
destroy() {
if (player.state.playing) player.pause();
listeners.abort();
observer?.disconnect();
Eif (mounted.get(el) === figureApi) mounted.delete(el);
},
};
mounted.set(el, figureApi);
return figureApi;
}
|