@tinyvolt/pie 0.9.0 → 0.10.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.
Files changed (135) hide show
  1. package/README.md +18 -1
  2. package/dist/components/SplitPane.d.ts +21 -0
  3. package/dist/components/SplitPane.jsx +113 -0
  4. package/dist/components/icons.d.ts +12 -0
  5. package/dist/components/icons.jsx +45 -0
  6. package/dist/lib/autodiff/index.d.ts +28 -0
  7. package/dist/lib/autodiff/index.js +39 -0
  8. package/dist/lib/customModules.d.ts +13 -0
  9. package/dist/lib/customModules.js +17 -0
  10. package/dist/lib/markdown/compile.d.ts +27 -0
  11. package/dist/lib/markdown/compile.js +26 -0
  12. package/dist/lib/markdown/components/CanvasPage.d.ts +9 -0
  13. package/dist/lib/markdown/components/CanvasPage.jsx +16 -0
  14. package/dist/lib/markdown/components/MarkdownBody.d.ts +11 -0
  15. package/dist/lib/markdown/components/MarkdownBody.jsx +37 -0
  16. package/dist/lib/markdown/components/PiePage.d.ts +14 -0
  17. package/dist/lib/markdown/components/PiePage.jsx +41 -0
  18. package/dist/lib/markdown/components/PythonEditor.d.ts +10 -0
  19. package/dist/lib/markdown/components/PythonEditor.jsx +209 -0
  20. package/dist/lib/markdown/features/build.d.ts +60 -0
  21. package/dist/lib/markdown/features/build.js +36 -0
  22. package/dist/lib/markdown/features/glossary/View.d.ts +9 -0
  23. package/dist/lib/markdown/features/glossary/View.jsx +62 -0
  24. package/dist/lib/markdown/features/glossary/build.d.ts +6 -0
  25. package/dist/lib/markdown/features/glossary/build.js +81 -0
  26. package/dist/lib/markdown/features/sidebar/View.d.ts +11 -0
  27. package/dist/lib/markdown/features/sidebar/View.jsx +45 -0
  28. package/dist/lib/markdown/features/sidebar/build.d.ts +3 -0
  29. package/dist/lib/markdown/features/sidebar/build.js +7 -0
  30. package/dist/lib/markdown/features/tags/build.d.ts +7 -0
  31. package/dist/lib/markdown/features/tags/build.js +22 -0
  32. package/dist/lib/markdown/features/tags/url.d.ts +6 -0
  33. package/dist/lib/markdown/features/tags/url.js +10 -0
  34. package/dist/lib/markdown/features/toc/build.d.ts +7 -0
  35. package/dist/lib/markdown/features/toc/build.js +62 -0
  36. package/dist/lib/markdown/features/views.d.ts +4 -0
  37. package/dist/lib/markdown/features/views.jsx +11 -0
  38. package/dist/lib/markdown/frontmatter.d.ts +44 -0
  39. package/dist/lib/markdown/frontmatter.js +109 -0
  40. package/dist/lib/markdown/render.d.ts +6 -0
  41. package/dist/lib/markdown/render.js +95 -0
  42. package/dist/lib/nodes/animation.d.ts +14 -0
  43. package/dist/lib/nodes/animation.js +34 -0
  44. package/dist/lib/nodes/components/CenteredGrid.d.ts +20 -0
  45. package/dist/lib/nodes/components/CenteredGrid.jsx +44 -0
  46. package/dist/lib/nodes/components/NodeCanvas.d.ts +7 -0
  47. package/dist/lib/nodes/components/NodeCanvas.jsx +50 -0
  48. package/dist/lib/nodes/execute.d.ts +27 -0
  49. package/dist/lib/nodes/execute.js +159 -0
  50. package/dist/lib/nodes/functions/Node2NodeFunc.d.ts +70 -0
  51. package/dist/lib/nodes/functions/Node2NodeFunc.js +223 -0
  52. package/dist/lib/nodes/functions/array.d.ts +12 -0
  53. package/dist/lib/nodes/functions/array.js +31 -0
  54. package/dist/lib/nodes/functions/autodiff.d.ts +12 -0
  55. package/dist/lib/nodes/functions/autodiff.js +60 -0
  56. package/dist/lib/nodes/functions/basic.d.ts +111 -0
  57. package/dist/lib/nodes/functions/basic.js +275 -0
  58. package/dist/lib/nodes/functions/registry.d.ts +9 -0
  59. package/dist/lib/nodes/functions/registry.js +45 -0
  60. package/dist/lib/nodes/functions/sideEffects.d.ts +78 -0
  61. package/dist/lib/nodes/functions/sideEffects.js +201 -0
  62. package/dist/lib/nodes/hooks/useCanvasGestures.d.ts +9 -0
  63. package/dist/lib/nodes/hooks/useCanvasGestures.js +120 -0
  64. package/dist/lib/nodes/hooks/useCanvasResize.d.ts +2 -0
  65. package/dist/lib/nodes/hooks/useCanvasResize.js +33 -0
  66. package/dist/lib/nodes/jax.d.ts +46 -0
  67. package/dist/lib/nodes/jax.js +120 -0
  68. package/dist/lib/nodes/render/renderLogic.d.ts +13 -0
  69. package/dist/lib/nodes/render/renderLogic.jsx +234 -0
  70. package/dist/lib/nodes/state/NameGenerator.d.ts +10 -0
  71. package/dist/lib/nodes/state/NameGenerator.js +29 -0
  72. package/dist/lib/nodes/state/Node.d.ts +134 -0
  73. package/dist/lib/nodes/state/Node.js +57 -0
  74. package/dist/lib/nodes/state/NodeStore.d.ts +49 -0
  75. package/dist/lib/nodes/state/NodeStore.js +138 -0
  76. package/dist/lib/nodes/tensors/broadcast.d.ts +18 -0
  77. package/dist/lib/nodes/tensors/broadcast.js +92 -0
  78. package/dist/lib/nodes/tensors/tensor.d.ts +13 -0
  79. package/dist/lib/nodes/tensors/tensor.js +34 -0
  80. package/dist/lib/python/lift.d.ts +51 -0
  81. package/dist/lib/python/lift.js +155 -0
  82. package/dist/lib/python/py/pie.py +303 -0
  83. package/dist/lib/python/py/pie_mpl.py +15 -0
  84. package/dist/lib/python/py/show_figures.py +5 -0
  85. package/dist/lib/python/runner.d.ts +36 -0
  86. package/dist/lib/python/runner.js +221 -0
  87. package/dist/lib/python/worker.d.ts +1 -0
  88. package/dist/lib/python/worker.js +111 -0
  89. package/dist/lib/ui/UiLayer.d.ts +2 -0
  90. package/dist/lib/ui/UiLayer.jsx +15 -0
  91. package/dist/lib/ui/UiView.d.ts +23 -0
  92. package/dist/lib/ui/UiView.jsx +56 -0
  93. package/dist/lib/ui/components/checkboxes.d.ts +10 -0
  94. package/dist/lib/ui/components/checkboxes.jsx +30 -0
  95. package/dist/lib/ui/components/latex.d.ts +8 -0
  96. package/dist/lib/ui/components/latex.jsx +41 -0
  97. package/dist/lib/ui/components/radio.d.ts +6 -0
  98. package/dist/lib/ui/components/radio.jsx +19 -0
  99. package/dist/lib/ui/components/slider.d.ts +8 -0
  100. package/dist/lib/ui/components/slider.jsx +7 -0
  101. package/dist/lib/ui/components/textbox.d.ts +5 -0
  102. package/dist/lib/ui/components/textbox.jsx +21 -0
  103. package/dist/lib/ui/dragUi.d.ts +10 -0
  104. package/dist/lib/ui/dragUi.js +129 -0
  105. package/dist/lib/ui/nodeHandle.d.ts +15 -0
  106. package/dist/lib/ui/nodeHandle.js +37 -0
  107. package/dist/lib/ui/registry.d.ts +10 -0
  108. package/dist/lib/ui/registry.js +42 -0
  109. package/dist/runtime.css +696 -0
  110. package/dist/runtime.d.ts +9 -0
  111. package/dist/runtime.jsx +6 -0
  112. package/init/index.js +2 -2
  113. package/init/site-agents.md +2 -1
  114. package/package.json +15 -6
  115. package/runtime-agents.md +146 -0
  116. package/src/app.css +7 -665
  117. package/src/lib/customModules.ts +30 -0
  118. package/src/lib/markdown/compile.ts +49 -0
  119. package/src/lib/markdown/components/PiePage.tsx +48 -0
  120. package/src/lib/markdown/features/build.ts +15 -6
  121. package/src/lib/markdown/features/sidebar/View.tsx +4 -2
  122. package/src/lib/markdown/features/tags/build.ts +6 -3
  123. package/src/lib/markdown/pages.ts +1 -9
  124. package/src/lib/markdown/vitePlugin.ts +4 -8
  125. package/src/lib/nodes/functions/registry.ts +30 -21
  126. package/src/lib/nodes/functions/sideEffects.ts +14 -8
  127. package/src/lib/nodes/functions/vitePlugin.ts +8 -10
  128. package/src/lib/nodes/state/Node.ts +27 -19
  129. package/src/lib/siteModules.ts +13 -0
  130. package/src/lib/ui/dragUi.ts +4 -2
  131. package/src/lib/ui/registry.ts +35 -14
  132. package/src/page.css +664 -0
  133. package/src/routes/[...slug].tsx +1 -0
  134. package/src/runtime.css +29 -0
  135. package/src/runtime.tsx +15 -0
