@tinyvolt/pie 0.6.1 → 0.8.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 +1 -0
- package/init/site-agents.md +98 -4
- package/package.json +2 -1
- package/pages/_terms.md +12 -0
- package/pages/about.md +1 -0
- package/pages/example.md +152 -19
- package/src/app.css +200 -0
- package/src/lib/markdown/components/CanvasPage.tsx +2 -0
- package/src/lib/markdown/components/PythonEditor.tsx +16 -0
- package/src/lib/markdown/features/build.ts +17 -11
- package/src/lib/markdown/features/glossary/View.tsx +64 -0
- package/src/lib/markdown/features/glossary/build.ts +89 -0
- package/src/lib/markdown/features/sidebar/build.ts +2 -1
- package/src/lib/markdown/features/tags/build.ts +22 -0
- package/src/lib/markdown/features/tags/pages.ts +42 -0
- package/src/lib/markdown/features/tags/url.ts +12 -0
- package/src/lib/markdown/features/views.tsx +2 -0
- package/src/lib/markdown/frontmatter.ts +14 -0
- package/src/lib/markdown/pages.ts +7 -4
- package/src/lib/markdown/render.ts +12 -2
- package/src/lib/markdown/vitePlugin.ts +14 -5
- package/src/lib/python/py/pie.py +42 -0
- package/src/lib/python/runner.ts +15 -3
- package/src/lib/python/worker.ts +4 -1
- package/src/lib/ui/UiLayer.tsx +15 -0
- package/src/lib/ui/UiView.tsx +74 -0
- package/src/lib/ui/components/checkboxes.tsx +40 -0
- package/src/lib/ui/components/latex.tsx +44 -0
- package/src/lib/ui/components/radio.tsx +25 -0
- package/src/lib/ui/components/slider.tsx +18 -0
- package/src/lib/ui/components/textbox.tsx +22 -0
- package/src/lib/ui/dragUi.ts +133 -0
- package/src/lib/ui/nodeHandle.ts +47 -0
- package/src/lib/ui/registry.ts +33 -0
- package/src/routes/_tags/[tag].tsx +47 -0
- package/src/routes/_tags/index.tsx +22 -0
- package/ui/stepper.tsx +17 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { useParams } from '@solidjs/router';
|
|
2
|
+
import { HttpStatusCode } from '@solidjs/start';
|
|
3
|
+
import { For, Show } from 'solid-js';
|
|
4
|
+
import { PageMeta } from '~/components/PageMeta';
|
|
5
|
+
import { PageTitle } from '~/components/PageTitle';
|
|
6
|
+
import { tagAt } from '~/lib/markdown/features/tags/pages';
|
|
7
|
+
import { TAGS_URL } from '~/lib/markdown/features/tags/url';
|
|
8
|
+
|
|
9
|
+
export default function Tag() {
|
|
10
|
+
const params = useParams();
|
|
11
|
+
|
|
12
|
+
return (
|
|
13
|
+
<Show
|
|
14
|
+
when={tagAt(params.tag ?? '')}
|
|
15
|
+
keyed
|
|
16
|
+
fallback={
|
|
17
|
+
<main>
|
|
18
|
+
<PageTitle>Page Not Found</PageTitle>
|
|
19
|
+
<HttpStatusCode code={404} />
|
|
20
|
+
<h1>Page Not Found</h1>
|
|
21
|
+
</main>
|
|
22
|
+
}
|
|
23
|
+
>
|
|
24
|
+
{({ tag, pages }) => (
|
|
25
|
+
<main>
|
|
26
|
+
<PageMeta title={`#${tag}`} />
|
|
27
|
+
<h1>#{tag}</h1>
|
|
28
|
+
<ul>
|
|
29
|
+
<For each={pages}>
|
|
30
|
+
{page => (
|
|
31
|
+
<li>
|
|
32
|
+
<a href={`/${page.slug}`}>{page.title}</a>
|
|
33
|
+
<Show when={page.description}>
|
|
34
|
+
<p class="tagged-description">{page.description}</p>
|
|
35
|
+
</Show>
|
|
36
|
+
</li>
|
|
37
|
+
)}
|
|
38
|
+
</For>
|
|
39
|
+
</ul>
|
|
40
|
+
<p>
|
|
41
|
+
<a href={TAGS_URL}>All tags</a>
|
|
42
|
+
</p>
|
|
43
|
+
</main>
|
|
44
|
+
)}
|
|
45
|
+
</Show>
|
|
46
|
+
);
|
|
47
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { For } from 'solid-js';
|
|
2
|
+
import { PageMeta } from '~/components/PageMeta';
|
|
3
|
+
import { allTags } from '~/lib/markdown/features/tags/pages';
|
|
4
|
+
import { tagUrl } from '~/lib/markdown/features/tags/url';
|
|
5
|
+
|
|
6
|
+
export default function Tags() {
|
|
7
|
+
return (
|
|
8
|
+
<main>
|
|
9
|
+
<PageMeta title="Tags" />
|
|
10
|
+
<h1>Tags</h1>
|
|
11
|
+
<ul>
|
|
12
|
+
<For each={allTags}>
|
|
13
|
+
{({ tag, pages }) => (
|
|
14
|
+
<li>
|
|
15
|
+
<a href={tagUrl(tag)}>#{tag}</a> ({pages.length})
|
|
16
|
+
</li>
|
|
17
|
+
)}
|
|
18
|
+
</For>
|
|
19
|
+
</ul>
|
|
20
|
+
</main>
|
|
21
|
+
);
|
|
22
|
+
}
|
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
|
+
}
|