@pencil-lang/figure 0.0.2 → 0.0.3

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
@@ -29,6 +29,25 @@ It owns the canvas, the labels over it, the GPU and the clock. It starts the GPU
29
29
  under `prefers-reduced-motion`, and every handle and beat can be worked from the keyboard. Its attributes, methods and
30
30
  events are described at the top of [`src/element.js`](src/element.js).
31
31
 
32
+ A param with a binding goes back to it when a reader sets a param that binding reads, as θ in Bounds does when `q` or
33
+ the case is set after a drag: the core says which params each binding reads (`info.params[].reads`), and the element
34
+ hands them back, so a page needs no `release` of its own for it. Params held together, by the `params` attribute or
35
+ setter, keep each other.
36
+
37
+ When a browser loses the GPU under a figure, as Chrome does after sleep or when its GPU process restarts, the figure
38
+ starts its GPU again where it was: the same sources, time, held params and pause, with its poster showing meanwhile. It
39
+ tries at once, after a second and after five, and then sends `error` (with `detail.gpu`), trying once more each time
40
+ the page is shown. One that draws again after that sends `recover`, so a page can take its message down. A GPU error
41
+ on a device that isn't lost is the figure's, and is an `error` at once. Other figures on the page draw on. `Player` has
42
+ `lose_device()` and `trap()` for testing this, and `on_lost(callback)`, which the element uses, and the host has
43
+ `let_go(id)`, which lets go of a trapped player's device. On WebGL2 the canvas keeps its context, lost and brought back
44
+ for the next player, so restarts don't use up a browser's cap on live contexts.
45
+
46
+ It owns its touch and selection behaviour too, so a page sets no `touch-action` or `user-select` for it. A touch within
47
+ a handle's reach drags the handle and doesn't scroll the page. One anywhere else on the figure scrolls and zooms the
48
+ page, as it would over an image, so a figure never traps a reader's scroll. A drag never selects text, in the figure or
49
+ on the page around it, and a long press shows no callout.
50
+
32
51
  Labels are set in the package's own fonts, in [`fonts/`](fonts/README.md): Libertinus, under the SIL Open Font License.
33
52
  They're the files the `pencil` command draws a poster with, so the figure that takes over from a poster sets the same
34
53
  glyphs in the same places. The element fetches the two text faces when it loads, and the math font the first time a
@@ -67,7 +86,8 @@ import Figure from '@pencil-lang/figure/Figure.astro';
67
86
  compile stops the build with the compiler's message.
68
87
  - **A page's own theme toggle is followed.** A page that pins a theme over the reader's system says so in its CSS,
69
88
  as `:root[data-theme='dark'] { color-scheme: dark; }`, and a figure there takes its dark sheets and its dark
70
- poster, from the first paint. With `color-scheme` listing both or neither, the reader's system picks. The element
89
+ poster, from the first paint, and its poster in the other theme isn't fetched. With `color-scheme` listing both or
90
+ neither, the reader's system picks. The element
71
91
  does this for any `<source media="(prefers-color-scheme: …)">` among its children, and looks again when `<html>`
72
92
  or `<body>` changes an attribute (`src/scheme.js`).
73
93
  - **The poster is an image with the figure's size,** so the page is laid out before any script runs. It's offered as
@@ -77,7 +97,10 @@ import Figure from '@pencil-lang/figure/Figure.astro';
77
97
  - **`astro dev` hands the element the sources,** served from where they are, and a figure reloads in place when one is
78
98
  saved, keeping its time and what a reader holds.
79
99
  - **`priority` is for a figure in view when the page opens.** Its poster is fetched at once with `fetchpriority="high"`,
