@grundyjs/algiviz 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,20 @@
1
1
  # Changelog
2
2
 
3
- ## 0.1.0 — unreleased
3
+ ## 0.2.0 — 2026-10-09
4
+
5
+ - Move the held key horizontally along the baseline without lifting it above the array;
6
+ remove the redundant key label while retaining its color highlight.
7
+
8
+ - Expand the demo with history/generator playback, array input, generation and speed
9
+ controls; hide individual bar labels on dense charts.
10
+
11
+ - Add `createSortPlayer` for forward-only playback with bounded snapshot storage,
12
+ interpolated canvas-compatible frames, final hold and iterator cleanup.
13
+
14
+ - Add `iterateInsertionSortSteps` for lazy immutable snapshots without retaining history.
15
+ - Keep `insertionSortSteps` compatible by collecting the shared generator implementation.
16
+
17
+ ## 0.1.0
4
18
 
5
19
  - Stable, immutable insertion sort traces with item identities and operation counters.
6
20
  - A seekable timeline with interpolated frames and final hold.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Grundy
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Grundy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -8,7 +8,7 @@ A TypeScript library for educational algorithm visualization: stable insertion s
8
8
  npm install @grundyjs/algiviz
9
9
  ```
10
10
 
11
- Try the [interactive insertion sort demo](https://grundyjs.ru/algorithms/insertion-sort/). Import the core from `@grundyjs/algiviz/core` and the browser renderer from `@grundyjs/algiviz/canvas`; there is no root entry point or CommonJS build. Version 0.1 is an initial API and may change in later minor releases.
11
+ Try the [interactive insertion sort demo](https://grundyjs.ru/algorithms/insertion-sort/). Import the core from `@grundyjs/algiviz/core` and the browser renderer from `@grundyjs/algiviz/canvas`; there is no root entry point or CommonJS build. Version 0.x is an initial API and may change in later minor releases.
12
12
 
13
13
  ## Development
14
14
 
@@ -42,6 +42,84 @@ The underlying sort uses O(n²) comparisons in the worst case and O(n) on alread
42
42
 
43
43
  Tests replay every event independently, check item conservation, stability, prefix ordering, counters, frozen snapshots and 1,093 exhaustive inputs with values -1, 0 and 1 of lengths 0–6.
44
44
 
45
+ ## Lazy steps
46
+
47
+ Use `iterateInsertionSortSteps` to consume steps on demand without retaining the
48
+ entire history. It yields the same immutable `SortStep` snapshots as
49
+ `insertionSortSteps`, which collects this iterator into a frozen array.
50
+
51
+ ```js
52
+ import { iterateInsertionSortSteps } from "@grundyjs/algiviz/core";
53
+
54
+ const iterator = iterateInsertionSortSteps([5, 2, 4, 2, 1]);
55
+ const start = iterator.next().value;
56
+ const selected = iterator.next().value;
57
+ iterator.return(); // Stop early when no more steps are needed.
58
+ ```
59
+
60
+ Creating the generator does not read the input or run the algorithm. The first
61
+ `next()` copies and validates the input; invalid values throw at that point.
62
+ Changes to the input before the first `next()` are observed; later changes do not
63
+ affect the iterator. Each subsequent `next()` runs only to the next step. An
64
+ iterator is single-use; create a new one to restart. A `for...of` loop can also
65
+ consume it, and `break` closes it early.
66
+
67
+ When the consumer retains only a fixed number of snapshots, memory is O(n).
68
+ Every snapshot still copies n slots, so consuming the complete worst-case trace
69
+ still takes O(n³) time. Collecting the iterator into an array restores the full
70
+ history memory cost. Iteration is synchronous; a long loop can block the UI.
71
+
72
+ The existing `createSortTimeline` still requires an array of steps for seeking.
73
+ It does not accept this iterator directly. Use `createSortPlayer` for forward-only
74
+ playback; the generator itself provides no timing or backward seeking.
75
+
76
+ ## Sequential playback
77
+
78
+ `createSortPlayer` consumes an iterable of steps and retains only the two adjacent
79
+ snapshots needed for rendering. With the lazy generator, playback uses O(n)
80
+ memory as long as the caller does not retain old frames.
81
+
82
+ ```js
83
+ import { createSortPlayer, iterateInsertionSortSteps } from "@grundyjs/algiviz/core";
84
+ import { createSortRenderer } from "@grundyjs/algiviz/canvas";
85
+
86
+ const player = createSortPlayer(iterateInsertionSortSteps([5, 2, 4, 1]), {
87
+ stepDurationMs: 650, finalHoldMs: 2000
88
+ });
89
+ const renderer = createSortRenderer({ theme: "dark" });
90
+ const ctx = canvas.getContext("2d");
91
+ let paused = false;
92
+ let speed = 1;
93
+ let last;
94
+ let requestId;
95
+ function tick(now) {
96
+ const delta = last === undefined ? 0 : now - last;
97
+ last = now;
98
+ if (!paused) player.advance(delta * speed);
99
+ renderer.render(ctx, player.frame);
100
+ if (!player.finished) requestId = requestAnimationFrame(tick);
101
+ }
102
+ requestId = requestAnimationFrame(tick);
103
+ // Set paused = true/false or speed = 2 from your controls.
104
+ // On teardown: cancelAnimationFrame(requestId); player.dispose();
105
+ ```
106
+
107
+ - Construction reads the first step immediately, including input validation by
108
+ the generator. The initial `frame` is fully rendered at progress 1.
109
+ - `advance(deltaMs)` accepts finite, non-negative elapsed playback time and
110
+ returns a `SortFrame` compatible with the existing canvas renderer. Zero does
111
+ not consume steps. Pause by not advancing; multiply delta by a non-negative
112
+ speed factor to change speed.
113
+ - `finished` becomes true after the final transition and `finalHoldMs`. Further
114
+ advances return the final frame. There is no known total duration or seeking.
115
+ - The source must end with a `done` event. The player closes the iterator when
116
+ that transition completes; unexpected exhaustion or source errors throw and
117
+ close playback. `dispose()` closes early and is safe to repeat; afterward the
118
+ frame remains readable but `advance()` throws.
119
+ - Restart by disposing the old player and creating a new player and generator.
120
+ Large deltas synchronously consume all intervening steps, so limit the elapsed
121
+ delta in the UI if resuming from a background tab should not cause a long catch-up.
122
+
45
123
  ## Timeline and canvas
46
124
 
47
125
  Import `createSortTimeline` from `@grundyjs/algiviz/core` and `createSortRenderer` from `@grundyjs/algiviz/canvas`.
@@ -57,7 +135,15 @@ const renderer = createSortRenderer({ theme: "dark" });
57
135
  renderer.render(canvas.getContext("2d"), timeline.sample(3250));
58
136
  ```
