@tinyvolt/pie 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +18 -1
  2. package/dist/components/SplitPane.d.ts +21 -0
  3. package/dist/components/SplitPane.jsx +113 -0
  4. package/dist/components/icons.d.ts +12 -0
  5. package/dist/components/icons.jsx +45 -0
  6. package/dist/lib/autodiff/index.d.ts +28 -0
  7. package/dist/lib/autodiff/index.js +39 -0
  8. package/dist/lib/customModules.d.ts +13 -0
  9. package/dist/lib/customModules.js +17 -0
  10. package/dist/lib/markdown/compile.d.ts +27 -0
  11. package/dist/lib/markdown/compile.js +26 -0
  12. package/dist/lib/markdown/components/CanvasPage.d.ts +9 -0
  13. package/dist/lib/markdown/components/CanvasPage.jsx +16 -0
  14. package/dist/lib/markdown/components/MarkdownBody.d.ts +11 -0
  15. package/dist/lib/markdown/components/MarkdownBody.jsx +37 -0
  16. package/dist/lib/markdown/components/PiePage.d.ts +14 -0
  17. package/dist/lib/markdown/components/PiePage.jsx +41 -0
  18. package/dist/lib/markdown/components/PythonEditor.d.ts +10 -0
  19. package/dist/lib/markdown/components/PythonEditor.jsx +209 -0
  20. package/dist/lib/markdown/features/build.d.ts +60 -0
  21. package/dist/lib/markdown/features/build.js +36 -0
  22. package/dist/lib/markdown/features/glossary/View.d.ts +9 -0
  23. package/dist/lib/markdown/features/glossary/View.jsx +62 -0
  24. package/dist/lib/markdown/features/glossary/build.d.ts +6 -0
  25. package/dist/lib/markdown/features/glossary/build.js +81 -0
  26. package/dist/lib/markdown/features/sidebar/View.d.ts +11 -0
  27. package/dist/lib/markdown/features/sidebar/View.jsx +45 -0
  28. package/dist/lib/markdown/features/sidebar/build.d.ts +3 -0
  29. package/dist/lib/markdown/features/sidebar/build.js +7 -0
  30. package/dist/lib/markdown/features/tags/build.d.ts +7 -0
  31. package/dist/lib/markdown/features/tags/build.js +22 -0
  32. package/dist/lib/markdown/features/tags/url.d.ts +6 -0
  33. package/dist/lib/markdown/features/tags/url.js +10 -0
  34. package/dist/lib/markdown/features/toc/build.d.ts +7 -0
  35. package/dist/lib/markdown/features/toc/build.js +62 -0
  36. package/dist/lib/markdown/features/views.d.ts +4 -0
  37. package/dist/lib/markdown/features/views.jsx +11 -0
  38. package/dist/lib/markdown/frontmatter.d.ts +44 -0
  39. package/dist/lib/markdown/frontmatter.js +109 -0
  40. package/dist/lib/markdown/render.d.ts +6 -0
  41. package/dist/lib/markdown/render.js +95 -0
  42. package/dist/lib/nodes/animation.d.ts +14 -0
  43. package/dist/lib/nodes/animation.js +34 -0
  44. package/dist/lib/nodes/components/CenteredGrid.d.ts +20 -0
  45. package/dist/lib/nodes/components/CenteredGrid.jsx +44 -0
  46. package/dist/lib/nodes/components/NodeCanvas.d.ts +7 -0
  47. package/dist/lib/nodes/components/NodeCanvas.jsx +50 -0
  48. package/dist/lib/nodes/execute.d.ts +27 -0
  49. package/dist/lib/nodes/execute.js +159 -0
  50. package/dist/lib/nodes/functions/Node2NodeFunc.d.ts +70 -0
  51. package/dist/lib/nodes/functions/Node2NodeFunc.js +223 -0
  52. package/dist/lib/nodes/functions/array.d.ts +12 -0
  53. package/dist/lib/nodes/functions/array.js +31 -0
  54. package/dist/lib/nodes/functions/autodiff.d.ts +12 -0
  55. package/dist/lib/nodes/functions/autodiff.js +60 -0
  56. package/dist/lib/nodes/functions/basic.d.ts +111 -0
  57. package/dist/lib/nodes/functions/basic.js +275 -0
  58. package/dist/lib/nodes/functions/registry.d.ts +9 -0
  59. package/dist/lib/nodes/functions/registry.js +45 -0
  60. package/dist/lib/nodes/functions/sideEffects.d.ts +78 -0
  61. package/dist/lib/nodes/functions/sideEffects.js +201 -0
  62. package/dist/lib/nodes/hooks/useCanvasGestures.d.ts +9 -0
  63. package/dist/lib/nodes/hooks/useCanvasGestures.js +120 -0
  64. package/dist/lib/nodes/hooks/useCanvasResize.d.ts +2 -0
  65. package/dist/lib/nodes/hooks/useCanvasResize.js +33 -0
  66. package/dist/lib/nodes/jax.d.ts +46 -0
  67. package/dist/lib/nodes/jax.js +120 -0
  68. package/dist/lib/nodes/render/renderLogic.d.ts +13 -0
  69. package/dist/lib/nodes/render/renderLogic.jsx +234 -0
  70. package/dist/lib/nodes/state/NameGenerator.d.ts +10 -0
  71. package/dist/lib/nodes/state/NameGenerator.js +29 -0
  72. package/dist/lib/nodes/state/Node.d.ts +134 -0
  73. package/dist/lib/nodes/state/Node.js +57 -0
  74. package/dist/lib/nodes/state/NodeStore.d.ts +49 -0
  75. package/dist/lib/nodes/state/NodeStore.js +138 -0
  76. package/dist/lib/nodes/tensors/broadcast.d.ts +18 -0
  77. package/dist/lib/nodes/tensors/broadcast.js +92 -0
  78. package/dist/lib/nodes/tensors/tensor.d.ts +13 -0
  79. package/dist/lib/nodes/tensors/tensor.js +34 -0
  80. package/dist/lib/python/lift.d.ts +51 -0
  81. package/dist/lib/python/lift.js +155 -0
  82. package/dist/lib/python/py/pie.py +303 -0
  83. package/dist/lib/python/py/pie_mpl.py +15 -0
  84. package/dist/lib/python/py/show_figures.py +5 -0
  85. package/dist/lib/python/runner.d.ts +36 -0
  86. package/dist/lib/python/runner.js +221 -0
  87. package/dist/lib/python/worker.d.ts +1 -0
  88. package/dist/lib/python/worker.js +111 -0
  89. package/dist/lib/ui/UiLayer.d.ts +2 -0
  90. package/dist/lib/ui/UiLayer.jsx +15 -0
  91. package/dist/lib/ui/UiView.d.ts +23 -0
  92. package/dist/lib/ui/UiView.jsx +56 -0
  93. package/dist/lib/ui/components/checkboxes.d.ts +10 -0
  94. package/dist/lib/ui/components/checkboxes.jsx +30 -0
  95. package/dist/lib/ui/components/latex.d.ts +8 -0
  96. package/dist/lib/ui/components/latex.jsx +41 -0
  97. package/dist/lib/ui/components/radio.d.ts +6 -0
  98. package/dist/lib/ui/components/radio.jsx +19 -0
  99. package/dist/lib/ui/components/slider.d.ts +8 -0
  100. package/dist/lib/ui/components/slider.jsx +7 -0
  101. package/dist/lib/ui/components/textbox.d.ts +5 -0
  102. package/dist/lib/ui/components/textbox.jsx +21 -0
  103. package/dist/lib/ui/dragUi.d.ts +10 -0
  104. package/dist/lib/ui/dragUi.js +129 -0
  105. package/dist/lib/ui/nodeHandle.d.ts +15 -0
  106. package/dist/lib/ui/nodeHandle.js +37 -0
  107. package/dist/lib/ui/registry.d.ts +10 -0
  108. package/dist/lib/ui/registry.js +42 -0
  109. package/dist/runtime.css +696 -0
  110. package/dist/runtime.d.ts +9 -0
  111. package/dist/runtime.jsx +6 -0
  112. package/init/index.js +2 -2
  113. package/init/site-agents.md +2 -1
  114. package/package.json +15 -6
  115. package/runtime-agents.md +146 -0
  116. package/src/app.css +7 -665
  117. package/src/lib/customModules.ts +30 -0
  118. package/src/lib/markdown/compile.ts +49 -0
  119. package/src/lib/markdown/components/PiePage.tsx +48 -0
  120. package/src/lib/markdown/features/build.ts +15 -6
  121. package/src/lib/markdown/features/sidebar/View.tsx +4 -2
  122. package/src/lib/markdown/features/tags/build.ts +6 -3
  123. package/src/lib/markdown/pages.ts +1 -9
  124. package/src/lib/markdown/vitePlugin.ts +4 -8
  125. package/src/lib/nodes/functions/registry.ts +30 -21
  126. package/src/lib/nodes/functions/sideEffects.ts +14 -8
  127. package/src/lib/nodes/functions/vitePlugin.ts +8 -10
  128. package/src/lib/nodes/state/Node.ts +27 -19
  129. package/src/lib/siteModules.ts +13 -0
  130. package/src/lib/ui/dragUi.ts +4 -2
  131. package/src/lib/ui/registry.ts +35 -14
  132. package/src/page.css +664 -0
  133. package/src/routes/[...slug].tsx +1 -0
  134. package/src/runtime.css +29 -0
  135. package/src/runtime.tsx +15 -0
