@slithy/prim-interface 0.2.10 → 0.3.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/README.md CHANGED
@@ -4,16 +4,23 @@ Browser-facing API for `@slithy/prim-lib`. Consumed by `apps/prim-demo`.
4
4
 
5
5
  ## What it does
6
6
 
7
- Wraps `prim-lib` in a simple `run()` API and provides save/copy/share helpers for exporting results.
7
+ Wraps `prim-lib` in a `run()` / `runWorker()` API and provides save/copy/share helpers for exporting results. `run()` runs the optimizer on the main thread; `runWorker()` moves computation into a Web Worker, keeping the main thread responsive during long jobs. Both share the same callback API.
8
8
 
9
9
  ## Exports
10
10
 
11
- ### `run(source, config, callbacks)`
11
+ ### `run(source, config, callbacks)` / `runWorker(source, config, callbacks)`
12
12
 
13
- Starts a reconstruction job. Returns a `JobHandle` for stopping, pausing, and resuming.
13
+ Start a reconstruction job. Both return a `JobHandle` for stopping, pausing, and resuming, and accept identical arguments.
14
14
 
15
15
  ```ts
16
- const job = run(imageUrl, config, {
16
+ const job = run(imageUrl, config, { // main-thread
17
+ onStart(raster, svg) {},
18
+ onStep({ raster, svg, svgString, stepData, progress }) {},
19
+ onComplete(serialized) {},
20
+ onStop() {},
21
+ });
22
+
23
+ const job = runWorker(imageUrl, config, { // off-thread
17
24
  onStart(raster, svg) {},
18
25
  onStep({ raster, svg, svgString, stepData, progress }) {},
19
26
  onComplete(serialized) {},
@@ -25,6 +32,10 @@ job.pause();
25
32
  job.resume();
26
33
  ```
27
34
 
35
+ **`run()`** — runs the optimizer on the main thread via `requestAnimationFrame`. Simpler; no worker overhead. UI may feel sluggish during compute-heavy steps at high `shapes` / `mutations` settings.
36
+
37
+ **`runWorker()`** — moves all computation into a Web Worker using `OffscreenCanvas`. The main thread only handles DOM updates (appending the canvas/SVG, calling callbacks). Requires a bundler that understands `new Worker(new URL(..., import.meta.url))` — Vite handles this automatically. Shape constructors in `config.shapeTypes` are mapped to names internally; only the built-in shapes (`Triangle`, `Rectangle`, `Ellipse`, `Circle`, `Square`, `Hexagon`, `Glyph`) are supported.
38
+
28
39
  ### Config
29
40
 