59
137
 
60
- Build, serve this project root using any static HTTP server, and open examples/index.html for play, pause, restart and seeking. The example changes bitmap size to fit its container; for video use a separate canvas with fixed export dimensions. Canvas rendering does not start any animation loop. There are no video recording dependencies.
138
+ Build, serve this project root using any static HTTP server, and open examples/index.html for play, pause, restart and seeking. The example changes bitmap size to fit its container; for video use a separate canvas with fixed export dimensions. Canvas rendering does not start any animation loop. There are no video recording dependencies.
139
+
140
+ The demo supports history (up to 64 items) and generator playback (up to 2,000).
141
+ Enter values or generate random, sorted or reversed arrays. Both modes support
142
+ pause, restart and speed changes; seeking is available only with full history.
143
+ Mode changes restart the loaded array. These limits apply only to the demo.
144
+ Dense charts hide bar labels. Hidden tabs pause playback, and delayed frames cap
145
+ catch-up work to keep controls responsive.
146
+
61
147
 
62
148
  ## API at a glance
63
149
 
@@ -70,4 +156,31 @@ For playback, call `timeline.sample(elapsedMs)` in your own requestAnimationFram
70
156
  ## Release
71
157
 
72
158
  Run `npm test`, `npm pack --dry-run` and test the resulting tarball in a separate consumer project. Source and issues: [urffin/algiviz](https://github.com/urffin/algiviz). Publishing is a separate maintainer action.
73
-
159
+
160
+ ### Publishing from GitHub Releases
161
+
162
+ The `.github/workflows/npm-publish.yml` workflow publishes to npm when a stable
163
+ GitHub Release is published (`release: published`). Drafts, prereleases and tag
164
+ pushes alone do not publish a package. The release tag must be `v` followed by
165
+ the exact version in `package.json` and `package-lock.json` (for example `v0.2.0`).
166
+ The workflow uses Node.js 24 and npm 11. The publish lifecycle runs the tests and
167
+ build before publishing with provenance, using npm trusted publishing (OIDC).
168
+
169
+ One-time setup in the npm package settings, under **Trusted Publisher**:
170
+
171
+ - Provider: GitHub Actions.
172
+ - Organization or user: `urffin`.
173
+ - Repository: `algiviz`.
174
+ - Workflow filename: `npm-publish.yml` (without the directory).
175
+ - Environment: leave empty; this workflow does not use a GitHub environment.
176
+ - Allow direct publishing with `npm publish` if the settings show this option.
177
+
178
+ No `NPM_TOKEN` secret is required. Keep account 2FA enabled.
179
+ See [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/).
180
+
181
+ For each release, update the version and changelog, commit and push the changes
182
+ (including the workflow), then publish a GitHub Release for the matching tag at
183
+ that commit. Check the Actions run and the npm package version afterward. Do not
184
+ reuse an already published npm version; if setup failed before publication,
185
+ correct the settings and rerun the failed workflow.
186
+
@@ -49,20 +49,19 @@ export function createSortRenderer(options) {
49
49
  for (const [id, next] of after) {
50
50
  const old = before.get(id) ?? next;
51
51
  const x = margin + ((old.index + (next.index - old.index) * p) + 0.5) * cell;
52
- const lift = ((old.held ? 1 : 0) + ((next.held ? 1 : 0) - (old.held ? 1 : 0)) * p) * height * 0.13;
53
52
  const size = Math.max(4, Math.abs(next.item.value) / maxMagnitude * available);
54
53
  const active = event.type === "compare" ? id === event.leftId || id === event.rightId :
55
54
  "itemId" in event && event.itemId === id;
56
55
  ctx.fillStyle = next.held ? colors.held : active ? colors.active :
57
56
  next.index < frame.current.sortedPrefixLength ? colors.sorted : colors.bar;
58
- ctx.fillRect(x - barWidth / 2, baseline - size - lift, barWidth, size);
57
+ ctx.fillRect(x - barWidth / 2, baseline - size, barWidth, size);
58
+ if (cell < 24)
59
+ continue;
59
60
  ctx.fillStyle = colors.text;
60
61
  ctx.font = `${fontSize}px sans-serif`;
61
62
  ctx.textAlign = "center";
62
- ctx.fillText(String(next.item.value), x, baseline - size - lift - fontSize, cell * 0.95);
63
+ ctx.fillText(String(next.item.value), x, baseline - size - fontSize, cell * 0.95);
63
64
  ctx.fillText(String(next.index), margin + (next.index + 0.5) * cell, baseline + height * 0.06);
64
- if (next.held)
65
- ctx.fillText("key", x, baseline - lift + fontSize, cell * 0.95);
66
65
  }
67
66
  ctx.textAlign = "left";
68
67
  ctx.font = `${Math.max(11, Math.min(18, width * 0.03))}px sans-serif`;
@@ -1,4 +1,6 @@
1
- export { insertionSortSteps } from "./insertion-sort.js";
1
+ export { insertionSortSteps, iterateInsertionSortSteps } from "./insertion-sort.js";
2
2
  export type { Item, SortEvent, SortSnapshot, SortStep } from "./types.js";
3
3
  export { createSortTimeline } from "./timeline.js";
4
4
  export type { SortFrame, SortTimeline } from "./timeline.js";
5
+ export { createSortPlayer } from "./player.js";
6
+ export type { SortPlayer } from "./player.js";
@@ -1,2 +1,3 @@
1
- export { insertionSortSteps } from "./insertion-sort.js";
1
+ export { insertionSortSteps, iterateInsertionSortSteps } from "./insertion-sort.js";
2
2
  export { createSortTimeline } from "./timeline.js";
3
+ export { createSortPlayer } from "./player.js";
@@ -1,3 +1,8 @@
1
1
  import type { SortStep } from "./types.js";
2
2
  /** Creates a stable ascending insertion-sort trace without modifying the input. */
3
3
  export declare function insertionSortSteps(values: readonly number[]): readonly SortStep[];
4
+ /**
5
+ * Yields immutable snapshots without retaining history.
6
+ * Input is copied and validated on the first next(), not when creating the iterator.
7
+ */
8
+ export declare function iterateInsertionSortSteps(values: readonly number[]): Generator<SortStep, void, unknown>;
@@ -1,5 +1,12 @@
1
1
  /** Creates a stable ascending insertion-sort trace without modifying the input. */
2
2
  export function insertionSortSteps(values) {
3
+ return Object.freeze([...iterateInsertionSortSteps(values)]);
4
+ }
5
+ /**
6
+ * Yields immutable snapshots without retaining history.
7
+ * Input is copied and validated on the first next(), not when creating the iterator.
8
+ */
9
+ export function* iterateInsertionSortSteps(values) {
3
10
  // Array.from also exposes sparse holes as undefined for validation.
4
11
  const input = Array.from(values);
5
12
  for (let i = 0; i < input.length; i++) {
@@ -8,14 +15,14 @@ export function insertionSortSteps(values) {
8
15
  }
9
16
  }
10
17
  const slots = input.map((value, index) => Object.freeze({ id: `item-${index}`, value }));
11
- const steps = [];
18
+ let index = 0;
12
19
  let held = null;
13
20
  let sortedPrefixLength = Math.min(1, slots.length);
14
21
  let comparisons = 0;
15
22
  let writes = 0;
16
23
  const emit = (event) => {
17
- steps.push(Object.freeze({
18
- index: steps.length,
24
+ return Object.freeze({
25
+ index: index++,
19
26
  event: Object.freeze(event),
20
27
  state: Object.freeze({
21
28
  slots: Object.freeze(slots.slice()),
@@ -24,36 +31,35 @@ export function insertionSortSteps(values) {
24
31
  comparisons,
25
32
  writes
26
33
  })
27
- }));
34
+ });
28
35
  };
29
- emit({ type: "start" });
36
+ yield emit({ type: "start" });
30
37
  for (let i = 1; i < slots.length; i++) {
31
38
  const key = slots[i];
32
39
  held = key;
33
40
  slots[i] = null;
34
41
  sortedPrefixLength = i;
35
- emit({ type: "select", itemId: key.id, from: i });
42
+ yield emit({ type: "select", itemId: key.id, from: i });
36
43
  let hole = i;
37
44
  while (hole > 0) {
38
45
  const left = slots[hole - 1];
39
46
  comparisons++;
40
- emit({ type: "compare", leftId: left.id, rightId: key.id });
47
+ yield emit({ type: "compare", leftId: left.id, rightId: key.id });
41
48
  if (left.value <= key.value)
42
49
  break;
43
50
  slots[hole] = left;
44
51
  slots[hole - 1] = null;
45
52
  writes++;
46
53
  sortedPrefixLength = hole - 1;
47
- emit({ type: "shift", itemId: left.id, from: hole - 1, to: hole });
54
+ yield emit({ type: "shift", itemId: left.id, from: hole - 1, to: hole });
48
55
  hole--;
49
56
  }
50
57
  slots[hole] = key;
51
58
  held = null;
52
59
  writes++;
53
60
  sortedPrefixLength = i + 1;
54
- emit({ type: "insert", itemId: key.id, to: hole });
61
+ yield emit({ type: "insert", itemId: key.id, to: hole });
55
62
  }
56
63
  sortedPrefixLength = slots.length;
57
- emit({ type: "done" });
58
- return Object.freeze(steps);
64
+ yield emit({ type: "done" });
59
65
  }
@@ -0,0 +1,15 @@
1
+ import type { SortStep } from "./types.js";
2
+ import type { SortFrame } from "./timeline.js";
3
+ export interface SortPlayer {
4
+ readonly frame: SortFrame;
5
+ readonly finished: boolean;
6
+ /** Advance by playback time; pass zero to redraw without consuming steps. */
7
+ advance(deltaMs: number): SortFrame;
8
+ /** Close the source early. The last frame remains readable. */
9
+ dispose(): void;
10
+ }
11
+ /** Forward-only playback. The source must end with a `done` event. */
12
+ export declare function createSortPlayer(steps: Iterable<SortStep>, options: {
13
+ stepDurationMs: number;
14
+ finalHoldMs: number;
15
+ }): SortPlayer;
@@ -0,0 +1,88 @@
1
+ /** Forward-only playback. The source must end with a `done` event. */
2
+ export function createSortPlayer(steps, options) {
3
+ const { stepDurationMs, finalHoldMs } = options;
4
+ if (!Number.isFinite(stepDurationMs) || stepDurationMs <= 0 ||
5
+ !Number.isFinite(finalHoldMs) || finalHoldMs < 0) {
6
+ throw new RangeError("Expected positive step duration and non-negative final hold");
7
+ }
8
+ const iterator = steps[Symbol.iterator]();
9
+ let closed = false;
10
+ const close = () => {
11
+ if (!closed) {
12
+ closed = true;
13
+ iterator.return?.();
14
+ }
15
+ };
16
+ let current;
17
+ try {
18
+ const first = iterator.next();
19
+ if (first.done)
20
+ throw new RangeError("Player requires at least one step");
21
+ current = first.value;
22
+ }
23
+ catch (error) {
24
+ close();
25
+ throw error;
26
+ }
27
+ let previous = current;
28
+ let elapsed = stepDurationMs;
29
+ let hold = 0;
30
+ let disposed = false;
31
+ let finished = false;
32
+ const complete = () => {
33
+ if (current.event.type === "done" && elapsed === stepDurationMs) {
34
+ previous = current;
35
+ close();
36
+ finished = hold >= finalHoldMs;
37
+ }
38
+ };
39
+ complete();
40
+ const frame = () => Object.freeze({
41
+ previous: previous.state, current: current.state,
42
+ progress: elapsed / stepDurationMs,
43
+ stepIndex: current.index, event: current.event
44
+ });
45
+ return Object.freeze({
46
+ get frame() { return frame(); },
47
+ get finished() { return finished; },
48
+ advance(deltaMs) {
49
+ if (disposed)
50
+ throw new Error("Player has been disposed");
51
+ if (!Number.isFinite(deltaMs) || deltaMs < 0) {
52
+ throw new RangeError("Expected finite non-negative playback time");
53
+ }
54
+ try {
55
+ let remaining = deltaMs;
56
+ while (remaining > 0 && !finished) {
57
+ if (elapsed === stepDurationMs) {
58
+ if (current.event.type === "done") {
59
+ hold += Math.min(remaining, finalHoldMs - hold);
60
+ complete();
61
+ break;
62
+ }
63
+ const next = iterator.next();
64
+ if (next.done)
65
+ throw new RangeError("Step source ended without a done event");
66
+ previous = current;
67
+ current = next.value;
68
+ elapsed = 0;
69
+ }
70
+ const amount = Math.min(remaining, stepDurationMs - elapsed);
71
+ elapsed += amount;
72
+ remaining -= amount;
73
+ complete();
74
+ }
75
+ return frame();
76
+ }
77
+ catch (error) {
78
+ disposed = true;
79
+ close();
80
+ throw error;
81
+ }
82
+ },
83
+ dispose() {
84
+ disposed = true;
85
+ close();
86
+ }
87
+ });
88
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grundyjs/algiviz",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Deterministic algorithm steps for educational visualizations",
5
5
  "type": "module",
6
6
  "files": [