@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
|
@@ -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
|
}
|
|
@@ -13,7 +13,9 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import type { MarkedExtension } from 'marked';
|
|
15
15
|
import type { Field } from '../frontmatter';
|
|
16
|
+
import { glossary } from './glossary/build';
|
|
16
17
|
import { sidebar } from './sidebar/build';
|
|
18
|
+
import { tags } from './tags/build';
|
|
17
19
|
import { toc } from './toc/build';
|
|
18
20
|
|
|
19
21
|
/** The second argument to a feature's `build`. */
|
|
@@ -22,8 +24,8 @@ export interface BuildContext {
|
|
|
22
24
|
file: string;
|
|
23
25
|
/** The file that set the value: the page, or `site.yml`. */
|
|
24
26
|
from: string;
|
|
25
|
-
/** The
|
|
26
|
-
|
|
27
|
+
/** The markdown of the `.md` file at `path`, relative to the folder of `from`, without its frontmatter. Throws if it's missing or outside the project. */
|
|
28
|
+
readFile(path: string): string;
|
|
27
29
|
}
|
|
28
30
|
|
|
29
31
|
/** A feature's build half. `T`: its frontmatter value. `D`: the data its view gets. */
|
|
@@ -31,19 +33,22 @@ export interface FeatureBuild<T, D> {
|
|
|
31
33
|
field: Field<T>;
|
|
32
34
|
/** Returns `undefined` to turn the feature off on this page. */
|
|
33
35
|
build(value: T, ctx: BuildContext): D | undefined;
|
|
34
|
-
/** Extra markdown syntax for this page. */
|
|
35
|
-
markdown?(
|
|
36
|
+
/** Extra markdown syntax for this page. Called only when `build` didn't turn the feature off. */
|
|
37
|
+
markdown?(value: T, ctx: BuildContext): MarkedExtension;
|
|
36
38
|
}
|
|
37
39
|
|
|
38
|
-
/**
|
|
39
|
-
|
|
40
|
+
/**
|
|
41
|
+
* Keyed by frontmatter key. The last feature's `postprocess` runs first, so `tags`, being after `glossary`,
|
|
42
|
+
* ends the page's text and the glossary comes after it.
|
|
43
|
+
*/
|
|
44
|
+
const FEATURES = { sidebar, toc, glossary, tags };
|
|
40
45
|
|
|
41
46
|
type DataOf<F> = F extends FeatureBuild<any, infer D> ? D : never;
|
|
42
47
|
|
|
43
|
-
// Today: `{ sidebar?: string; toc?: true }`.
|
|
48
|
+
// Today: `{ sidebar?: string; toc?: true; glossary?: true; tags?: true }`.
|
|
44
49
|
export type FeatureData = { [K in keyof typeof FEATURES]?: DataOf<(typeof FEATURES)[K]> };
|
|
45
50
|
|
|
46
|
-
// Today: `{ sidebar: sidebar.field, toc: toc.field }`. `site.yml` reads these too.
|
|
51
|
+
// Today: `{ sidebar: sidebar.field, toc: toc.field, glossary: glossary.field, tags: tags.field }`. `site.yml` reads these too.
|
|
47
52
|
export const FEATURE_FIELDS = Object.fromEntries(
|
|
48
53
|
Object.entries(FEATURES).map(([key, feature]) => [key, feature.field]),
|
|
49
54
|
) as { [K in keyof typeof FEATURES]: (typeof FEATURES)[K]['field'] };
|
|
@@ -53,7 +58,7 @@ export function buildFeatures(
|
|
|
53
58
|
file: string,
|
|
54
59
|
raw: Record<string, string>,
|
|
55
60
|
site: Record<string, unknown>,
|
|
56
|
-
|
|
61
|
+
readFile: (from: string, path: string) => string,
|
|
57
62
|
): { data: FeatureData; extensions: MarkedExtension[] } {
|
|
58
63
|
const data: Record<string, unknown> = {};
|
|
59
64
|
const extensions: MarkedExtension[] = [];
|
|
@@ -61,10 +66,11 @@ export function buildFeatures(
|
|
|
61
66
|
const from = Object.hasOwn(raw, key) ? file : 'site.yml';
|
|
62
67
|
try {
|
|
63
68
|
const value = from === file ? feature.field.parse(raw[key]) : site[key];
|
|
64
|
-
const
|
|
69
|
+
const ctx: BuildContext = { file, from, readFile: path => readFile(from, path) };
|
|
70
|
+
const built = feature.build(value, ctx);
|
|
65
71
|
if (built === undefined) continue;
|
|
66
72
|
data[key] = built;
|
|
67
|
-
if (feature.markdown) extensions.push(feature.markdown(
|
|
73
|
+
if (feature.markdown) extensions.push(feature.markdown(value, ctx));
|
|
68
74
|
} catch (e) {
|
|
69
75
|
throw new Error(`${from}: \`${key}\` ${(e as Error).message}`);
|
|
70
76
|
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { onCleanup, onMount, type JSX } from 'solid-js';
|
|
2
|
+
|
|
3
|
+
/** A popup for `term`: the start of its definition, copied from the page's glossary, and a "more" link to all of it. */
|
|
4
|
+
function makePopup(term: HTMLElement): HTMLElement {
|
|
5
|
+
const id = term.dataset.term!;
|
|
6
|
+
const definition = document.getElementById(id)!.nextElementSibling!;
|
|
7
|
+
const popup = document.createElement('div');
|
|
8
|
+
popup.className = 'term-popup';
|
|
9
|
+
popup.innerHTML = `<div class="term-popup-text">${definition.innerHTML}</div><a class="term-more" href="#${id}">more</a>`;
|
|
10
|
+
return popup;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Gives `term` its popup if it has none, and puts it under the term, or over it when the term is in the lower half of the screen. */
|
|
14
|
+
function place(term: HTMLElement) {
|
|
15
|
+
const popup = term.querySelector<HTMLElement>(':scope > .term-popup') ?? term.appendChild(makePopup(term));
|
|
16
|
+
const rect = term.getBoundingClientRect();
|
|
17
|
+
const height = document.documentElement.clientHeight;
|
|
18
|
+
const below = rect.bottom < height / 2;
|
|
19
|
+
popup.style.top = below ? `${rect.bottom}px` : '';
|
|
20
|
+
popup.style.bottom = below ? '' : `${height - rect.top}px`;
|
|
21
|
+
popup.style.setProperty('--term-left', `${rect.left}px`);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* `children`, whose glossary terms show a popup on hover. A tap on a term also shows it, for touch screens,
|
|
26
|
+
* and a tap anywhere else hides it. The popup's "more" opens the page's glossary at the term.
|
|
27
|
+
*/
|
|
28
|
+
export function GlossaryView(props: { data: true; children: JSX.Element }) {
|
|
29
|
+
onMount(() => {
|
|
30
|
+
const onPointerOver = (e: PointerEvent) => {
|
|
31
|
+
const term = (e.target as Element).closest<HTMLElement>('.term');
|
|
32
|
+
if (term) place(term);
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
// Capture: runs before the router follows a "more" link, so the glossary is open when it scrolls to the term.
|
|
36
|
+
const onClick = (e: MouseEvent) => {
|
|
37
|
+
const target = e.target as Element;
|
|
38
|
+
const inPopup = target.closest('.term-popup') !== null;
|
|
39
|
+
const more = target.closest('.term-more') !== null;
|
|
40
|
+
if (inPopup && !more) return;
|
|
41
|
+
if (more) document.querySelector<HTMLDetailsElement>('.glossary')!.open = true;
|
|
42
|
+
const term = inPopup ? null : target.closest<HTMLElement>('.term');
|
|
43
|
+
for (const open of document.querySelectorAll('.term--open')) if (open !== term) open.classList.remove('term--open');
|
|
44
|
+
if (term) {
|
|
45
|
+
place(term);
|
|
46
|
+
term.classList.toggle('term--open');
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
// A popup is fixed to the screen, so it's moved to follow its term.
|
|
51
|
+
const onScroll = () => document.querySelectorAll<HTMLElement>('.term--open, .term:hover').forEach(place);
|
|
52
|
+
|
|
53
|
+
document.addEventListener('pointerover', onPointerOver);
|
|
54
|
+
document.addEventListener('click', onClick, true);
|
|
55
|
+
document.addEventListener('scroll', onScroll, true);
|
|
56
|
+
onCleanup(() => {
|
|
57
|
+
document.removeEventListener('pointerover', onPointerOver);
|
|
58
|
+
document.removeEventListener('click', onClick, true);
|
|
59
|
+
document.removeEventListener('scroll', onScroll, true);
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
return props.children;
|
|
64
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { Lexer, type MarkedExtension } from 'marked';
|
|
2
|
+
import { markdownFile } from '../../frontmatter';
|
|
3
|
+
import { renderInline, renderMarkdown } from '../../render';
|
|
4
|
+
import type { FeatureBuild } from '../build';
|
|
5
|
+
|
|
6
|
+
interface Term {
|
|
7
|
+
/** The `id` of its entry in the page's glossary, e.g. `term-3`. */
|
|
8
|
+
id: string;
|
|
9
|
+
/** Its heading as HTML, e.g. with its math rendered. */
|
|
10
|
+
name: string;
|
|
11
|
+
/** Its definition as HTML. */
|
|
12
|
+
html: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Matching ignores case. */
|
|
16
|
+
const key = (name: string) => name.trim().toLowerCase();
|
|
17
|
+
|
|
18
|
+
/** The section's title when the glossary file has no `#` heading. */
|
|
19
|
+
const DEFAULT_TITLE = 'Glossary';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The glossary file `file`. `title`: its `#` heading, as HTML. `terms`: by `key`, in the file's order.
|
|
23
|
+
* Each `##` heading is a term, and the text up to the next one is its definition.
|
|
24
|
+
* Other text before the first `##` is ignored.
|
|
25
|
+
*/
|
|
26
|
+
function parseGlossary(file: string, markdown: string): { title: string; terms: Map<string, Term> } {
|
|
27
|
+
let title = DEFAULT_TITLE;
|
|
28
|
+
const sections: { name: string; body: string }[] = [];
|
|
29
|
+
for (const token of Lexer.lex(markdown)) {
|
|
30
|
+
if (token.type === 'heading' && token.depth === 2) sections.push({ name: token.text, body: '' });
|
|
31
|
+
else if (sections.length > 0) sections[sections.length - 1].body += token.raw;
|
|
32
|
+
else if (token.type === 'heading' && token.depth === 1) title = renderInline(token.text);
|
|
33
|
+
}
|
|
34
|
+
const terms = new Map<string, Term>();
|
|
35
|
+
sections.forEach(({ name, body }, i) => {
|
|
36
|
+
if (terms.has(key(name))) throw new Error(`file ${file} has the term ${JSON.stringify(name)} twice`);
|
|
37
|
+
terms.set(key(name), { id: `term-${i + 1}`, name: renderInline(name), html: renderMarkdown(body) });
|
|
38
|
+
});
|
|
39
|
+
return { title, terms };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The page's glossary, collapsed: the terms it uses, in the glossary file's order. */
|
|
43
|
+
function glossaryHtml(title: string, terms: Term[]): string {
|
|
44
|
+
const entries = terms.map(t => `<dt id="${t.id}">${t.name}</dt><dd>${t.html}</dd>`).join('');
|
|
45
|
+
return `<details class="glossary"><summary>${title}</summary><dl>${entries}</dl></details>\n`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* `glossary: _terms.md`: `[[term]]` and `[[shown|term]]` in the page become terms with a popup (see `View.tsx`),
|
|
50
|
+
* and the page ends with a collapsed glossary of the terms it uses. A term missing from the file fails the build.
|
|
51
|
+
*/
|
|
52
|
+
export const glossary: FeatureBuild<string, true> = {
|
|
53
|
+
field: markdownFile(),
|
|
54
|
+
build: file => (file === '' || file === 'none' ? undefined : true),
|
|
55
|
+
markdown(file, ctx) {
|
|
56
|
+
const { title, terms } = parseGlossary(file, ctx.readFile(file));
|
|
57
|
+
const used = new Set<Term>();
|
|
58
|
+
return {
|
|
59
|
+
extensions: [
|
|
60
|
+
{
|
|
61
|
+
name: 'term',
|
|
62
|
+
level: 'inline',
|
|
63
|
+
start(src) {
|
|
64
|
+
const at = src.indexOf('[[');
|
|
65
|
+
return at === -1 ? undefined : at;
|
|
66
|
+
},
|
|
67
|
+
tokenizer(src) {
|
|
68
|
+
const match = /^\[\[([^[\]|]+)(?:\|([^[\]|]+))?\]\]/.exec(src);
|
|
69
|
+
if (!match) return undefined;
|
|
70
|
+
const [raw, shown, name = shown] = match;
|
|
71
|
+
const term = terms.get(key(name));
|
|
72
|
+
if (!term) throw new Error(`[[${name}]]: ${file} has no such term`);
|
|
73
|
+
used.add(term);
|
|
74
|
+
return { type: 'term', raw, term, tokens: this.lexer.inlineTokens(shown) };
|
|
75
|
+
},
|
|
76
|
+
renderer(token) {
|
|
77
|
+
return `<span class="term" data-term="${token.term.id}">${this.parser.parseInline(token.tokens!)}</span>`;
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
],
|
|
81
|
+
hooks: {
|
|
82
|
+
postprocess(html) {
|
|
83
|
+
if (used.size === 0) return html;
|
|
84
|
+
return html + glossaryHtml(title, [...terms.values()].filter(t => used.has(t)));
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
} satisfies MarkedExtension;
|
|
88
|
+
},
|
|
89
|
+
};
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { markdownFile } from '../../frontmatter';
|
|
2
|
+
import { renderMarkdown } from '../../render';
|
|
2
3
|
import type { FeatureBuild } from '../build';
|
|
3
4
|
|
|
4
5
|
/** `sidebar: _topics.md`: that file's HTML, shown in a sidebar. `none`: no sidebar, even when `site.yml` sets one. */
|
|
5
6
|
export const sidebar: FeatureBuild<string, string> = {
|
|
6
7
|
field: markdownFile(),
|
|
7
|
-
build: (file, ctx) => (file === '' || file === 'none' ? undefined : ctx.
|
|
8
|
+
build: (file, ctx) => (file === '' || file === 'none' ? undefined : renderMarkdown(ctx.readFile(file))),
|
|
8
9
|
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { MarkedExtension } from 'marked';
|
|
2
|
+
import { hashtags } from '../../frontmatter';
|
|
3
|
+
import { escapeHtml } from '../../render';
|
|
4
|
+
import type { FeatureBuild } from '../build';
|
|
5
|
+
import { tagUrl } from './url';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* `tags: #math #linear-algebra`: the page's tags, as links at the end of its text. Each link opens the page
|
|
9
|
+
* listing the pages with that tag, in `src/routes/_tags/`. Only a page's own frontmatter counts, not `site.yml`.
|
|
10
|
+
*/
|
|
11
|
+
export const tags: FeatureBuild<string[], true> = {
|
|
12
|
+
field: hashtags(),
|
|
13
|
+
build: (tags, ctx) => (ctx.from === ctx.file && tags.length > 0 ? true : undefined),
|
|
14
|
+
markdown(tags) {
|
|
15
|
+
const links = tags.map(tag => `<a href="${escapeHtml(tagUrl(tag))}">#${escapeHtml(tag)}</a>`).join('');
|
|
16
|
+
return {
|
|
17
|
+
hooks: {
|
|
18
|
+
postprocess: html => `${html}<nav class="tags">${links}</nav>\n`,
|
|
19
|
+
},
|
|
20
|
+
} satisfies MarkedExtension;
|
|
21
|
+
},
|
|
22
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { slugOf } from '../../pages';
|
|
2
|
+
import { tagSegment } from './url';
|
|
3
|
+
|
|
4
|
+
/** One `pages/**\/*.md` imported with `?tags`, as `vitePlugin.ts` turns it into a module at build time. */
|
|
5
|
+
export interface PageTags {
|
|
6
|
+
title: string;
|
|
7
|
+
description: string;
|
|
8
|
+
tags: string[];
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface TaggedPage {
|
|
12
|
+
slug: string;
|
|
13
|
+
/** The page's `title`, or its slug if it has none. */
|
|
14
|
+
title: string;
|
|
15
|
+
description: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Eager: a tag's page needs every page's tags at once. Only the routes in `src/routes/_tags/` import this file.
|
|
19
|
+
const modules = import.meta.glob<PageTags>(['/pages/**/*.md', '!/pages/**/_*.md'], {
|
|
20
|
+
eager: true,
|
|
21
|
+
query: '?tags',
|
|
22
|
+
import: 'default',
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const byTag = new Map<string, TaggedPage[]>();
|
|
26
|
+
for (const [path, { title, description, tags }] of Object.entries(modules)) {
|
|
27
|
+
const slug = slugOf(path);
|
|
28
|
+
for (const tag of tags) {
|
|
29
|
+
if (!byTag.has(tag)) byTag.set(tag, []);
|
|
30
|
+
byTag.get(tag)!.push({ slug, title: title || slug, description });
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Every tag, sorted, with its pages sorted by title. */
|
|
35
|
+
export const allTags = [...byTag]
|
|
36
|
+
.map(([tag, pages]) => ({ tag, pages: pages.sort((a, b) => a.title.localeCompare(b.title)) }))
|
|
37
|
+
.sort((a, b) => a.tag.localeCompare(b.tag));
|
|
38
|
+
|
|
39
|
+
/** The tag whose page has `segment` as the last part of its URL, which is still encoded, e.g. `caf%C3%A9`. */
|
|
40
|
+
export function tagAt(segment: string) {
|
|
41
|
+
return allTags.find(({ tag }) => tagSegment(tag) === segment);
|
|
42
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** The page listing every tag. Starts with `_` so it can't be taken by a site's own page. */
|
|
2
|
+
export const TAGS_URL = '/_tags';
|
|
3
|
+
|
|
4
|
+
/** The last part of the URL of the page for `tag`. Not `encodeURIComponent`: prerendering would encode its `%2B` again. */
|
|
5
|
+
export function tagSegment(tag: string): string {
|
|
6
|
+
return encodeURI(tag);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** The page listing the pages with `tag`. */
|
|
10
|
+
export function tagUrl(tag: string): string {
|
|
11
|
+
return `${TAGS_URL}/${tagSegment(tag)}`;
|
|
12
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// The view part of every feature: runs in the browser. Each feature's build part is in `build.ts`.
|
|
2
2
|
import type { Component, JSX } from 'solid-js';
|
|
3
3
|
import type { FeatureData } from './build';
|
|
4
|
+
import { GlossaryView } from './glossary/View';
|
|
4
5
|
import { SidebarView } from './sidebar/View';
|
|
5
6
|
|
|
6
7
|
/** A feature's view: wraps the page, given the feature's data. */
|
|
@@ -9,6 +10,7 @@ type FeatureView<D> = Component<{ data: D; children: JSX.Element }>;
|
|
|
9
10
|
/** Every feature's view, by key, outermost first. A feature with no view, like `toc`, is left out. */
|
|
10
11
|
const VIEWS: { [K in keyof FeatureData]: FeatureView<NonNullable<FeatureData[K]>> } = {
|
|
11
12
|
sidebar: SidebarView,
|
|
13
|
+
glossary: GlossaryView,
|
|
12
14
|
};
|
|
13
15
|
|
|
14
16
|
/** `body` wrapped in the view of every feature that is on for the page, the first in `VIEWS` outermost. */
|
|
@@ -45,6 +45,20 @@ export function markdownFile(): Field<string> {
|
|
|
45
45
|
};
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
+
/**
|
|
49
|
+
* Words written `#tag`, separated by spaces or commas, lowercased and without repeats. Other words are ignored.
|
|
50
|
+
* A tag has only letters, numbers, `-`, `_` and `+`: it's also a URL, and prerendering can't reach one with `/`, `?` or `.`.
|
|
51
|
+
*/
|
|
52
|
+
export function hashtags(): Field<string[]> {
|
|
53
|
+
return {
|
|
54
|
+
default: [],
|
|
55
|
+
parse(raw) {
|
|
56
|
+
const words = raw.split(/[\s,]+/).map(word => /^#([\p{L}\p{N}_+-]+)$/u.exec(word)?.[1].toLowerCase());
|
|
57
|
+
return [...new Set(words.filter(tag => tag !== undefined))];
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
48
62
|
/** Every frontmatter field a page can set. Keys not listed here are ignored. */
|
|
49
63
|
const FIELDS = {
|
|
50
64
|
canvas: oneOf(['left', 'right', 'top', 'bottom', 'none'], 'none'),
|
|
@@ -12,10 +12,13 @@ export interface Page {
|
|
|
12
12
|
// A file whose name starts with `_` is not a page; it can still be used by a feature, e.g. as a sidebar.
|
|
13
13
|
const loaders = import.meta.glob<Page>(['/pages/**/*.md', '!/pages/**/_*.md'], { import: 'default' });
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
15
|
+
/** `/pages/a/b.md` -> `a/b`. */
|
|
16
|
+
export function slugOf(path: string): string {
|
|
17
|
+
return path.replace(/^\/pages\//, '').replace(/\.md$/, '');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Slug -> loader.
|
|
21
|
+
const bySlug = new Map(Object.entries(loaders).map(([path, load]) => [slugOf(path), load]));
|
|
19
22
|
|
|
20
23
|
export const slugs = [...bySlug.keys()];
|
|
21
24
|
|
|
@@ -7,7 +7,7 @@ function renderMath(formula: string, displayMode: boolean): string {
|
|
|
7
7
|
return katex.renderToString(formula, { displayMode, throwOnError: false });
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
-
function escapeHtml(text: string): string {
|
|
10
|
+
export function escapeHtml(text: string): string {
|
|
11
11
|
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
12
12
|
}
|
|
13
13
|
|
|
@@ -90,5 +90,15 @@ const marked = new Marked(BASE);
|
|
|
90
90
|
/** `extensions`: markdown syntax the page's features add. */
|
|
91
91
|
export function renderMarkdown(markdown: string, extensions: MarkedExtension[] = []): string {
|
|
92
92
|
const parser = extensions.length === 0 ? marked : new Marked(BASE, ...extensions);
|
|
93
|
-
|
|
93
|
+
try {
|
|
94
|
+
return parser.parse(markdown) as string;
|
|
95
|
+
} catch (e) {
|
|
96
|
+
// marked adds "Please report this to …" to every error, even a feature's, e.g. an unknown glossary term.
|
|
97
|
+
throw new Error((e as Error).message.replace(/\nPlease report this to .*$/, ''));
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** One line of markdown as HTML, without the `<p>` around it. */
|
|
102
|
+
export function renderInline(markdown: string): string {
|
|
103
|
+
return marked.parseInline(markdown) as string;
|
|
94
104
|
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import type { Plugin } from 'vite';
|
|
4
|
-
import { buildFeatures } from './features/build';
|
|
4
|
+
import { buildFeatures, FEATURE_FIELDS } from './features/build';
|
|
5
|
+
import type { PageTags } from './features/tags/pages';
|
|
5
6
|
import { parseFrontmatter } from './frontmatter';
|
|
6
7
|
import type { Page } from './pages';
|
|
7
8
|
import { renderMarkdown } from './render';
|
|
@@ -11,6 +12,7 @@ import { parseSite } from '../site/vitePlugin';
|
|
|
11
12
|
/**
|
|
12
13
|
* Turns each `pages/**\/*.md` into a module whose default export is a `Page`, at build time,
|
|
13
14
|
* so the browser gets finished HTML and never runs the markdown tools.
|
|
15
|
+
* With `?tags`, the module's default export is a `PageTags` instead, so the tag pages don't load every page's HTML.
|
|
14
16
|
* Bad frontmatter, or a feature's bad value, fails the build; in dev it shows Vite's error screen.
|
|
15
17
|
*/
|
|
16
18
|
export function markdownPages(): Plugin {
|
|
@@ -23,16 +25,23 @@ export function markdownPages(): Plugin {
|
|
|
23
25
|
root = config.root;
|
|
24
26
|
},
|
|
25
27
|
transform(markdown, id) {
|
|
26
|
-
const
|
|
28
|
+
const [filePath, query] = id.split('?');
|
|
29
|
+
const file = path.relative(root, filePath);
|
|
27
30
|
if (!file.startsWith(`pages${path.sep}`) || !file.endsWith('.md')) return;
|
|
28
31
|
const { frontmatter, raw, body } = parseFrontmatter(file, markdown);
|
|
29
32
|
|
|
33
|
+
if (new URLSearchParams(query).has('tags')) {
|
|
34
|
+
const { title, description } = frontmatter;
|
|
35
|
+
const page: PageTags = { title, description, tags: FEATURE_FIELDS.tags.parse(raw.tags ?? '') };
|
|
36
|
+
return { code: `export default ${JSON.stringify(page)};`, map: null };
|
|
37
|
+
}
|
|
38
|
+
|
|
30
39
|
// Features read `site.yml` for the keys a page leaves out, so editing it rebuilds every page.
|
|
31
40
|
const siteFile = path.join(root, 'site.yml');
|
|
32
41
|
this.addWatchFile(siteFile);
|
|
33
42
|
const site = parseSite('site.yml', fs.readFileSync(siteFile, 'utf8'));
|
|
34
43
|
|
|
35
|
-
const
|
|
44
|
+
const readFile = (from: string, mdPath: string) => {
|
|
36
45
|
const target = path.resolve(root, path.dirname(from), mdPath);
|
|
37
46
|
const relative = path.relative(root, target);
|
|
38
47
|
if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
@@ -41,10 +50,10 @@ export function markdownPages(): Plugin {
|
|
|
41
50
|
const shown = relative.split(path.sep).join('/');
|
|
42
51
|
if (!fs.existsSync(target)) throw new Error(`file ${shown} does not exist`);
|
|
43
52
|
this.addWatchFile(target);
|
|
44
|
-
return
|
|
53
|
+
return parseFrontmatter(shown, fs.readFileSync(target, 'utf8')).body;
|
|
45
54
|
};
|
|
46
55
|
|
|
47
|
-
const { data, extensions } = buildFeatures(file, raw, site,
|
|
56
|
+
const { data, extensions } = buildFeatures(file, raw, site, readFile);
|
|
48
57
|
const page: Page = { frontmatter, html: renderMarkdown(body, extensions), features: data };
|
|
49
58
|
return { code: `export default ${JSON.stringify(page)};`, map: null };
|
|
50
59
|
},
|
package/src/lib/python/py/pie.py
CHANGED
|
@@ -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)
|
package/src/lib/python/runner.ts
CHANGED
|
@@ -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();
|
package/src/lib/python/worker.ts
CHANGED
|
@@ -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
|
+
}
|