@tinyvolt/pie 0.6.0 → 0.7.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/init/index.js CHANGED
@@ -14,6 +14,7 @@ const FILES = {
14
14
  'pages': 'pages',
15
15
  'functions': 'functions',
16
16
  'nodes': 'nodes',
17
+ 'ui': 'ui',
17
18
  'styles': 'styles',
18
19
  'layouts': 'layouts',
19
20
  'public': 'public',
@@ -19,6 +19,7 @@ npm run preview # preview the build with vite
19
19
  | `pages/` | Markdown pages. `pages/a/b.md` is served at `/a/b`. A file whose name starts with `_`, e.g. `pages/_topics.md`, gets no URL; use it as a sidebar. |
20
20
  | `functions/` | Your own TypeScript functions, called from Python as `pie.<keyword>(...)`. |
21
21
  | `nodes/` | Your own node types: what a node holds and how it is drawn. |
22
+ | `ui/` | Your own UIs for nodes, called from Python as `pie.ui.<name>(...)`. |
22
23
  | `layouts/` | Optional overrides: `header.tsx` (top of every page) and `index.tsx` (homepage, `/`). |
23
24
  | `styles/` | CSS. Every `.css` file here loads after the built-in styles, so it wins. |
24
25
  | `public/` | Static files, served as-is. |
@@ -168,6 +169,46 @@ Limits:
168
169
  - A lifted function can't call `pie.*` or index arrays.
169
170
  - `pie.partial` can't differentiate through a lifted function.
170
171
 
172
+ ### UIs for nodes: `pie.ui`
173
+
174
+ `pie.ui.<name>(...)` shows a UI, such as a slider, for one or more nodes. The UI shows the nodes' values and updates when they change. A UI that writes, such as a slider, changes its node, and every node built from it updates:
175
+
176
+ ```python
177
+ r = pie.scalar(1, out='r')
178
+ pie.circle(pie.point(0, 0), r)
179
+ pie.ui.slider(r, min=0, max=4, label='radius')
180
+ pie.ui.latex(r)
181
+ ```
182
+
183
+ - Positional arguments are nodes, or lists of nodes at any depth. Keyword arguments are plain values, never nodes.
184
+ - Every UI takes `label='<text>'`, shown in front of it. Default: none.
185
+ - The UIs show below the editor that made them, outside its box: collapsing the editor doesn't hide them. Running the block again replaces them, instead of adding more.
186
+ - A UI hides while one of its nodes is removed, and shows again if a node with the same id comes back.
187
+ - Writing a node is like `translate_*`: the node stops following the nodes it was built from.
188
+
189
+ | Call | Shows |
190
+ | --- | --- |
191
+ | `pie.ui.slider(n, min=0, max=1, step=0.01)` | a slider for Scalar `n` |
192
+ | `pie.ui.textbox(n)` | a text box for Scalar or Text `n`. It writes on Enter or on leaving the box. Text that isn't a number puts a Scalar's value back |
193
+ | `pie.ui.radio(n, options=['a', 'b'])` | one radio button per option. Scalar `n` holds the chosen index. `options` is required |
194
+ | `pie.ui.checkboxes(mask, options=['a', 'b'])` | one checkbox per item of Array of Scalars `mask`, in row-major order: 1 when ticked, 0 when not; any value other than 0 shows ticked. `options`: one label per item; without it, the labels are the item positions |
195
+ | `pie.ui.latex(a, b, ...)` | the nodes as LaTeX, side by side. A Scalar shows its number (at most 4 decimals), a Point `(x, y)`, a Text its value as LaTeX source, an Array of 1 dimension a column and of 2 a matrix. A list of nodes is shown like an Array |
196
+
197
+ Errors:
198
+
199
+ - Python raises for an unknown UI name, an unknown node, a node in a keyword argument, or a keyword argument named `args`.
200
+ - A UI given the wrong kind of node, e.g. `pie.ui.slider(point)`, shows the error in red in its place. Python doesn't raise.
201
+ - Sidebar editors have no canvas, so `pie.ui.*` there raises "this page has no canvas".
202
+
203
+ #### Dragging UIs
204
+
205
+ **Every UI can be dragged; readers may not notice unless the text tells them.** Each UI has a grip, ⋮⋮, at its left. With a mouse it shows on hover; on touchscreens it always shows. Only the grip starts a drag, so sliders and text boxes work as usual. Dragging the grip:
206
+
207
+ - into the page's text puts the UI between two top-level blocks (paragraphs, headings, editors, …), never inside an editor. A line shows where it will land. Near the text's top or bottom edge, the text scrolls.
208
+ - onto the canvas puts the UI at that spot on the screen. Panning and zooming the canvas don't move it. Resizing the canvas keeps it inside.
209
+
210
+ A UI moves freely between the text and the canvas. Running its block again puts it back below the editor. Positions aren't saved when the page reloads.
211
+
171
212
  ## Your own functions: `functions/`
172
213
 
173
214
  Each `functions/**/*.ts` file exports one or more `Node2NodeFunc` objects. Each becomes `pie.<keyword>` in Python. Copy `functions/midpoint.ts` as a starting point:
@@ -245,6 +286,39 @@ export const Square: NodeDefinition<SquareNode> = { type: 'Square', prefix: 'sq'
245
286
  - The built-in node types are in `node_modules/@tinyvolt/pie/src/lib/nodes/state/Node.ts`, and their render functions are in `node_modules/@tinyvolt/pie/src/lib/nodes/render/renderLogic.tsx`.
246
287
  - A type name used twice, by two of your files or by yours and a built-in, fails the build.
247
288
 
289
+ ## Your own UIs: `ui/`
290
+
291
+ Each PascalCase export of a `ui/**/*.{ts,tsx}` file is a UI: a Solid component. Its Python name is the export name in snake_case: `Slider` is `pie.ui.slider`, `MatrixProduct` is `pie.ui.matrix_product`. Other exports, e.g. a camelCase helper, are ignored. Copy `ui/stepper.tsx` as a starting point:
292
+
293
+ ```tsx
294
+ import type { ScalarNode } from '~/lib/nodes/state/Node';
295
+ import { num, scalar } from '~/lib/nodes/jax';
296
+ import { expectNode, type UiArg } from '~/lib/ui/nodeHandle';
297
+
298
+ /** `pie.ui.stepper(n, step=1)`: − and + buttons that change Scalar `n` by `step`, with its value between them. */
299
+ export function Stepper(props: { args: UiArg[]; step?: number }) {
300
+ const [n, setN] = expectNode<ScalarNode>(props.args[0], ['Scalar']);
301
+ const step = props.step ?? 1;
302
+ const add = (delta: number) => setN({ value: scalar(num(n().value) + delta) });
303
+ return (
304
+ <span>
305
+ <button type="button" onClick={() => add(-step)}>−</button>
306
+ {' '}{num(n().value)}{' '}
307
+ <button type="button" onClick={() => add(step)}>+</button>
308
+ </span>
309
+ );
310
+ }
311
+ ```
312
+
313
+ - `props.args` holds the positional arguments. Each node in them is a pair `[n, setN]`, like a Solid signal: `n()` returns the node's current data; call it inside the JSX so the UI updates. `setN(changes)` writes fields of the node, e.g. `{ value: scalar(2) }`. A list stays a list of pairs.
314
+ - The keyword arguments are the other props, as plain values.
315
+ - `expectNode(arg, types)` checks that `arg` is one node of one of `types` and returns its pair. Otherwise it throws, and the UI shows the error.
316
+ - `useSetNode()` returns `setNode(node, changes)`, to write a node that isn't an argument, such as an Array's item: `setNode(array().items[i], { value: scalar(1) })`. Write an Array's items one by one: replacing the whole Array removes its item nodes and everything built from them.
317
+ - A UI that throws shows `pie.ui.<name>: <message>` in red in its place.
318
+ - Don't add a grip or a label: every UI gets both. `args` and `label` are reserved prop names.
319
+ - The built-in UIs are in `node_modules/@tinyvolt/pie/src/lib/ui/components/`.
320
+ - A name used twice, by two of your files or by yours and a built-in, raises an error when a page with a Python editor loads. It doesn't fail the build.
321
+
248
322
  ## Layouts: `layouts/`
249
323
 
250
324
  - `layouts/header.tsx`: replaces the header on every page.
@@ -258,6 +332,13 @@ Change the CSS variables in `styles/theme.css` (colors, fonts, text width), or a
258
332
 
259
333
  - Sidebar: `--sidebar-width` (default `16rem`), `--sidebar-drawer-below` (default `768px`; narrower screens open it over the page) and `--color-backdrop` (behind it when it opens over the page). Its parts have the classes `.sidebar`, `.sidebar-text`, `.sidebar-edge`, `.sidebar-toggle` and `.sidebar-backdrop`.
260
334
  - Table of contents: `.toc`.
335
+ - UIs (`pie.ui.*`):
336
+ - `.python-editor-uis`: a block's UIs below its editor.
337
+ - `.python-editor-ui`: one UI, wherever it is. It holds `.python-editor-ui-grip` (the ⋮⋮ drag grip), `.python-editor-ui-label` (the `label`) and `.python-editor-ui-body` (the UI itself).
338
+ - Where it is: `main > .python-editor-ui` (dropped in the text), `.canvas-ui-layer > .python-editor-ui` (on the canvas), `.python-editor-ui-dragging` (while dragged).
339
+ - `.python-editor-ui-drop-line`: the line that shows where a dragged UI lands in the text.
340
+ - Built-in UIs: match by element, e.g. `.python-editor-ui input[type=range]` (slider), `.python-editor-ui input[type=text]` (text box), `.python-editor-ui .katex` (LaTeX). `.pie-ui-choices` holds the radio buttons or checkboxes.
341
+ - E.g. a wider slider: `.python-editor-ui input[type=range] { width: 16rem; }`. A grip that always shows: `.python-editor-ui-grip { opacity: 1; }`.
261
342
 
262
343
  ## Build checks
263
344
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tinyvolt/pie",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "A Markdown-based SSG for interactive science explainers. Create a site with: npx @tinyvolt/pie init my-site",
5
5
  "type": "module",
6
6
  "repository": {
@@ -20,6 +20,7 @@
20
20
  "pages",
21
21
  "functions",
22
22
  "nodes",
23
+ "ui",
23
24
  "styles",
24
25
  "layouts",
25
26
  "public",
package/pages/example.md CHANGED
@@ -1,41 +1,173 @@
1
1
  ---
2
2
  toc: true
3
3
  sidebar: _topics.md
4
+ canvas: right
4
5
  ---
5
- # Table of contents test
6
6
 
7
- ### Before any h2
7
+ ## Heading
8
8
 
9
- Should be a top-level entry.
9
+ Lorem ipsum dolor sit amet, consectetur adipiscing elit.
10
10
 
11
- ## The $\nabla$ operator
11
+ Lorem ipsum dolor sit amet, consectetur adipiscing elit.
12
12
 
13
- Math in a heading.
13
+ Lorem ipsum dolor sit amet, consectetur adipiscing elit.
14
14
 
15
- ### Sub *one*
15
+ ---
16
16
 
17
- Nested under the operator.
17
+ ## Generative UI
18
18
 
19
- ### Sub two
19
+ Run the blocks in order. Most examples start with `pie.clear()`, which removes every node, so the UIs of earlier examples hide.
20
20
 
21
- Also nested.
21
+ ### One Scalar, three UIs
22
22
 
23
- ## Repeat
23
+ Move the slider: the text box, the LaTeX and the circle follow. Type `2.5` in the text box and press Enter: the slider moves. Collapse the editor: the UIs stay. Run it again: the UIs are replaced, not doubled.
24
24
 
25
- First "Repeat", links to `#repeat`.
25
+ ```python-editor
26
+ r = pie.scalar(1, out='r')
27
+ c = pie.point(0, 0, out='c')
28
+ pie.circle(c, r)
29
+ pie.ui.slider(r, min=0, max=4, label='radius')
30
+ pie.ui.textbox(r)
31
+ pie.ui.latex(r)
32
+ ```
26
33
 
27
- ## Repeat
34
+ A UI for `r` from another block. It stays in sync with the ones above.
28
35
 
29
- Second "Repeat", links to `#repeat-2`.
36
+ ```python-editor
37
+ pie.ui.slider(r, min=0, max=4, step=0.5)
38
+ ```
30
39
 
31
- #### Deep
40
+ Remove `r`: its UIs in both blocks hide, and so does the circle. Run the first block again to bring them back.
32
41
 
33
- Not listed: only `##` and `###` are.
42
+ ```python-editor
43
+ pie.remove(r)
44
+ ```
34
45
 
35
- ## Last
46
+ ### Radio and slider: pick a function
36
47
 
37
- Lorem ipsum dolor sit amet, consectetur adipiscing elit.
48
+ The radio button sets `choice` to 0, 1 or 2. The slider sets the amplitude.
38
49
 
39
- Lorem ipsum dolor sit amet, consectetur adipiscing elit.
50
+ ```python-editor
51
+ import numpy as np
52
+ pie.clear()
53
+ choice = pie.scalar(0, out='choice')
54
+ amp = pie.scalar(1, out='amp')
40
55
 
41
- Lorem ipsum dolor sit amet, consectetur adipiscing elit.
56
+ def curve(k, a):
57
+ xs = np.linspace(-4, 4, 81)
58
+ f = [np.sin, np.cos, np.tanh][int(k)]
59
+ return np.stack([xs, a * f(xs)], axis=1)
60
+
61
+ pie.lift(curve, pie.Array[pie.Point])(choice, amp)
62
+ pie.ui.radio(choice, options=['sin', 'cos', 'tanh'])
63
+ pie.ui.slider(amp, min=-2, max=2, label='amplitude')
64
+ pie.ui.latex(choice, amp)
65
+ ```
66
+
67
+ ### Checkboxes: build a square wave
68
+
69
+ Each checkbox adds one odd harmonic. Tick them all to get close to a square wave.
70
+
71
+ ```python-editor
72
+ import numpy as np
73
+ pie.clear()
74
+ harmonics = pie.scalar([1, 0, 0, 0, 0], out='harmonics')
75
+
76
+ def wave(mask):
77
+ xs = np.linspace(-4, 4, 161)
78
+ ys = sum(m * np.sin((2 * k + 1) * xs) / (2 * k + 1) for k, m in enumerate(mask))
79
+ return np.stack([xs, 4 / np.pi * ys], axis=1)
80
+
81
+ pie.lift(wave, pie.Array[pie.Point])(harmonics)
82
+ pie.ui.checkboxes(harmonics, options=['sin x', 'sin 3x', 'sin 5x', 'sin 7x', 'sin 9x'])
83
+ pie.ui.latex(harmonics)
84
+ ```
85
+
86
+ ### Text box and slider: a label on the canvas
87
+
88
+ ```python-editor
89
+ pie.clear()
90
+ label = pie.text('Hello', out='label')
91
+ size = pie.scalar(24, out='size')
92
+ pie.text(label, 0, 0, size)
93
+ pie.ui.textbox(label)
94
+ pie.ui.slider(size, min=8, max=60, step=1, label='font size')
95
+ ```
96
+
97
+ ### Text box and LaTeX: a live formula
98
+
99
+ A Text node holds LaTeX source. Edit it and press Enter.
100
+
101
+ ```python-editor
102
+ formula = pie.text(r'e^{i\pi} + 1 = 0', out='formula')
103
+ pie.ui.textbox(formula)
104
+ pie.ui.latex(formula)
105
+ ```
106
+
107
+ ### Matrix playground
108
+
109
+ `q = m p`. The sliders set the items of `m`. Drag `p` on the canvas: the LaTeX and `q` follow.
110
+
111
+ ```python-editor
112
+ import numpy as np
113
+ pie.clear()
114
+ m = pie.scalar([[1, 0], [0, 1]], out='m')
115
+ o = pie.point(0, 0, out='o')
116
+ p = pie.point(1, 1, out='p')
117
+
118
+ def apply(m, p):
119
+ return tuple(m @ np.array(p))
120
+
121
+ q = pie.lift(apply, pie.Point)(m, p, out='q', fill='crimson')
122
+ pie.line(o, p)
123
+ pie.line(o, q, stroke='crimson')
124
+ eq = pie.text('=', out='eq')
125
+ pie.ui.latex(m, p, eq, q)
126
+ for i in range(2):
127
+ for j in range(2):
128
+ pie.ui.slider(m[i, j], min=-2, max=2, label=f'm[{i}, {j}]')
129
+ ```
130
+
131
+ ### Canvas controls
132
+
133
+ UIs on the system nodes. Zooming or panning the canvas moves the sliders too. `pie.clear()` resets these nodes, and the UIs keep following them.
134
+
135
+ ```python-editor
136
+ pie.ui.radio(pie.get_node('gridOpacity'), options=['grid off', 'grid on'])
137
+ pie.ui.slider(pie.get_node('unit'), min=10, max=120, step=1, label='zoom')
138
+ pie.ui.slider(pie.get_node('originX'), min=-5, max=5, label='origin x')
139
+ pie.ui.slider(pie.get_node('originY'), min=-5, max=5, label='origin y')
140
+ ```
141
+
142
+ ### A UI from `/ui`
143
+
144
+ `Stepper` in `ui/stepper.tsx` is a site's own UI. Its buttons and the slider stay in sync.
145
+
146
+ ```python-editor
147
+ pie.clear()
148
+ k = pie.scalar(2, out='k')
149
+ pie.circle(pie.point(0, 0), k)
150
+ pie.ui.stepper(k, step=0.5, label='radius')
151
+ pie.ui.slider(k, min=0, max=5)
152
+ ```
153
+
154
+ ### Errors
155
+
156
+ A wrong node type: the error shows in red below the editor. Python doesn't raise.
157
+
158
+ ```python-editor
159
+ pie.ui.slider(pie.point(0, 0))
160
+ ```
161
+
162
+ An unknown UI: Python raises.
163
+
164
+ ```python-editor
165
+ pie.ui.dial(pie.scalar(1))
166
+ ```
167
+
168
+ A node in a keyword argument: Python raises.
169
+
170
+ ```python-editor
171
+ n = pie.scalar(1)
172
+ pie.ui.slider(n, max=n)
173
+ ```
package/src/app.css CHANGED
@@ -254,6 +254,7 @@ main .katex-display {
254
254
  }
255
255
 
256
256
  .canvas-page-canvas {
257
+ position: relative;
257
258
  height: 100%;
258
259
  }
259
260
 
@@ -513,6 +514,105 @@ pre:has(> code.language-python-editor) {
513
514
  color: var(--color-error, #c00);
514
515
  }
515
516
 
517
+ /* Outside the editor's box, so collapsing the editor keeps them. */
518
+ .python-editor-uis {
519
+ margin: 1rem 0;
520
+ }
521
+
522
+ /* Hidden when its UIs were all dragged away. */
523
+ .python-editor-uis:not(:has(.python-editor-ui)) {
524
+ display: none;
525
+ }
526
+
527
+ /* A UI: a grip to drag it, then the UI. */
528
+ .python-editor-ui {
529
+ display: flex;
530
+ align-items: center;
531
+ gap: 0.25rem;
532
+ margin: 0.25rem 0;
533
+ }
534
+
535
+ /* Dropped into the page's text. */
536
+ main > .python-editor-ui {
537
+ margin: 1rem 0;
538
+ }
539
+
540
+ /* One of its nodes is removed. */
541
+ .python-editor-ui-hidden {
542
+ display: none;
543
+ }
544
+
545
+ .python-editor-ui-grip {
546
+ padding: 0 0.125rem;
547
+ color: var(--color-subtle, #666);
548
+ line-height: 1;
549
+ cursor: grab;
550
+ user-select: none;
551
+ /* A touch drag moves the UI, not the page. */
552
+ touch-action: none;
553
+ opacity: 0;
554
+ }
555
+
556
+ .python-editor-ui:hover > .python-editor-ui-grip,
557
+ .python-editor-ui-dragging > .python-editor-ui-grip {
558
+ opacity: 1;
559
+ }
560
+
561
+ .python-editor-ui-label {
562
+ white-space: nowrap;
563
+ }
564
+
565
+ /* Touchscreens have no hover. */
566
+ @media (hover: none) {
567
+ .python-editor-ui-grip {
568
+ opacity: 1;
569
+ }
570
+ }
571
+
572
+ /* Floating over the page while dragged, or on the canvas: a box, so it reads over anything under it. */
573
+ .python-editor-ui-dragging,
574
+ .canvas-ui-layer > .python-editor-ui {
575
+ margin: 0;
576
+ padding: 0.25rem 0.5rem;
577
+ background: var(--color-bg, #fff);
578
+ border: 1px solid var(--color-border, #ddd);
579
+ border-radius: 4px;
580
+ }
581
+
582
+ .python-editor-ui-dragging {
583
+ z-index: 1000;
584
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
585
+ cursor: grabbing;
586
+ }
587
+
588
+ /* Where a dragged UI lands in the text. */
589
+ .python-editor-ui-drop-line {
590
+ position: fixed;
591
+ z-index: 1000;
592
+ height: 2px;
593
+ margin-top: -1px;
594
+ background: var(--color-hover, #000);
595
+ pointer-events: none;
596
+ }
597
+
598
+ /* Lets clicks through to the canvas, except on the UIs in it. */
599
+ .canvas-ui-layer {
600
+ position: absolute;
601
+ inset: 0;
602
+ overflow: hidden;
603
+ pointer-events: none;
604
+ }
605
+
606
+ .canvas-ui-layer > * {
607
+ pointer-events: auto;
608
+ }
609
+
610
+ .pie-ui-choices {
611
+ display: inline-flex;
612
+ flex-wrap: wrap;
613
+ gap: 0.75rem;
614
+ }
615
+
516
616
  .python-editor-note {
517
617
  color: var(--color-subtle, #666);
518
618
  }
@@ -1,6 +1,7 @@
1
1
  import { SplitPane } from '~/components/SplitPane';
2
2
  import { NodeCanvas } from '~/lib/nodes/components/NodeCanvas';
3
3
  import { NodeStore } from '~/lib/nodes/state/NodeStore';
4
+ import { UiLayer } from '~/lib/ui/UiLayer';
4
5
  import type { CanvasSide } from '../frontmatter';
5
6
  import { MarkdownBody } from './MarkdownBody';
6
7
 
@@ -15,6 +16,7 @@ export function CanvasPage(props: { side: Exclude<CanvasSide, 'none'>; html: str
15
16
  first={
16
17
  <div class="canvas-page-canvas">
17
18
  <NodeCanvas store={store} />
19
+ <UiLayer />
18
20
  </div>
19
21
  }
20
22
  second={<MarkdownBody class="canvas-page-text" html={props.html} store={store} />}
@@ -5,6 +5,7 @@ import { keymap } from '@codemirror/view';
5
5
  import { python } from '@codemirror/lang-python';
6
6
  import { CheckIcon, Chevron, CopyIcon, CrossIcon, PlayIcon, ResetIcon, StopIcon } from '~/components/icons';
7
7
  import type { PythonScope, RunStatus } from '~/lib/python/runner';
8
+ import { checkUi, UiView, type UiCall } from '~/lib/ui/UiView';
8
9
 
9
10
  const STATUS_TEXT: Record<RunStatus | 'idle', string> = {
10
11
  idle: '',
@@ -49,6 +50,8 @@ export function PythonEditor(props: { code: string; collapsed?: boolean; scope:
49
50
 
50
51
  const [status, setStatus] = createSignal<RunStatus | 'idle'>('idle');
51
52
  const [output, setOutput] = createSignal<OutputEntry[]>([]);
53
+ // `pie.ui.*` calls of the last run. Shown below the editor, not in its output, so they stay when it collapses.
54
+ const [uis, setUis] = createSignal<UiCall[]>([]);
52
55
  const [error, setError] = createSignal('');
53
56
  const [note, setNote] = createSignal('');
54
57
  const [collapsed, setCollapsed] = createSignal(props.collapsed ?? false);
@@ -73,6 +76,7 @@ export function PythonEditor(props: { code: string; collapsed?: boolean; scope:
73
76
  const run = () => {
74
77
  if (active() || !view) return;
75
78
  setOutput([]);
79
+ setUis([]);
76
80
  setError('');
77
81
  setNote('');
78
82
  stop = props.scope.run(
@@ -86,6 +90,11 @@ export function PythonEditor(props: { code: string; collapsed?: boolean; scope:
86
90
  },
87
91
  addText,
88
92
  (png) => setOutput((prev) => [...prev, { type: 'plot', png }]),
93
+ (call) => {
94
+ // The runner calls this only when the page has a canvas.
95
+ checkUi(props.scope.store!, call);
96
+ setUis((prev) => [...prev, call]);
97
+ },
89
98
  );
90
99
  };
91
100
 
@@ -177,6 +186,7 @@ export function PythonEditor(props: { code: string; collapsed?: boolean; scope:
177
186
  });
178
187
 
179
188
  return (
189
+ <>
180
190
  <div class="python-editor" classList={{ 'python-editor-collapsed': collapsed() }}>
181
191
  <div class="python-editor-code" ref={host} />
182
192
  <div class="python-editor-resize" title="Drag to resize" onPointerDown={startResize} />
@@ -250,5 +260,11 @@ export function PythonEditor(props: { code: string; collapsed?: boolean; scope:
250
260
  </div>
251
261
  </Show>
252
262
  </div>
263
+ <Show when={uis().length > 0}>
264
+ <div class="python-editor-uis">
265
+ <For each={uis()}>{(call) => <UiView store={props.scope.store!} call={call} />}</For>
266
+ </div>
267
+ </Show>
268
+ </>
253
269
  );
254
270
  }
@@ -40,11 +40,17 @@ function argType(arg: Arg, store: NodeStore): string {
40
40
  }
41
41
 
42
42
  /** The item type and shape of an argument that is an array, before any node is created for it. */
43
- function arrayOf(arg: Arg, store: NodeStore): { itemType: NodeType; shape: number[] } {
43
+ function arrayOf(arg: Arg, store: NodeStore): { itemType: NodeType | 'Mixed'; shape: number[] } {
44
44
  if (Array.isArray(arg)) return { itemType: listItemType(arg, item => argType(item, store)), shape: listShape(arg) };
45
45
  return store.getNodeValue((arg as { id: string }).id) as ArrayNode;
46
46
  }
47
47
 
48
+ /** The types of the items of an argument that is an array, without repeats. */
49
+ function itemTypesOf(arg: Arg, store: NodeStore): string[] {
50
+ if (Array.isArray(arg)) return [...new Set(leaves(arg).map(item => argType(item, store)))];
51
+ return [...new Set((store.getNodeValue((arg as { id: string }).id) as ArrayNode).items.map(item => item.type))];
52
+ }
53
+
48
54
  /**
49
55
  * A list gets one hidden Array node, reused by every call that passes the same list.
50
56
  * Its items follow the nodes they name.
@@ -130,8 +136,10 @@ export async function execute(store: NodeStore, keyword: string, args: Arg[], {
130
136
  if (func.broadcastable === false) throw new Error(`${keyword} does not take arrays`);
131
137
  const array = arrayOf(arg, store);
132
138
  broadcastInputShapes.push(array.shape);
133
- got = `Array of ${array.itemType}`;
134
- if (types.includes(array.itemType)) return;
139
+ // A Mixed array passes when every one of its item types does.
140
+ const itemTypes = array.itemType === 'Mixed' ? itemTypesOf(arg, store) : [array.itemType];
141
+ got = `Array of ${itemTypes.join(', ')}`;
142
+ if (itemTypes.every(type => types.includes(type as NodeType))) return;
135
143
  }
136
144
  if (!types.includes(got as NodeType)) {
137
145
  throw new Error(`${keyword}: expected ${types.join(' or ')} but got ${got} for argument '${param.name}'`);
@@ -141,7 +141,8 @@ const PointGradDefinition: NodeDefinition<PointGradNode> = { type: 'PointGrad',
141
141
  /** `items` in row-major order: shape [2, 3] holds row 0's three items, then row 1's. */
142
142
  export interface ArrayNode extends Node {
143
143
  type: 'Array';
144
- itemType: NodeType;
144
+ /** 'Mixed' when the items are not all one type. */
145
+ itemType: NodeType | 'Mixed';
145
146
  shape: number[];
146
147
  items: AnyNode[];
147
148
  }
@@ -31,12 +31,10 @@ export function getItem(store: NodeStore, arrayId: string, position: number): Ex
31
31
  return { id: item.id, type: item.type };
32
32
  }
33
33
 
34
- /** The one type all items of a nested list share. `typeOf` gives an item's type. */
35
- export function listItemType(list: Arg[], typeOf: (item: LeafArg) => string): NodeType {
34
+ /** The one type all items of a nested list share, or 'Mixed' when they differ. `typeOf` gives an item's type. */
35
+ export function listItemType(list: Arg[], typeOf: (item: LeafArg) => string): NodeType | 'Mixed' {
36
36
  listShape(list);
37
37
  const types = new Set(leaves(list).map(typeOf));
38
- if (types.size > 1) {
39
- throw new Error(`all items of a list must have the same type, got ${[...types].join(', ')}`);
40
- }
38
+ if (types.size > 1) return 'Mixed';
41
39
  return [...types][0] as NodeType;
42
40
  }
@@ -61,6 +61,7 @@ function inputValue(node: AnyNode | undefined, id: string): InputValue {
61
61
  if (node.type === 'Point') return [num(node.x), num(node.y)];
62
62
  if (node.type === 'Text') return node.value;
63
63
  if (node.type === 'Array') {
64
+ if (node.itemType === 'Mixed') throw new Error(`'${id}' is an Array of mixed types; an Array input must hold one type`);
64
65
  const values = node.items.flatMap(item => inputValue(item, item.id)) as number[];
65
66
  return { shape: node.itemType === 'Point' ? [...node.shape, 2] : node.shape, values };
66
67
  }
@@ -253,6 +253,48 @@ def _check_out_type_and_flatten(name, returns, result):
253
253
  shape = result.shape[:-1] if item == "Point" else result.shape
254
254
  return list(shape), result.astype(np.float64).ravel().tolist()
255
255
 
256
+ class _UI:
257
+ """
258
+ `pie.ui.<name>(*nodes, **options)` shows UI `<name>` for the nodes below the block. A rerun of the block replaces it.
259
+ Every UI takes `label`, text shown in front of it (default: none).
260
+ """
261
+ def __getattr__(self, name):
262
+ if name.startswith("_"):
263
+ raise AttributeError(name)
264
+ def show(*args, **options):
265
+ _show_ui(name, args, options)
266
+ show.__name__ = show.__qualname__ = f"ui.{name}"
267
+ return show
268
+
269
+ ui = _UI()
270
+
271
+ def _ui_arg(name, a):
272
+ if isinstance(a, Node):
273
+ return {"id": a.id}
274
+ if isinstance(a, (list, tuple)):
275
+ return [_ui_arg(name, x) for x in a]
276
+ raise TypeError(f"pie.ui.{name}: positional arguments must be nodes or lists of nodes, got {type(a).__name__}")
277
+
278
+ def _holds_node(v):
279
+ if isinstance(v, Node):
280
+ return True
281
+ if isinstance(v, (list, tuple)):
282
+ return any(map(_holds_node, v))
283
+ if isinstance(v, dict):
284
+ return any(map(_holds_node, v.values()))
285
+ return False
286
+
287
+ def _show_ui(name, args, options):
288
+ _check_bridge()
289
+ if "args" in options:
290
+ raise TypeError(f"pie.ui.{name}: 'args' can't be a keyword argument")
291
+ for key, value in options.items():
292
+ if _holds_node(value):
293
+ raise TypeError(f"pie.ui.{name}: keyword argument '{key}' holds a node; pass nodes as positional arguments")
294
+ js_args = to_js([_ui_arg(name, a) for a in args], dict_converter=Object.fromEntries)
295
+ js_options = to_js(options, dict_converter=Object.fromEntries)
296
+ run_sync(bridge.ui(name, js_args, js_options))
297
+
256
298
  def __getattr__(name):
257
299
  if name.startswith("_"):
258
300
  raise AttributeError(name)
@@ -2,6 +2,7 @@ import type { NodeStore } from '~/lib/nodes/state/NodeStore';
2
2
  import { execute } from '~/lib/nodes/execute';
3
3
  import { getItem } from '~/lib/nodes/tensors/tensor';
4
4
  import { prepareLifts, saveLift, startLift, type BatchJob, type BatchResult, type InputValue, type PyResult } from './lift';
5
+ import type { UiCall } from '~/lib/ui/UiView';
5
6
 
6
7
  export type RunStatus = 'waiting' | 'loading' | 'running' | 'finished' | 'stopped' | 'killed';
7
8
 
@@ -12,6 +13,8 @@ interface Run {
12
13
  onOutput: (text: string) => void;
13
14
  /** `png`: a matplotlib figure as a base64 PNG. */
14
15
  onPlot: (png: string) => void;
16
+ /** A `pie.ui.*` call. Throws when the call is wrong; Python raises the error. */
17
+ onUi: (call: UiCall) => void;
15
18
  }
16
19
 
17
20
  let worker: Worker | undefined;
@@ -45,7 +48,7 @@ function onMessage(this: Worker, { data }: MessageEvent) {
45
48
  loaded = true;
46
49
  run?.onStatus('running');
47
50
  }
48
- if (data.type === 'call' || data.type === 'item' || data.type === 'get_node' || data.type === 'lift') {
51
+ if (data.type === 'call' || data.type === 'item' || data.type === 'get_node' || data.type === 'lift' || data.type === 'ui') {
49
52
  // The request to answer: this one, or, after a batch, Python's request with the batch's results.
50
53
  let reqId: number = data.reqId;
51
54
  // A reply from before a kill must not reach the new worker.
@@ -72,6 +75,15 @@ function onMessage(this: Worker, { data }: MessageEvent) {
72
75
  else reply({ result: { id: node.id, type: node.type } });
73
76
  return;
74
77
  }
78
+ if (data.type === 'ui') {
79
+ try {
80
+ run!.onUi({ name: data.name, args: data.args, options: data.options });
81
+ reply({ result: null });
82
+ } catch (err) {
83
+ reply({ error: message(err) });
84
+ }
85
+ return;
86
+ }
75
87
  if (data.type === 'lift') {
76
88
  try {
77
89
  reply({ result: startLift(store, data.name, data.inputIds, data.kind, data.out, data.fill, data.stroke) });
@@ -188,8 +200,8 @@ export class PythonScope {
188
200
  constructor(readonly store?: NodeStore) {}
189
201
 
190
202
  /** Queues `code`. Returns a stop function. `error` comes only with `finished`. */
191
- run(code: string, onStatus: Run['onStatus'], onOutput: Run['onOutput'], onPlot: Run['onPlot']): () => void {
192
- const run: Run = { scope: this, code, onStatus, onOutput, onPlot };
203
+ 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 };
193
205
  queue.push(run);
194
206
  onStatus('waiting');
195
207
  startNext();
@@ -32,6 +32,9 @@ const lift = (name: string, inputIds: string[], kind: string, out?: string, fill
32
32
  /** Second half of `g(a)`: the first result. Python doesn't wait for a reply. */
33
33
  const lift_save = (save: object) => postMessage({ type: 'lift_save', ...save });
34
34
 
35
+ /** `pie.ui.<name>(...)`: shows a UI below the block. `args`: nodes as `{id}`, or lists of them. */
36
+ const ui = (name: string, args: unknown[], options: object) => request({ type: 'ui', name, args, options });
37
+
35
38
  /** Results of a batch the page asked for in a reply, before an animation. Waits for the call's next reply. */
36
39
  const batch_done = (results: unknown) => request({ type: 'batch_done', results });
37
40
 
@@ -41,7 +44,7 @@ const ready = (async () => {
41
44
  py.setStdout({ batched: (text: string) => postMessage({ type: 'output', text: text + '\n' }) });
42
45
  py.setStderr({ batched: (text: string) => postMessage({ type: 'output', text: text + '\n' }) });
43
46
  py.registerJsModule('bridge', {
44
- call, item, get_node, lift, lift_save, batch_done, plot: (png: string) => postMessage({ type: 'plot', png }),
47
+ call, item, get_node, lift, lift_save, batch_done, ui, plot: (png: string) => postMessage({ type: 'plot', png }),
45
48
  });
46
49
  py.FS.writeFile('/home/pyodide/pie.py', PIE_PY);
47
50
  py.FS.writeFile('/home/pyodide/pie_mpl.py', PIE_MPL_PY);
@@ -0,0 +1,15 @@
1
+ import { onCleanup, onMount } from 'solid-js';
2
+ import { clampToLayer, UI_LAYER_CLASS } from './dragUi';
3
+
4
+ /** A layer over the canvas for UIs dropped there. When the canvas resizes, they are kept inside it. */
5
+ export function UiLayer() {
6
+ let layer!: HTMLDivElement;
7
+ onMount(() => {
8
+ const observer = new ResizeObserver(() => {
9
+ for (const box of layer.children) clampToLayer(box as HTMLElement, layer);
10
+ });
11
+ observer.observe(layer);
12
+ onCleanup(() => observer.disconnect());
13
+ });
14
+ return <div ref={layer} class={UI_LAYER_CLASS} />;
15
+ }
@@ -0,0 +1,74 @@
1
+ import { ErrorBoundary, onCleanup, Show } from 'solid-js';
2
+ import { Dynamic } from 'solid-js/web';
3
+ import type { NodeStore } from '~/lib/nodes/state/NodeStore';
4
+ import { getUi } from './registry';
5
+ import { nodeHandle, StoreContext, type UiArg } from './nodeHandle';
6
+ import { dragUi } from './dragUi';
7
+
8
+ /** A node as Python sends it, or a list of them at any depth. */
9
+ type SentArg = { id: string } | SentArg[];
10
+
11
+ /** A `pie.ui.<name>(*args, **options)` call. */
12
+ export interface UiCall {
13
+ name: string;
14
+ args: SentArg[];
15
+ options: Record<string, unknown>;
16
+ }
17
+
18
+ const nodeIds = (args: SentArg[]): string[] => args.flatMap((a) => (Array.isArray(a) ? nodeIds(a) : [a.id]));
19
+
20
+ const toHandles = (store: NodeStore, args: SentArg[]): UiArg[] =>
21
+ args.map((a) => (Array.isArray(a) ? toHandles(store, a) : nodeHandle(store, a.id)));
22
+
23
+ const present = (store: NodeStore, id: string) => {
24
+ const node = store.getNodeValue(id);
25
+ return node !== undefined && node.type !== 'Dummy';
26
+ };
27
+
28
+ /** Throws, for Python to raise, when there is no such UI or a node is missing. */
29
+ export function checkUi(store: NodeStore, call: UiCall) {
30
+ if (!getUi(call.name)) throw new Error(`pie.ui: no UI named '${call.name}'`);
31
+ const missing = nodeIds(call.args).find((id) => !present(store, id));
32
+ if (missing !== undefined) throw new Error(`pie.ui.${call.name}: no node with id '${missing}'`);
33
+ }
34
+
35
+ /**
36
+ * Shows a UI, with a grip to drag it into the page's text or onto the canvas. Shows nothing while one of its
37
+ * nodes is removed, and the error, after the UI's name, if it throws.
38
+ * The `label` option is shown in front of the UI, for every UI, so the UI itself doesn't get it.
39
+ */
40
+ export function UiView(props: { store: NodeStore; call: UiCall }) {
41
+ const { name, args, options: { label, ...options } } = props.call;
42
+ const ids = nodeIds(args);
43
+ const handles = toHandles(props.store, args);
44
+ const shown = () => ids.every((id) => present(props.store, id));
45
+ // `box` starts in `home`. Dragging moves it out, so the editor's list, which holds `home`, is left alone.
46
+ let home!: HTMLDivElement;
47
+ let box!: HTMLDivElement;
48
+ onCleanup(() => box.remove());
49
+
50
+ const startDrag = (e: PointerEvent) => {
51
+ const text = home.closest('main');
52
+ if (text) dragUi(e, box, text);
53
+ };
54
+
55
+ return (
56
+ <div ref={home}>
57
+ <div ref={box} class="python-editor-ui" classList={{ 'python-editor-ui-hidden': !shown() }}>
58
+ <span class="python-editor-ui-grip" title="Drag to move" onPointerDown={startDrag}>⋮⋮</span>
59
+ <Show when={label != null && label !== ''}>
60
+ <span class="python-editor-ui-label">{String(label)}</span>
61
+ </Show>
62
+ <div class="python-editor-ui-body">
63
+ <StoreContext.Provider value={props.store}>
64
+ <ErrorBoundary fallback={(err) => <span class="python-editor-error">pie.ui.{name}: {err instanceof Error ? err.message : String(err)}</span>}>
65
+ <Show when={shown()}>
66
+ <Dynamic component={getUi(name)!} {...options} args={handles} />
67
+ </Show>
68
+ </ErrorBoundary>
69
+ </StoreContext.Provider>
70
+ </div>
71
+ </div>
72
+ </div>
73
+ );
74
+ }
@@ -0,0 +1,40 @@
1
+ import { Index } from 'solid-js';
2
+ import type { ArrayNode, ScalarNode } from '~/lib/nodes/state/Node';
3
+ import { num, scalar } from '~/lib/nodes/jax';
4
+ import { expectNode, useSetNode, type UiArg } from '../nodeHandle';
5
+
6
+ /**
7
+ * `pie.ui.checkboxes(mask, options=['a', 'b'])`: one checkbox per item of the Array of Scalars `mask`.
8
+ * An item is 1 when ticked, 0 when not; any value other than 0 shows as ticked.
9
+ * `options`: one label per item, in row-major order. Without it, the labels are the item positions.
10
+ */
11
+ export function Checkboxes(props: { args: UiArg[]; options?: string[] }) {
12
+ const [mask] = expectNode<ArrayNode>(props.args[0], ['Array']);
13
+ const setNode = useSetNode();
14
+ const items = () => {
15
+ const array = mask();
16
+ if (array.itemType !== 'Scalar') throw new Error(`expects an Array of Scalars, got an Array of ${array.itemType}`);
17
+ if (props.options && props.options.length !== array.items.length) {
18
+ throw new Error(`got ${props.options.length} options for ${array.items.length} items`);
19
+ }
20
+ return array.items as ScalarNode[];
21
+ };
22
+
23
+ // `Index`, not `For`: the items are new objects after every change, but their positions stay.
24
+ return (
25
+ <span class="pie-ui-choices">
26
+ <Index each={items()}>
27
+ {(item, i) => (
28
+ <label>
29
+ <input
30
+ type="checkbox"
31
+ checked={num(item().value) !== 0}
32
+ onChange={(e) => setNode(item(), { value: scalar(e.currentTarget.checked ? 1 : 0) })}
33
+ />
34
+ {props.options?.[i] ?? String(i)}
35
+ </label>
36
+ )}
37
+ </Index>
38
+ </span>
39
+ );
40
+ }
@@ -0,0 +1,44 @@
1
+ import katex from 'katex';
2
+ import type { AnyNode } from '~/lib/nodes/state/Node';
3
+ import { num, type Dtype } from '~/lib/nodes/jax';
4
+ import { isHandle, type UiArg } from '../nodeHandle';
5
+
6
+ const fmt = (v: Dtype) => String(Number(num(v).toFixed(4)));
7
+
8
+ /** Rows of a 1D (a column) or 2D list of entries, as a bmatrix. */
9
+ function matrix(entries: string[], shape: number[]): string {
10
+ if (shape.length > 2) throw new Error(`an array needs 1 or 2 dimensions, got shape [${shape.join(', ')}]`);
11
+ const cols = shape[1] ?? 1;
12
+ const rows = Array.from({ length: shape[0] }, (_, r) => entries.slice(r * cols, (r + 1) * cols).join(' & '));
13
+ return `\\begin{bmatrix} ${rows.join(' \\\\ ')} \\end{bmatrix}`;
14
+ }
15
+
16
+ function nodeTex(node: AnyNode): string {
17
+ switch (node.type) {
18
+ case 'Scalar': return fmt(node.value);
19
+ case 'Point': return `\\left(${fmt(node.x)}, ${fmt(node.y)}\\right)`;
20
+ // A Text holds LaTeX source.
21
+ case 'Text': return node.value;
22
+ case 'Array': return matrix(node.items.map(nodeTex), node.shape);
23
+ default: throw new Error(`can't show a ${node.type}`);
24
+ }
25
+ }
26
+
27
+ /** A list is shown like an Array: 1D as a column, 2D as a matrix. */
28
+ function argTex(arg: UiArg): string {
29
+ if (isHandle(arg)) return nodeTex(arg[0]());
30
+ if (arg.every(isHandle)) return matrix(arg.map(argTex), [arg.length]);
31
+ if (arg.every((row) => !isHandle(row) && row.every(isHandle) && row.length === arg[0].length)) {
32
+ return matrix(arg.flatMap((row) => (row as UiArg[]).map(argTex)), [arg.length, (arg[0] as UiArg[]).length]);
33
+ }
34
+ throw new Error('a list must be a list of nodes, or a list of equal-length lists of nodes');
35
+ }
36
+
37
+ /**
38
+ * `pie.ui.latex(a, b, ...)`: the nodes as LaTeX, side by side. A Scalar shows its number, a Point (x, y),
39
+ * a Text its value as LaTeX source, an Array of 1 or 2 dimensions a matrix.
40
+ */
41
+ export function Latex(props: { args: UiArg[] }) {
42
+ const html = () => katex.renderToString(props.args.map(argTex).join(' '), { throwOnError: false });
43
+ return <span innerHTML={html()} />;
44
+ }
@@ -0,0 +1,25 @@
1
+ import { createUniqueId, For } from 'solid-js';
2
+ import type { ScalarNode } from '~/lib/nodes/state/Node';
3
+ import { num, scalar } from '~/lib/nodes/jax';
4
+ import { expectNode, type UiArg } from '../nodeHandle';
5
+
6
+ /** `pie.ui.radio(n, options=['a', 'b'])`: one radio button per option. Scalar `n` holds the chosen one's index. */
7
+ export function Radio(props: { args: UiArg[]; options?: string[] }) {
8
+ const [n, setN] = expectNode<ScalarNode>(props.args[0], ['Scalar']);
9
+ if (!props.options?.length) throw new Error('needs `options`, a list of labels');
10
+ // Groups the buttons, so choosing one unchecks the others.
11
+ const group = createUniqueId();
12
+
13
+ return (
14
+ <span class="pie-ui-choices">
15
+ <For each={props.options}>
16
+ {(label, i) => (
17
+ <label>
18
+ <input type="radio" name={group} checked={num(n().value) === i()} onChange={() => setN({ value: scalar(i()) })} />
19
+ {label}
20
+ </label>
21
+ )}
22
+ </For>
23
+ </span>
24
+ );
25
+ }
@@ -0,0 +1,18 @@
1
+ import type { ScalarNode } from '~/lib/nodes/state/Node';
2
+ import { num, scalar } from '~/lib/nodes/jax';
3
+ import { expectNode, type UiArg } from '../nodeHandle';
4
+
5
+ /** `pie.ui.slider(n, min=0, max=1, step=0.01)`: a slider for Scalar `n`. */
6
+ export function Slider(props: { args: UiArg[]; min?: number; max?: number; step?: number }) {
7
+ const [n, setN] = expectNode<ScalarNode>(props.args[0], ['Scalar']);
8
+ return (
9
+ <input
10
+ type="range"
11
+ min={props.min ?? 0}
12
+ max={props.max ?? 1}
13
+ step={props.step ?? 0.01}
14
+ value={num(n().value)}
15
+ onInput={(e) => setN({ value: scalar(e.currentTarget.valueAsNumber) })}
16
+ />
17
+ );
18
+ }
@@ -0,0 +1,22 @@
1
+ import type { ScalarNode, TextNode } from '~/lib/nodes/state/Node';
2
+ import { num, scalar } from '~/lib/nodes/jax';
3
+ import { expectNode, type UiArg } from '../nodeHandle';
4
+
5
+ /** `pie.ui.textbox(n)`: a text box for Scalar or Text `n`. It writes on Enter or on leaving the box. */
6
+ export function Textbox(props: { args: UiArg[] }) {
7
+ const [n, setN] = expectNode<ScalarNode | TextNode>(props.args[0], ['Scalar', 'Text']);
8
+ const shown = () => {
9
+ const node = n();
10
+ return node.type === 'Scalar' ? String(num(node.value)) : node.value;
11
+ };
12
+
13
+ const write = (input: HTMLInputElement) => {
14
+ if (n().type === 'Text') return setN({ value: input.value });
15
+ const value = Number(input.value);
16
+ // Not a number: put the current value back.
17
+ if (input.value.trim() === '' || Number.isNaN(value)) input.value = shown();
18
+ else setN({ value: scalar(value) });
19
+ };
20
+
21
+ return <input type="text" value={shown()} onChange={(e) => write(e.currentTarget)} />;
22
+ }
@@ -0,0 +1,133 @@
1
+ /** Class of the layer over the canvas that holds the UIs dropped there. */
2
+ export const UI_LAYER_CLASS = 'canvas-ui-layer';
3
+
4
+ /** Pixels the pointer must move before a press on the grip becomes a drag. */
5
+ const DRAG_THRESHOLD = 4;
6
+ /** Within this many pixels of the text's visible top or bottom, a drag scrolls the text. */
7
+ const SCROLL_EDGE = 40;
8
+ const SCROLL_STEP = 10;
9
+
10
+ type Pixel = { x: number; y: number };
11
+
12
+ const inside = (r: DOMRect, p: Pixel) => p.x >= r.left && p.x <= r.right && p.y >= r.top && p.y <= r.bottom;
13
+
14
+ /** Keeps `box` inside `layer`, with its top left corner at (`left`, `top`) if that fits. */
15
+ export function clampToLayer(box: HTMLElement, layer: HTMLElement, left = box.offsetLeft, top = box.offsetTop) {
16
+ const maxLeft = Math.max(0, layer.clientWidth - box.offsetWidth);
17
+ const maxTop = Math.max(0, layer.clientHeight - box.offsetHeight);
18
+ box.style.left = `${Math.min(Math.max(0, left), maxLeft)}px`;
19
+ box.style.top = `${Math.min(Math.max(0, top), maxTop)}px`;
20
+ }
21
+
22
+ /** The gap between the blocks of `text` nearest to height `y`: the block it sits before (null: the end) and its height. */
23
+ function nearestGap(text: HTMLElement, box: HTMLElement, y: number): { before: Element | null; y: number } {
24
+ // Hidden blocks have no box, so their position means nothing.
25
+ const blocks = [...text.children].filter((block) => block !== box && block.getClientRects().length > 0);
26
+ const rects = blocks.map((block) => block.getBoundingClientRect());
27
+ if (rects.length === 0) return { before: null, y: text.getBoundingClientRect().top };
28
+ let best = { before: blocks[0] as Element | null, y: rects[0].top };
29
+ for (let i = 1; i <= rects.length; i++) {
30
+ const gapY = i === rects.length ? rects[i - 1].bottom : (rects[i - 1].bottom + rects[i].top) / 2;
31
+ if (Math.abs(gapY - y) < Math.abs(best.y - y)) best = { before: blocks[i] ?? null, y: gapY };
32
+ }
33
+ return best;
34
+ }
35
+
36
+ /** The nearest ancestor of `el` that scrolls, or the page. */
37
+ function scrollParent(el: HTMLElement): HTMLElement {
38
+ for (let p = el.parentElement; p; p = p.parentElement) {
39
+ const { overflowY } = getComputedStyle(p);
40
+ if (overflowY === 'auto' || overflowY === 'scroll') return p;
41
+ }
42
+ return document.scrollingElement as HTMLElement;
43
+ }
44
+
45
+ /**
46
+ * Drags `box`, a UI, from a press `e` on its grip. Dropped over the canvas, it stays at that spot on the screen.
47
+ * Dropped anywhere else, it goes into the nearest gap between the blocks of `text`, the page's text.
48
+ * Near the text's top or bottom edge, the text scrolls.
49
+ */
50
+ export function dragUi(e: PointerEvent, box: HTMLElement, text: HTMLElement) {
51
+ if (e.button !== 0) return;
52
+ e.preventDefault();
53
+ const layer = document.querySelector<HTMLElement>(`.${UI_LAYER_CLASS}`);
54
+ const scroller = scrollParent(text);
55
+ const rect = box.getBoundingClientRect();
56
+ // Where the pointer holds the box, so the box doesn't jump under it.
57
+ const offset = { x: e.clientX - rect.left, y: e.clientY - rect.top };
58
+ const start = { x: e.clientX, y: e.clientY };
59
+ let pointer = start;
60
+ let dragging = false;
61
+ let frame = 0;
62
+ const line = document.createElement('div');
63
+ line.className = 'python-editor-ui-drop-line';
64
+
65
+ const overLayer = () => layer !== null && inside(layer.getBoundingClientRect(), pointer);
66
+
67
+ const update = () => {
68
+ box.style.left = `${pointer.x - offset.x}px`;
69
+ box.style.top = `${pointer.y - offset.y}px`;
70
+ if (overLayer()) return line.remove();
71
+ const textRect = text.getBoundingClientRect();
72
+ line.style.left = `${textRect.left}px`;
73
+ line.style.width = `${textRect.width}px`;
74
+ line.style.top = `${nearestGap(text, box, pointer.y).y}px`;
75
+ if (!line.isConnected) document.body.append(line);
76
+ };
77
+
78
+ const autoScroll = () => {
79
+ if (!overLayer()) {
80
+ const edges = scroller === document.scrollingElement ? { top: 0, bottom: window.innerHeight } : scroller.getBoundingClientRect();
81
+ const step = pointer.y < edges.top + SCROLL_EDGE ? -SCROLL_STEP : pointer.y > edges.bottom - SCROLL_EDGE ? SCROLL_STEP : 0;
82
+ if (step !== 0) {
83
+ scroller.scrollTop += step;
84
+ update();
85
+ }
86
+ }
87
+ frame = requestAnimationFrame(autoScroll);
88
+ };
89
+
90
+ // The box floats under the pointer, above everything, until it is dropped.
91
+ const begin = () => {
92
+ dragging = true;
93
+ document.body.style.userSelect = 'none';
94
+ box.classList.add('python-editor-ui-dragging');
95
+ box.style.position = 'fixed';
96
+ document.body.append(box);
97
+ frame = requestAnimationFrame(autoScroll);
98
+ };
99
+
100
+ const move = (ev: PointerEvent) => {
101
+ pointer = { x: ev.clientX, y: ev.clientY };
102
+ if (!dragging) {
103
+ if (Math.hypot(pointer.x - start.x, pointer.y - start.y) < DRAG_THRESHOLD) return;
104
+ begin();
105
+ }
106
+ update();
107
+ };
108
+
109
+ const drop = () => {
110
+ window.removeEventListener('pointermove', move);
111
+ window.removeEventListener('pointerup', drop);
112
+ window.removeEventListener('pointercancel', drop);
113
+ if (!dragging) return;
114
+ cancelAnimationFrame(frame);
115
+ document.body.style.userSelect = '';
116
+ line.remove();
117
+ box.classList.remove('python-editor-ui-dragging');
118
+ if (layer && overLayer()) {
119
+ const boxRect = box.getBoundingClientRect();
120
+ const layerRect = layer.getBoundingClientRect();
121
+ layer.append(box);
122
+ box.style.position = 'absolute';
123
+ clampToLayer(box, layer, boxRect.left - layerRect.left, boxRect.top - layerRect.top);
124
+ } else {
125
+ box.style.position = box.style.left = box.style.top = '';
126
+ text.insertBefore(box, nearestGap(text, box, pointer.y).before);
127
+ }
128
+ };
129
+
130
+ window.addEventListener('pointermove', move);
131
+ window.addEventListener('pointerup', drop);
132
+ window.addEventListener('pointercancel', drop);
133
+ }
@@ -0,0 +1,47 @@
1
+ import { Accessor, createContext, untrack, useContext } from 'solid-js';
2
+ import type { AnyNode } from '~/lib/nodes/state/Node';
3
+ import type { NodeStore } from '~/lib/nodes/state/NodeStore';
4
+ import { replaceNode } from '~/lib/nodes/functions/sideEffects';
5
+
6
+ /** A node passed to a UI, as a Solid signal pair: read it with `n()`, write it with `setN(changes)`. */
7
+ export type NodeHandle<N extends AnyNode = AnyNode> = [Accessor<N>, (changes: Partial<N>) => void];
8
+
9
+ /** A positional argument of `pie.ui.<name>(...)`: a node, or a list of them at any depth. */
10
+ export type UiArg = NodeHandle | UiArg[];
11
+
12
+ export const isHandle = (arg: UiArg): arg is NodeHandle => typeof arg[0] === 'function';
13
+
14
+ /**
15
+ * Saves `node` with `changes`, like dragging a point: it no longer follows its inputs.
16
+ * To change an Array, write its items: replacing the Array removes its item nodes.
17
+ */
18
+ function setNode<N extends AnyNode>(store: NodeStore, node: N, changes: Partial<N>) {
19
+ replaceNode(store, node, changes, false);
20
+ }
21
+
22
+ /** Reads node `id` from the store each time, so it follows the node when it is replaced. */
23
+ export function nodeHandle<N extends AnyNode>(store: NodeStore, id: string): NodeHandle<N> {
24
+ const get = () => store.getNodeValue(id) as N;
25
+ const set = (changes: Partial<N>) => {
26
+ const node = untrack(get);
27
+ if (node && node.type !== 'Dummy') setNode(store, node, changes);
28
+ };
29
+ return [get, set];
30
+ }
31
+
32
+ export const StoreContext = createContext<NodeStore>();
33
+
34
+ /** Inside a UI: writes a node it did not get as an argument, e.g. an Array's item. */
35
+ export function useSetNode() {
36
+ const store = useContext(StoreContext);
37
+ if (!store) throw new Error('useSetNode works only inside a UI');
38
+ return <N extends AnyNode>(node: N, changes: Partial<N>) => setNode(store, node, changes);
39
+ }
40
+
41
+ /** `arg` as a node of one of `types`. Throws otherwise; the UI shows the error. */
42
+ export function expectNode<N extends AnyNode>(arg: UiArg | undefined, types: N['type'][]): NodeHandle<N> {
43
+ if (arg === undefined || !isHandle(arg)) throw new Error(`expects a ${types.join(' or ')} node, got ${arg === undefined ? 'nothing' : 'a list'}`);
44
+ const type = untrack(arg[0]).type;
45
+ if (!types.includes(type as N['type'])) throw new Error(`expects a ${types.join(' or ')} node, got a ${type}`);
46
+ return arg as unknown as NodeHandle<N>;
47
+ }
@@ -0,0 +1,33 @@
1
+ import type { Component } from 'solid-js';
2
+
3
+ /** A UI: a Solid component. `args` holds the call's positional arguments; its keyword arguments are the other props. */
4
+ export type UiComponent = Component<any>;
5
+
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 });
9
+
10
+ const isComponent = (name: string, value: unknown): value is UiComponent =>
11
+ /^[A-Z][A-Za-z0-9]*$/.test(name) && typeof value === 'function';
12
+
13
+ /** Its name in Python: `Slider` gives `pie.ui.slider`, `MatrixProduct` gives `pie.ui.matrix_product`. */
14
+ const pythonName = (exportName: string) => exportName.replace(/(?<!^)([A-Z])/g, '_$1').toLowerCase();
15
+
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}`);
25
+ }
26
+ components.set(name, value);
27
+ sourceFile.set(name, file);
28
+ }
29
+ }
30
+
31
+ export function getUi(name: string): UiComponent | undefined {
32
+ return components.get(name);
33
+ }
package/ui/stepper.tsx ADDED
@@ -0,0 +1,17 @@
1
+ import type { ScalarNode } from '~/lib/nodes/state/Node';
2
+ import { num, scalar } from '~/lib/nodes/jax';
3
+ import { expectNode, type UiArg } from '~/lib/ui/nodeHandle';
4
+
5
+ /** `pie.ui.stepper(n, step=1)`: − and + buttons that change Scalar `n` by `step`, with its value between them. */
6
+ export function Stepper(props: { args: UiArg[]; step?: number }) {
7
+ const [n, setN] = expectNode<ScalarNode>(props.args[0], ['Scalar']);
8
+ const step = props.step ?? 1;
9
+ const add = (delta: number) => setN({ value: scalar(num(n().value) + delta) });
10
+ return (
11
+ <span>
12
+ <button type="button" onClick={() => add(-step)}>−</button>
13
+ {' '}{num(n().value)}{' '}
14
+ <button type="button" onClick={() => add(step)}>+</button>
15
+ </span>
16
+ );
17
+ }