@tinyvolt/pie 0.9.0 → 0.11.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 (139) 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 +19 -0
  9. package/dist/lib/customModules.js +52 -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 +42 -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/runPage.d.ts +21 -0
  86. package/dist/lib/python/runPage.js +60 -0
  87. package/dist/lib/python/runner.d.ts +68 -0
  88. package/dist/lib/python/runner.js +243 -0
  89. package/dist/lib/python/worker.d.ts +1 -0
  90. package/dist/lib/python/worker.js +111 -0
  91. package/dist/lib/ui/UiLayer.d.ts +2 -0
  92. package/dist/lib/ui/UiLayer.jsx +15 -0
  93. package/dist/lib/ui/UiView.d.ts +23 -0
  94. package/dist/lib/ui/UiView.jsx +56 -0
  95. package/dist/lib/ui/components/checkboxes.d.ts +10 -0
  96. package/dist/lib/ui/components/checkboxes.jsx +30 -0
  97. package/dist/lib/ui/components/latex.d.ts +8 -0
  98. package/dist/lib/ui/components/latex.jsx +41 -0
  99. package/dist/lib/ui/components/radio.d.ts +6 -0
  100. package/dist/lib/ui/components/radio.jsx +19 -0
  101. package/dist/lib/ui/components/slider.d.ts +8 -0
  102. package/dist/lib/ui/components/slider.jsx +7 -0
  103. package/dist/lib/ui/components/textbox.d.ts +5 -0
  104. package/dist/lib/ui/components/textbox.jsx +21 -0
  105. package/dist/lib/ui/dragUi.d.ts +10 -0
  106. package/dist/lib/ui/dragUi.js +129 -0
  107. package/dist/lib/ui/nodeHandle.d.ts +15 -0
  108. package/dist/lib/ui/nodeHandle.js +37 -0
  109. package/dist/lib/ui/registry.d.ts +10 -0
  110. package/dist/lib/ui/registry.js +42 -0
  111. package/dist/runtime.css +696 -0
  112. package/dist/runtime.d.ts +10 -0
  113. package/dist/runtime.jsx +7 -0
  114. package/init/index.js +2 -2
  115. package/init/site-agents.md +2 -1
  116. package/package.json +15 -6
  117. package/runtime-agents.md +168 -0
  118. package/src/app.css +7 -665
  119. package/src/lib/customModules.ts +67 -0
  120. package/src/lib/markdown/compile.ts +49 -0
  121. package/src/lib/markdown/components/PiePage.tsx +49 -0
  122. package/src/lib/markdown/features/build.ts +15 -6
  123. package/src/lib/markdown/features/sidebar/View.tsx +4 -2
  124. package/src/lib/markdown/features/tags/build.ts +6 -3
  125. package/src/lib/markdown/pages.ts +1 -9
  126. package/src/lib/markdown/vitePlugin.ts +4 -8
  127. package/src/lib/nodes/functions/registry.ts +30 -21
  128. package/src/lib/nodes/functions/sideEffects.ts +14 -8
  129. package/src/lib/nodes/functions/vitePlugin.ts +8 -10
  130. package/src/lib/nodes/state/Node.ts +27 -19
  131. package/src/lib/python/runPage.ts +78 -0
  132. package/src/lib/python/runner.ts +189 -164
  133. package/src/lib/siteModules.ts +13 -0
  134. package/src/lib/ui/dragUi.ts +4 -2
  135. package/src/lib/ui/registry.ts +35 -14
  136. package/src/page.css +664 -0
  137. package/src/routes/[...slug].tsx +1 -0
  138. package/src/runtime.css +29 -0
  139. package/src/runtime.tsx +16 -0
@@ -17,10 +17,6 @@ interface Run {
17
17
  onUi: (call: UiCall) => void;
18
18
  }
19
19
 
20
- let worker: Worker | undefined;
21
- let loaded = false;
22
- let active: Run | undefined;
23
- const queue: Run[] = [];
24
20
  let nextScopeId = 0;
25
21
 
26
22
  /** A request to rerun the `pie.lift`ed function of node `nodeId` with new input values. */
