@strategicprojects/rpic 0.1.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 ADDED
@@ -0,0 +1,48 @@
1
+ # rpic
2
+
3
+ JS/TS bindings for [rpic](https://github.com/milkway/rpic-lang) — the pic
4
+ graphics language compiled to **SVG** with an **animation manifest**, via
5
+ WebAssembly. Works in the browser and in Node, ships TypeScript types.
6
+
7
+ ```js
8
+ import * as rpic from '@strategicprojects/rpic';
9
+
10
+ await rpic.ready(); // browser: wasm fetched automatically
11
+
12
+ const { svg, animations } = rpic.compile('box "A"; arrow; box "B"');
13
+ document.querySelector('#stage').innerHTML = svg;
14
+
15
+ // animate with GSAP:
16
+ import { gsap } from 'gsap';
17
+ rpic.animate(document.querySelector('#stage'), animations, gsap);
18
+
19
+ // circuit library:
20
+ rpic.renderSvg('A:(0,0); B:(2,0)\nresistor(A,B)', { circuits: true });
21
+ ```
22
+
23
+ ### Node
24
+
25
+ ```js
26
+ import { readFileSync } from 'node:fs';
27
+ import * as rpic from '@strategicprojects/rpic';
28
+ await rpic.ready(readFileSync(new URL('./node_modules/rpic/pkg/rpic_wasm_bg.wasm', import.meta.url)));
29
+ console.log(rpic.renderSvg('box "hi"'));
30
+ ```
31
+
32
+ ## API
33
+
34
+ | Function | Description |
35
+ |----------|-------------|
36
+ | `ready(wasmInput?)` | Initialize WASM. Browser: no arg. Node: pass `.wasm` bytes/URL. |
37
+ | `compile(src, {circuits?})` | → `{ svg, animations }` (throws on a pic error). |
38
+ | `renderSvg(src, {circuits?})` | → SVG string. |
39
+ | `animate(root, animations, gsap)` | Build/play a GSAP timeline (`draw`/`fade`/`pop`). Browser only. |
40
+
41
+ PNG/PDF are available via the CLI, the Python package, or the R package (the
42
+ WASM core renders SVG; rasterization isn't bundled here).
43
+
44
+ ## Rebuild
45
+
46
+ ```sh
47
+ wasm-pack build crates/wasm --target web --out-dir bindings/js/pkg
48
+ ```
package/index.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ // Type definitions for rpic
2
+
3
+ export interface Anim {
4
+ id: string;
5
+ effect: string;
6
+ /** absolute start time in seconds */
7
+ start: number;
8
+ duration: number;
9
+ }
10
+
11
+ export interface Bundle {
12
+ svg: string;
13
+ animations: Anim[];
14
+ }
15
+
16
+ export interface CompileOptions {
17
+ /** prepend the native circuit-element library (resistor, and_gate, …) */
18
+ circuits?: boolean;
19
+ }
20
+
21
+ /**
22
+ * Initialize the WebAssembly module. In the browser call with no argument; in
23
+ * Node pass the `.wasm` bytes or a file URL.
24
+ */
25
+ export function ready(wasmInput?: BufferSource | URL | string): Promise<void>;
26
+
27
+ /** Compile pic source into `{ svg, animations }`. Throws on a pic error. */
28
+ export function compile(src: string, opts?: CompileOptions): Bundle;
29
+
30
+ /** Compile and return only the SVG string. */
31
+ export function renderSvg(src: string, opts?: CompileOptions): string;
32
+
33
+ /**
34
+ * Build and play a GSAP timeline from an animation manifest on the SVG inside
35
+ * `root`. Browser-only.
36
+ */
37
+ export function animate(root: Element, animations: Anim[], gsap: unknown): unknown;
package/index.js ADDED
@@ -0,0 +1,113 @@
1
+ // rpic — JS/TS bindings for the rpic pic graphics language (WASM).
2
+ //
3
+ // Browser: await ready(); // wasm fetched automatically
4
+ // Node: await ready(fs.readFileSync(url)); // pass the .wasm bytes/URL
5
+ import initWasm, {
6
+ compile as wasmCompile,
7
+ compile_circuits as wasmCompileCircuits,
8
+ } from './pkg/rpic_wasm.js';
9
+
10
+ let initPromise = null;
11
+ let initialized = false;
12
+
13
+ /**
14
+ * Initialize the WebAssembly module (idempotent; concurrent calls share one
15
+ * init). In the browser, call with no argument (the .wasm is fetched relative
16
+ * to the module). In Node, pass the wasm bytes or a file URL.
17
+ */
18
+ export function ready(wasmInput) {
19
+ if (!initPromise) {
20
+ initPromise = initWasm(
21
+ wasmInput === undefined ? undefined : { module_or_path: wasmInput }
22
+ ).then(() => {
23
+ initialized = true;
24
+ });
25
+ }
26
+ return initPromise;
27
+ }
28
+
29
+ function ensure() {
30
+ if (!initialized) {
31
+ throw new Error('rpic: call `await ready()` before compiling');
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Compile pic source into `{ svg, animations }` (throws on a pic error).
37
+ * @param {string} src
38
+ * @param {{circuits?: boolean}} [opts]
39
+ */
40
+ export function compile(src, opts = {}) {
41
+ ensure();
42
+ const json = opts.circuits ? wasmCompileCircuits(src) : wasmCompile(src);
43
+ const out = JSON.parse(json);
44
+ if (out.error) throw new Error(out.error);
45
+ return out;
46
+ }
47
+
48
+ /** Compile and return just the SVG string. */
49
+ export function renderSvg(src, opts) {
50
+ return compile(src, opts).svg;
51
+ }
52
+
53
+ /**
54
+ * Build a GSAP timeline from a drawing's animation manifest and play it on the
55
+ * SVG inside `root`. Browser-only (needs the DOM and a GSAP instance).
56
+ * @param {Element} root container holding the injected SVG
57
+ * @param {Array<{id:string,effect:string,start:number,duration:number}>} animations
58
+ * @param {*} gsap the GSAP instance
59
+ * @returns the GSAP timeline
60
+ */
61
+ export function animate(root, animations, gsap) {
62
+ const tl = gsap.timeline();
63
+ for (const a of animations) {
64
+ const sel =
65
+ typeof CSS !== 'undefined' && CSS.escape ? '#' + CSS.escape(a.id) : `[id="${a.id}"]`;
66
+ const el = root.querySelector(sel);
67
+ if (!el) continue;
68
+ switch (a.effect) {
69
+ case 'fade':
70
+ tl.from(el, { opacity: 0, duration: a.duration, ease: 'power1.out' }, a.start);
71
+ break;
72
+ case 'pop':
73
+ tl.from(
74
+ el,
75
+ { scale: 0, transformOrigin: '50% 50%', duration: a.duration, ease: 'back.out(1.7)' },
76
+ a.start
77
+ );
78
+ break;
79
+ case 'draw':
80
+ drawOn(el, a, tl);
81
+ break;
82
+ default:
83
+ tl.from(el, { opacity: 0, duration: a.duration }, a.start);
84
+ }
85
+ }
86
+ return tl;
87
+ }
88
+
89
+ function drawOn(group, a, tl) {
90
+ const els = group.querySelectorAll('path, polyline, line, rect, circle, ellipse, polygon');
91
+ els.forEach((el) => {
92
+ let len = 0;
93
+ try {
94
+ len = el.getTotalLength();
95
+ } catch {
96
+ len = 0;
97
+ }
98
+ if (len > 0) {
99
+ tl.fromTo(
100
+ el,
101
+ { strokeDasharray: len, strokeDashoffset: len },
102
+ { strokeDashoffset: 0, duration: a.duration, ease: 'none' },
103
+ a.start
104
+ );
105
+ } else {
106
+ tl.from(el, { opacity: 0, duration: a.duration }, a.start);
107
+ }
108
+ });
109
+ const texts = group.querySelectorAll('text');
110
+ if (texts.length) {
111
+ tl.from(texts, { opacity: 0, duration: a.duration * 0.6 }, a.start + a.duration * 0.4);
112
+ }
113
+ }
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@strategicprojects/rpic",
3
+ "version": "0.1.0",
4
+ "description": "The pic graphics language compiled to SVG with animation manifests, via WebAssembly. Browser + Node.",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "module": "./index.js",
8
+ "types": "./index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./index.d.ts",
12
+ "default": "./index.js"
13
+ },
14
+ "./pkg/rpic_wasm_bg.wasm": "./pkg/rpic_wasm_bg.wasm"
15
+ },
16
+ "files": [
17
+ "index.js",
18
+ "index.d.ts",
19
+ "pkg/rpic_wasm.js",
20
+ "pkg/rpic_wasm.d.ts",
21
+ "pkg/rpic_wasm_bg.wasm",
22
+ "pkg/rpic_wasm_bg.wasm.d.ts",
23
+ "README.md"
24
+ ],
25
+ "scripts": {
26
+ "prepack": "wasm-pack build ../../crates/wasm --target web --out-dir pkg"
27
+ },
28
+ "keywords": ["pic", "svg", "diagram", "graphics", "wasm", "gsap", "animation", "circuits"],
29
+ "author": "André Leite <leite@de.ufpe.br>",
30
+ "license": "BSD-2-Clause",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://github.com/milkway/rpic-lang.git",
34
+ "directory": "bindings/js"
35
+ },
36
+ "sideEffects": false
37
+ }
@@ -0,0 +1,48 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+
4
+ /**
5
+ * Compile pic source to a JSON `{svg, animations}` bundle (or `{error}`).
6
+ */
7
+ export function compile(src: string): string;
8
+
9
+ /**
10
+ * Like [`compile`], but with the native circuit-element library prepended
11
+ * (so `resistor`, `and_gate`, … are available).
12
+ */
13
+ export function compile_circuits(src: string): string;
14
+
15
+ export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
16
+
17
+ export interface InitOutput {
18
+ readonly memory: WebAssembly.Memory;
19
+ readonly compile: (a: number, b: number) => [number, number];
20
+ readonly compile_circuits: (a: number, b: number) => [number, number];
21
+ readonly __wbindgen_externrefs: WebAssembly.Table;
22
+ readonly __wbindgen_malloc: (a: number, b: number) => number;
23
+ readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
24
+ readonly __wbindgen_free: (a: number, b: number, c: number) => void;
25
+ readonly __wbindgen_start: () => void;
26
+ }
27
+
28
+ export type SyncInitInput = BufferSource | WebAssembly.Module;
29
+
30
+ /**
31
+ * Instantiates the given `module`, which can either be bytes or
32
+ * a precompiled `WebAssembly.Module`.
33
+ *
34
+ * @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated.
35
+ *
36
+ * @returns {InitOutput}
37
+ */
38
+ export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput;
39
+
40
+ /**
41
+ * If `module_or_path` is {RequestInfo} or {URL}, makes a request and
42
+ * for everything else, calls `WebAssembly.instantiate` directly.
43
+ *
44
+ * @param {{ module_or_path: InitInput | Promise<InitInput> }} module_or_path - Passing `InitInput` directly is deprecated.
45
+ *
46
+ * @returns {Promise<InitOutput>}
47
+ */
48
+ export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise<InitInput> } | InitInput | Promise<InitInput>): Promise<InitOutput>;
@@ -0,0 +1,231 @@
1
+ /* @ts-self-types="./rpic_wasm.d.ts" */
2
+
3
+ /**
4
+ * Compile pic source to a JSON `{svg, animations}` bundle (or `{error}`).
5
+ * @param {string} src
6
+ * @returns {string}
7
+ */
8
+ export function compile(src) {
9
+ let deferred2_0;
10
+ let deferred2_1;
11
+ try {
12
+ const ptr0 = passStringToWasm0(src, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
13
+ const len0 = WASM_VECTOR_LEN;
14
+ const ret = wasm.compile(ptr0, len0);
15
+ deferred2_0 = ret[0];
16
+ deferred2_1 = ret[1];
17
+ return getStringFromWasm0(ret[0], ret[1]);
18
+ } finally {
19
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Like [`compile`], but with the native circuit-element library prepended
25
+ * (so `resistor`, `and_gate`, … are available).
26
+ * @param {string} src
27
+ * @returns {string}
28
+ */
29
+ export function compile_circuits(src) {
30
+ let deferred2_0;
31
+ let deferred2_1;
32
+ try {
33
+ const ptr0 = passStringToWasm0(src, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
34
+ const len0 = WASM_VECTOR_LEN;
35
+ const ret = wasm.compile_circuits(ptr0, len0);
36
+ deferred2_0 = ret[0];
37
+ deferred2_1 = ret[1];
38
+ return getStringFromWasm0(ret[0], ret[1]);
39
+ } finally {
40
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
41
+ }
42
+ }
43
+ function __wbg_get_imports() {
44
+ const import0 = {
45
+ __proto__: null,
46
+ __wbindgen_init_externref_table: function() {
47
+ const table = wasm.__wbindgen_externrefs;
48
+ const offset = table.grow(4);
49
+ table.set(0, undefined);
50
+ table.set(offset + 0, undefined);
51
+ table.set(offset + 1, null);
52
+ table.set(offset + 2, true);
53
+ table.set(offset + 3, false);
54
+ },
55
+ };
56
+ return {
57
+ __proto__: null,
58
+ "./rpic_wasm_bg.js": import0,
59
+ };
60
+ }
61
+
62
+ function getStringFromWasm0(ptr, len) {
63
+ return decodeText(ptr >>> 0, len);
64
+ }
65
+
66
+ let cachedUint8ArrayMemory0 = null;
67
+ function getUint8ArrayMemory0() {
68
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
69
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
70
+ }
71
+ return cachedUint8ArrayMemory0;
72
+ }
73
+
74
+ function passStringToWasm0(arg, malloc, realloc) {
75
+ if (realloc === undefined) {
76
+ const buf = cachedTextEncoder.encode(arg);
77
+ const ptr = malloc(buf.length, 1) >>> 0;
78
+ getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
79
+ WASM_VECTOR_LEN = buf.length;
80
+ return ptr;
81
+ }
82
+
83
+ let len = arg.length;
84
+ let ptr = malloc(len, 1) >>> 0;
85
+
86
+ const mem = getUint8ArrayMemory0();
87
+
88
+ let offset = 0;
89
+
90
+ for (; offset < len; offset++) {
91
+ const code = arg.charCodeAt(offset);
92
+ if (code > 0x7F) break;
93
+ mem[ptr + offset] = code;
94
+ }
95
+ if (offset !== len) {
96
+ if (offset !== 0) {
97
+ arg = arg.slice(offset);
98
+ }
99
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
100
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
101
+ const ret = cachedTextEncoder.encodeInto(arg, view);
102
+
103
+ offset += ret.written;
104
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
105
+ }
106
+
107
+ WASM_VECTOR_LEN = offset;
108
+ return ptr;
109
+ }
110
+
111
+ let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
112
+ cachedTextDecoder.decode();
113
+ const MAX_SAFARI_DECODE_BYTES = 2146435072;
114
+ let numBytesDecoded = 0;
115
+ function decodeText(ptr, len) {
116
+ numBytesDecoded += len;
117
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
118
+ cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
119
+ cachedTextDecoder.decode();
120
+ numBytesDecoded = len;
121
+ }
122
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
123
+ }
124
+
125
+ const cachedTextEncoder = new TextEncoder();
126
+
127
+ if (!('encodeInto' in cachedTextEncoder)) {
128
+ cachedTextEncoder.encodeInto = function (arg, view) {
129
+ const buf = cachedTextEncoder.encode(arg);
130
+ view.set(buf);
131
+ return {
132
+ read: arg.length,
133
+ written: buf.length
134
+ };
135
+ };
136
+ }
137
+
138
+ let WASM_VECTOR_LEN = 0;
139
+
140
+ let wasmModule, wasmInstance, wasm;
141
+ function __wbg_finalize_init(instance, module) {
142
+ wasmInstance = instance;
143
+ wasm = instance.exports;
144
+ wasmModule = module;
145
+ cachedUint8ArrayMemory0 = null;
146
+ wasm.__wbindgen_start();
147
+ return wasm;
148
+ }
149
+
150
+ async function __wbg_load(module, imports) {
151
+ if (typeof Response === 'function' && module instanceof Response) {
152
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
153
+ try {
154
+ return await WebAssembly.instantiateStreaming(module, imports);
155
+ } catch (e) {
156
+ const validResponse = module.ok && expectedResponseType(module.type);
157
+
158
+ if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
159
+ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
160
+
161
+ } else { throw e; }
162
+ }
163
+ }
164
+
165
+ const bytes = await module.arrayBuffer();
166
+ return await WebAssembly.instantiate(bytes, imports);
167
+ } else {
168
+ const instance = await WebAssembly.instantiate(module, imports);
169
+
170
+ if (instance instanceof WebAssembly.Instance) {
171
+ return { instance, module };
172
+ } else {
173
+ return instance;
174
+ }
175
+ }
176
+
177
+ function expectedResponseType(type) {
178
+ switch (type) {
179
+ case 'basic': case 'cors': case 'default': return true;
180
+ }
181
+ return false;
182
+ }
183
+ }
184
+
185
+ function initSync(module) {
186
+ if (wasm !== undefined) return wasm;
187
+
188
+
189
+ if (module !== undefined) {
190
+ if (Object.getPrototypeOf(module) === Object.prototype) {
191
+ ({module} = module)
192
+ } else {
193
+ console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
194
+ }
195
+ }
196
+
197
+ const imports = __wbg_get_imports();
198
+ if (!(module instanceof WebAssembly.Module)) {
199
+ module = new WebAssembly.Module(module);
200
+ }
201
+ const instance = new WebAssembly.Instance(module, imports);
202
+ return __wbg_finalize_init(instance, module);
203
+ }
204
+
205
+ async function __wbg_init(module_or_path) {
206
+ if (wasm !== undefined) return wasm;
207
+
208
+
209
+ if (module_or_path !== undefined) {
210
+ if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
211
+ ({module_or_path} = module_or_path)
212
+ } else {
213
+ console.warn('using deprecated parameters for the initialization function; pass a single object instead')
214
+ }
215
+ }
216
+
217
+ if (module_or_path === undefined) {
218
+ module_or_path = new URL('rpic_wasm_bg.wasm', import.meta.url);
219
+ }
220
+ const imports = __wbg_get_imports();
221
+
222
+ if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
223
+ module_or_path = fetch(module_or_path);
224
+ }
225
+
226
+ const { instance, module } = await __wbg_load(await module_or_path, imports);
227
+
228
+ return __wbg_finalize_init(instance, module);
229
+ }
230
+
231
+ export { initSync, __wbg_init as default };
Binary file
@@ -0,0 +1,10 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ export const memory: WebAssembly.Memory;
4
+ export const compile: (a: number, b: number) => [number, number];
5
+ export const compile_circuits: (a: number, b: number) => [number, number];
6
+ export const __wbindgen_externrefs: WebAssembly.Table;
7
+ export const __wbindgen_malloc: (a: number, b: number) => number;
8
+ export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
9
+ export const __wbindgen_free: (a: number, b: number, c: number) => void;
10
+ export const __wbindgen_start: () => void;