@tinyvolt/pie 0.3.0 → 0.6.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/README.md CHANGED
@@ -35,6 +35,14 @@ The site installs the app as the `@tinyvolt/pie` package. To update it:
35
35
  npm install @tinyvolt/pie@latest
36
36
  ```
37
37
 
38
+ With pnpm:
39
+
40
+ ```sh
41
+ pnpm add @tinyvolt/pie@latest
42
+ ```
43
+
44
+ Updating also refreshes the site's `AGENTS.md` and `vite.config.ts`. If either differs from the new version, the old one is saved as `AGENTS.old.md` or `vite.config.old.ts`. Copy back anything you want to keep.
45
+
38
46
  Requires Node 24. Package: [@tinyvolt/pie](https://www.npmjs.com/package/@tinyvolt/pie).
39
47
 
40
48
  ## Developing pie-ssg
package/init/index.js CHANGED
@@ -74,8 +74,12 @@ const pkg = {
74
74
  dependencies: { [app.name]: app.version, ...app.peerDependencies },
75
75
  devDependencies: { '@types/node': app.devDependencies['@types/node'], typescript: app.devDependencies.typescript },
76
76
  engines: app.engines,
77
+ // npm blocks dependencies' install scripts unless allowed. This lets `init/postinstall.js` refresh files on upgrade.
78
+ allowScripts: { [app.name]: true },
77
79
  };
78
80
  fs.writeFileSync(path.join(target, 'package.json'), JSON.stringify(pkg, null, 2) + '\n');
81
+ // The same for pnpm.
82
+ fs.writeFileSync(path.join(target, 'pnpm-workspace.yaml'), `allowBuilds:\n "${app.name}": true\n`);
79
83
 
80
84
  const usesPnpm = (process.env.npm_config_user_agent ?? '').startsWith('pnpm');
81
85
  console.log(`
@@ -0,0 +1,38 @@
1
+ // Runs after a site installs or upgrades `@tinyvolt/pie`: refreshes the files below from this version.
2
+ // A changed file is first backed up, so a user's edits are kept.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+
6
+ const root = path.resolve(import.meta.dirname, '..');
7
+
8
+ // Package path -> [path in the site, backup path in the site].
9
+ const FILES = {
10
+ 'init/site-agents.md': ['AGENTS.md', 'AGENTS.old.md'],
11
+ 'init/site-vite.config.ts': ['vite.config.ts', 'vite.config.old.ts'],
12
+ };
13
+
14
+ /** The folder of the nearest `package.json` at or above `dir`, or null. */
15
+ function findProject(dir) {
16
+ for (let d = dir; ; d = path.dirname(d)) {
17
+ if (fs.existsSync(path.join(d, 'package.json'))) return d;
18
+ if (d === path.dirname(d)) return null;
19
+ }
20
+ }
21
+
22
+ // `INIT_CWD` is where the install command was run. Skip anything that isn't a site depending on this package,
23
+ // such as this repo's own `pnpm install` or a one-off `npx @tinyvolt/pie init`.
24
+ const app = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
25
+ const site = process.env.INIT_CWD && findProject(process.env.INIT_CWD);
26
+ const sitePkg = site && JSON.parse(fs.readFileSync(path.join(site, 'package.json'), 'utf8'));
27
+ if (!sitePkg?.dependencies?.[app.name] && !sitePkg?.devDependencies?.[app.name]) process.exit(0);
28
+
29
+ for (const [from, [to, backup]] of Object.entries(FILES)) {
30
+ const target = path.join(site, to);
31
+ // A file the user removed stays removed.
32
+ if (!fs.existsSync(target)) continue;
33
+ const fresh = fs.readFileSync(path.join(root, from));
34
+ if (fresh.equals(fs.readFileSync(target))) continue;
35
+ fs.copyFileSync(target, path.join(site, backup));
36
+ fs.writeFileSync(target, fresh);
37
+ console.log(`@tinyvolt/pie: updated ${to}; the old one is in ${backup}.`);
38
+ }
@@ -16,7 +16,7 @@ npm run preview # preview the build with vite
16
16
 
17
17
  | Folder / file | What it holds |
18
18
  | --- | --- |
19
- | `pages/` | Markdown pages. `pages/a/b.md` is served at `/a/b`. |
19
+ | `pages/` | Markdown pages. `pages/a/b.md` is served at `/a/b`. A file whose name starts with `_`, e.g. `pages/_topics.md`, gets no URL; use it as a sidebar. |
20
20
  | `functions/` | Your own TypeScript functions, called from Python as `pie.<keyword>(...)`. |
21
21
  | `nodes/` | Your own node types: what a node holds and how it is drawn. |
22
22
  | `layouts/` | Optional overrides: `header.tsx` (top of every page) and `index.tsx` (homepage, `/`). |
@@ -34,10 +34,11 @@ Flat `key: value` lines. Values may be quoted. A key may appear only once.
34
34
  - `title` (required): shown in the header and in every browser tab title.
35
35
  - `url`: where the site is deployed, e.g. `https://example.com`. Needed for `sitemap.xml`, `robots.txt`, canonical links and `og:url`; without it the build skips them and warns.
36
36
  - `description`: shown in search results and link previews for a page with no `description` of its own.
37
+ - `sidebar`, `toc`: the value for every page that doesn't set the key itself (see "Pages"). A `sidebar` path here is relative to the project root, e.g. `sidebar: pages/_topics.md`.
37
38
 
38
39
  ## Pages
39
40
 
40
- A page is a `.md` file under `pages/`. `/pages` lists every page.
41
+ A page is a `.md` file under `pages/`. `/pages` lists every page. A file whose name starts with `_` is not a page: it gets no URL and isn't listed.
41
42
 
42
43
  Optional frontmatter at the very top, as flat `key: value` lines:
43
44
 
@@ -51,6 +52,11 @@ canvas: left
51
52
  - `title`: the tab title. Empty means the tab shows the site title alone.
52
53
  - `description`: shown in search results and link previews. Empty means `site.yml`'s `description`.
53
54
  - `canvas`: `left`, `right`, `top`, `bottom` or `none` (default). Adds a canvas on that side of the page.
55
+ - `sidebar`: a `.md` file shown in a collapsible sidebar on the left, e.g. `sidebar: _topics.md`. The path is relative to the page's file. `none`: no sidebar, even when `site.yml` sets one. Left out: `site.yml`'s `sidebar`.
56
+ - It starts collapsed. A button opens it, and the rest of the page shrinks to make room. A new page starts with it collapsed.
57
+ - On screens narrower than `--sidebar-drawer-below` (768px by default), it opens over the page instead. Tapping outside it or on one of its links closes it.
58
+ - Its frontmatter is ignored. Its Python editors share variables only with each other, and have no canvas: a `pie.*` call there raises "this page has no canvas".
59
+ - `toc`: `true` or `false`. `true` adds a table of contents of the page's `##` and `###` headings, after its leading `#` title, or at the very start if it has none. Each `###` is nested under the `##` before it. Every heading gets an `id`, and duplicate headings get `-2`, `-3`, …. No list if the page has no `##` or `###`. Left out: `site.yml`'s `toc`, else `false`.
54
60
 
55
61
  Other keys are ignored. A bad value fails the build, and shows an error screen in dev.
56
62
 
@@ -71,7 +77,7 @@ pie.circle(a, r)
71
77
  ````
72
78
 