80
- since it's likely the page's largest first paint. Every other poster is lazy. Mark one or two a page. A build also
100
+ since it's likely the page's largest first paint. Every other poster is lazy. Mark one or two a page. One with
101
+ `dark` sheets is written lazy and made eager by a line of script after it, once its theme is known: a browser
102
+ reading ahead while the page's stylesheet loads would fetch the poster the reader's system picks, and skips a lazy
103
+ one. So that poster starts once the page's stylesheet is in. A build also
81
104
  writes a line of inline script that starts fetching what that figure will need, the WASM and the compiled figure its
82
105
  media picks, at low priority, so they start as the page is read and not after the element's script has run. The
83
106
  element takes them over, and each is downloaded once. (`<link rel="preload" as="fetch">` isn't used: WebKit fetches
@@ -88,7 +111,8 @@ import Figure from '@pencil-lang/figure/Figure.astro';
88
111
  and builds it again otherwise. Where `pencil` isn't there, it stops and says which figure needs building and why.
89
112
  A compiled figure is read only by the build of Pencil that wrote it, so after the package is upgraded every figure
90
113
  is built again, with a `pencil` from the same source as the package. A build names the folders nothing asked for,
91
- and leaves them: one that skips drafts asks for fewer.
114
+ and leaves them: one that skips drafts asks for fewer. A figure is built elsewhere and put in the folder only once
115
+ it has built, so a build that fails, or has no `pencil`, never removes what's kept.
92
116
  - **`alt` is required.** It's the poster's text and the figure's name.
93
117
  - Anything else, such as `id`, `class`, `params`, `paused` or `data-*`, goes on `<pencil-figure>`.
94
118
 
@@ -110,7 +134,13 @@ a figure. Where the link goes on the page is the page's to say.
110
134
  The integration's options are `root`, where `src` and `sheets` paths start (the Astro project by default),
111
135
  `playground`, and `bin`, the `pencil` command. Without `bin` it tries `PENCIL_BIN`, then `target/release/pencil` in the checkout around `root`
112
136
  or around this package, then `pencil` on the `PATH`. Drawing a poster takes a GPU, so a site is built where there is
113
- one. A build stops if `pencil` and the package's WASM are different builds of the core.
137
+ one. A build stops if `pencil` and the package's WASM are different builds of the core. `kept` is the folder of built
138
+ figures above.
139
+
140
+ The integration lets `astro dev` serve the package's own files (the element, its WASM and fonts) by adding the
141
+ package's folder to Vite's `server.fs.allow`, after Vite has worked out its own list, so a site's files are served as
142
+ they were. The package has types for the integration and `build()` (`astro/index.d.ts`), and `Figure.astro` declares
143
+ its props, so a TypeScript site needs no declarations of its own.
114
144
 
115
145
  ## Tests
116
146
 
@@ -122,7 +152,8 @@ pnpm test
122
152
 
123
153
  Playwright's, in [`tests/`](tests), against the corpus in this repo, headless, on its own Chromium and WebKit: each at
124
154
  a desktop size and as a phone (a Pixel 7 and an iPhone 15, emulated). They cover drawing, every key on a handle and on
125
- beats, a mouse drag and a touch drag, a range that follows another param, reduced motion, sheets picked by theme, the
155
+ beats, a mouse drag and a touch drag, a swipe that scrolls past a figure, a drag that selects no text, a range that follows another param, reduced motion, sheets picked by theme, the
126
156
  poster's swap, and a compiled figure. `PENCIL_GL=1 pnpm test` runs them all on WebGL2 in place of WebGPU, and `PENCIL_MIN=1 pnpm test` on the minified bundle.
127
157
  [`playwright.config.js`](playwright.config.js) says which GPU path each browser has headless. An emulated phone is a
128
- desktop engine at a phone's size with touch, not Mobile Safari: a real iPhone isn't covered.
158
+ desktop engine at a phone's size with touch, not Mobile Safari: a real iPhone isn't covered, and touches are sent
159
+ through Chromium's CDP, so the touch tests run on the Pixel 7 only.
@@ -49,7 +49,7 @@ const [main, ...others] = await Promise.all(
49
49
  );
50
50
  // A build ships the compiled figure. `astro dev` hands over the sources.
51
51
  const from = (built: Awaited<ReturnType<typeof build>>) =>
52
- built.src ? { src: built.src, sheets: built.sheets.join(' ') } : { compiled: built.compiled };
52
+ built.src ? { src: built.src, sheets: (built.sheets ?? []).join(' ') } : { compiled: built.compiled };
53
53
 
54
54
  // The poster takes the figure's exact shape, which its own pixels only round to, so nothing
55
55
  // moves by even a pixel when the figure takes over. A choice with another shape, as a narrow
@@ -64,6 +64,14 @@ const reshaped = others
64
64
  // one. And for a figure in view it starts on what the element will fetch, the WASM and the
65
65
  // compiled figure for the first choice whose media matches, and leaves them for it (`ahead`, in
66
66
  // host.js). `astro dev` loads the sources, so there that would fetch what's never used.
67
+ //
68
+ // The poster a browser fetches first can be the other theme's, for a reader whose page pins one
69
+ // against their system: while the page's stylesheet loads, which the script waits for, the browser
70
+ // reads ahead and fetches the image the system picks. The poster painted is still the pinned one.
71
+ // A `priority` poster stays eager anyway, since it's likely the page's largest first paint, and
72
+ // that one extra fetch is only for the few who pin. (A script between the `<source>`s and the
73
+ // `<img>` was measured, and is worse: then a browser reading ahead ignores the sources and fetches
74
+ // the fallback, for every reader.)
67
75
  const themed = choices.some((choice) => choice.media.includes('prefers-color-scheme'));
68
76
  const early = priority && main.compiled && !main.src;
69
77
  const fetchAhead = `const s=self.__pencilAhead??={},get=(u)=>fetch(u,{priority:'low'}).catch(()=>null);s.wasm??=get(${JSON.stringify(wasm).replace(/</g, '\\u003c')});const c=([...f.children].find((e)=>e.localName==='source'&&(!e.media||matchMedia(e.media).matches))??f).getAttribute('compiled');if(c){const u=new URL(c,document.baseURI).href;s[u]??=get(u)}`;
@@ -0,0 +1,95 @@
1
+ // Types for `build.js`, for a TypeScript site.
2
+
3
+ /** Where a site serves what a build made. */
4
+ export declare const PUBLIC: '_pencil';
5
+
6
+ /** A list of sheets, or their names with spaces between. */
7
+ export type Sheets = string | readonly string[];
8
+
9
+ /** What the integration worked out, which the pages it renders read from the environment. */
10
+ export interface PencilConfig {
11
+ root: string;
12
+ bin: string;
13
+ cache: string;
14
+ kept: string | null;
15
+ wasm: string;
16
+ dev: boolean;
17
+ base: string;
18
+ playground: string | null;
19
+ }
20
+
21
+ export declare function config(): PencilConfig;
22
+
23
+ /** A set of sheets that stands in for a figure's own under a media query. */
24
+ export interface Choice {
25
+ media: string;
26
+ sheets: string[];
27
+ }
28
+
29
+ /**
30
+ * The sets of sheets a reader can get: the figure's own, and each that stands in for them under a
31
+ * media query, the first that matches winning.
32
+ */
33
+ export declare function alternates(options: {
34
+ sheets?: Sheets;
35
+ dark?: Sheets;
36
+ narrow?: Sheets;
37
+ narrowMedia?: string;
38
+ }): { sheets: string[]; others: Choice[] };
39
+
40
+ /** What a figure says of itself, as the element's `info` does. */
41
+ export interface FigureInfo {
42
+ /** Its design size, `[width, height]`. */
43
+ size: [number, number];
44
+ panels: { id: string; title: string | null; formula: string | null; rect: [number, number, number, number] }[];
45
+ duration: number | null;
46
+ viewport: { x: [number, number]; y: [number, number]; width: number; height: number };
47
+ beats: string[];
48
+ beatLengths: number[];
49
+ timeDriven: string[];
50
+ usesTime: boolean;
51
+ params: {
52
+ id: string;
53
+ min: number;
54
+ max: number;
55
+ step: number | null;
56
+ follows: string[];
57
+ choice: { of: string; options: string[] } | null;
58
+ }[];
59
+ handles: { panel: number; mark: string; param: string }[];
60
+ poster: { time: number; params: Record<string, number> };
61
+ /** The named colors its sheets define, as CSS. */
62
+ colors: Record<string, string>;
63
+ }
64
+
65
+ export interface Built {
66
+ /** In `astro dev`, the document's URL, which the element is given in place of `compiled`. */
67
+ src?: string;
68
+ /** In `astro dev`, the sheets' URLs. */
69
+ sheets?: string[];
70
+ /** The compiled figure's URL. Null only in `astro dev`, while a source doesn't compile. */
71
+ compiled: string | null;
72
+ poster: { src: string; srcset?: string; webp?: string; width: number; height: number } | null;
73
+ card: { src: string; width: number; height: number } | null;
74
+ info: FigureInfo | null;
75
+ /** The figure as its poster shows it: the time, and every param's value and range by name. */
76
+ moment: { time: number; values: Record<string, number>; ranges: Record<string, [number, number]> } | null;
77
+ /** A link that opens the figure's sources in a playground, when the integration has one. */
78
+ playground: string | null;
79
+ hash: string | null;
80
+ }
81
+
82
+ /** Builds one figure under one set of sheets, by running `pencil build`. Paths are from the
83
+ * integration's `root`. */
84
+ export declare function build(options: {
85
+ src: string;
86
+ sheets?: readonly string[];
87
+ /** The poster's time, if not the document's own `poster`. */
88
+ time?: number;
89
+ /** The poster's params. */
90
+ params?: Record<string, number>;
91
+ /** The poster's width, for a figure with no design width. */
92
+ size?: number;
93
+ /** Also a 1200×630 card for sharing. */
94
+ card?: boolean;
95
+ }): Promise<Built>;
package/astro/build.js CHANGED
@@ -8,7 +8,7 @@
8
8
  // committed, for as long as the sources still hold what they did.
9
9
  import { execFile } from 'node:child_process';
10
10
  import { createHash } from 'node:crypto';
11
- import { cp, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
11
+ import { cp, mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
12
12
  import { existsSync } from 'node:fs';
13
13
  import path from 'node:path';
14
14
  import { pack } from '../src/pack.js';
@@ -148,6 +148,39 @@ async function playgroundLink(cfg, name, doc, sheets, sources) {
148
148
  }
149
149
 
150
150
  const making = new Map();
151
+ let serial = 0;
152
+
153
+ const mismatch = (cfg, manifest) =>
154
+ new Error(
155
+ `@pencil-lang/figure: \`${cfg.bin}\` is build ${manifest.build} of Pencil and the package's WASM is ${cfg.wasm}, so a page couldn't load what it compiles. Build both from the same source: \`cargo build --release -p pencil-cli\` and \`scripts/build-web.sh\`.`,
156
+ );
157
+
158
+ /** Puts a folder that has just been built where an older one may be. The older one is moved
159
+ * aside first and removed only once the new one is in place, and put back if that fails, so a
160
+ * kept figure is never lost to a failed build. Exported for its test. */
161
+ export async function replace(dir, built) {
162
+ await mkdir(path.dirname(dir), { recursive: true });
163
+ // Beside it, so it's on the same disk, and named with a dot, so a build's list of folders
164
+ // nothing asked for leaves it out.
165
+ const aside = path.join(path.dirname(dir), `.${path.basename(dir)}.old-${process.pid}-${(serial += 1)}`);
166
+ const had = existsSync(dir);
167
+ if (had) await rename(dir, aside);
168
+ try {
169
+ try {
170
+ await rename(built, dir);
171
+ } catch (error) {
172
+ // The cache and a kept folder can be on different disks.
173
+ if (error.code !== 'EXDEV') throw error;
174
+ await cp(built, dir, { recursive: true });
175
+ await rm(built, { recursive: true, force: true });
176
+ }
177
+ } catch (error) {
178
+ await rm(dir, { recursive: true, force: true });
179
+ if (had) await rename(aside, dir);
180
+ throw error;
181
+ }
182
+ if (had) await rm(aside, { recursive: true, force: true });
183
+ }
151
184
 
152
185
  /**
153
186
  * Builds one figure under one set of sheets.
@@ -187,7 +220,6 @@ async function make(cfg, key, { src, sheets, time, params, size, card }) {
187
220
  const stem = path.basename(src).replace(/\.[^.]+$/, '');
188
221
  const folder = `${stem}-${key.slice(0, 12)}`;
189
222
  const dir = path.join(cfg.kept ?? path.join(cfg.cache, 'made'), folder);
190
- const manifestFile = path.join(dir, `${stem}.json`);
191
223
  // So a build can say afterwards which kept folders nothing asked for.
192
224
  if (cfg.kept && !cfg.dev) {
193
225
  await mkdir(path.join(cfg.cache, 'used'), { recursive: true });
@@ -201,12 +233,16 @@ async function make(cfg, key, { src, sheets, time, params, size, card }) {
201
233
  for (const [name, value] of Object.entries(params)) args.push('--param', `${name}=${value}`);
202
234
  if (size != null) args.push('--size', String(size));
203
235
  if (card) args.push('--card');
204
- args.push('--out', dir);
205
- // Whatever an older `pencil` left there under another name would be shipped, and named in.
206
- await rm(dir, { recursive: true, force: true });
236
+ // It's built somewhere else and put in place once it has built, so a build that fails, or a
237
+ // `pencil` that isn't there, leaves what was there, and what a site keeps is never lost. A
238
+ // new folder, so whatever an older `pencil` left under another name isn't shipped.
239
+ const building = path.join(cfg.cache, 'building', `${folder}-${process.pid}-${(serial += 1)}`);
240
+ await rm(building, { recursive: true, force: true });
241
+ args.push('--out', building);
207
242
  try {
208
243
  await turn(() => run(cfg.bin, args, cfg.root));
209
244
  } catch (error) {
245
+ await rm(building, { recursive: true, force: true });
210
246
  // While a figure is being written it's often broken for a moment.
211
247
  if (cfg.dev) {
212
248
  console.warn(`[pencil] ${error.message}`);
@@ -222,15 +258,17 @@ async function make(cfg, key, { src, sheets, time, params, size, card }) {
222
258
  }
223
259
  throw error;
224
260
  }
225
- manifest = JSON.parse(await readFile(manifestFile, 'utf8'));
226
- if (cfg.kept) await writeFile(path.join(dir, STAMP), `${await sourcesHash(manifest.sources, cfg)}\n`);
261
+ manifest = JSON.parse(await readFile(path.join(building, `${stem}.json`), 'utf8'));
262
+ // One a page couldn't load is no better than none, and doesn't take the place of what's there.
263
+ if (manifest.build !== cfg.wasm) {
264
+ await rm(building, { recursive: true, force: true });
265
+ throw mismatch(cfg, manifest);
266
+ }
267
+ if (cfg.kept) await writeFile(path.join(building, STAMP), `${await sourcesHash(manifest.sources, cfg)}\n`);
268
+ await replace(dir, building);
227
269
  }
228
270
 
229
- if (manifest.build !== cfg.wasm) {
230
- throw new Error(
231
- `@pencil-lang/figure: \`${cfg.bin}\` is build ${manifest.build} of Pencil and the package's WASM is ${cfg.wasm}, so a page couldn't load what it compiles. Build both from the same source: \`cargo build --release -p pencil-cli\` and \`scripts/build-web.sh\`.`,
232
- );
233
- }
271
+ if (manifest.build !== cfg.wasm) throw mismatch(cfg, manifest);
234
272
 
235
273
  // What a reader fetches is named for what's in it, so a copy they kept is never a stale one. That's
236
274
  // the files' own bytes: a change to the renderer draws the same figure's poster differently, and
@@ -0,0 +1,20 @@
1
+ // Types for the Astro integration, for a TypeScript site. `Figure.astro` declares its own props.
2
+ import type { AstroIntegration } from 'astro';
3
+
4
+ export { alternates, build, PUBLIC } from './build.js';
5
+ export type { Built, Choice, FigureInfo, Sheets } from './build.js';
6
+
7
+ export interface PencilOptions {
8
+ /** Where `src` and `sheets` paths start, from the Astro project. The project, by default. */
9
+ root?: string;
10
+ /** The `pencil` command. By default PENCIL_BIN, then a Pencil checkout's, then `pencil` on the PATH. */
11
+ bin?: string;
12
+ /** A Pencil playground's address, as `https://pencil-lang.dev/playground/`, for links that open a
13
+ * figure's sources there. */
14
+ playground?: string;
15
+ /** A folder in the project to keep built figures in, committed with the site, for a build that
16
+ * runs where there's no `pencil` or no GPU. */
17
+ kept?: string;
18
+ }
19
+
20
+ export default function pencil(options?: PencilOptions): AstroIntegration;
package/astro/index.js CHANGED
@@ -71,6 +71,21 @@ async function wasmBuild() {
71
71
  return wasm.fingerprint();
72
72
  }
73
73
 
74
+ /** Lets `astro dev` serve the package's files (the element, its WASM and fonts) wherever the
75
+ * package is installed. A `server.fs.allow` in the config would replace Vite's own list, the
76
+ * workspace the site is in, and then the site's own files would be refused. So the folder is
77
+ * added to the list Vite worked out, whatever that is, which it reads on each request. */
78
+ function allowPackage() {
79
+ const dir = path.resolve(PACKAGE).split(path.sep).join('/');
80
+ return {
81
+ name: '@pencil-lang/figure:allow',
82
+ configResolved(config) {
83
+ const allow = config.server.fs.allow;
84
+ if (!allow.some((each) => dir === each || dir.startsWith(`${each.replace(/\/$/, '')}/`))) allow.push(dir);
85
+ },
86
+ };
87
+ }
88
+
74
89
  export default function pencil({ root, bin, playground, kept } = {}) {
75
90
  let cfg;
76
91
  return {
@@ -93,7 +108,7 @@ export default function pencil({ root, bin, playground, kept } = {}) {
93
108
  vite: {
94
109
  // The WASM is found beside the script that loads it, which bundling ahead would move.
95
110
  optimizeDeps: { exclude: ['@pencil-lang/figure'] },
96
- server: { fs: { allow: [PACKAGE] } },
111
+ plugins: [allowPackage()],
97
112
  },
98
113
  });
99
114
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pencil-lang/figure",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "Pencil figures on a page: the <pencil-figure> element, the WASM host it runs on, and an Astro component that builds a figure and its poster.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -22,7 +22,10 @@
22
22
  ".": "./src/element.js",
23
23
  "./host": "./src/host.js",
24
24
  "./pack": "./src/pack.js",
25
- "./astro": "./astro/index.js",
25
+ "./astro": {
26
+ "types": "./astro/index.d.ts",
27
+ "default": "./astro/index.js"
28
+ },
26
29
  "./Figure.astro": "./astro/Figure.astro",
27
30
  "./pencil_web_bg.wasm": "./pkg/pencil_web_bg.wasm"
28
31
  },