@@ -0,0 +1,62 @@
1
+ import { boolean } from '../../frontmatter';
2
+ /** Heading levels listed: `##` and `###`. */
3
+ const LEVELS = [2, 3];
4
+ /** `The $\nabla$ operator` -> `the-nabla-operator`. */
5
+ function slug(text) {
6
+ return text.toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, '').trim().replace(/\s+/g, '-') || 'section';
7
+ }
8
+ /** The entries as a list. Each `###` is nested under the `##` before it; a `###` before any `##` stands on its own. */
9
+ function tocHtml(entries) {
10
+ const groups = [];
11
+ for (const entry of entries) {
12
+ const last = groups.at(-1);
13
+ if (entry.depth === 3 && last?.entry.depth === 2)
14
+ last.children.push(entry);
15
+ else
16
+ groups.push({ entry, children: [] });
17
+ }
18
+ const link = (e) => `<a href="#${e.id}">${e.html}</a>`;
19
+ const items = groups.map(({ entry, children }) => {
20
+ const sublist = children.length === 0 ? '' : `<ul>${children.map(c => `<li>${link(c)}</li>`).join('')}</ul>`;
21
+ return `<li>${link(entry)}${sublist}</li>`;
22
+ });
23
+ return `<nav class="toc"><ul>${items.join('')}</ul></nav>\n`;
24
+ }
25
+ /**
26
+ * `toc: true`: a table of contents of the page's `##` and `###` headings, after its leading `#` title,
27
+ * or at the very start if the page doesn't begin with one. Every heading gets an `id` to link to.
28
+ * No list when the page has no such heading.
29
+ */
30
+ export const toc = {
31
+ field: boolean(false),
32
+ build: on => (on ? true : undefined),
33
+ // The list is made while the page renders, from the headings as they're rendered, so each entry's text
34
+ // and `id` match its heading's.
35
+ markdown() {
36
+ const entries = [];
37
+ const used = new Map();
38
+ return {
39
+ renderer: {
40
+ heading(token) {
41
+ const base = slug(token.text);
42
+ const count = (used.get(base) ?? 0) + 1;
43
+ used.set(base, count);
44
+ const id = count === 1 ? base : `${base}-${count}`;
45
+ const html = this.parser.parseInline(token.tokens);
46
+ if (LEVELS.includes(token.depth))
47
+ entries.push({ depth: token.depth, id, html });
48
+ return `<h${token.depth} id="${id}">${html}</h${token.depth}>\n`;
49
+ },
50
+ },
51
+ hooks: {
52
+ postprocess(html) {
53
+ if (entries.length === 0)
54
+ return html;
55
+ const title = /^\s*<h1[\s>][\s\S]*?<\/h1>\n?/.exec(html);
56
+ const at = title ? title[0].length : 0;
57
+ return html.slice(0, at) + tocHtml(entries) + html.slice(at);
58
+ },
59
+ },
60
+ };
61
+ },
62
+ };
@@ -0,0 +1,4 @@
1
+ import type { JSX } from 'solid-js';
2
+ import type { FeatureData } from './build';
3
+ /** `body` wrapped in the view of every feature that is on for the page, the first in `VIEWS` outermost. */
4
+ export declare function wrapPage(data: FeatureData, body: JSX.Element): JSX.Element;
@@ -0,0 +1,11 @@
1
+ import { GlossaryView } from './glossary/View';
2
+ import { SidebarView } from './sidebar/View';
3
+ /** Every feature's view, by key, outermost first. A feature with no view, like `toc`, is left out. */
4
+ const VIEWS = {
5
+ sidebar: SidebarView,
6
+ glossary: GlossaryView,
7
+ };
8
+ /** `body` wrapped in the view of every feature that is on for the page, the first in `VIEWS` outermost. */
9
+ export function wrapPage(data, body) {
10
+ return Object.entries(VIEWS).reduceRight((inner, [key, View]) => (data[key] === undefined ? inner : <View data={data[key]}>{inner}</View>), body);
11
+ }
@@ -0,0 +1,44 @@
1
+ /** How one field is read: its value when absent, and how to check the raw text. */
2
+ export interface Field<T> {
3
+ default: T;
4
+ /** Throws a message that reads after the field name, e.g. "must be one of …". */
5
+ parse: (raw: string) => T;
6
+ }
7
+ export type Values<F extends Record<string, Field<unknown>>> = {
8
+ [K in keyof F]: F[K]['default'];
9
+ };
10
+ export declare function text(fallback: string): Field<string>;
11
+ /** `true` or `false`. */
12
+ export declare function boolean(fallback: boolean): Field<boolean>;
13
+ /** A path to a `.md` file, or `none`. Empty when absent. */
14
+ export declare function markdownFile(): Field<string>;
15
+ /**
16
+ * Words written `#tag`, separated by spaces or commas, lowercased and without repeats. Other words are ignored.
17
+ * A tag has only letters, numbers, `-`, `_` and `+`: it's also a URL, and prerendering can't reach one with `/`, `?` or `.`.
18
+ */
19
+ export declare function hashtags(): Field<string[]>;
20
+ /** Every frontmatter field a page can set. Keys not listed here are ignored. */
21
+ declare const FIELDS: {
22
+ canvas: Field<"bottom" | "left" | "none" | "right" | "top">;
23
+ title: Field<string>;
24
+ description: Field<string>;
25
+ };
26
+ export type Frontmatter = Values<typeof FIELDS>;
27
+ export type CanvasSide = Frontmatter['canvas'];
28
+ /**
29
+ * Reads flat `key: value` lines, skipping blank ones. Values may be wrapped in single or double quotes.
30
+ * Shared by frontmatter and `site.yml`.
31
+ */
32
+ export declare function parseKeyValues(text: string): Record<string, string>;
33
+ /** Reads each of `fields` from `raw`, using its default when absent. Unknown keys are ignored. */
34
+ export declare function readFields<F extends Record<string, Field<unknown>>>(fields: F, raw: Record<string, string>): Values<F>;
35
+ /**
36
+ * Reads the frontmatter of the file at `path`. `raw`: every key it sets, unchecked, for the features to read.
37
+ * Throws, naming `path`, on a malformed block or a bad value.
38
+ */
39
+ export declare function parseFrontmatter(path: string, markdown: string): {
40
+ frontmatter: Frontmatter;
41
+ raw: Record<string, string>;
42
+ body: string;
43
+ };
44
+ export {};
@@ -0,0 +1,109 @@
1
+ function oneOf(values, fallback) {
2
+ return {
3
+ default: fallback,
4
+ parse(raw) {
5
+ if (!values.includes(raw)) {
6
+ throw new Error(`must be one of ${values.join(', ')}, got ${JSON.stringify(raw)}`);
7
+ }
8
+ return raw;
9
+ },
10
+ };
11
+ }
12
+ export function text(fallback) {
13
+ return { default: fallback, parse: raw => raw };
14
+ }
15
+ /** `true` or `false`. */
16
+ export function boolean(fallback) {
17
+ return {
18
+ default: fallback,
19
+ parse(raw) {
20
+ if (raw !== 'true' && raw !== 'false')
21
+ throw new Error(`must be true or false, got ${JSON.stringify(raw)}`);
22
+ return raw === 'true';
23
+ },
24
+ };
25
+ }
26
+ /** A path to a `.md` file, or `none`. Empty when absent. */
27
+ export function markdownFile() {
28
+ return {
29
+ default: '',
30
+ parse(raw) {
31
+ if (raw !== 'none' && !raw.endsWith('.md'))
32
+ throw new Error(`must be a .md file or none, got ${JSON.stringify(raw)}`);
33
+ return raw;
34
+ },
35
+ };
36
+ }
37
+ /**
38
+ * Words written `#tag`, separated by spaces or commas, lowercased and without repeats. Other words are ignored.
39
+ * A tag has only letters, numbers, `-`, `_` and `+`: it's also a URL, and prerendering can't reach one with `/`, `?` or `.`.
40
+ */
41
+ export function hashtags() {
42
+ return {
43
+ default: [],
44
+ parse(raw) {
45
+ const words = raw.split(/[\s,]+/).map(word => /^#([\p{L}\p{N}_+-]+)$/u.exec(word)?.[1].toLowerCase());
46
+ return [...new Set(words.filter(tag => tag !== undefined))];
47
+ },
48
+ };
49
+ }
50
+ /** Every frontmatter field a page can set. Keys not listed here are ignored. */
51
+ const FIELDS = {
52
+ canvas: oneOf(['left', 'right', 'top', 'bottom', 'none'], 'none'),
53
+ // Empty: the tab shows the site title alone.
54
+ title: text(''),
55
+ // Empty: `site.yml`'s `description`.
56
+ description: text(''),
57
+ };
58
+ /**
59
+ * Reads flat `key: value` lines, skipping blank ones. Values may be wrapped in single or double quotes.
60
+ * Shared by frontmatter and `site.yml`.
61
+ */
62
+ export function parseKeyValues(text) {
63
+ const raw = {};
64
+ for (const line of text.split(/\r?\n/)) {
65
+ if (line.trim() === '')
66
+ continue;
67
+ const kv = /^([A-Za-z_][\w-]*)[ \t]*:[ \t]*(.*?)[ \t]*$/.exec(line);
68
+ if (!kv)
69
+ throw new Error(`line is not \`key: value\`: ${JSON.stringify(line)}`);
70
+ const [, key, value] = kv;
71
+ if (Object.hasOwn(raw, key))
72
+ throw new Error(`key \`${key}\` appears twice`);
73
+ raw[key] = /^(["']).*\1$/.test(value) ? value.slice(1, -1) : value;
74
+ }
75
+ return raw;
76
+ }
77
+ /** Reads each of `fields` from `raw`, using its default when absent. Unknown keys are ignored. */
78
+ export function readFields(fields, raw) {
79
+ const values = {};
80
+ for (const [key, field] of Object.entries(fields)) {
81
+ try {
82
+ values[key] = Object.hasOwn(raw, key) ? field.parse(raw[key]) : field.default;
83
+ }
84
+ catch (e) {
85
+ throw new Error(`\`${key}\` ${e.message}`);
86
+ }
87
+ }
88
+ return values;
89
+ }
90
+ /** Splits off a `---` block at the very start of the markdown. No block: no fields, whole markdown as body. */
91
+ function splitFrontmatter(markdown) {
92
+ const match = /^---\r?\n([\s\S]*?)\r?\n?^---[ \t]*(?:\r?\n|$)/m.exec(markdown);
93
+ if (!match || match.index !== 0)
94
+ return { raw: {}, body: markdown };
95
+ return { raw: parseKeyValues(match[1]), body: markdown.slice(match[0].length) };
96
+ }
97
+ /**
98
+ * Reads the frontmatter of the file at `path`. `raw`: every key it sets, unchecked, for the features to read.
99
+ * Throws, naming `path`, on a malformed block or a bad value.
100
+ */
101
+ export function parseFrontmatter(path, markdown) {
102
+ try {
103
+ const { raw, body } = splitFrontmatter(markdown);
104
+ return { frontmatter: readFields(FIELDS, raw), raw, body };
105
+ }
106
+ catch (e) {
107
+ throw new Error(`${path}: ${e.message}`);
108
+ }
109
+ }
@@ -0,0 +1,6 @@
1
+ import { type MarkedExtension } from 'marked';
2
+ export declare function escapeHtml(text: string): string;
3
+ /** `extensions`: markdown syntax the page's features add. */
4
+ export declare function renderMarkdown(markdown: string, extensions?: MarkedExtension[]): string;
5
+ /** One line of markdown as HTML, without the `<p>` around it. */
6
+ export declare function renderInline(markdown: string): string;
@@ -0,0 +1,95 @@
1
+ import katex from 'katex';
2
+ import { Marked, Renderer } from 'marked';
3
+ import { pythonLanguage } from '@codemirror/lang-python';
4
+ import { classHighlighter, highlightCode } from '@lezer/highlight';
5
+ function renderMath(formula, displayMode) {
6
+ return katex.renderToString(formula, { displayMode, throwOnError: false });
7
+ }
8
+ export function escapeHtml(text) {
9
+ return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
10
+ }
11
+ /** Python as HTML, with `tok-*` classes on each token. app.css colors them like the editor. */
12
+ function highlightPython(code) {
13
+ let html = '';
14
+ highlightCode(code, pythonLanguage.parser.parse(code), classHighlighter, (text, classes) => {
15
+ html += classes ? `<span class="${classes}">${escapeHtml(text)}</span>` : escapeHtml(text);
16
+ }, () => {
17
+ html += '\n';
18
+ });
19
+ return html;
20
+ }
21
+ const BASE = {
22
+ extensions: [
23
+ {
24
+ // `$$…$$` that fills its own lines.
25
+ name: 'mathblock',
26
+ level: 'block',
27
+ start(src) {
28
+ const at = src.indexOf('\n$$');
29
+ return at === -1 ? undefined : at + 1;
30
+ },
31
+ tokenizer(src) {
32
+ const match = /^\$\$([^$]+)\$\$[ \t]*(?:\n|$)/.exec(src);
33
+ if (!match)
34
+ return undefined;
35
+ return { type: 'mathblock', raw: match[0], formula: match[1].trim() };
36
+ },
37
+ renderer(token) {
38
+ return `${renderMath(token.formula, true)}\n`;
39
+ },
40
+ },
41
+ {
42
+ // `$…$`, and `$$…$$` inside a line of text.
43
+ name: 'math',
44
+ level: 'inline',
45
+ start(src) {
46
+ const at = src.indexOf('$');
47
+ return at === -1 ? undefined : at;
48
+ },
49
+ tokenizer(src) {
50
+ const match = /^\$\$([^$]+)\$\$/.exec(src) ?? /^\$([^$]+)\$/.exec(src);
51
+ if (!match)
52
+ return undefined;
53
+ return {
54
+ type: 'math',
55
+ raw: match[0],
56
+ formula: match[1].trim(),
57
+ displayMode: match[0].startsWith('$$'),
58
+ };
59
+ },
60
+ renderer(token) {
61
+ return renderMath(token.formula, token.displayMode);
62
+ },
63
+ },
64
+ ],
65
+ renderer: {
66
+ // ```python-editor collapsed: marked keeps only the first word, so mark the block for the editor here.
67
+ // ```python: color each token here, at build time.
68
+ code(token) {
69
+ const [lang, ...flags] = (token.lang ?? '').split(/\s+/);
70
+ if (lang === 'python') {
71
+ const code = token.text.replace(/\n$/, '') + '\n';
72
+ return `<pre><code class="language-python">${highlightPython(code)}</code></pre>\n`;
73
+ }
74
+ if (lang !== 'python-editor' || !flags.includes('collapsed'))
75
+ return false;
76
+ return new Renderer().code(token).replace('<code ', '<code data-collapsed ');
77
+ },
78
+ },
79
+ };
80
+ const marked = new Marked(BASE);
81
+ /** `extensions`: markdown syntax the page's features add. */
82
+ export function renderMarkdown(markdown, extensions = []) {
83
+ const parser = extensions.length === 0 ? marked : new Marked(BASE, ...extensions);
84
+ try {
85
+ return parser.parse(markdown);
86
+ }
87
+ catch (e) {
88
+ // marked adds "Please report this to …" to every error, even a feature's, e.g. an unknown glossary term.
89
+ throw new Error(e.message.replace(/\nPlease report this to .*$/, ''));
90
+ }
91
+ }
92
+ /** One line of markdown as HTML, without the `<p>` around it. */
93
+ export function renderInline(markdown) {
94
+ return marked.parseInline(markdown);
95
+ }
@@ -0,0 +1,14 @@
1
+ /** One animated change, e.g. a point moving. */
2
+ export interface Track {
3
+ /** Shows the change at `t`, from 0 (start) to 1 (end). */
4
+ seek: (t: number) => void;
5
+ /** True once the node was replaced or removed: the track no longer changes anything. */
6
+ stopped: () => boolean;
7
+ }
8
+ /**
9
+ * Runs before an animation plays, e.g. to get every value its steps need. `visitSteps` shows each step
10
+ * in turn, then goes back to the start. Can return a function to call when the animation ends.
11
+ */
12
+ export type Prepare = (visitSteps: () => void) => Promise<(() => void) | void>;
13
+ /** Plays `tracks` together, after `prepare`. Resolves when they end, or once every track is stopped. */
14
+ export declare function play(tracks: Track[], prepare?: Prepare): Promise<void>;
@@ -0,0 +1,34 @@
1
+ import { batch } from 'solid-js';
2
+ /** How long an animation takes. */
3
+ const ANIMATION_MS = 500;
4
+ /** The steps an animation plays: one per frame at 60 frames a second. Each frame shows the nearest step. */
5
+ const STEPS = 30;
6
+ /** Slow at the start and end, fast in the middle. `t` and the result go from 0 to 1. */
7
+ const easeInOut = (t) => (t < 0.5 ? 2 * t * t : 1 - 2 * (1 - t) ** 2);
8
+ /** Plays `tracks` together, after `prepare`. Resolves when they end, or once every track is stopped. */
9
+ export async function play(tracks, prepare) {
10
+ const seek = (step) => batch(() => {
11
+ const t = easeInOut(step / STEPS);
12
+ for (const track of tracks)
13
+ track.seek(t);
14
+ });
15
+ const end = await prepare?.(() => {
16
+ for (let step = 0; step <= STEPS; step++)
17
+ seek(step);
18
+ seek(0);
19
+ });
20
+ await new Promise((resolve) => {
21
+ const start = performance.now();
22
+ requestAnimationFrame(function frame() {
23
+ if (tracks.every(track => track.stopped()))
24
+ return resolve();
25
+ const step = Math.min(Math.round((performance.now() - start) / ANIMATION_MS * STEPS), STEPS);
26
+ seek(step);
27
+ if (step < STEPS)
28
+ requestAnimationFrame(frame);
29
+ else
30
+ resolve();
31
+ });
32
+ });
33
+ end?.();
34
+ }
@@ -0,0 +1,20 @@
1
+ import { JSX } from 'solid-js';
2
+ interface CenteredGridProps {
3
+ /** Canvas size in viewBox units. */
4
+ width: number;
5
+ height: number;
6
+ /** Pixels per grid unit. */
7
+ unit: number;
8
+ /** Opacity multiplier for the grid lines and axes (0 hides them). Defaults to 1. */
9
+ gridOpacity?: number;
10
+ /** Solid fill painted behind the grid. Defaults to transparent (no rect). */
11
+ backgroundColor?: string;
12
+ /** Position of the origin in the viewBox. Defaults to the center of the canvas. */
13
+ origin?: {
14
+ x: number;
15
+ y: number;
16
+ };
17
+ children: JSX.Element;
18
+ }
19
+ export declare function CenteredGrid(props: CenteredGridProps): JSX.Element;
20
+ export {};
@@ -0,0 +1,44 @@
1
+ import { createMemo, Show } from 'solid-js';
2
+ import { MIN_GRID_UNIT } from '../state/NodeStore';
3
+ const GRID_OPACITY = 0.15;
4
+ const AXIS_OPACITY = 0.4;
5
+ export function CenteredGrid(props) {
6
+ const originX = () => props.origin?.x ?? props.width / 2;
7
+ const originY = () => props.origin?.y ?? props.height / 2;
8
+ // Local (post-transform) extents of the canvas relative to the origin.
9
+ const extents = createMemo(() => ({
10
+ xLeft: -originX(),
11
+ xRight: props.width - originX(),
12
+ yBottom: -(props.height - originY()),
13
+ yTop: originY(),
14
+ }));
15
+ const gridLines = createMemo(() => {
16
+ const lines = [];
17
+ const { xLeft, xRight, yBottom, yTop } = extents();
18
+ if (props.unit >= MIN_GRID_UNIT) {
19
+ // Vertical lines (every 1 unit)
20
+ for (let x = Math.ceil(xLeft); x <= Math.floor(xRight); x += 1) {
21
+ if (x === 0)
22
+ continue;
23
+ lines.push(<line x1={x} y1={yBottom} x2={x} y2={yTop} stroke="currentColor" stroke-width={1 / props.unit} opacity={GRID_OPACITY}/>);
24
+ }
25
+ // Horizontal lines (every 1 unit)
26
+ for (let y = Math.ceil(yBottom); y <= Math.floor(yTop); y += 1) {
27
+ if (y === 0)
28
+ continue;
29
+ lines.push(<line x1={xLeft} y1={y} x2={xRight} y2={y} stroke="currentColor" stroke-width={1 / props.unit} opacity={GRID_OPACITY}/>);
30
+ }
31
+ }
32
+ // Axes (thicker lines)
33
+ lines.push(<line x1={xLeft} y1={0} x2={xRight} y2={0} stroke="currentColor" stroke-width={2 / props.unit} opacity={AXIS_OPACITY}/>);
34
+ lines.push(<line x1={0} y1={yBottom} x2={0} y2={yTop} stroke="currentColor" stroke-width={2 / props.unit} opacity={AXIS_OPACITY}/>);
35
+ return lines;
36
+ });
37
+ return (<g transform={`translate(${originX()}, ${originY()}) scale(1, -1)`}>
38
+ <Show when={props.backgroundColor}>
39
+ <rect x={extents().xLeft} y={extents().yBottom} width={props.width} height={props.height} fill={props.backgroundColor}/>
40
+ </Show>
41
+ <g opacity={props.gridOpacity ?? 1}>{gridLines()}</g>
42
+ {props.children}
43
+ </g>);
44
+ }
@@ -0,0 +1,7 @@
1
+ import { JSX } from 'solid-js';
2
+ import { NodeStore } from '../state/NodeStore';
3
+ interface NodeCanvasProps {
4
+ store: NodeStore;
5
+ }
6
+ export declare function NodeCanvas(props: NodeCanvasProps): JSX.Element;
7
+ export {};
@@ -0,0 +1,50 @@
1
+ import { For, createMemo } from 'solid-js';
2
+ import { getNodeDefinition } from '../state/Node';
3
+ import { CenteredGrid } from './CenteredGrid';
4
+ import { useCanvasResize } from '../hooks/useCanvasResize';
5
+ import { useCanvasGestures } from '../hooks/useCanvasGestures';
6
+ export function NodeCanvas(props) {
7
+ let svgContainerRef;
8
+ useCanvasResize(() => svgContainerRef, props.store);
9
+ useCanvasGestures(() => svgContainerRef, props.store);
10
+ // Canvas size in grid units: the viewBox maps one unit to `unit` pixels.
11
+ const viewWidth = () => props.store.canvasBounds().width / props.store.unit();
12
+ const viewHeight = () => props.store.canvasBounds().height / props.store.unit();
13
+ // One pass over the store, partitioned into the two draw layers.
14
+ const layers = createMemo(() => {
15
+ const geometry = [];
16
+ const points = [];
17
+ for (const nodeSignal of Object.values(props.store.nodes)) {
18
+ if (!nodeSignal)
19
+ continue;
20
+ const node = nodeSignal.signal();
21
+ if (!node || node.type === 'Dummy' || node.hidden)
22
+ continue;
23
+ if (node.type === 'Point')
24
+ points.push(nodeSignal);
25
+ else
26
+ geometry.push(nodeSignal);
27
+ }
28
+ return { geometry, points };
29
+ });
30
+ const nodeGroup = (nodeSignal) => {
31
+ const node = createMemo(() => nodeSignal?.signal());
32
+ // The element is rebuilt only when the type changes.
33
+ const type = createMemo(() => node()?.type);
34
+ return (<g data-node-id={node()?.id}>
35
+ {/* The browser shows the `<title>` as a tooltip when hovering any shape in the group. */}
36
+ <title>{node()?.id}</title>
37
+ {type() && (getNodeDefinition(type())?.render?.(node, props.store.unit) ?? null)}
38
+ </g>);
39
+ };
40
+ return (<div class="node-canvas" ref={svgContainerRef}>
41
+ <svg viewBox={`0 0 ${viewWidth()} ${viewHeight()}`}>
42
+ <CenteredGrid width={viewWidth()} height={viewHeight()} unit={props.store.unit()} gridOpacity={props.store.gridOpacity()} backgroundColor={props.store.canvasColor()} origin={props.store.origin()}>
43
+ {/* Step 1: Draw non-`Point` nodes first */}
44
+ <For each={layers().geometry}>{(nodeSignal) => nodeGroup(nodeSignal)}</For>
45
+ {/* Step 2: Draw `Point` nodes above geometry */}
46
+ <For each={layers().points}>{(nodeSignal) => nodeGroup(nodeSignal)}</For>
47
+ </CenteredGrid>
48
+ </svg>
49
+ </div>);
50
+ }
@@ -0,0 +1,27 @@
1
+ import { NodeStore } from './state/NodeStore';
2
+ import { type Prepare } from './animation';
3
+ /** One argument of a Python call: a number, a string, a handle to an existing node, or a nested list of these. */
4
+ export type Arg = number | string | {
5
+ id: string;
6
+ } | Arg[];
7
+ export interface ExecuteResult {
8
+ id: string;
9
+ type: string;
10
+ /** Only for an Array. */
11
+ shape?: number[];
12
+ itemType?: string;
13
+ }
14
+ /** Checks `out`, the id asked for the output node of a call with arguments `args`. */
15
+ export declare function checkOut(keyword: string, out: unknown, args: Arg[]): void;
16
+ /** The keyword arguments of a Python call. */
17
+ export interface CallOptions {
18
+ /** The id for the output node. Without it the id is generated. */
19
+ out?: string;
20
+ hidden?: boolean;
21
+ fill?: string;
22
+ stroke?: string;
23
+ /** Only for `animatable` side effects: numbers move to their new values instead of jumping. */
24
+ animate?: boolean;
25
+ }
26
+ /** `prepare`: runs before an animation the call starts plays. */
27
+ export declare function execute(store: NodeStore, keyword: string, args: Arg[], { out, hidden, fill, stroke, animate }?: CallOptions, prepare?: Prepare): Promise<ExecuteResult>;