Examples
Three integrations using the published v0.1.0 packages.
Embed a React lesson
Save as SortingLesson.tsx. Render the exported component in a React 18 or 19 application with an optional Theme prop. Pass a stable input to reuse it across multiple lessons.
npm install @gvejs/algorithms@0.1.0 @gvejs/react@0.1.0 @gvejs/themes@0.1.0import { bubbleSort } from "@gvejs/algorithms";
import { AlgorithmVisualizer } from "@gvejs/react";
import type { Theme } from "@gvejs/themes";
import "@gvejs/themes/style.css";
const exampleInput = [8, 3, 5, 1, 9];
const systemTheme: Theme = { mode: "auto", colors: {} };
export function SortingLesson({
theme = systemTheme,
input = exampleInput,
}: {
theme?: Theme;
input?: number[];
}) {
return (
<AlgorithmVisualizer
algorithm={bubbleSort}
input={input}
theme={theme}
showControls
showCode
showVariables
showInput
/>
);
}Replay a saved trace
Save as headless-replay.ts in an ESM TypeScript project. Compile and run the emitted JavaScript in Node.js to print the sorted cell labels. The trace passes through the same validation it would receive after loading a saved recording.
npm install @gvejs/algorithms@0.1.0 @gvejs/core@0.1.0 @gvejs/runtime@0.1.0 @gvejs/renderers@0.1.0import { bubbleSort } from "@gvejs/algorithms";
import { parseTrace, serializeTrace } from "@gvejs/core";
import { layoutCells } from "@gvejs/renderers";
import { createPlayback, generateTrace } from "@gvejs/runtime";
const recording = serializeTrace(generateTrace(bubbleSort, [3, 1, 2]));
const trace = parseTrace(recording, bubbleSort, bubbleSort.input);
const playback = createPlayback(bubbleSort, trace);
try {
playback.seek(trace.events.length);
const [row] = layoutCells(playback.getSnapshot().state);
console.log(row.map((cell) => cell.label).join(", "));
} finally {
playback.dispose();
}Define a custom algorithm
Save as gnome-sort.ts and install @gvejs/core@0.1.0. Import the exported gnomeSort in place of bubbleSort in either example above. A namespaced event tracks the moving cursor and built-in events handle comparisons and swaps.
import { defineAlgorithm } from '@gvejs/core';
import type { CustomEvent, Schema } from '@gvejs/core';
type Move = CustomEvent<{ index: number }> & { type: 'example:move' };
const moveSchema: Schema<Move['payload']> = (value): value is Move['payload'] =>
typeof value === 'object' && value !== null && 'index' in value &&
typeof value.index === 'number' && Number.isSafeInteger(value.index) && value.index >= 0;
export const gnomeSort = defineAlgorithm<number[], number[], Move>({
metadata: {
id: 'gnome-sort',
title: 'Gnome Sort',
category: 'Sorting',
description: 'Walk forward on ordered pairs and step back after swapping an inversion.',
code: ['move the cursor', 'compare neighbors', 'swap inverted neighbors', 'return the ordered values'],
examples: [[4, 2, 3, 1]],
},
input: (value): value is number[] =>
Array.isArray(value) && Array.from(value).every(item => typeof item === 'number' && Number.isFinite(item)),
initial: input => ({ kind: 'array', values: [...input] }),
customEvents: { 'example:move': moveSchema },
reduceCustom: (state, event) => ({
...state,
pointers: { cursor: event.payload.index },
variables: { ...state.variables, cursor: event.payload.index },
}),
*execute(input) {
const values = [...input];
let index = 1;
while (index < values.length) {
yield { type: 'example:move', payload: { index }, line: 1, explanation: `Inspect position ${index}.` };
yield { type: 'compare', a: index - 1, b: index, line: 2 };
if (values[index - 1] <= values[index]) {
index++;
} else {
[values[index - 1], values[index]] = [values[index], values[index - 1]];
yield { type: 'swap', a: index - 1, b: index, line: 3, explanation: 'Swap an inverted pair.' };
index = Math.max(1, index - 1);
}
}
yield { type: 'highlight', targets: [], line: 4, explanation: 'The array is sorted.' };
return values;
},
});