30
41
  ```ts
package/dist/index.d.ts CHANGED
@@ -43,6 +43,8 @@ interface JobHandle {
43
43
 
44
44
  declare function run(source: string | File, cfg: Config, callbacks?: RunCallbacks): JobHandle;
45
45
 
46
+ declare function runWorker(source: string | File, cfg: Config, callbacks?: RunCallbacks): JobHandle;
47
+
46
48
  interface SaveOptions {
47
49
  suffix?: string;
48
50
  filename?: string;
@@ -56,4 +58,4 @@ declare function copyVector(svgString: string): Promise<void>;
56
58
  declare function copyRaster(canvas: HTMLCanvasElement): Promise<void>;
57
59
  declare function share(canvas: HTMLCanvasElement, options?: SaveOptions): Promise<void>;
58
60
 
59
- export { type Config, type JobHandle, type RunCallbacks, type SaveOptions, type StepResult, copyRaster, copyRasterFromVector, copyVector, run, saveRaster, saveRasterFromVector, saveVector, share, shareFromVector };
61
+ export { type Config, type JobHandle, type RunCallbacks, type SaveOptions, type StepResult, copyRaster, copyRasterFromVector, copyVector, run, runWorker, saveRaster, saveRasterFromVector, saveVector, share, shareFromVector };
package/dist/index.js CHANGED
@@ -16,10 +16,12 @@ function run(source, cfg, callbacks = {}) {
16
16
  const deviceViewCfg = { ...viewCfg, width: viewCfg.width * pixelRatio, height: viewCfg.height * pixelRatio };
17
17
  const result = Canvas.empty(deviceViewCfg);
18
18
  result.ctx.scale(computeCfg.scale * pixelRatio, computeCfg.scale * pixelRatio);
19
+ if (!(result.node instanceof HTMLCanvasElement)) throw new Error("[prim] Expected HTMLCanvasElement");
20
+ const rasterNode = result.node;
19
21
  const svg = Canvas.empty(computeCfg, true);
20
22
  svg.setAttribute("width", String(viewCfg.width));
21
23
  svg.setAttribute("height", String(viewCfg.height));
22
- callbacks.onStart?.(result.node, svg);
24
+ callbacks.onStart?.(rasterNode, svg);
23
25
  const serializer = new XMLSerializer();
24
26
  const accumulatedSteps = [];
25
27
  optimizer = new Optimizer(original, computeCfg);
@@ -32,7 +34,7 @@ function run(source, cfg, callbacks = {}) {
32
34
  const stepData = step.serialize();
33
35
  accumulatedSteps.push(stepData);
34
36
  callbacks.onStep?.({
35
- raster: result.node,
37
+ raster: rasterNode,
36
38
  svg,
37
39
  svgString: serializer.serializeToString(svg),
38
40
  stepData,
@@ -69,6 +71,80 @@ function run(source, cfg, callbacks = {}) {
69
71
  };
70
72
  }
71
73
 
74
+ // src/runWorker.ts
75
+ import { Canvas as Canvas2, renderStepToCtx, stepDataToSVGElement } from "@slithy/prim-lib";
76
+ function runWorker(source, cfg, callbacks = {}) {
77
+ const url = source instanceof File ? URL.createObjectURL(source) : source;
78
+ const isBlob = source instanceof File;
79
+ let stopped = false;
80
+ let result = null;
81
+ let svgEl = null;
82
+ const serializer = new XMLSerializer();
83
+ const worker = new Worker(new URL("./worker-entry.js", import.meta.url), { type: "module" });
84
+ worker.onmessage = (e) => {
85
+ const msg = e.data;
86
+ if (msg.type === "ready") {
87
+ const { width, height, scale, fill } = msg;
88
+ const pixelRatio = cfg.pixelRatio ?? 1;
89
+ const computeCfg = { ...cfg, width, height, scale, fill };
90
+ const viewCfg = {
91
+ ...computeCfg,
92
+ width: scale * width,
93
+ height: scale * height
94
+ };
95
+ const deviceViewCfg = {
96
+ ...viewCfg,
97
+ width: viewCfg.width * pixelRatio,
98
+ height: viewCfg.height * pixelRatio
99
+ };
100
+ result = Canvas2.empty(deviceViewCfg);
101
+ const displayCanvas = result.node;
102
+ displayCanvas.style.width = `${viewCfg.width}px`;
103
+ result.ctx.scale(scale * pixelRatio, scale * pixelRatio);
104
+ svgEl = Canvas2.empty(computeCfg, true);
105
+ svgEl.setAttribute("width", String(viewCfg.width));
106
+ svgEl.setAttribute("height", String(viewCfg.height));
107
+ callbacks.onStart?.(displayCanvas, svgEl);
108
+ } else if (msg.type === "step") {
109
+ if (!result || !svgEl) return;
110
+ const { stepData, progress } = msg;
111
+ renderStepToCtx(stepData, result.ctx);
112
+ svgEl.appendChild(stepDataToSVGElement(stepData));
113
+ callbacks.onStep?.({
114
+ raster: result.node,
115
+ svg: svgEl,
116
+ svgString: serializer.serializeToString(svgEl),
117
+ stepData,
118
+ progress
119
+ });
120
+ } else if (msg.type === "complete") {
121
+ if (isBlob) URL.revokeObjectURL(url);
122
+ callbacks.onComplete?.(msg.serialized);
123
+ } else if (msg.type === "stopped") {
124
+ if (isBlob) URL.revokeObjectURL(url);
125
+ callbacks.onStop?.();
126
+ }
127
+ };
128
+ worker.onerror = (e) => {
129
+ console.error("[prim worker]", e);
130
+ };
131
+ const { shapeTypes, pixelRatio: _pr, width: _w, height: _h, scale: _s, ...rest } = cfg;
132
+ const workerCfg = {
133
+ ...rest,
134
+ shapeTypeNames: shapeTypes.map((ctor) => ctor.name)
135
+ };
136
+ worker.postMessage({ type: "start", url, cfg: workerCfg });
137
+ return {
138
+ stop: () => {
139
+ if (stopped) return;
140
+ stopped = true;
141
+ worker.postMessage({ type: "stop" });
142
+ },
143
+ pause: () => worker.postMessage({ type: "pause" }),
144
+ resume: () => worker.postMessage({ type: "resume" })
145
+ };
146
+ }
147
+
72
148
  // src/exit.ts
73
149
  function buildFilename(ext, options) {
74
150
  const suffix = options?.suffix ?? "prim";
@@ -164,6 +240,7 @@ export {
164
240
  copyVector,
165
241
  replayOutput,
166
242
  run,
243
+ runWorker,
167
244
  saveRaster,
168
245
  saveRasterFromVector,
169
246
  saveVector,
@@ -0,0 +1,38 @@
1
+ import { PreCfg, StepData, SerializedOutput } from '@slithy/prim-lib';
2
+
3
+ type WorkerCfg = Omit<PreCfg, 'shapeTypes'> & {
4
+ shapeTypeNames: string[];
5
+ };
6
+ type WorkerInbound = {
7
+ type: 'start';
8
+ url: string;
9
+ cfg: WorkerCfg;
10
+ } | {
11
+ type: 'pause';
12
+ } | {
13
+ type: 'resume';
14
+ } | {
15
+ type: 'stop';
16
+ };
17
+ type WorkerOutbound = {
18
+ type: 'ready';
19
+ width: number;
20
+ height: number;
21
+ scale: number;
22
+ fill: string;
23
+ } | {
24
+ type: 'step';
25
+ stepData: StepData;
26
+ progress: {
27
+ current: number;
28
+ total: number;
29
+ similarity: number;
30
+ };
31
+ } | {
32
+ type: 'complete';
33
+ serialized: SerializedOutput;
34
+ } | {
35
+ type: 'stopped';
36
+ };
37
+
38
+ export type { WorkerCfg, WorkerInbound, WorkerOutbound };
@@ -0,0 +1,83 @@
1
+ // src/worker-entry.ts
2
+ import { Canvas, Optimizer, parseColor } from "@slithy/prim-lib";
3
+ import { Triangle, Rectangle, Ellipse, Circle, Square, Hexagon, Glyph } from "@slithy/prim-lib";
4
+ var SHAPES = {
5
+ Triangle,
6
+ Rectangle,
7
+ Ellipse,
8
+ Circle,
9
+ Square,
10
+ Hexagon,
11
+ Glyph
12
+ };
13
+ var optimizer = null;
14
+ self.onmessage = async (e) => {
15
+ const msg = e.data;
16
+ switch (msg.type) {
17
+ case "start": {
18
+ const { url, cfg: workerCfg } = msg;
19
+ const { shapeTypeNames, ...rest } = workerCfg;
20
+ const shapeTypes = shapeTypeNames.map((name) => {
21
+ const ctor = SHAPES[name];
22
+ if (!ctor) throw new Error(`[prim worker] Unknown shape type: ${name}`);
23
+ return ctor;
24
+ });
25
+ const preCfg = { ...rest, shapeTypes };
26
+ const blob = await fetch(url).then((r) => r.blob());
27
+ const bitmap = await createImageBitmap(blob);
28
+ const original = Canvas.fromBitmap(bitmap, preCfg);
29
+ bitmap.close();
30
+ const computeCfg = { ...preCfg, width: preCfg.width, height: preCfg.height };
31
+ self.postMessage({
32
+ type: "ready",
33
+ width: computeCfg.width,
34
+ height: computeCfg.height,
35
+ scale: computeCfg.scale,
36
+ fill: computeCfg.fill
37
+ });
38
+ const accumulatedSteps = [];
39
+ let stepCount = 0;
40
+ optimizer = new Optimizer(original, computeCfg, (fn) => setTimeout(fn, 0));
41
+ optimizer.onStep = (step) => {
42
+ stepCount++;
43
+ if (step) {
44
+ const stepData = step.serialize();
45
+ accumulatedSteps.push(stepData);
46
+ const outbound = {
47
+ type: "step",
48
+ stepData,
49
+ progress: {
50
+ current: stepCount,
51
+ total: computeCfg.steps,
52
+ similarity: parseFloat((100 * (1 - step.distance)).toFixed(2))
53
+ }
54
+ };
55
+ self.postMessage(outbound);
56
+ }
57
+ if (stepCount >= computeCfg.steps) {
58
+ const serialized = {
59
+ v: 1,
60
+ w: computeCfg.width,
61
+ h: computeCfg.height,
62
+ scale: computeCfg.scale,
63
+ fill: parseColor(computeCfg.fill),
64
+ steps: accumulatedSteps
65
+ };
66
+ self.postMessage({ type: "complete", serialized });
67
+ }
68
+ };
69
+ optimizer.start();
70
+ break;
71
+ }
72
+ case "pause":
73
+ optimizer?.pause();
74
+ break;
75
+ case "resume":
76
+ optimizer?.resume();
77
+ break;
78
+ case "stop":
79
+ optimizer?.stop();
80
+ self.postMessage({ type: "stopped" });
81
+ break;
82
+ }
83
+ };
package/package.json CHANGED
@@ -1,12 +1,16 @@
1
1
  {
2
2
  "name": "@slithy/prim-interface",
3
- "version": "0.2.10",
3
+ "version": "0.3.0",
4
4
  "description": "Browser-facing API for primitive-based image reconstruction.",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": {
8
8
  "import": "./dist/index.js",
9
9
  "types": "./dist/index.d.ts"
10
+ },
11
+ "./worker-entry": {
12
+ "import": "./dist/worker-entry.js",
13
+ "types": "./dist/worker-entry.d.ts"
10
14
  }
11
15
  },
12
16
  "files": [
@@ -14,16 +18,16 @@
14
18
  ],
15
19
  "sideEffects": false,
16
20
  "dependencies": {
17
- "@slithy/prim-lib": "0.3.2"
21
+ "@slithy/prim-lib": "0.4.0"
18
22
  },
19
23
  "devDependencies": {
20
- "@vitest/coverage-v8": "^4.1.0",
21
- "jsdom": "^28",
24
+ "@vitest/coverage-v8": "^4.1.2",
25
+ "jsdom": "^29.0.1",
22
26
  "tsup": "^8",
23
27
  "typescript": "^5",
24
- "vitest": "^4",
25
- "@slithy/eslint-config": "0.0.0",
26
- "@slithy/tsconfig": "0.0.0"
28
+ "vitest": "^4.1.2",
29
+ "@slithy/tsconfig": "0.0.0",
30
+ "@slithy/eslint-config": "0.0.0"
27
31
  },
28
32
  "author": {
29
33
  "name": "Matthew Campagna",
@@ -47,8 +51,8 @@
47
51
  },
48
52
  "scripts": {
49
53
  "clean": "rm -rf dist",
50
- "build": "rm -rf dist && tsup src/index.ts --format esm --dts",
51
- "dev": "tsup src/index.ts --format esm --watch",
54
+ "build": "rm -rf dist && tsup src/index.ts src/worker-entry.ts --format esm --dts",
55
+ "dev": "tsup src/index.ts src/worker-entry.ts --format esm --watch",
52
56
  "typecheck": "tsc --noEmit",
53
57
  "lint": "eslint .",
54
58
  "test": "vitest run",