@@ -0,0 +1,36 @@
1
+ import type { NodeStore } from '../nodes/state/NodeStore';
2
+ import { type InputValue, type PyResult } from './lift';
3
+ import type { UiCall } from '../ui/UiView';
4
+ export type RunStatus = 'waiting' | 'loading' | 'running' | 'finished' | 'stopped' | 'killed';
5
+ interface Run {
6
+ scope: PythonScope;
7
+ code: string;
8
+ onStatus: (status: RunStatus, error?: string) => void;
9
+ onOutput: (text: string) => void;
10
+ /** `png`: a matplotlib figure as a base64 PNG. */
11
+ onPlot: (png: string) => void;
12
+ /** A `pie.ui.*` call. Throws when the call is wrong; Python raises the error. */
13
+ onUi: (call: UiCall) => void;
14
+ }
15
+ /** A request to rerun the `pie.lift`ed function of node `nodeId` with new input values. */
16
+ interface Rerun {
17
+ scope: PythonScope;
18
+ nodeId: string;
19
+ values: InputValue[];
20
+ done: (result?: PyResult, error?: string) => void;
21
+ }
22
+ /** Runs that share Python variables, and the store their `pie.*` calls draw on. */
23
+ export declare class PythonScope {
24
+ readonly store?: NodeStore | undefined;
25
+ readonly id: string;
26
+ disposed: boolean;
27
+ /** `store`: where `pie.*` calls draw. Without it they fail with "this page has no canvas". */
28
+ constructor(store?: NodeStore | undefined);
29
+ /** Queues `code`. Returns a stop function. `error` comes only with `finished`. */
30
+ run(code: string, onStatus: Run['onStatus'], onOutput: Run['onOutput'], onPlot: Run['onPlot'], onUi: Run['onUi']): () => void;
31
+ /** Queues a rerun of node `nodeId`'s `pie.lift`ed function. It waits while a block runs. */
32
+ rerun(nodeId: string, values: InputValue[], done: Rerun['done']): void;
33
+ /** Frees the variables. Call when the page goes away. */
34
+ dispose(): void;
35
+ }
36
+ export {};
@@ -0,0 +1,221 @@
1
+ import { execute } from '../nodes/execute';
2
+ import { getItem } from '../nodes/tensors/tensor';
3
+ import { prepareLifts, saveLift, startLift } from './lift';
4
+ let worker;
5
+ let loaded = false;
6
+ let active;
7
+ const queue = [];
8
+ let nextScopeId = 0;
9
+ // Reruns waiting for the running block to end, by scope and node id. A newer request replaces a waiting one.
10
+ const waitingReruns = new Map();
11
+ // Reruns sent to the worker, by request id.
12
+ const sentReruns = new Map();
13
+ let nextRerunId = 0;
14
+ // Set while a `pie.*` call waits for Python to run a batch: takes Python's results and the id of its request.
15
+ let batchDone;
16
+ const message = (err) => (err instanceof Error ? err.message : String(err));
17
+ function onMessage({ data }) {
18
+ const run = active;
19
+ if (data.type === 'loaded') {
20
+ loaded = true;
21
+ run?.onStatus('running');
22
+ }
23
+ if (data.type === 'call' || data.type === 'item' || data.type === 'get_node' || data.type === 'lift' || data.type === 'ui') {
24
+ // The request to answer: this one, or, after a batch, Python's request with the batch's results.
25
+ let reqId = data.reqId;
26
+ // A reply from before a kill must not reach the new worker.
27
+ const reply = (msg) => {
28
+ if (worker === this)
29
+ this.postMessage({ type: 'reply', reqId, ...msg });
30
+ };
31
+ const store = run?.scope.store;
32
+ if (!store) {
33
+ reply({ error: 'this page has no canvas' });
34
+ return;
35
+ }
36
+ if (data.type === 'item') {
37
+ try {
38
+ reply({ result: getItem(store, data.arrayId, data.position) });
39
+ }
40
+ catch (err) {
41
+ reply({ error: message(err) });
42
+ }
43
+ return;
44
+ }
45
+ if (data.type === 'get_node') {
46
+ const node = store.getNodeValue(data.id);
47
+ if (!node)
48
+ reply({ error: `pie.get_node: no node with id '${data.id}'` });
49
+ else if (node.type === 'Array')
50
+ reply({ result: { id: node.id, type: node.type, shape: node.shape, itemType: node.itemType } });
51
+ else
52
+ reply({ result: { id: node.id, type: node.type } });
53
+ return;
54
+ }
55
+ if (data.type === 'ui') {
56
+ try {
57
+ run.onUi({ name: data.name, args: data.args, options: data.options });
58
+ reply({ result: null });
59
+ }
60
+ catch (err) {
61
+ reply({ error: message(err) });
62
+ }
63
+ return;
64
+ }
65
+ if (data.type === 'lift') {
66
+ try {
67
+ reply({ result: startLift(store, data.name, data.inputIds, data.kind, data.out, data.fill, data.stroke) });
68
+ }
69
+ catch (err) {
70
+ reply({ error: message(err) });
71
+ }
72
+ return;
73
+ }
74
+ // Python runs a batch inside this call: the reply asks for it, and Python sends the results back as a new request.
75
+ const runBatch = (jobs) => new Promise((resolve) => {
76
+ batchDone = (next, results) => {
77
+ reqId = next;
78
+ resolve(results);
79
+ };
80
+ reply({ result: { batch: jobs } });
81
+ });
82
+ execute(store, data.keyword, data.args, data.options, (visitSteps) => prepareLifts(visitSteps, runBatch)).then((result) => reply({ result }), (err) => reply({ error: message(err) }));
83
+ }
84
+ if (data.type === 'batch_done') {
85
+ const done = batchDone;
86
+ batchDone = undefined;
87
+ done?.(data.reqId, data.results);
88
+ }
89
+ // No reply: Python doesn't wait for it.
90
+ if (data.type === 'lift_save') {
91
+ const scope = run?.scope;
92
+ try {
93
+ if (scope?.store)
94
+ saveLift(scope.store, data, (nodeId, values, done) => scope.rerun(nodeId, values, done));
95
+ }
96
+ catch (err) {
97
+ console.error(`${data.name}: ${message(err)}`);
98
+ }
99
+ }
100
+ if (data.type === 'rerun_done') {
101
+ const rerun = sentReruns.get(data.reqId);
102
+ sentReruns.delete(data.reqId);
103
+ rerun?.done(data.result, data.error);
104
+ }
105
+ if (data.type === 'output') {
106
+ run?.onOutput(data.text);
107
+ }
108
+ if (data.type === 'plot') {
109
+ run?.onPlot(data.png);
110
+ }
111
+ if (data.type === 'done') {
112
+ finish(data.error);
113
+ }
114
+ }
115
+ function startNext() {
116
+ if (active || queue.length === 0)
117
+ return;
118
+ active = queue.shift();
119
+ if (!worker) {
120
+ worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });
121
+ worker.onmessage = onMessage;
122
+ worker.onerror = (e) => finish(e.message || 'Python worker failed to start');
123
+ }
124
+ active.onStatus(loaded ? 'running' : 'loading');
125
+ worker.postMessage({ type: 'run', scope: active.scope.id, code: active.code });
126
+ }
127
+ function finish(error) {
128
+ const run = active;
129
+ if (!run)
130
+ return;
131
+ active = undefined;
132
+ // Pyodide failed to load: start a fresh worker next time instead of reusing the broken one.
133
+ if (!loaded)
134
+ killWorker();
135
+ if (run.scope.disposed)
136
+ worker?.postMessage({ type: 'dispose', scope: run.scope.id });
137
+ run.onStatus('finished', error);
138
+ sendReruns();
139
+ startNext();
140
+ }
141
+ /**
142
+ * Sends the waiting reruns, unless a block is running. After a kill they wait for the next worker,
143
+ * which answers that Python was restarted.
144
+ */
145
+ function sendReruns() {
146
+ if (active || !worker)
147
+ return;
148
+ for (const rerun of waitingReruns.values()) {
149
+ const reqId = nextRerunId++;
150
+ sentReruns.set(reqId, rerun);
151
+ worker.postMessage({ type: 'rerun', reqId, scope: rerun.scope.id, nodeId: rerun.nodeId, values: rerun.values });
152
+ }
153
+ waitingReruns.clear();
154
+ }
155
+ function killWorker() {
156
+ worker?.terminate();
157
+ worker = undefined;
158
+ loaded = false;
159
+ // Their replies will never come.
160
+ sentReruns.clear();
161
+ batchDone = undefined;
162
+ }
163
+ /** Kills Python. The running run and every queued run end as killed. */
164
+ function killPython() {
165
+ killWorker();
166
+ const ended = [...(active ? [active] : []), ...queue];
167
+ active = undefined;
168
+ queue.length = 0;
169
+ for (const run of ended)
170
+ run.onStatus('killed');
171
+ }
172
+ /** Runs that share Python variables, and the store their `pie.*` calls draw on. */
173
+ export class PythonScope {
174
+ store;
175
+ id = String(nextScopeId++);
176
+ disposed = false;
177
+ /** `store`: where `pie.*` calls draw. Without it they fail with "this page has no canvas". */
178
+ constructor(store) {
179
+ this.store = store;
180
+ }
181
+ /** Queues `code`. Returns a stop function. `error` comes only with `finished`. */
182
+ run(code, onStatus, onOutput, onPlot, onUi) {
183
+ const run = { scope: this, code, onStatus, onOutput, onPlot, onUi };
184
+ queue.push(run);
185
+ onStatus('waiting');
186
+ startNext();
187
+ // The stop function (the editor's ■ button): drops the run if queued, kills Python if it's running.
188
+ return () => {
189
+ const at = queue.indexOf(run);
190
+ if (at !== -1) {
191
+ queue.splice(at, 1);
192
+ onStatus('stopped');
193
+ }
194
+ else if (active === run) {
195
+ killPython();
196
+ }
197
+ };
198
+ }
199
+ /** Queues a rerun of node `nodeId`'s `pie.lift`ed function. It waits while a block runs. */
200
+ rerun(nodeId, values, done) {
201
+ if (this.disposed)
202
+ return;
203
+ waitingReruns.set(`${this.id}/${nodeId}`, { scope: this, nodeId, values, done });
204
+ sendReruns();
205
+ }
206
+ /** Frees the variables. Call when the page goes away. */
207
+ dispose() {
208
+ this.disposed = true;
209
+ for (let i = queue.length - 1; i >= 0; i--) {
210
+ if (queue[i].scope === this)
211
+ queue.splice(i, 1);
212
+ }
213
+ for (const [key, rerun] of waitingReruns) {
214
+ if (rerun.scope === this)
215
+ waitingReruns.delete(key);
216
+ }
217
+ // A running run still uses the variables; `finish` frees them.
218
+ if (active?.scope !== this)
219
+ worker?.postMessage({ type: 'dispose', scope: this.id });
220
+ }
221
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,111 @@
1
+ import PIE_PY from './py/pie.py?raw';
2
+ import PIE_MPL_PY from './py/pie_mpl.py?raw';
3
+ import SHOW_FIGURES from './py/show_figures.py?raw';
4
+ const BASE = 'https://cdn.jsdelivr.net/pyodide/v0.28.2/full/';
5
+ const pending = new Map();
6
+ let next = 0;
7
+ /** Posts `message` to the page and waits for its reply. */
8
+ const request = (message) => new Promise((resolve, reject) => {
9
+ const reqId = next++;
10
+ pending.set(reqId, { resolve, reject });
11
+ postMessage({ ...message, reqId });
12
+ });
13
+ const call = (keyword, args, options) => request({ type: 'call', keyword, args, options });
14
+ /** The node at `position` of an array's items. Creates nothing. */
15
+ const item = (arrayId, position) => request({ type: 'item', arrayId, position });
16
+ /** The node with id `id`. Creates nothing. */
17
+ const get_node = (id) => request({ type: 'get_node', id });
18
+ /** First half of `g(a)` for `g = pie.lift(f, ...)`: the input values and the output id. */
19
+ const lift = (name, inputIds, kind, out, fill, stroke) => request({ type: 'lift', name, inputIds, kind, out, fill, stroke });
20
+ /** Second half of `g(a)`: the first result. Python doesn't wait for a reply. */
21
+ const lift_save = (save) => postMessage({ type: 'lift_save', ...save });
22
+ /** `pie.ui.<name>(...)`: shows a UI below the block. `args`: nodes as `{id}`, or lists of them. */
23
+ const ui = (name, args, options) => request({ type: 'ui', name, args, options });
24
+ /** Results of a batch the page asked for in a reply, before an animation. Waits for the call's next reply. */
25
+ const batch_done = (results) => request({ type: 'batch_done', results });
26
+ const ready = (async () => {
27
+ const { loadPyodide } = await import(/* @vite-ignore */ `${BASE}pyodide.mjs`);
28
+ const py = await loadPyodide({ indexURL: BASE, env: { MPLBACKEND: 'module://pie_mpl' } });
29
+ py.setStdout({ batched: (text) => postMessage({ type: 'output', text: text + '\n' }) });
30
+ py.setStderr({ batched: (text) => postMessage({ type: 'output', text: text + '\n' }) });
31
+ py.registerJsModule('bridge', {
32
+ call, item, get_node, lift, lift_save, batch_done, ui, plot: (png) => postMessage({ type: 'plot', png }),
33
+ });
34
+ py.FS.writeFile('/home/pyodide/pie.py', PIE_PY);
35
+ py.FS.writeFile('/home/pyodide/pie_mpl.py', PIE_MPL_PY);
36
+ postMessage({ type: 'loaded' });
37
+ return py;
38
+ })();
39
+ // Scope id -> the Python globals its runs share. One scope per page.
40
+ const scopes = new Map();
41
+ const message = (e) => (e instanceof Error ? e.message : String(e));
42
+ self.onmessage = async ({ data }) => {
43
+ if (data.type === 'reply') {
44
+ const { resolve, reject } = pending.get(data.reqId);
45
+ pending.delete(data.reqId);
46
+ if (data.error !== undefined)
47
+ reject(new Error(data.error));
48
+ else
49
+ resolve(data.result);
50
+ }
51
+ if (data.type === 'run') {
52
+ let error;
53
+ try {
54
+ const py = await ready;
55
+ let globals = scopes.get(data.scope);
56
+ if (!globals) {
57
+ globals = py.globals.get('dict')();
58
+ py.runPython('import pie', { globals });
59
+ scopes.set(data.scope, globals);
60
+ }
61
+ // A batch finds lifted functions in the running block's globals.
62
+ const pie = py.pyimport('pie');
63
+ pie._scope = globals;
64
+ pie.destroy();
65
+ // Downloads packages the code imports (numpy, scipy, matplotlib, ...) on first use.
66
+ await py.loadPackagesFromImports(data.code);
67
+ try {
68
+ await py.runPythonAsync(data.code, { globals }); // Async entry is required for run_sync
69
+ }
70
+ catch (e) {
71
+ error = message(e);
72
+ }
73
+ // Runs after an error too, so figures drawn before it still show.
74
+ py.runPython(SHOW_FIGURES);
75
+ }
76
+ catch (e) {
77
+ error ??= message(e);
78
+ }
79
+ postMessage({ type: 'done', error });
80
+ }
81
+ // The page sends reruns only between runs, so this never interleaves with a run.
82
+ if (data.type === 'rerun') {
83
+ let result;
84
+ let error;
85
+ try {
86
+ const py = await ready;
87
+ const globals = scopes.get(data.scope);
88
+ if (!globals)
89
+ throw new Error("Python was restarted, so this node can't rerun. Run the block that made it again.");
90
+ const pie = py.pyimport('pie');
91
+ const values = py.toPy(data.values);
92
+ try {
93
+ const out = pie._rerun(globals, data.nodeId, values);
94
+ result = out.toJs({ dict_converter: Object.fromEntries });
95
+ out.destroy();
96
+ }
97
+ finally {
98
+ values.destroy();
99
+ pie.destroy();
100
+ }
101
+ }
102
+ catch (e) {
103
+ error = message(e);
104
+ }
105
+ postMessage({ type: 'rerun_done', reqId: data.reqId, result, error });
106
+ }
107
+ if (data.type === 'dispose') {
108
+ scopes.get(data.scope)?.destroy();
109
+ scopes.delete(data.scope);
110
+ }
111
+ };
@@ -0,0 +1,2 @@
1
+ /** A layer over the canvas for UIs dropped there. When the canvas resizes, they are kept inside it. */
2
+ export declare function UiLayer(): import("solid-js").JSX.Element;
@@ -0,0 +1,15 @@
1
+ import { onCleanup, onMount } from 'solid-js';
2
+ import { clampToLayer, UI_LAYER_CLASS } from './dragUi';
3
+ /** A layer over the canvas for UIs dropped there. When the canvas resizes, they are kept inside it. */
4
+ export function UiLayer() {
5
+ let layer;
6
+ onMount(() => {
7
+ const observer = new ResizeObserver(() => {
8
+ for (const box of layer.children)
9
+ clampToLayer(box, layer);
10
+ });
11
+ observer.observe(layer);
12
+ onCleanup(() => observer.disconnect());
13
+ });
14
+ return <div ref={layer} class={UI_LAYER_CLASS}/>;
15
+ }
@@ -0,0 +1,23 @@
1
+ import type { NodeStore } from '../nodes/state/NodeStore';
2
+ /** A node as Python sends it, or a list of them at any depth. */
3
+ type SentArg = {
4
+ id: string;
5
+ } | SentArg[];
6
+ /** A `pie.ui.<name>(*args, **options)` call. */
7
+ export interface UiCall {
8
+ name: string;
9
+ args: SentArg[];
10
+ options: Record<string, unknown>;
11
+ }
12
+ /** Throws, for Python to raise, when there is no such UI or a node is missing. */
13
+ export declare function checkUi(store: NodeStore, call: UiCall): void;
14
+ /**
15
+ * Shows a UI, with a grip to drag it into the page's text or onto the canvas. Shows nothing while one of its
16
+ * nodes is removed, and the error, after the UI's name, if it throws.
17
+ * The `label` option is shown in front of the UI, for every UI, so the UI itself doesn't get it.
18
+ */
19
+ export declare function UiView(props: {
20
+ store: NodeStore;
21
+ call: UiCall;
22
+ }): import("solid-js").JSX.Element;
23
+ export {};
@@ -0,0 +1,56 @@
1
+ import { ErrorBoundary, onCleanup, Show } from 'solid-js';
2
+ import { Dynamic } from 'solid-js/web';
3
+ import { getUi } from './registry';
4
+ import { nodeHandle, StoreContext } from './nodeHandle';
5
+ import { dragUi } from './dragUi';
6
+ const nodeIds = (args) => args.flatMap((a) => (Array.isArray(a) ? nodeIds(a) : [a.id]));
7
+ const toHandles = (store, args) => args.map((a) => (Array.isArray(a) ? toHandles(store, a) : nodeHandle(store, a.id)));
8
+ const present = (store, id) => {
9
+ const node = store.getNodeValue(id);
10
+ return node !== undefined && node.type !== 'Dummy';
11
+ };
12
+ /** Throws, for Python to raise, when there is no such UI or a node is missing. */
13
+ export function checkUi(store, call) {
14
+ if (!getUi(call.name))
15
+ throw new Error(`pie.ui: no UI named '${call.name}'`);
16
+ const missing = nodeIds(call.args).find((id) => !present(store, id));
17
+ if (missing !== undefined)
18
+ throw new Error(`pie.ui.${call.name}: no node with id '${missing}'`);
19
+ }
20
+ /**
21
+ * Shows a UI, with a grip to drag it into the page's text or onto the canvas. Shows nothing while one of its
22
+ * nodes is removed, and the error, after the UI's name, if it throws.
23
+ * The `label` option is shown in front of the UI, for every UI, so the UI itself doesn't get it.
24
+ */
25
+ export function UiView(props) {
26
+ const { name, args, options: { label, ...options } } = props.call;
27
+ const ids = nodeIds(args);
28
+ const handles = toHandles(props.store, args);
29
+ const shown = () => ids.every((id) => present(props.store, id));
30
+ // `box` starts in `home`. Dragging moves it out, so the editor's list, which holds `home`, is left alone.
31
+ let home;
32
+ let box;
33
+ onCleanup(() => box.remove());
34
+ const startDrag = (e) => {
35
+ const text = home.closest('main');
36
+ if (text)
37
+ dragUi(e, box, text);
38
+ };
39
+ return (<div ref={home}>
40
+ <div ref={box} class="python-editor-ui" classList={{ 'python-editor-ui-hidden': !shown() }}>
41
+ <span class="python-editor-ui-grip" title="Drag to move" onPointerDown={startDrag}>⋮⋮</span>
42
+ <Show when={label != null && label !== ''}>
43
+ <span class="python-editor-ui-label">{String(label)}</span>
44
+ </Show>
45
+ <div class="python-editor-ui-body">
46
+ <StoreContext.Provider value={props.store}>
47
+ <ErrorBoundary fallback={(err) => <span class="python-editor-error">pie.ui.{name}: {err instanceof Error ? err.message : String(err)}</span>}>
48
+ <Show when={shown()}>
49
+ <Dynamic component={getUi(name)} {...options} args={handles}/>
50
+ </Show>
51
+ </ErrorBoundary>
52
+ </StoreContext.Provider>
53
+ </div>
54
+ </div>
55
+ </div>);
56
+ }
@@ -0,0 +1,10 @@
1
+ import { type UiArg } from '../nodeHandle';
2
+ /**
3
+ * `pie.ui.checkboxes(mask, options=['a', 'b'])`: one checkbox per item of the Array of Scalars `mask`.
4
+ * An item is 1 when ticked, 0 when not; any value other than 0 shows as ticked.
5
+ * `options`: one label per item, in row-major order. Without it, the labels are the item positions.
6
+ */
7
+ export declare function Checkboxes(props: {
8
+ args: UiArg[];
9
+ options?: string[];
10
+ }): import("solid-js").JSX.Element;
@@ -0,0 +1,30 @@
1
+ import { Index } from 'solid-js';
2
+ import { num, scalar } from '../../nodes/jax';
3
+ import { expectNode, useSetNode } from '../nodeHandle';
4
+ /**
5
+ * `pie.ui.checkboxes(mask, options=['a', 'b'])`: one checkbox per item of the Array of Scalars `mask`.
6
+ * An item is 1 when ticked, 0 when not; any value other than 0 shows as ticked.
7
+ * `options`: one label per item, in row-major order. Without it, the labels are the item positions.
8
+ */
9
+ export function Checkboxes(props) {
10
+ const [mask] = expectNode(props.args[0], ['Array']);
11
+ const setNode = useSetNode();
12
+ const items = () => {
13
+ const array = mask();
14
+ if (array.itemType !== 'Scalar')
15
+ throw new Error(`expects an Array of Scalars, got an Array of ${array.itemType}`);
16
+ if (props.options && props.options.length !== array.items.length) {
17
+ throw new Error(`got ${props.options.length} options for ${array.items.length} items`);
18
+ }
19
+ return array.items;
20
+ };
21
+ // `Index`, not `For`: the items are new objects after every change, but their positions stay.
22
+ return (<span class="pie-ui-choices">
23
+ <Index each={items()}>
24
+ {(item, i) => (<label>
25
+ <input type="checkbox" checked={num(item().value) !== 0} onChange={(e) => setNode(item(), { value: scalar(e.currentTarget.checked ? 1 : 0) })}/>
26
+ {props.options?.[i] ?? String(i)}
27
+ </label>)}
28
+ </Index>
29
+ </span>);
30
+ }
@@ -0,0 +1,8 @@
1
+ import { type UiArg } from '../nodeHandle';
2
+ /**
3
+ * `pie.ui.latex(a, b, ...)`: the nodes as LaTeX, side by side. A Scalar shows its number, a Point (x, y),
4
+ * a Text its value as LaTeX source, an Array of 1 or 2 dimensions a matrix.
5
+ */
6
+ export declare function Latex(props: {
7
+ args: UiArg[];
8
+ }): import("solid-js").JSX.Element;
@@ -0,0 +1,41 @@
1
+ import katex from 'katex';
2
+ import { num } from '../../nodes/jax';
3
+ import { isHandle } from '../nodeHandle';
4
+ const fmt = (v) => String(Number(num(v).toFixed(4)));
5
+ /** Rows of a 1D (a column) or 2D list of entries, as a bmatrix. */
6
+ function matrix(entries, shape) {
7
+ if (shape.length > 2)
8
+ throw new Error(`an array needs 1 or 2 dimensions, got shape [${shape.join(', ')}]`);
9
+ const cols = shape[1] ?? 1;
10
+ const rows = Array.from({ length: shape[0] }, (_, r) => entries.slice(r * cols, (r + 1) * cols).join(' & '));
11
+ return `\\begin{bmatrix} ${rows.join(' \\\\ ')} \\end{bmatrix}`;
12
+ }
13
+ function nodeTex(node) {
14
+ switch (node.type) {
15
+ case 'Scalar': return fmt(node.value);
16
+ case 'Point': return `\\left(${fmt(node.x)}, ${fmt(node.y)}\\right)`;
17
+ // A Text holds LaTeX source.
18
+ case 'Text': return node.value;
19
+ case 'Array': return matrix(node.items.map(nodeTex), node.shape);
20
+ default: throw new Error(`can't show a ${node.type}`);
21
+ }
22
+ }
23
+ /** A list is shown like an Array: 1D as a column, 2D as a matrix. */
24
+ function argTex(arg) {
25
+ if (isHandle(arg))
26
+ return nodeTex(arg[0]());
27
+ if (arg.every(isHandle))
28
+ return matrix(arg.map(argTex), [arg.length]);
29
+ if (arg.every((row) => !isHandle(row) && row.every(isHandle) && row.length === arg[0].length)) {
30
+ return matrix(arg.flatMap((row) => row.map(argTex)), [arg.length, arg[0].length]);
31
+ }
32
+ throw new Error('a list must be a list of nodes, or a list of equal-length lists of nodes');
33
+ }
34
+ /**
35
+ * `pie.ui.latex(a, b, ...)`: the nodes as LaTeX, side by side. A Scalar shows its number, a Point (x, y),
36
+ * a Text its value as LaTeX source, an Array of 1 or 2 dimensions a matrix.
37
+ */
38
+ export function Latex(props) {
39
+ const html = () => katex.renderToString(props.args.map(argTex).join(' '), { throwOnError: false });
40
+ return <span innerHTML={html()}/>;
41
+ }
@@ -0,0 +1,6 @@
1
+ import { type UiArg } from '../nodeHandle';
2
+ /** `pie.ui.radio(n, options=['a', 'b'])`: one radio button per option. Scalar `n` holds the chosen one's index. */
3
+ export declare function Radio(props: {
4
+ args: UiArg[];
5
+ options?: string[];
6
+ }): import("solid-js").JSX.Element;
@@ -0,0 +1,19 @@
1
+ import { createUniqueId, For } from 'solid-js';
2
+ import { num, scalar } from '../../nodes/jax';
3
+ import { expectNode } from '../nodeHandle';
4
+ /** `pie.ui.radio(n, options=['a', 'b'])`: one radio button per option. Scalar `n` holds the chosen one's index. */
5
+ export function Radio(props) {
6
+ const [n, setN] = expectNode(props.args[0], ['Scalar']);
7
+ if (!props.options?.length)
8
+ throw new Error('needs `options`, a list of labels');
9
+ // Groups the buttons, so choosing one unchecks the others.
10
+ const group = createUniqueId();
11
+ return (<span class="pie-ui-choices">
12
+ <For each={props.options}>
13
+ {(label, i) => (<label>
14
+ <input type="radio" name={group} checked={num(n().value) === i()} onChange={() => setN({ value: scalar(i()) })}/>
15
+ {label}
16
+ </label>)}
17
+ </For>
18
+ </span>);
19
+ }
@@ -0,0 +1,8 @@
1
+ import { type UiArg } from '../nodeHandle';
2
+ /** `pie.ui.slider(n, min=0, max=1, step=0.01)`: a slider for Scalar `n`. */
3
+ export declare function Slider(props: {
4
+ args: UiArg[];
5
+ min?: number;
6
+ max?: number;
7
+ step?: number;
8
+ }): import("solid-js").JSX.Element;
@@ -0,0 +1,7 @@
1
+ import { num, scalar } from '../../nodes/jax';
2
+ import { expectNode } from '../nodeHandle';
3
+ /** `pie.ui.slider(n, min=0, max=1, step=0.01)`: a slider for Scalar `n`. */
4
+ export function Slider(props) {
5
+ const [n, setN] = expectNode(props.args[0], ['Scalar']);
6
+ return (<input type="range" min={props.min ?? 0} max={props.max ?? 1} step={props.step ?? 0.01} value={num(n().value)} onInput={(e) => setN({ value: scalar(e.currentTarget.valueAsNumber) })}/>);
7
+ }
@@ -0,0 +1,5 @@
1
+ import { type UiArg } from '../nodeHandle';
2
+ /** `pie.ui.textbox(n)`: a text box for Scalar or Text `n`. It writes on Enter or on leaving the box. */
3
+ export declare function Textbox(props: {
4
+ args: UiArg[];
5
+ }): import("solid-js").JSX.Element;
@@ -0,0 +1,21 @@
1
+ import { num, scalar } from '../../nodes/jax';
2
+ import { expectNode } from '../nodeHandle';
3
+ /** `pie.ui.textbox(n)`: a text box for Scalar or Text `n`. It writes on Enter or on leaving the box. */
4
+ export function Textbox(props) {
5
+ const [n, setN] = expectNode(props.args[0], ['Scalar', 'Text']);
6
+ const shown = () => {
7
+ const node = n();
8
+ return node.type === 'Scalar' ? String(num(node.value)) : node.value;
9
+ };
10
+ const write = (input) => {
11
+ if (n().type === 'Text')
12
+ return setN({ value: input.value });
13
+ const value = Number(input.value);
14
+ // Not a number: put the current value back.
15
+ if (input.value.trim() === '' || Number.isNaN(value))
16
+ input.value = shown();
17
+ else
18
+ setN({ value: scalar(value) });
19
+ };
20
+ return <input type="text" value={shown()} onChange={(e) => write(e.currentTarget)}/>;
21
+ }
@@ -0,0 +1,10 @@
1
+ /** Class of the layer over the canvas that holds the UIs dropped there. */
2
+ export declare const UI_LAYER_CLASS = "canvas-ui-layer";
3
+ /** Keeps `box` inside `layer`, with its top left corner at (`left`, `top`) if that fits. */
4
+ export declare function clampToLayer(box: HTMLElement, layer: HTMLElement, left?: number, top?: number): void;
5
+ /**
6
+ * Drags `box`, a UI, from a press `e` on its grip. Dropped over the canvas, it stays at that spot on the screen.
7
+ * Dropped anywhere else, it goes into the nearest gap between the blocks of `text`, the page's text.
8
+ * Near the text's top or bottom edge, the text scrolls.
9
+ */
10
+ export declare function dragUi(e: PointerEvent, box: HTMLElement, text: HTMLElement): void;