73
79
  - Python runs in the browser with Pyodide 0.28.2. `pie` is already imported.
74
- - All editors on one page share the same Python variables and the same canvas.
80
+ - All editors on one page share the same Python variables and the same canvas. Editors in the page's sidebar are separate: see `sidebar` under "Pages".
75
81
  - `import numpy`, `scipy`, `matplotlib` and other [Pyodide packages](https://pyodide.org/en/0.28.2/usage/packages-in-pyodide.html) load on first use.
76
82
  - `plt.show()` shows matplotlib figures under the editor.
77
83
  - `` ```python-editor collapsed `` starts the editor collapsed: only its toolbar shows until the reader expands it. Other words after `python-editor` are ignored.
@@ -88,16 +94,19 @@ pie.scalar(3, out='r') # the circle above now has radius 3
88
94
 
89
95
  Common mistake: `center = pie.point(1, 2)` does not give the node the id `center`. It gets an automatic id. Use `pie.point(1, 2, out='center')`.
90
96
 
97
+ `pie.get_node('<id>')` returns the existing node with that id, e.g. `c = pie.get_node('center')`, in any editor on the page. It makes no new node. An unknown id raises an error. It can't be called inside a lifted function.
98
+
91
99
  `fill='<color>'` and `stroke='<color>'` color a node, e.g. `pie.circle(a, r, fill='orange', stroke='#333')`:
92
100
 
93
101
  - A color is any CSS color (`'red'`, `'#ff0000'`, `'rgb(255, 0, 0)'`) or `'none'`. A bad color raises an error.
94
102
  - Every node the call makes gets the colors, including extra nodes such as the center point of `ellipse_from_foci`.
95
103
  - A node shows only the colors its render function draws with. A point uses only `fill`, a line only `stroke`. For `partial`'s arrow, `stroke` colors the line and `fill` the head.
96
104
 
97
- There are three system nodes:
105
+ There are five system nodes:
98
106
  - `unit`: a scalar holding the pixels per grid unit (default 50). Changing it changes the grid unit, e.g. `pie.scalar(80, out='unit')`.
99
107
  - `gridOpacity`: a scalar that multiplies the opacity of the grid lines and axes (default 1; 0 hides them), e.g. `pie.scalar(0.5, out='gridOpacity')`.
100
108
  - `canvasColor`: a text holding a CSS color for the canvas background (default `''`: no background), e.g. `pie.text('#111', out='canvasColor')`.
109
+ - `originX`, `originY`: scalars holding where the origin sits, in grid units from the canvas center (default 0; positive is right and up), e.g. `pie.scalar(1, out='originX')`. Every node moves with the origin.
101
110
 
102
111
  Built-in functions:
103
112
 
@@ -125,7 +134,7 @@ These change existing nodes instead of making a new one. They run once, when cal
125
134
 
126
135
  | Call | Does |
127
136
  | --- | --- |
128
- | `pie.clear()` | removes every node and resets the system nodes: `unit` (pixels per grid unit) to 50, `gridOpacity` to 1, `canvasColor` to `''` |
137
+ | `pie.clear()` | removes every node and resets the system nodes: `unit` (pixels per grid unit) to 50, `gridOpacity` to 1, `canvasColor` to `''`, `originX` and `originY` to 0 |
129
138
  | `pie.translate_point_to(p, x, y)` | moves point `p` to (x, y) |
130
139
  | `pie.translate_point_by(p, dx, dy)` | moves point `p` by (dx, dy) |
131
140
  | `pie.translate_scalar_to(s, value)` | sets scalar `s` to `value` |
@@ -247,11 +256,15 @@ Each must `export default` a Solid component (Solid JSX: `class`, not `className
247
256
 
248
257
  Change the CSS variables in `styles/theme.css` (colors, fonts, text width), or add rules, e.g. `main h1 { color: crimson; }`.
249
258
 
259
+ - Sidebar: `--sidebar-width` (default `16rem`), `--sidebar-drawer-below` (default `768px`; narrower screens open it over the page) and `--color-backdrop` (behind it when it opens over the page). Its parts have the classes `.sidebar`, `.sidebar-text`, `.sidebar-edge`, `.sidebar-toggle` and `.sidebar-backdrop`.
260
+ - Table of contents: `.toc`.
261
+
250
262
  ## Build checks
251
263
 
252
264
  `npm run build` fails, with a message naming the file, when:
253
265
 
254
266
  - a page's frontmatter or `site.yml` has a bad line or value, or `site.yml` has no `title`
267
+ - a `sidebar` file doesn't exist or is outside the project
255
268
  - a page's URL matches a route in `node_modules/@tinyvolt/pie/src/routes/`
256
269
  - a `functions/` keyword is used twice
257
270
  - a `nodes/` type name is used twice
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tinyvolt/pie",
3
- "version": "0.3.0",
3
+ "version": "0.6.0",
4
4
  "description": "A Markdown-based SSG for interactive science explainers. Create a site with: npx @tinyvolt/pie init my-site",
5
5
  "type": "module",
6
6
  "repository": {
@@ -30,7 +30,8 @@
30
30
  "dev": "vite dev",
31
31
  "build": "vite build",
32
32
  "start": "node .output/server/index.mjs",
33
- "preview": "vite preview"
33
+ "preview": "vite preview",
34
+ "postinstall": "node init/postinstall.js"
34
35
  },
35
36
  "dependencies": {
36
37
  "@codemirror/lang-python": "6.2.1",
@@ -0,0 +1,7 @@
1
+ ### Topics
2
+ - [example](/example)
3
+ - [about](/about)
4
+
5
+ ```python-editor
6
+ print('Hello')
7
+ ```
package/pages/about.md CHANGED
@@ -1,5 +1,6 @@
1
1
  ---
2
2
  title: About
3
+ sidebar: _topics.md
3
4
  ---
4
5
 
5
6
  # About
package/pages/example.md CHANGED
@@ -1,7 +1,41 @@
1
1
  ---
2
- canvas: none
2
+ toc: true
3
+ sidebar: _topics.md
3
4
  ---
5
+ # Table of contents test
4
6
 
5
- # Example
7
+ ### Before any h2
6
8
 
7
- Euler's identity: $e^{i\pi} + 1 = 0$
9
+ Should be a top-level entry.
10
+
11
+ ## The $\nabla$ operator
12
+
13
+ Math in a heading.
14
+
15
+ ### Sub *one*
16
+
17
+ Nested under the operator.
18
+
19
+ ### Sub two
20
+
21
+ Also nested.
22
+
23
+ ## Repeat
24
+
25
+ First "Repeat", links to `#repeat`.
26
+
27
+ ## Repeat
28
+
29
+ Second "Repeat", links to `#repeat-2`.
30
+
31
+ #### Deep
32
+
33
+ Not listed: only `##` and `###` are.
34
+
35
+ ## Last
36
+
37
+ Lorem ipsum dolor sit amet, consectetur adipiscing elit.
38
+
39
+ Lorem ipsum dolor sit amet, consectetur adipiscing elit.
40
+
41
+ Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Binary file
Binary file
package/public/logo.svg CHANGED
@@ -1,5 +1,5 @@
1
1
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 21 64 45" width="256" height="180">
2
- <path d="M32 29 L8 29 A24 24 0 0 0 20 49.78 Z" fill="#41DBC9"/>
3
- <path d="M32 29 L44 49.78 A24 24 0 0 0 56 29 Z" fill="#41DBC9"/>
4
- <path d="M32 34 L20 54.78 A24 24 0 0 0 44 54.78 Z" fill="#0B6B73"/>
2
+ <path d="M32 29 L8 29 A24 24 0 0 0 20 49.78 Z" fill="#b45309"/>
3
+ <path d="M32 29 L44 49.78 A24 24 0 0 0 56 29 Z" fill="#b45309"/>
4
+ <path d="M32 34 L20 54.78 A24 24 0 0 0 44 54.78 Z" fill="#78350f"/>
5
5
  </svg>
package/src/app.css CHANGED
@@ -261,6 +261,8 @@ main .katex-display {
261
261
  .node-canvas {
262
262
  width: 100%;
263
263
  height: 100%;
264
+ /* Drags and pinches move the canvas, not the page. */
265
+ touch-action: none;
264
266
  }
265
267
 
266
268
  .canvas-page-canvas svg {
@@ -269,6 +271,119 @@ main .katex-display {
269
271
  height: 100%;
270
272
  }
271
273
 
274
+ /* A page with a sidebar: the sidebar, a line with its button, then the page. */
275
+ .sidebar-page {
276
+ display: flex;
277
+ flex: 1 1 auto;
278
+ min-height: 0;
279
+ }
280
+
281
+ /* Collapsed: hidden with CSS so its editors keep their code. Open: stays in view while the page scrolls. */
282
+ .sidebar {
283
+ display: none;
284
+ flex: 0 0 var(--sidebar-width, 16rem);
285
+ box-sizing: border-box;
286
+ position: sticky;
287
+ top: 0;
288
+ align-self: flex-start;
289
+ max-height: 100dvh;
290
+ overflow-y: auto;
291
+ }
292
+
293
+ .sidebar-page--open .sidebar {
294
+ display: block;
295
+ }
296
+
297
+ /* A canvas page doesn't scroll, so the sidebar fills its height and scrolls on its own. */
298
+ #app:has(.canvas-page) .sidebar {
299
+ align-self: stretch;
300
+ max-height: none;
301
+ }
302
+
303
+ .sidebar-text {
304
+ padding: 1rem 1.25rem 2rem;
305
+ }
306
+
307
+ .sidebar-edge {
308
+ position: relative;
309
+ z-index: 5;
310
+ flex: 0 0 1px;
311
+ background: var(--color-border, #ddd);
312
+ }
313
+
314
+ .sidebar-toggle {
315
+ position: sticky;
316
+ top: 0.75rem;
317
+ display: flex;
318
+ align-items: center;
319
+ justify-content: center;
320
+ width: 1.5rem;
321
+ height: 1.5rem;
322
+ margin-top: 0.75rem;
323
+ padding: 0;
324
+ background: var(--color-bg, #fff);
325
+ border: 1px solid var(--color-border, #ddd);
326
+ border-radius: 50%;
327
+ color: var(--color-subtle, #666);
328
+ cursor: pointer;
329
+ }
330
+
331
+ .sidebar-toggle:hover {
332
+ color: var(--color-hover, #000);
333
+ border-color: var(--color-border-hover, #999);
334
+ }
335
+
336
+ /* Fills the rest; a canvas page inside fills its height. */
337
+ .sidebar-page-content {
338
+ display: flex;
339
+ flex-direction: column;
340
+ flex: 1 1 0;
341
+ min-width: 0;
342
+ }
343
+
344
+ /* Narrow screens: the open sidebar covers the page, over a dimmed backdrop. */
345
+ .sidebar-page--drawer .sidebar {
346
+ position: fixed;
347
+ top: 0;
348
+ bottom: 0;
349
+ left: 0;
350
+ z-index: 20;
351
+ width: min(var(--sidebar-width, 16rem), 85vw);
352
+ max-height: none;
353
+ background: var(--color-bg, #fff);
354
+ box-shadow: 0 0 1rem rgb(0 0 0 / 0.2);
355
+ }
356
+
357
+ .sidebar-backdrop {
358
+ position: fixed;
359
+ inset: 0;
360
+ z-index: 19;
361
+ background: var(--color-backdrop, rgb(0 0 0 / 0.3));
362
+ }
363
+
364
+ /* `toc: true`: the table of contents, a box at the start of the page's text. */
365
+ .toc {
366
+ margin: 0 0 1.5rem;
367
+ padding: 0.75rem 1rem;
368
+ border: 1px solid var(--color-border, #ddd);
369
+ border-radius: 4px;
370
+ font-size: 0.95em;
371
+ }
372
+
373
+ .toc ul {
374
+ margin: 0;
375
+ padding-left: 1.25rem;
376
+ }
377
+
378
+ .toc a {
379
+ text-decoration: none;
380
+ }
381
+
382
+ .toc a:hover {
383
+ color: var(--color-hover, #000);
384
+ text-decoration: underline;
385
+ }
386
+
272
387
  /* Hidden until MarkdownBody swaps it for the editor; keeps its space so the text below doesn't jump. */
273
388
  pre:has(> code.language-python-editor) {
274
389
  visibility: hidden;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * A feature is an optional extra that a page turns on in its frontmatter, e.g. `sidebar: _topics.md`.
3
+ * If the page leaves the key out, the value in `site.yml` is used.
4
+ *
5
+ * Each feature has two halves:
6
+ * - Build half (this file). Runs in Node when the site is generated. Its `build` turns the frontmatter value
7
+ * into data, e.g. the path `_topics.md` into that file's HTML. The data is saved in the page's JSON.
8
+ * - View half (`views.tsx`). Runs in the browser. A component that gets that data and wraps the page,
9
+ * e.g. draws the sidebar next to it.
10
+ *
11
+ * To add a feature: add its build half to `FEATURES` below, and its view, if it has one, to `VIEWS` in `views.tsx`.
12
+ * A feature that only changes the page's HTML, like `toc`, has no view.
13
+ */
14
+ import type { MarkedExtension } from 'marked';
15
+ import type { Field } from '../frontmatter';
16
+ import { sidebar } from './sidebar/build';
17
+ import { toc } from './toc/build';
18
+
19
+ /** The second argument to a feature's `build`. */
20
+ export interface BuildContext {
21
+ /** The page, e.g. `pages/about.md`. */
22
+ file: string;
23
+ /** The file that set the value: the page, or `site.yml`. */
24
+ from: string;
25
+ /** The HTML of the `.md` file at `path`, relative to the folder of `from`. Throws if it's missing or outside the project. */
26
+ renderFile(path: string): string;
27
+ }
28
+
29
+ /** A feature's build half. `T`: its frontmatter value. `D`: the data its view gets. */
30
+ export interface FeatureBuild<T, D> {
31
+ field: Field<T>;
32
+ /** Returns `undefined` to turn the feature off on this page. */
33
+ build(value: T, ctx: BuildContext): D | undefined;
34
+ /** Extra markdown syntax for this page. */
35
+ markdown?(data: D): MarkedExtension;
36
+ }
37
+
38
+ /** Keyed by frontmatter key. */
39
+ const FEATURES = { sidebar, toc };
40
+
41
+ type DataOf<F> = F extends FeatureBuild<any, infer D> ? D : never;
42
+
43
+ // Today: `{ sidebar?: string; toc?: true }`.
44
+ export type FeatureData = { [K in keyof typeof FEATURES]?: DataOf<(typeof FEATURES)[K]> };
45
+
46
+ // Today: `{ sidebar: sidebar.field, toc: toc.field }`. `site.yml` reads these too.
47
+ export const FEATURE_FIELDS = Object.fromEntries(
48
+ Object.entries(FEATURES).map(([key, feature]) => [key, feature.field]),
49
+ ) as { [K in keyof typeof FEATURES]: (typeof FEATURES)[K]['field'] };
50
+
51
+ /** Runs every feature's `build` for the page `file`. Throws, naming the file and key, on a bad value. */
52
+ export function buildFeatures(
53
+ file: string,
54
+ raw: Record<string, string>,
55
+ site: Record<string, unknown>,
56
+ renderFile: (from: string, path: string) => string,
57
+ ): { data: FeatureData; extensions: MarkedExtension[] } {
58
+ const data: Record<string, unknown> = {};
59
+ const extensions: MarkedExtension[] = [];
60
+ for (const [key, feature] of Object.entries(FEATURES) as [string, FeatureBuild<unknown, unknown>][]) {
61
+ const from = Object.hasOwn(raw, key) ? file : 'site.yml';
62
+ try {
63
+ const value = from === file ? feature.field.parse(raw[key]) : site[key];
64
+ const built = feature.build(value, { file, from, renderFile: path => renderFile(from, path) });
65
+ if (built === undefined) continue;
66
+ data[key] = built;
67
+ if (feature.markdown) extensions.push(feature.markdown(built));
68
+ } catch (e) {
69
+ throw new Error(`${from}: \`${key}\` ${(e as Error).message}`);
70
+ }
71
+ }
72
+ return { data: data as FeatureData, extensions };
73
+ }
@@ -0,0 +1,56 @@
1
+ import { createSignal, onCleanup, onMount, Show, type JSX } from 'solid-js';
2
+ import { Chevron } from '~/components/icons';
3
+ import { MarkdownBody } from '../../components/MarkdownBody';
4
+
5
+ // Used when `theme.css` doesn't set `--sidebar-drawer-below`.
6
+ const DRAWER_BELOW = '768px';
7
+
8
+ /**
9
+ * `children` with a sidebar on the left showing `data`, the sidebar file's HTML. It starts collapsed; opening it squeezes `children`.
10
+ * On screens narrower than `--sidebar-drawer-below`, it opens over the page instead,
11
+ * and a tap outside it or on one of its links closes it.
12
+ * Its Python editors share variables only with each other, and have no canvas.
13
+ */
14
+ export function SidebarView(props: { data: string; children: JSX.Element }) {
15
+ const [open, setOpen] = createSignal(false);
16
+ const [drawer, setDrawer] = createSignal(false);
17
+
18
+ onMount(() => {
19
+ const below = getComputedStyle(document.documentElement).getPropertyValue('--sidebar-drawer-below').trim() || DRAWER_BELOW;
20
+ const query = matchMedia(`(width < ${below})`);
21
+ const update = () => setDrawer(query.matches);
22
+ update();
23
+ query.addEventListener('change', update);
24
+ onCleanup(() => query.removeEventListener('change', update));
25
+ });
26
+
27
+ // In the drawer, following a link closes it, even a link to a place on this page.
28
+ const closeOnLink = (e: MouseEvent) => {
29
+ if (drawer() && (e.target as Element).closest('a')) setOpen(false);
30
+ };
31
+ const label = () => (open() ? 'Hide sidebar' : 'Show sidebar');
32
+
33
+ return (
34
+ <div class="sidebar-page" classList={{ 'sidebar-page--open': open(), 'sidebar-page--drawer': drawer() }}>
35
+ <aside id="sidebar" class="sidebar" onClick={closeOnLink}>
36
+ <MarkdownBody class="sidebar-text" html={props.data} />
37
+ </aside>
38
+ <div class="sidebar-edge">
39
+ <button
40
+ class="sidebar-toggle"
41
+ onClick={() => setOpen(!open())}
42
+ aria-expanded={open()}
43
+ aria-controls="sidebar"
44
+ aria-label={label()}
45
+ title={label()}
46
+ >
47
+ <Chevron direction={open() ? 'left' : 'right'} />
48
+ </button>
49
+ </div>
50
+ <Show when={drawer() && open()}>
51
+ <div class="sidebar-backdrop" onClick={() => setOpen(false)} />
52
+ </Show>
53
+ <div class="sidebar-page-content">{props.children}</div>
54
+ </div>
55
+ );
56
+ }
@@ -0,0 +1,8 @@
1
+ import { markdownFile } from '../../frontmatter';
2
+ import type { FeatureBuild } from '../build';
3
+
4
+ /** `sidebar: _topics.md`: that file's HTML, shown in a sidebar. `none`: no sidebar, even when `site.yml` sets one. */
5
+ export const sidebar: FeatureBuild<string, string> = {
6
+ field: markdownFile(),
7
+ build: (file, ctx) => (file === '' || file === 'none' ? undefined : ctx.renderFile(file)),
8
+ };
@@ -0,0 +1,71 @@
1
+ import type { MarkedExtension } from 'marked';
2
+ import { boolean } from '../../frontmatter';
3
+ import type { FeatureBuild } from '../build';
4
+
5
+ /** Heading levels listed: `##` and `###`. */
6
+ const LEVELS = [2, 3];
7
+
8
+ interface Entry {
9
+ depth: number;
10
+ id: string;
11
+ /** The heading's text as HTML, e.g. with its math rendered. */
12
+ html: string;
13
+ }
14
+
15
+ /** `The $\nabla$ operator` -> `the-nabla-operator`. */
16
+ function slug(text: string): string {
17
+ return text.toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, '').trim().replace(/\s+/g, '-') || 'section';
18
+ }
19
+
20
+ /** The entries as a list. Each `###` is nested under the `##` before it; a `###` before any `##` stands on its own. */
21
+ function tocHtml(entries: Entry[]): string {
22
+ const groups: { entry: Entry; children: Entry[] }[] = [];
23
+ for (const entry of entries) {
24
+ const last = groups.at(-1);
25
+ if (entry.depth === 3 && last?.entry.depth === 2) last.children.push(entry);
26
+ else groups.push({ entry, children: [] });
27
+ }
28
+ const link = (e: Entry) => `<a href="#${e.id}">${e.html}</a>`;
29
+ const items = groups.map(({ entry, children }) => {
30
+ const sublist = children.length === 0 ? '' : `<ul>${children.map(c => `<li>${link(c)}</li>`).join('')}</ul>`;
31
+ return `<li>${link(entry)}${sublist}</li>`;
32
+ });
33
+ return `<nav class="toc"><ul>${items.join('')}</ul></nav>\n`;
34
+ }
35
+
36
+ /**
37
+ * `toc: true`: a table of contents of the page's `##` and `###` headings, after its leading `#` title,
38
+ * or at the very start if the page doesn't begin with one. Every heading gets an `id` to link to.
39
+ * No list when the page has no such heading.
40
+ */
41
+ export const toc: FeatureBuild<boolean, true> = {
42
+ field: boolean(false),
43
+ build: on => (on ? true : undefined),
44
+ // The list is made while the page renders, from the headings as they're rendered, so each entry's text
45
+ // and `id` match its heading's.
46
+ markdown() {
47
+ const entries: Entry[] = [];
48
+ const used = new Map<string, number>();
49
+ return {
50
+ renderer: {
51
+ heading(token) {
52
+ const base = slug(token.text);
53
+ const count = (used.get(base) ?? 0) + 1;
54
+ used.set(base, count);
55
+ const id = count === 1 ? base : `${base}-${count}`;
56
+ const html = this.parser.parseInline(token.tokens);
57
+ if (LEVELS.includes(token.depth)) entries.push({ depth: token.depth, id, html });
58
+ return `<h${token.depth} id="${id}">${html}</h${token.depth}>\n`;
59
+ },
60
+ },
61
+ hooks: {
62
+ postprocess(html) {
63
+ if (entries.length === 0) return html;
64
+ const title = /^\s*<h1[\s>][\s\S]*?<\/h1>\n?/.exec(html);
65
+ const at = title ? title[0].length : 0;
66
+ return html.slice(0, at) + tocHtml(entries) + html.slice(at);
67
+ },
68
+ },
69
+ } satisfies MarkedExtension;
70
+ },
71
+ };
@@ -0,0 +1,20 @@
1
+ // The view part of every feature: runs in the browser. Each feature's build part is in `build.ts`.
2
+ import type { Component, JSX } from 'solid-js';
3
+ import type { FeatureData } from './build';
4
+ import { SidebarView } from './sidebar/View';
5
+
6
+ /** A feature's view: wraps the page, given the feature's data. */
7
+ type FeatureView<D> = Component<{ data: D; children: JSX.Element }>;
8
+
9
+ /** Every feature's view, by key, outermost first. A feature with no view, like `toc`, is left out. */
10
+ const VIEWS: { [K in keyof FeatureData]: FeatureView<NonNullable<FeatureData[K]>> } = {
11
+ sidebar: SidebarView,
12
+ };
13
+
14
+ /** `body` wrapped in the view of every feature that is on for the page, the first in `VIEWS` outermost. */
15
+ export function wrapPage(data: FeatureData, body: JSX.Element): JSX.Element {
16
+ return (Object.entries(VIEWS) as [keyof FeatureData, FeatureView<unknown>][]).reduceRight<JSX.Element>(
17
+ (inner, [key, View]) => (data[key] === undefined ? inner : <View data={data[key]}>{inner}</View>),
18
+ body,
19
+ );
20
+ }
@@ -23,6 +23,28 @@ export function text(fallback: string): Field<string> {
23
23
  return { default: fallback, parse: raw => raw };
24
24
  }
25
25
 
26
+ /** `true` or `false`. */
27
+ export function boolean(fallback: boolean): Field<boolean> {
28
+ return {
29
+ default: fallback,
30
+ parse(raw) {
31
+ if (raw !== 'true' && raw !== 'false') throw new Error(`must be true or false, got ${JSON.stringify(raw)}`);
32
+ return raw === 'true';
33
+ },
34
+ };
35
+ }
36
+
37
+ /** A path to a `.md` file, or `none`. Empty when absent. */
38
+ export function markdownFile(): Field<string> {
39
+ return {
40
+ default: '',
41
+ parse(raw) {
42
+ if (raw !== 'none' && !raw.endsWith('.md')) throw new Error(`must be a .md file or none, got ${JSON.stringify(raw)}`);
43
+ return raw;
44
+ },
45
+ };
46
+ }
47
+
26
48
  /** Every frontmatter field a page can set. Keys not listed here are ignored. */
27
49
  const FIELDS = {
28
50
  canvas: oneOf(['left', 'right', 'top', 'bottom', 'none'], 'none'),
@@ -72,11 +94,14 @@ function splitFrontmatter(markdown: string): { raw: Record<string, string>; body
72
94
  return { raw: parseKeyValues(match[1]), body: markdown.slice(match[0].length) };
73
95
  }
74
96
 
75
- /** Reads the frontmatter of the file at `path`. Throws, naming `path`, on a malformed block or a bad value. */
76
- export function parseFrontmatter(path: string, markdown: string): { frontmatter: Frontmatter; body: string } {
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: string, markdown: string): { frontmatter: Frontmatter; raw: Record<string, string>; body: string } {
77
102
  try {
78
103
  const { raw, body } = splitFrontmatter(markdown);
79
- return { frontmatter: readFields(FIELDS, raw), body };
104
+ return { frontmatter: readFields(FIELDS, raw), raw, body };
80
105
  } catch (e) {
81
106
  throw new Error(`${path}: ${(e as Error).message}`);
82
107
  }
@@ -1,13 +1,16 @@
1
+ import type { FeatureData } from './features/build';
1
2
  import type { Frontmatter } from './frontmatter';
2
3
 
3
4
  /** One `pages/**\/*.md`, as `vitePlugin.ts` turns it into a module at build time. */
4
5
  export interface Page {
5
6
  frontmatter: Frontmatter;
6
7
  html: string;
8
+ features: FeatureData;
7
9
  }
8
10
 
9
11
  // Not eager: each page is its own file, downloaded only when that page is opened.
10
- const loaders = import.meta.glob<Page>('/pages/**/*.md', { import: 'default' });
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
+ const loaders = import.meta.glob<Page>(['/pages/**/*.md', '!/pages/**/_*.md'], { import: 'default' });
11
14
 
12
15
  // Slug -> loader. `/pages/a/b.md` has the slug `a/b`.
13
16
  const bySlug = new Map(
@@ -1,5 +1,5 @@
1
1
  import katex from 'katex';
2
- import { Marked, Renderer } from 'marked';
2
+ import { Marked, Renderer, type MarkedExtension } from 'marked';
3
3
  import { pythonLanguage } from '@codemirror/lang-python';
4
4
  import { classHighlighter, highlightCode } from '@lezer/highlight';
5
5
 
@@ -28,7 +28,7 @@ function highlightPython(code: string): string {
28
28
  return html;
29
29
  }
30
30
 
31
- const marked = new Marked({
31
+ const BASE: MarkedExtension = {
32
32
  extensions: [
33
33
  {
34
34
  // `$$…$$` that fills its own lines.
@@ -83,8 +83,12 @@ const marked = new Marked({
83
83
  return new Renderer().code(token).replace('<code ', '<code data-collapsed ');
84
84
  },
85
85
  },
86
- });
86
+ };
87
87
 
88
- export function renderMarkdown(markdown: string): string {
89
- return marked.parse(markdown) as string;
88
+ const marked = new Marked(BASE);
89
+
90
+ /** `extensions`: markdown syntax the page's features add. */
91
+ export function renderMarkdown(markdown: string, extensions: MarkedExtension[] = []): string {
92
+ const parser = extensions.length === 0 ? marked : new Marked(BASE, ...extensions);
93
+ return parser.parse(markdown) as string;
90
94
  }
@@ -1,15 +1,17 @@
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
5
  import { parseFrontmatter } from './frontmatter';
5
6
  import type { Page } from './pages';
6
7
  import { renderMarkdown } from './render';
7
8
  import { APP_DIR } from '../appDir';
9
+ import { parseSite } from '../site/vitePlugin';
8
10
 
9
11
  /**
10
12
  * Turns each `pages/**\/*.md` into a module whose default export is a `Page`, at build time,
11
13
  * so the browser gets finished HTML and never runs the markdown tools.
12
- * Bad frontmatter fails the build; in dev it shows Vite's error screen.
14
+ * Bad frontmatter, or a feature's bad value, fails the build; in dev it shows Vite's error screen.
13
15
  */
14
16
  export function markdownPages(): Plugin {
15
17
  let root = '';
@@ -23,8 +25,27 @@ export function markdownPages(): Plugin {
23
25
  transform(markdown, id) {
24
26
  const file = path.relative(root, id.split('?')[0]);
25
27
  if (!file.startsWith(`pages${path.sep}`) || !file.endsWith('.md')) return;
26
- const { frontmatter, body } = parseFrontmatter(file, markdown);
27
- const page: Page = { frontmatter, html: renderMarkdown(body) };
28
+ const { frontmatter, raw, body } = parseFrontmatter(file, markdown);
29
+
30
+ // Features read `site.yml` for the keys a page leaves out, so editing it rebuilds every page.
31
+ const siteFile = path.join(root, 'site.yml');
32
+ this.addWatchFile(siteFile);
33
+ const site = parseSite('site.yml', fs.readFileSync(siteFile, 'utf8'));
34
+
35
+ const renderFile = (from: string, mdPath: string) => {
36
+ const target = path.resolve(root, path.dirname(from), mdPath);
37
+ const relative = path.relative(root, target);
38
+ if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
39
+ throw new Error(`must be inside the project, got ${JSON.stringify(mdPath)}`);
40
+ }
41
+ const shown = relative.split(path.sep).join('/');
42
+ if (!fs.existsSync(target)) throw new Error(`file ${shown} does not exist`);
43
+ this.addWatchFile(target);
44
+ return renderMarkdown(parseFrontmatter(shown, fs.readFileSync(target, 'utf8')).body);
45
+ };
46
+
47
+ const { data, extensions } = buildFeatures(file, raw, site, renderFile);
48
+ const page: Page = { frontmatter, html: renderMarkdown(body, extensions), features: data };
28
49
  return { code: `export default ${JSON.stringify(page)};`, map: null };
29
50
  },
30
51
  };
@@ -56,7 +77,9 @@ export function checkPageRoutes(): Plugin {
56
77
  .filter(file => /\.(tsx|ts|jsx|js)$/.test(file) && file !== PAGE_ROUTE)
57
78
  .map(file => ({ file, pattern: routePattern(file) }));
58
79
  const clashes: string[] = [];
59
- for (const file of listFiles(path.join(root, 'pages')).filter(file => file.endsWith('.md'))) {
80
+ // A file whose name starts with `_` has no URL.
81
+ const pages = listFiles(path.join(root, 'pages')).filter(file => file.endsWith('.md') && !path.posix.basename(file).startsWith('_'));
82
+ for (const file of pages) {
60
83
  const url = file.replace(/\.md$/, '').split('/');
61
84
  for (const route of routes) {
62
85
  if (matches(route.pattern, url)) {
@@ -2,7 +2,7 @@ import { JSX, createMemo, Show } from 'solid-js';
2
2
  import { MIN_GRID_UNIT } from '../state/NodeStore';
3
3
 
4
4
  interface CenteredGridProps {
5
- /** Canvas size in viewBox units. The origin sits at the center. */
5
+ /** Canvas size in viewBox units. */
6
6
  width: number;
7
7
  height: number;
8
8
  /** Pixels per grid unit. */
@@ -11,6 +11,8 @@ interface CenteredGridProps {
11
11
  gridOpacity?: number;
12
12
  /** Solid fill painted behind the grid. Defaults to transparent (no rect). */
13
13
  backgroundColor?: string;
14
+ /** Position of the origin in the viewBox. Defaults to the center of the canvas. */
15
+ origin?: { x: number; y: number };
14
16
  children: JSX.Element;
15
17
  }
16
18
 
@@ -18,8 +20,8 @@ const GRID_OPACITY = 0.15;
18
20
  const AXIS_OPACITY = 0.4;
19
21
 
20
22
  export function CenteredGrid(props: CenteredGridProps) {
21
- const originX = () => props.width / 2;
22
- const originY = () => props.height / 2;
23
+ const originX = () => props.origin?.x ?? props.width / 2;
24
+ const originY = () => props.origin?.y ?? props.height / 2;
23
25
 
24
26
  // Local (post-transform) extents of the canvas relative to the origin.
25
27
  const extents = createMemo(() => ({
@@ -3,6 +3,7 @@ import { NodeStore, type NodeSignal } from '../state/NodeStore';
3
3
  import { getNodeDefinition } from '../state/Node';
4
4
  import { CenteredGrid } from './CenteredGrid';
5
5
  import { useCanvasResize } from '../hooks/useCanvasResize';
6
+ import { useCanvasGestures } from '../hooks/useCanvasGestures';
6
7
 
7
8
  interface NodeCanvasProps {
8
9
  store: NodeStore;
@@ -11,6 +12,7 @@ interface NodeCanvasProps {
11
12
  export function NodeCanvas(props: NodeCanvasProps): JSX.Element {
12
13
  let svgContainerRef: HTMLDivElement | undefined;
13
14
  useCanvasResize(() => svgContainerRef, props.store);
15
+ useCanvasGestures(() => svgContainerRef, props.store);
14
16
 
15
17
  // Canvas size in grid units: the viewBox maps one unit to `unit` pixels.
16
18
  const viewWidth = () => props.store.canvasBounds().width / props.store.unit();
@@ -52,6 +54,7 @@ export function NodeCanvas(props: NodeCanvasProps): JSX.Element {
52
54
  unit={props.store.unit()}
53
55
  gridOpacity={props.store.gridOpacity()}
54
56
  backgroundColor={props.store.canvasColor()}
57
+ origin={props.store.origin()}
55
58
  >
56
59
  {/* Step 1: Draw non-`Point` nodes first */}
57
60
  <For each={layers().geometry}>{(nodeSignal) => nodeGroup(nodeSignal)}</For>
@@ -10,7 +10,7 @@ import type { Track } from '../animation';
10
10
  * It has no inputs, so it no longer follows the old node's.
11
11
  * With `animate`, returns a track that moves the numbers from their old values to the new ones.
12
12
  */
13
- function replaceNode<N extends AnyNode>(store: NodeStore, node: N, changes: Partial<N>, animate: boolean): Track | undefined {
13
+ export function replaceNode<N extends AnyNode>(store: NodeStore, node: N, changes: Partial<N>, animate: boolean): Track | undefined {
14
14
  const { __graph_deps, ...unchanged } = node;
15
15
  const end = { ...unchanged, ...changes } as AnyNode;
16
16
  if (!animate) {
@@ -0,0 +1,128 @@
1
+ import { batch, onCleanup, onMount } from 'solid-js';
2
+ import { NodeStore } from '../state/NodeStore';
3
+ import { num, scalar } from '../jax';
4
+ import { replaceNode } from '../functions/sideEffects';
5
+
6
+ type Pixel = { x: number; y: number };
7
+
8
+ /** A trackpad pinch with a `deltaY` of 100 zooms by a factor of e. */
9
+ const PINCH_SPEED = 0.01;
10
+ /** Slower than a pinch: a scroll's `deltaY` is larger. */
11
+ const SCROLL_SPEED = 0.002;
12
+
13
+ /**
14
+ * Lets the reader move the canvas with a pointer:
15
+ * - Dragging a point moves it, like `translate_point_to`: it stops following its inputs.
16
+ * - Dragging anywhere else pans the canvas, through `originX` and `originY`.
17
+ * - A pinch, a two-finger trackpad slide or a mouse wheel zooms through `unit`, and moves the origin so the spot
18
+ * under the cursor or fingers stays put.
19
+ */
20
+ export function useCanvasGestures(containerRef: () => HTMLDivElement | undefined, store: NodeStore) {
21
+ // Pointers panning or pinching the canvas.
22
+ const pointers = new Map<number, Pixel>();
23
+ // The pointer dragging a point, and that point's id.
24
+ let drag: { pointerId: number; nodeId: string } | undefined;
25
+
26
+ /** Pixels from the canvas's top left. */
27
+ const toPixel = (e: MouseEvent): Pixel => {
28
+ const rect = containerRef()!.getBoundingClientRect();
29
+ return { x: e.clientX - rect.left, y: e.clientY - rect.top };
30
+ };
31
+
32
+ /** Sets system scalar `id` to `change(its value)`. Skipped if it is no longer a scalar. */
33
+ const changeScalar = (id: string, change: (value: number) => number) => {
34
+ const node = store.getNodeValue(id);
35
+ if (node?.type === 'Scalar') replaceNode(store, node, { value: scalar(change(num(node.value))) }, false);
36
+ };
37
+
38
+ const pan = (dx: number, dy: number) => {
39
+ const unit = store.unit();
40
+ changeScalar('originX', x => x + dx / unit);
41
+ // Pixels go down, grid units go up.
42
+ changeScalar('originY', y => y - dy / unit);
43
+ };
44
+
45
+ const zoomAt = (at: Pixel, factor: number) => {
46
+ const unit = store.unit();
47
+ const next = Math.max(1, unit * factor);
48
+ const { width, height } = store.canvasBounds();
49
+ // The spot `at` is a fixed number of pixels from the center; keep it on the same grid position.
50
+ const shift = 1 / next - 1 / unit;
51
+ changeScalar('unit', () => next);
52
+ changeScalar('originX', x => x + (at.x - width / 2) * shift);
53
+ changeScalar('originY', y => y + (height / 2 - at.y) * shift);
54
+ };
55
+
56
+ const movePoint = (id: string, at: Pixel) => {
57
+ const point = store.getNodeValue(id);
58
+ // Removed or replaced while being dragged.
59
+ if (point?.type !== 'Point') return;
60
+ const unit = store.unit();
61
+ const origin = store.origin();
62
+ replaceNode(store, point, { x: scalar(at.x / unit - origin.x), y: scalar(origin.y - at.y / unit) }, false);
63
+ };
64
+
65
+ /** The pointers' center, and their mean distance from it. */
66
+ const spread = () => {
67
+ const all = [...pointers.values()];
68
+ const x = all.reduce((sum, p) => sum + p.x, 0) / all.length;
69
+ const y = all.reduce((sum, p) => sum + p.y, 0) / all.length;
70
+ const size = all.reduce((sum, p) => sum + Math.hypot(p.x - x, p.y - y), 0) / all.length;
71
+ return { x, y, size };
72
+ };
73
+
74
+ const onPointerDown = (e: PointerEvent) => {
75
+ if (drag) return;
76
+ // Keeps text from being selected while dragging with a mouse.
77
+ e.preventDefault();
78
+ containerRef()!.setPointerCapture(e.pointerId);
79
+ const nodeId = (e.target as Element).closest('[data-node-id]')?.getAttribute('data-node-id');
80
+ if (nodeId && pointers.size === 0 && store.getNodeValue(nodeId)?.type === 'Point') {
81
+ drag = { pointerId: e.pointerId, nodeId };
82
+ } else {
83
+ pointers.set(e.pointerId, toPixel(e));
84
+ }
85
+ };
86
+
87
+ const onPointerMove = (e: PointerEvent) => {
88
+ if (drag?.pointerId === e.pointerId) return movePoint(drag.nodeId, toPixel(e));
89
+ if (!pointers.has(e.pointerId)) return;
90
+ const before = spread();
91
+ pointers.set(e.pointerId, toPixel(e));
92
+ const after = spread();
93
+ batch(() => {
94
+ pan(after.x - before.x, after.y - before.y);
95
+ // One pointer has no spread: it only pans.
96
+ if (before.size > 0) zoomAt(after, after.size / before.size);
97
+ });
98
+ };
99
+
100
+ const onPointerUp = (e: PointerEvent) => {
101
+ if (drag?.pointerId === e.pointerId) drag = undefined;
102
+ pointers.delete(e.pointerId);
103
+ };
104
+
105
+ const onWheel = (e: WheelEvent) => {
106
+ // The browser reports a trackpad pinch as a wheel event with `ctrlKey`, and a scroll as one without.
107
+ e.preventDefault();
108
+ const speed = e.ctrlKey ? PINCH_SPEED : SCROLL_SPEED;
109
+ batch(() => zoomAt(toPixel(e), Math.exp(-e.deltaY * speed)));
110
+ };
111
+
112
+ onMount(() => {
113
+ const container = containerRef()!;
114
+ container.addEventListener('pointerdown', onPointerDown);
115
+ container.addEventListener('pointermove', onPointerMove);
116
+ container.addEventListener('pointerup', onPointerUp);
117
+ container.addEventListener('pointercancel', onPointerUp);
118
+ // Not passive, so `preventDefault` can stop the browser zooming or scrolling the page.
119
+ container.addEventListener('wheel', onWheel, { passive: false });
120
+ onCleanup(() => {
121
+ container.removeEventListener('pointerdown', onPointerDown);
122
+ container.removeEventListener('pointermove', onPointerMove);
123
+ container.removeEventListener('pointerup', onPointerUp);
124
+ container.removeEventListener('pointercancel', onPointerUp);
125
+ container.removeEventListener('wheel', onWheel);
126
+ });
127
+ });
128
+ }
@@ -26,6 +26,8 @@ export class NodeStore {
26
26
  public gridOpacity!: Accessor<number>;
27
27
  /** Canvas background color, read from the `canvasColor` node. `undefined` when empty: no background. */
28
28
  public canvasColor!: Accessor<string | undefined>;
29
+ /** Where the grid origin sits in the viewBox, read from the `originX` and `originY` nodes. */
30
+ public origin!: Accessor<{ x: number; y: number }>;
29
31
 
30
32
  public nameGenerator: NameGenerator;
31
33
 
@@ -55,6 +57,17 @@ export class NodeStore {
55
57
  const node = this.nodes['canvasColor']?.signal() as TextNode | undefined;
56
58
  return node?.value?.trim() || undefined;
57
59
  });
60
+
61
+ this.origin = createMemo(() => {
62
+ const xNode = this.nodes['originX']?.signal() as ScalarNode | undefined;
63
+ const yNode = this.nodes['originY']?.signal() as ScalarNode | undefined;
64
+ const viewWidth = this.canvasBounds().width / this.unit();
65
+ const viewHeight = this.canvasBounds().height / this.unit();
66
+ // The offset is in grid units from the canvas center. The viewBox is y-down, hence `- y`.
67
+ const x = xNode ? num(xNode.value) : 0;
68
+ const y = yNode ? num(yNode.value) : 0;
69
+ return { x: viewWidth / 2 + x, y: viewHeight / 2 - y };
70
+ });
58
71
  });
59
72
 
60
73
  // untrack: names are generated inside reactive computations, which must not rerun when the checked node changes.
@@ -81,6 +94,18 @@ export class NodeStore {
81
94
  const signal = createMemo(() => ({ id: canvasColorId, type: 'Text', value: '' } as TextNode));
82
95
  this.saveNode(canvasColorId, signal, dispose);
83
96
  });
97
+
98
+ const originXId = 'originX';
99
+ createRoot((dispose) => {
100
+ const signal = createMemo(() => ({ id: originXId, type: 'Scalar', value: scalar(0) } as ScalarNode));
101
+ this.saveNode(originXId, signal, dispose);
102
+ });
103
+
104
+ const originYId = 'originY';
105
+ createRoot((dispose) => {
106
+ const signal = createMemo(() => ({ id: originYId, type: 'Scalar', value: scalar(0) } as ScalarNode));
107
+ this.saveNode(originYId, signal, dispose);
108
+ });
84
109
  }
85
110
 
86
111
  public clearNodes() {
@@ -74,6 +74,13 @@ def _node(result):
74
74
  return Text(result.id)
75
75
  return Node(result.id, result.type)
76
76
 
77
+ def get_node(id):
78
+ """The existing node with id `id`, e.g. `a = pie.get_node("A")`. Creates nothing."""
79
+ if not isinstance(id, str):
80
+ raise TypeError(f"pie.get_node: id must be a str, got {type(id).__name__}")
81
+ _check_bridge()
82
+ return _node(run_sync(bridge.get_node(id)))
83
+
77
84
  def _arg(a):
78
85
  if isinstance(a, Node):
79
86
  return {"id": a.id}
@@ -45,7 +45,7 @@ function onMessage(this: Worker, { data }: MessageEvent) {
45
45
  loaded = true;
46
46
  run?.onStatus('running');
47
47
  }
48
- if (data.type === 'call' || data.type === 'item' || data.type === 'lift') {
48
+ if (data.type === 'call' || data.type === 'item' || data.type === 'get_node' || data.type === 'lift') {
49
49
  // The request to answer: this one, or, after a batch, Python's request with the batch's results.
50
50
  let reqId: number = data.reqId;
51
51
  // A reply from before a kill must not reach the new worker.
@@ -65,6 +65,13 @@ function onMessage(this: Worker, { data }: MessageEvent) {
65
65
  }
66
66
  return;
67
67
  }
68
+ if (data.type === 'get_node') {
69
+ const node = store.getNodeValue(data.id);
70
+ if (!node) reply({ error: `pie.get_node: no node with id '${data.id}'` });
71
+ else if (node.type === 'Array') reply({ result: { id: node.id, type: node.type, shape: node.shape, itemType: node.itemType } });
72
+ else reply({ result: { id: node.id, type: node.type } });
73
+ return;
74
+ }
68
75
  if (data.type === 'lift') {
69
76
  try {
70
77
  reply({ result: startLift(store, data.name, data.inputIds, data.kind, data.out, data.fill, data.stroke) });
@@ -22,6 +22,9 @@ const call = (keyword: string, args: unknown[], options: CallOptions) =>
22
22
  /** The node at `position` of an array's items. Creates nothing. */
23
23
  const item = (arrayId: string, position: number) => request({ type: 'item', arrayId, position });
24
24
 
25
+ /** The node with id `id`. Creates nothing. */
26
+ const get_node = (id: string) => request({ type: 'get_node', id });
27
+
25
28
  /** First half of `g(a)` for `g = pie.lift(f, ...)`: the input values and the output id. */
26
29
  const lift = (name: string, inputIds: string[], kind: string, out?: string, fill?: string, stroke?: string) =>
27
30
  request({ type: 'lift', name, inputIds, kind, out, fill, stroke });
@@ -38,7 +41,7 @@ const ready = (async () => {
38
41
  py.setStdout({ batched: (text: string) => postMessage({ type: 'output', text: text + '\n' }) });
39
42
  py.setStderr({ batched: (text: string) => postMessage({ type: 'output', text: text + '\n' }) });
40
43
  py.registerJsModule('bridge', {
41
- call, item, lift, lift_save, batch_done, plot: (png: string) => postMessage({ type: 'plot', png }),
44
+ call, item, get_node, lift, lift_save, batch_done, plot: (png: string) => postMessage({ type: 'plot', png }),
42
45
  });
43
46
  py.FS.writeFile('/home/pyodide/pie.py', PIE_PY);
44
47
  py.FS.writeFile('/home/pyodide/pie_mpl.py', PIE_MPL_PY);
@@ -1,5 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import type { Plugin } from 'vite';
3
+ import { FEATURE_FIELDS } from '../markdown/features/build';
3
4
  import { parseKeyValues, readFields, text, type Field, type Values } from '../markdown/frontmatter';
4
5
 
5
6
  /** An `http://` or `https://` address, without a trailing `/`. */
@@ -21,6 +22,8 @@ const FIELDS = {
21
22
  url: address(),
22
23
  /** The search-result description of a page that has no `description` of its own. */
23
24
  description: text(''),
25
+ /** Each feature's frontmatter key, as the value of pages that leave it out. Paths are relative to the project root. */
26
+ ...FEATURE_FIELDS,
24
27
  };
25
28
 
26
29
  export type Site = Values<typeof FIELDS>;
@@ -6,6 +6,7 @@ import { PageMeta } from '~/components/PageMeta';
6
6
  import { PageTitle } from '~/components/PageTitle';
7
7
  import { CanvasPage } from '~/lib/markdown/components/CanvasPage';
8
8
  import { MarkdownBody } from '~/lib/markdown/components/MarkdownBody';
9
+ import { wrapPage } from '~/lib/markdown/features/views';
9
10
  import { loadPage } from '~/lib/markdown/pages';
10
11
 
11
12
  export default function Page() {
@@ -13,7 +14,7 @@ export default function Page() {
13
14
  const page = createAsync(() => loadPage(params.slug ?? ''));
14
15
 
15
16
  // `undefined` while loading, `null` when there is no such page.
16
- // Keyed: a new page gets a fresh canvas and fresh Python variables.
17
+ // Keyed: a new page gets a fresh canvas, fresh Python variables and fresh features, e.g. a collapsed sidebar.
17
18
  return (
18
19
  <Switch>
19
20
  <Match when={page() === null}>
@@ -26,10 +27,11 @@ export default function Page() {
26
27
  <Match when={page()} keyed>
27
28
  {(page) => {
28
29
  const canvas = page.frontmatter.canvas;
30
+ const body = canvas === 'none' ? <MarkdownBody html={page.html} /> : <CanvasPage side={canvas} html={page.html} />;
29
31
  return (
30
32
  <>
31
33
  <PageMeta title={page.frontmatter.title} description={page.frontmatter.description} />
32
- {canvas === 'none' ? <MarkdownBody html={page.html} /> : <CanvasPage side={canvas} html={page.html} />}
34
+ {wrapPage(page.features, body)}
33
35
  </>
34
36
  );
35
37
  }}
package/styles/theme.css CHANGED
@@ -14,6 +14,7 @@
14
14
  --color-border-hover: #999;
15
15
  --color-code-bg: #f4f4f4;
16
16
  --color-error: #c00;
17
+ --color-backdrop: rgb(0 0 0 / 0.3); /* behind the open sidebar on narrow screens */
17
18
 
18
19
  /* Fonts */
19
20
  --font-ui: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; /* header, editor */
@@ -24,4 +25,6 @@
24
25
 
25
26
  /* Layout */
26
27
  --content-width: 40rem; /* page text column, about 70 characters */
28
+ --sidebar-width: 16rem;
29
+ --sidebar-drawer-below: 768px; /* on narrower screens the sidebar opens over the page */
27
30
  }