@@ -31,210 +27,239 @@ interface Rerun {
31
27
  done: (result?: PyResult, error?: string) => void;
32
28
  }
33
29
 
34
- // Reruns waiting for the running block to end, by scope and node id. A newer request replaces a waiting one.
35
- const waitingReruns = new Map<string, Rerun>();
36
- // Reruns sent to the worker, by request id.
37
- const sentReruns = new Map<number, Rerun>();
38
- let nextRerunId = 0;
30
+ const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
39
31
 
40
- // Set while a `pie.*` call waits for Python to run a batch: takes Python's results and the id of its request.
41
- let batchDone: ((reqId: number, results: BatchResult[][]) => void) | undefined;
32
+ /** One Python worker and its queue of runs, which it runs one at a time. */
33
+ export class PythonRunner {
34
+ private worker: Worker | undefined;
35
+ private loaded = false;
36
+ private active: Run | undefined;
37
+ private readonly queue: Run[] = [];
42
38
 
43
- const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
39
+ // Reruns waiting for the running block to end, by scope and node id. A newer request replaces a waiting one.
40
+ private readonly waitingReruns = new Map<string, Rerun>();
41
+ // Reruns sent to the worker, by request id.
42
+ private readonly sentReruns = new Map<number, Rerun>();
43
+ private nextRerunId = 0;
44
44
 
45
- function onMessage(this: Worker, { data }: MessageEvent) {
46
- const run = active;
47
- if (data.type === 'loaded') {
48
- loaded = true;
49
- run?.onStatus('running');
50
- }
51
- if (data.type === 'call' || data.type === 'item' || data.type === 'get_node' || data.type === 'lift' || data.type === 'ui') {
52
- // The request to answer: this one, or, after a batch, Python's request with the batch's results.
53
- let reqId: number = data.reqId;
54
- // A reply from before a kill must not reach the new worker.
55
- const reply = (msg: { result?: unknown; error?: string }) => {
56
- if (worker === this) this.postMessage({ type: 'reply', reqId, ...msg });
57
- };
58
- const store = run?.scope.store;
59
- if (!store) {
60
- reply({ error: 'this page has no canvas' });
61
- return;
45
+ // Set while a `pie.*` call waits for Python to run a batch: takes Python's results and the id of its request.
46
+ private batchDone: ((reqId: number, results: BatchResult[][]) => void) | undefined;
47
+
48
+ private onMessage(from: Worker, { data }: MessageEvent) {
49
+ const run = this.active;
50
+ if (data.type === 'loaded') {
51
+ this.loaded = true;
52
+ run?.onStatus('running');
62
53
  }
63
- if (data.type === 'item') {
64
- try {
65
- reply({ result: getItem(store, data.arrayId, data.position) });
66
- } catch (err) {
67
- reply({ error: message(err) });
54
+ if (data.type === 'call' || data.type === 'item' || data.type === 'get_node' || data.type === 'lift' || data.type === 'ui') {
55
+ // The request to answer: this one, or, after a batch, Python's request with the batch's results.
56
+ let reqId: number = data.reqId;
57
+ // A reply from before a kill must not reach the new worker.
58
+ const reply = (msg: { result?: unknown; error?: string }) => {
59
+ if (this.worker === from) from.postMessage({ type: 'reply', reqId, ...msg });
60
+ };
61
+ const store = run?.scope.store;
62
+ if (!store) {
63
+ reply({ error: 'this page has no canvas' });
64
+ return;
65
+ }
66
+ if (data.type === 'item') {
67
+ try {
68
+ reply({ result: getItem(store, data.arrayId, data.position) });
69
+ } catch (err) {
70
+ reply({ error: message(err) });
71
+ }
72
+ return;
73
+ }
74
+ if (data.type === 'get_node') {
75
+ const node = store.getNodeValue(data.id);
76
+ if (!node) reply({ error: `pie.get_node: no node with id '${data.id}'` });
77
+ else if (node.type === 'Array') reply({ result: { id: node.id, type: node.type, shape: node.shape, itemType: node.itemType } });
78
+ else reply({ result: { id: node.id, type: node.type } });
79
+ return;
68
80
  }
69
- return;
81
+ if (data.type === 'ui') {
82
+ try {
83
+ run!.onUi({ name: data.name, args: data.args, options: data.options });
84
+ reply({ result: null });
85
+ } catch (err) {
86
+ reply({ error: message(err) });
87
+ }
88
+ return;
89
+ }
90
+ if (data.type === 'lift') {
91
+ try {
92
+ reply({ result: startLift(store, data.name, data.inputIds, data.kind, data.out, data.fill, data.stroke) });
93
+ } catch (err) {
94
+ reply({ error: message(err) });
95
+ }
96
+ return;
97
+ }
98
+ // Python runs a batch inside this call: the reply asks for it, and Python sends the results back as a new request.
99
+ const runBatch = (jobs: BatchJob[]) => new Promise<BatchResult[][]>((resolve) => {
100
+ this.batchDone = (next, results) => {
101
+ reqId = next;
102
+ resolve(results);
103
+ };
104
+ reply({ result: { batch: jobs } });
105
+ });
106
+ execute(store, data.keyword, data.args, data.options, (visitSteps) => prepareLifts(visitSteps, runBatch)).then(
107
+ (result) => reply({ result }),
108
+ (err) => reply({ error: message(err) }),
109
+ );
70
110
  }
71
- if (data.type === 'get_node') {
72
- const node = store.getNodeValue(data.id);
73
- if (!node) reply({ error: `pie.get_node: no node with id '${data.id}'` });
74
- else if (node.type === 'Array') reply({ result: { id: node.id, type: node.type, shape: node.shape, itemType: node.itemType } });
75
- else reply({ result: { id: node.id, type: node.type } });
76
- return;
111
+ if (data.type === 'batch_done') {
112
+ const done = this.batchDone;
113
+ this.batchDone = undefined;
114
+ done?.(data.reqId, data.results);
77
115
  }
78
- if (data.type === 'ui') {
116
+ // No reply: Python doesn't wait for it.
117
+ if (data.type === 'lift_save') {
118
+ const scope = run?.scope;
79
119
  try {
80
- run!.onUi({ name: data.name, args: data.args, options: data.options });
81
- reply({ result: null });
120
+ if (scope?.store) saveLift(scope.store, data, (nodeId, values, done) => scope.rerun(nodeId, values, done));
82
121
  } catch (err) {
83
- reply({ error: message(err) });
122
+ console.error(`${data.name}: ${message(err)}`);
84
123
  }
85
- return;
86
124
  }
87
- if (data.type === 'lift') {
88
- try {
89
- reply({ result: startLift(store, data.name, data.inputIds, data.kind, data.out, data.fill, data.stroke) });
90
- } catch (err) {
91
- reply({ error: message(err) });
92
- }
93
- return;
125
+ if (data.type === 'rerun_done') {
126
+ const rerun = this.sentReruns.get(data.reqId);
127
+ this.sentReruns.delete(data.reqId);
128
+ rerun?.done(data.result, data.error);
94
129
  }
95
- // Python runs a batch inside this call: the reply asks for it, and Python sends the results back as a new request.
96
- const runBatch = (jobs: BatchJob[]) => new Promise<BatchResult[][]>((resolve) => {
97
- batchDone = (next, results) => {
98
- reqId = next;
99
- resolve(results);
100
- };
101
- reply({ result: { batch: jobs } });
102
- });
103
- execute(store, data.keyword, data.args, data.options, (visitSteps) => prepareLifts(visitSteps, runBatch)).then(
104
- (result) => reply({ result }),
105
- (err) => reply({ error: message(err) }),
106
- );
107
- }
108
- if (data.type === 'batch_done') {
109
- const done = batchDone;
110
- batchDone = undefined;
111
- done?.(data.reqId, data.results);
112
- }
113
- // No reply: Python doesn't wait for it.
114
- if (data.type === 'lift_save') {
115
- const scope = run?.scope;
116
- try {
117
- if (scope?.store) saveLift(scope.store, data, (nodeId, values, done) => scope.rerun(nodeId, values, done));
118
- } catch (err) {
119
- console.error(`${data.name}: ${message(err)}`);
130
+ if (data.type === 'output') {
131
+ run?.onOutput(data.text);
132
+ }
133
+ if (data.type === 'plot') {
134
+ run?.onPlot(data.png);
135
+ }
136
+ if (data.type === 'done') {
137
+ this.finish(data.error);
120
138
  }
121
139
  }
122
- if (data.type === 'rerun_done') {
123
- const rerun = sentReruns.get(data.reqId);
124
- sentReruns.delete(data.reqId);
125
- rerun?.done(data.result, data.error);
140
+
141
+ private startNext() {
142
+ if (this.active || this.queue.length === 0) return;
143
+ this.active = this.queue.shift()!;
144
+ if (!this.worker) {
145
+ const worker = new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' });
146
+ worker.onmessage = (e) => this.onMessage(worker, e);
147
+ worker.onerror = (e) => this.finish(e.message || 'Python worker failed to start');
148
+ this.worker = worker;
149
+ }
150
+ this.active.onStatus(this.loaded ? 'running' : 'loading');
151
+ this.worker.postMessage({ type: 'run', scope: this.active.scope.id, code: this.active.code });
126
152
  }
127
- if (data.type === 'output') {
128
- run?.onOutput(data.text);
153
+
154
+ private finish(error?: string) {
155
+ const run = this.active;
156
+ if (!run) return;
157
+ this.active = undefined;
158
+ // Pyodide failed to load: start a fresh worker next time instead of reusing the broken one.
159
+ if (!this.loaded) this.killWorker();
160
+ if (run.scope.disposed) this.worker?.postMessage({ type: 'dispose', scope: run.scope.id });
161
+ run.onStatus('finished', error);
162
+ this.sendReruns();
163
+ this.startNext();
129
164
  }
130
- if (data.type === 'plot') {
131
- run?.onPlot(data.png);
165
+
166
+ /**
167
+ * Sends the waiting reruns, unless a block is running. After a kill they wait for the next worker,
168
+ * which answers that Python was restarted.
169
+ */
170
+ private sendReruns() {
171
+ if (this.active || !this.worker) return;
172
+ for (const rerun of this.waitingReruns.values()) {
173
+ const reqId = this.nextRerunId++;
174
+ this.sentReruns.set(reqId, rerun);
175
+ this.worker.postMessage({ type: 'rerun', reqId, scope: rerun.scope.id, nodeId: rerun.nodeId, values: rerun.values });
176
+ }
177
+ this.waitingReruns.clear();
132
178
  }
133
- if (data.type === 'done') {
134
- finish(data.error);
179
+
180
+ private killWorker() {
181
+ this.worker?.terminate();
182
+ this.worker = undefined;
183
+ this.loaded = false;
184
+ // Their replies will never come.
185
+ this.sentReruns.clear();
186
+ this.batchDone = undefined;
135
187
  }
136
- }
137
188
 
138
- function startNext() {
139
- if (active || queue.length === 0) return;
140
- active = queue.shift()!;
141
- if (!worker) {
142
- worker = new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' });
143
- worker.onmessage = onMessage;
144
- worker.onerror = (e) => finish(e.message || 'Python worker failed to start');
189
+ /** Kills Python. The running run and every queued run end as killed. */
190
+ kill() {
191
+ this.killWorker();
192
+ const ended = [...(this.active ? [this.active] : []), ...this.queue];
193
+ this.active = undefined;
194
+ this.queue.length = 0;
195
+ for (const run of ended) run.onStatus('killed');
145
196
  }
146
- active.onStatus(loaded ? 'running' : 'loading');
147
- worker.postMessage({ type: 'run', scope: active.scope.id, code: active.code });
148
- }
149
197
 
150
- function finish(error?: string) {
151
- const run = active;
152
- if (!run) return;
153
- active = undefined;
154
- // Pyodide failed to load: start a fresh worker next time instead of reusing the broken one.
155
- if (!loaded) killWorker();
156
- if (run.scope.disposed) worker?.postMessage({ type: 'dispose', scope: run.scope.id });
157
- run.onStatus('finished', error);
158
- sendReruns();
159
- startNext();
160
- }
198
+ /** Queues `run`. Returns its stop function. */
199
+ enqueue(run: Run): () => void {
200
+ this.queue.push(run);
201
+ run.onStatus('waiting');
202
+ this.startNext();
161
203
 
162
- /**
163
- * Sends the waiting reruns, unless a block is running. After a kill they wait for the next worker,
164
- * which answers that Python was restarted.
165
- */
166
- function sendReruns() {
167
- if (active || !worker) return;
168
- for (const rerun of waitingReruns.values()) {
169
- const reqId = nextRerunId++;
170
- sentReruns.set(reqId, rerun);
171
- worker.postMessage({ type: 'rerun', reqId, scope: rerun.scope.id, nodeId: rerun.nodeId, values: rerun.values });
204
+ // The stop function (the editor's ■ button): drops the run if queued, kills Python if it's running.
205
+ return () => {
206
+ const at = this.queue.indexOf(run);
207
+ if (at !== -1) {
208
+ this.queue.splice(at, 1);
209
+ run.onStatus('stopped');
210
+ } else if (this.active === run) {
211
+ this.kill();
212
+ }
213
+ };
172
214
  }
173
- waitingReruns.clear();
174
- }
175
215
 
176
- function killWorker() {
177
- worker?.terminate();
178
- worker = undefined;
179
- loaded = false;
180
- // Their replies will never come.
181
- sentReruns.clear();
182
- batchDone = undefined;
183
- }
216
+ /** Queues `rerun`. It waits while a block runs. */
217
+ rerun(rerun: Rerun) {
218
+ this.waitingReruns.set(`${rerun.scope.id}/${rerun.nodeId}`, rerun);
219
+ this.sendReruns();
220
+ }
184
221
 
185
- /** Kills Python. The running run and every queued run end as killed. */
186
- function killPython() {
187
- killWorker();
188
- const ended = [...(active ? [active] : []), ...queue];
189
- active = undefined;
190
- queue.length = 0;
191
- for (const run of ended) run.onStatus('killed');
222
+ /** Drops `scope`'s queued runs and reruns, and frees its variables. */
223
+ dispose(scope: PythonScope) {
224
+ for (let i = this.queue.length - 1; i >= 0; i--) {
225
+ if (this.queue[i].scope === scope) this.queue.splice(i, 1);
226
+ }
227
+ for (const [key, rerun] of this.waitingReruns) {
228
+ if (rerun.scope === scope) this.waitingReruns.delete(key);
229
+ }
230
+ // A running run still uses the variables; `finish` frees them.
231
+ if (this.active?.scope !== scope) this.worker?.postMessage({ type: 'dispose', scope: scope.id });
232
+ }
192
233
  }
193
234
 
235
+ /** The worker every page's editors share. */
236
+ const pageRunner = new PythonRunner();
237
+
194
238
  /** Runs that share Python variables, and the store their `pie.*` calls draw on. */
195
239
  export class PythonScope {
196
240
  readonly id = String(nextScopeId++);
197
241
  disposed = false;
198
242
 
199
- /** `store`: where `pie.*` calls draw. Without it they fail with "this page has no canvas". */
200
- constructor(readonly store?: NodeStore) {}
243
+ /**
244
+ * `store`: where `pie.*` calls draw. Without it they fail with "this page has no canvas".
245
+ * `runner`: the worker to run in. Default: the one every page shares.
246
+ */
247
+ constructor(readonly store?: NodeStore, private readonly runner: PythonRunner = pageRunner) {}
201
248
 
202
249
  /** Queues `code`. Returns a stop function. `error` comes only with `finished`. */
203
250
  run(code: string, onStatus: Run['onStatus'], onOutput: Run['onOutput'], onPlot: Run['onPlot'], onUi: Run['onUi']): () => void {
204
- const run: Run = { scope: this, code, onStatus, onOutput, onPlot, onUi };
205
- queue.push(run);
206
- onStatus('waiting');
207
- startNext();
208
-
209
- // The stop function (the editor's ■ button): drops the run if queued, kills Python if it's running.
210
- return () => {
211
- const at = queue.indexOf(run);
212
- if (at !== -1) {
213
- queue.splice(at, 1);
214
- onStatus('stopped');
215
- } else if (active === run) {
216
- killPython();
217
- }
218
- };
251
+ return this.runner.enqueue({ scope: this, code, onStatus, onOutput, onPlot, onUi });
219
252
  }
220
253
 
221
254
  /** Queues a rerun of node `nodeId`'s `pie.lift`ed function. It waits while a block runs. */
222
255
  rerun(nodeId: string, values: InputValue[], done: Rerun['done']) {
223
256
  if (this.disposed) return;
224
- waitingReruns.set(`${this.id}/${nodeId}`, { scope: this, nodeId, values, done });
225
- sendReruns();
257
+ this.runner.rerun({ scope: this, nodeId, values, done });
226
258
  }
227
259
 
228
260
  /** Frees the variables. Call when the page goes away. */
229
261
  dispose() {
230
262
  this.disposed = true;
231
- for (let i = queue.length - 1; i >= 0; i--) {
232
- if (queue[i].scope === this) queue.splice(i, 1);
233
- }
234
- for (const [key, rerun] of waitingReruns) {
235
- if (rerun.scope === this) waitingReruns.delete(key);
236
- }
237
- // A running run still uses the variables; `finish` frees them.
238
- if (active?.scope !== this) worker?.postMessage({ type: 'dispose', scope: this.id });
263
+ this.runner.dispose(this);
239
264
  }
240
265
  }
@@ -0,0 +1,13 @@
1
+ // The site's own functions, node types and UIs: its `functions/`, `nodes/` and `ui/` folders.
2
+ // The page route imports this file. `checkFunctions` loads it at build start, so a name used twice fails the build.
3
+ import { setCustomModules, type CustomModule } from './customModules';
4
+
5
+ /** `/functions/a.ts` -> `functions/a.ts`, with its exports. */
6
+ const files = (modules: Record<string, Record<string, unknown>>): CustomModule[] =>
7
+ Object.entries(modules).map(([path, exports]) => ({ file: path.slice(1), exports }));
8
+
9
+ setCustomModules({
10
+ functions: files(import.meta.glob('/functions/**/*.ts', { eager: true })),
11
+ nodes: files(import.meta.glob('/nodes/**/*.{ts,tsx}', { eager: true })),
12
+ ui: files(import.meta.glob('/ui/**/*.{ts,tsx}', { eager: true })),
13
+ });
@@ -61,6 +61,8 @@ export function dragUi(e: PointerEvent, box: HTMLElement, text: HTMLElement) {
61
61
  let frame = 0;
62
62
  const line = document.createElement('div');
63
63
  line.className = 'python-editor-ui-drop-line';
64
+ // Holds the box and the line while dragging. Inside the page, so styles limited to it apply; `fixed` keeps them unclipped.
65
+ const floating = text.parentElement!;
64
66
 
65
67
  const overLayer = () => layer !== null && inside(layer.getBoundingClientRect(), pointer);
66
68
 
@@ -72,7 +74,7 @@ export function dragUi(e: PointerEvent, box: HTMLElement, text: HTMLElement) {
72
74
  line.style.left = `${textRect.left}px`;
73
75
  line.style.width = `${textRect.width}px`;
74
76
  line.style.top = `${nearestGap(text, box, pointer.y).y}px`;
75
- if (!line.isConnected) document.body.append(line);
77
+ if (!line.isConnected) floating.append(line);
76
78
  };
77
79
 
78
80
  const autoScroll = () => {
@@ -93,7 +95,7 @@ export function dragUi(e: PointerEvent, box: HTMLElement, text: HTMLElement) {
93
95
  document.body.style.userSelect = 'none';
94
96
  box.classList.add('python-editor-ui-dragging');
95
97
  box.style.position = 'fixed';
96
- document.body.append(box);
98
+ floating.append(box);
97
99
  frame = requestAnimationFrame(autoScroll);
98
100
  };
99
101
 
@@ -1,11 +1,21 @@
1
1
  import type { Component } from 'solid-js';
2
+ import type { CustomModule } from '~/lib/customModules';
3
+ import * as checkboxes from './components/checkboxes';
4
+ import * as latex from './components/latex';
5
+ import * as radio from './components/radio';
6
+ import * as slider from './components/slider';
7
+ import * as textbox from './components/textbox';
2
8
 
3
9
  /** A UI: a Solid component. `args` holds the call's positional arguments; its keyword arguments are the other props. */
4
10
  export type UiComponent = Component<any>;
5
11
 
6
- // Built-ins, then the site's own: each PascalCase export of a `ui/**/*.{ts,tsx}` file is a UI.
7
- const builtinModules = import.meta.glob<Record<string, unknown>>('./components/*.tsx', { eager: true });
8
- const customModules = import.meta.glob<Record<string, unknown>>('/ui/**/*.{ts,tsx}', { eager: true });
12
+ const BUILTINS: CustomModule[] = [
13
+ { file: 'src/lib/ui/components/checkboxes.tsx', exports: checkboxes },
14
+ { file: 'src/lib/ui/components/latex.tsx', exports: latex },
15
+ { file: 'src/lib/ui/components/radio.tsx', exports: radio },
16
+ { file: 'src/lib/ui/components/slider.tsx', exports: slider },
17
+ { file: 'src/lib/ui/components/textbox.tsx', exports: textbox },
18
+ ];
9
19
 
10
20
  const isComponent = (name: string, value: unknown): value is UiComponent =>
11
21
  /^[A-Z][A-Za-z0-9]*$/.test(name) && typeof value === 'function';
@@ -13,21 +23,32 @@ const isComponent = (name: string, value: unknown): value is UiComponent =>
13
23
  /** Its name in Python: `Slider` gives `pie.ui.slider`, `MatrixProduct` gives `pie.ui.matrix_product`. */
14
24
  const pythonName = (exportName: string) => exportName.replace(/(?<!^)([A-Z])/g, '_$1').toLowerCase();
15
25
 
16
- const components = new Map<string, UiComponent>();
17
- const sourceFile = new Map<string, string>();
18
- for (const [file, mod] of [...Object.entries(builtinModules), ...Object.entries(customModules)]) {
19
- for (const [exportName, value] of Object.entries(mod)) {
20
- if (!isComponent(exportName, value)) continue;
21
- const name = pythonName(exportName);
22
- const other = sourceFile.get(name);
23
- if (other !== undefined) {
24
- throw new Error(`Duplicate UI 'pie.ui.${name}': ${file} and ${other}`);
26
+ let components = new Map<string, UiComponent>();
27
+
28
+ /**
29
+ * Replaces the custom UIs with the PascalCase exports of `modules`, e.g. a site's `ui/**\/*.{ts,tsx}`.
30
+ * Throws on a name used twice, leaving the UIs as they were.
31
+ */
32
+ export function setCustomUis(modules: CustomModule[]) {
33
+ const uis = new Map<string, UiComponent>();
34
+ const sourceFile = new Map<string, string>();
35
+ for (const { file, exports } of [...BUILTINS, ...modules]) {
36
+ for (const [exportName, value] of Object.entries(exports)) {
37
+ if (!isComponent(exportName, value)) continue;
38
+ const name = pythonName(exportName);
39
+ const other = sourceFile.get(name);
40
+ if (other !== undefined) {
41
+ throw new Error(`Duplicate UI 'pie.ui.${name}': ${file} and ${other}`);
42
+ }
43
+ uis.set(name, value);
44
+ sourceFile.set(name, file);
25
45
  }
26
- components.set(name, value);
27
- sourceFile.set(name, file);
28
46
  }
47
+ components = uis;
29
48
  }
30
49
 
50
+ setCustomUis([]);
51
+
31
52
  export function getUi(name: string): UiComponent | undefined {
32
53
  return components.get(name);
33
54
  }