@pencil-lang/figure 0.0.0-stage → 0.0.1
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/LICENSE +21 -0
- package/README.md +122 -2
- package/astro/Figure.astro +102 -0
- package/astro/build.js +264 -0
- package/astro/client.js +9 -0
- package/astro/index.js +153 -0
- package/fonts/LibertinusMath-Regular.otf +0 -0
- package/fonts/LibertinusSans-Regular.otf +0 -0
- package/fonts/LibertinusSerif-Italic.otf +0 -0
- package/fonts/OFL.txt +94 -0
- package/fonts/README.md +18 -0
- package/package.json +54 -3
- package/pkg/pencil-figure.min.js +32 -0
- package/pkg/pencil_web.js +3094 -0
- package/pkg/pencil_web_bg.wasm +0 -0
- package/src/element.js +984 -0
- package/src/fit.js +14 -0
- package/src/host.js +109 -0
- package/src/labels.js +266 -0
- package/src/pack.js +67 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kris Selden
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,123 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @pencil-lang/figure
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Pencil figures on a page. One package with three ways in, since they have to be the same build: a figure a build
|
|
4
|
+
compiles is only read by the WASM built from the same source.
|
|
5
|
+
|
|
6
|
+
| Import | What it is |
|
|
7
|
+
|--------|------------|
|
|
8
|
+
| `@pencil-lang/figure` | Defines `<pencil-figure>`, and exports `PencilFigure`. |
|
|
9
|
+
| `@pencil-lang/figure/host` | The WASM as a page calls it: `ready()`, `Player`, `gather`, `uses`, `inspect`, `from_latex` and the rest. |
|
|
10
|
+
| `@pencil-lang/figure/pack` | `pack` and `unpack`: a figure's sources as a string for a link's `#pen=`, which the playground opens. |
|
|
11
|
+
| `@pencil-lang/figure/astro` | The Astro integration (the default export), `build()` and `alternates()`. |
|
|
12
|
+
| `@pencil-lang/figure/Figure.astro` | The Astro component. |
|
|
13
|
+
|
|
14
|
+
It isn't published yet. From another project, install it from a checkout, after building the WASM into `pkg/` here:
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
scripts/build-web.sh # in the Pencil repo
|
|
18
|
+
pnpm add ../pencil-lang/packages/figure # in the other project, with its own path to the checkout
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## The element
|
|
22
|
+
|
|
23
|
+
```html
|
|
24
|
+
<script type="module">import '@pencil-lang/figure';</script>
|
|
25
|
+
<pencil-figure src="tube.pen" sheets="theme.style tube.style"></pencil-figure>
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
It owns the canvas, the labels over it, the GPU and the clock. It starts the GPU when it's near the viewport, pauses
|
|
29
|
+
under `prefers-reduced-motion`, and every handle and beat can be worked from the keyboard. Its attributes, methods and
|
|
30
|
+
events are described at the top of [`src/element.js`](src/element.js).
|
|
31
|
+
|
|
32
|
+
Labels are set in the package's own fonts, in [`fonts/`](fonts/README.md): Libertinus, under the SIL Open Font License.
|
|
33
|
+
They're the files the `pencil` command draws a poster with, so the figure that takes over from a poster sets the same
|
|
34
|
+
glyphs in the same places. The element fetches the two text faces when it loads, and the math font the first time a
|
|
35
|
+
label needs it.
|
|
36
|
+
|
|
37
|
+
A bundler has to keep the WASM and the fonts where the scripts that load them look, `../pkg` and `../fonts` from `src/`. Vite does, once the package is left out of its
|
|
38
|
+
dependency pre-bundling (`optimizeDeps: { exclude: ['@pencil-lang/figure'] }`), which the Astro integration sets.
|
|
39
|
+
|
|
40
|
+
`scripts/build-web.sh` ends by writing `pkg/pencil-figure.min.js`, the element and the host bundled and minified into
|
|
41
|
+
one ES module with esbuild (`pnpm install` first). It exports what `@pencil-lang/figure` and `@pencil-lang/figure/host`
|
|
42
|
+
do, and finds its WASM beside itself, so it has to stay in `pkg/`. The pages in `web/` load it with `?min` on the URL
|
|
43
|
+
(`web/imports.js` is an import map for that), and `PENCIL_MIN=1 pnpm test` runs the tests on it. It's for measuring
|
|
44
|
+
the JavaScript a site would ship, with Lighthouse for one.
|
|
45
|
+
|
|
46
|
+
## Astro
|
|
47
|
+
|
|
48
|
+
```js
|
|
49
|
+
// astro.config.mjs
|
|
50
|
+
import pencil from '@pencil-lang/figure/astro';
|
|
51
|
+
|
|
52
|
+
export default defineConfig({
|
|
53
|
+
integrations: [pencil({ root: './figures' })],
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
```astro
|
|
58
|
+
---
|
|
59
|
+
import Figure from '@pencil-lang/figure/Figure.astro';
|
|
60
|
+
---
|
|
61
|
+
<Figure src="tube.pen" sheets="theme.style tube.style" dark="dark.style" alt="The strip rolling up into a tube." />
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
- **A build compiles each figure** with `pencil build`, once for each set of sheets a reader can get: `sheets`, with
|
|
65
|
+
`dark` added under a dark theme, and `narrow` added when `narrowMedia` matches (`(max-width: 600px)` unless said).
|
|
66
|
+
The page ships the compiled figures and their posters under `_pencil/`, and no sources. A figure that doesn't
|
|
67
|
+
compile stops the build with the compiler's message.
|
|
68
|
+
- **The poster is an image with the figure's size,** so the page is laid out before any script runs. It's offered as
|
|
69
|
+
WebP, with the PNG behind it. It shows until the
|
|
70
|
+
figure's first frame, and stays where a figure can't run. Nothing moves when the figure takes over. `poster={{ time,
|
|
71
|
+
params }}` picks another moment than the document's own `poster`.
|
|
72
|
+
- **`astro dev` hands the element the sources,** served from where they are, and a figure reloads in place when one is
|
|
73
|
+
saved, keeping its time and what a reader holds.
|
|
74
|
+
- **`priority` is for a figure in view when the page opens.** Its poster is fetched at once with `fetchpriority="high"`,
|
|
75
|
+
since it's likely the page's largest first paint. Every other poster is lazy. Mark one or two a page. A build also
|
|
76
|
+
writes a line of inline script that starts fetching what that figure will need, the WASM and the compiled figure its
|
|
77
|
+
media picks, at low priority, so they start as the page is read and not after the element's script has run. The
|
|
78
|
+
element takes them over, and each is downloaded once. (`<link rel="preload" as="fetch">` isn't used: WebKit fetches
|
|
79
|
+
the file again.)
|
|
80
|
+
- **A site can keep its built figures in its repo,** for a build that runs where there's no `pencil` or no GPU, as
|
|
81
|
+
most hosts' builders are. `pencil({ kept: 'figures' })` builds into that folder, and the folder is committed with
|
|
82
|
+
the site. A build uses what's kept for a figure for as long as its sources hold what they did when it was built,
|
|
83
|
+
and builds it again otherwise. Where `pencil` isn't there, it stops and says which figure needs building and why.
|
|
84
|
+
A compiled figure is read only by the build of Pencil that wrote it, so after the package is upgraded every figure
|
|
85
|
+
is built again, with a `pencil` from the same source as the package. A build names the folders nothing asked for,
|
|
86
|
+
and leaves them: one that skips drafts asks for fewer.
|
|
87
|
+
- **`alt` is required.** It's the poster's text and the figure's name.
|
|
88
|
+
- Anything else, such as `id`, `class`, `params`, `paused` or `data-*`, goes on `<pencil-figure>`.
|
|
89
|
+
|
|
90
|
+
`build({ src, sheets, time, params, size, card })` is what the component calls. A page can call it too, for a
|
|
91
|
+
figure's `info` (its size, params with their ranges, beats and captions, and the colors its sheets name) and its
|
|
92
|
+
`moment` (the time, and every param's value and range, where the poster shows it), to write its controls in their
|
|
93
|
+
first state before any script runs, or with `card: true` for a 1200×630 image for sharing.
|
|
94
|
+
|
|
95
|
+
`alternates({ sheets, dark, narrow, narrowMedia })` gives the sets of sheets the component builds a figure under: its
|
|
96
|
+
own as `sheets`, and as `others` each `{ media, sheets }` it writes a `<source>` for. A page that swaps one figure
|
|
97
|
+
for another, as a choice of styles does, swaps those `<source>`s too: one whose media matches is used before the
|
|
98
|
+
element's own attributes.
|
|
99
|
+
|
|
100
|
+
With `playground` set on the integration to a playground's address, as `https://pencil-lang.dev/playground/`,
|
|
101
|
+
`build()` also gives `playground`: a link that opens the figure's sources there, for a reader to read and change. A
|
|
102
|
+
built page ships no sources, so the link carries them all, compressed, after its `#`. It's a few thousand characters
|
|
103
|
+
a figure. Where the link goes on the page is the page's to say.
|
|
104
|
+
|
|
105
|
+
The integration's options are `root`, where `src` and `sheets` paths start (the Astro project by default),
|
|
106
|
+
`playground`, and `bin`, the `pencil` command. Without `bin` it tries `PENCIL_BIN`, then `target/release/pencil` in the checkout around `root`
|
|
107
|
+
or around this package, then `pencil` on the `PATH`. Drawing a poster takes a GPU, so a site is built where there is
|
|
108
|
+
one. A build stops if `pencil` and the package's WASM are different builds of the core.
|
|
109
|
+
|
|
110
|
+
## Tests
|
|
111
|
+
|
|
112
|
+
```bash
|
|
113
|
+
pnpm install
|
|
114
|
+
pnpm exec playwright install chromium webkit # once
|
|
115
|
+
pnpm test
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Playwright's, in [`tests/`](tests), against the corpus in this repo, headless, on its own Chromium and WebKit: each at
|
|
119
|
+
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
|
|
120
|
+
beats, a mouse drag and a touch drag, a range that follows another param, reduced motion, sheets picked by theme, the
|
|
121
|
+
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.
|
|
122
|
+
[`playwright.config.js`](playwright.config.js) says which GPU path each browser has headless. An emulated phone is a
|
|
123
|
+
desktop engine at a phone's size with touch, not Mobile Safari: a real iPhone isn't covered.
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
---
|
|
2
|
+
// A Pencil figure on an Astro page. A build compiles it and draws its poster, for each set of
|
|
3
|
+
// sheets a reader can get, and writes the element around them:
|
|
4
|
+
//
|
|
5
|
+
// <Figure src="tube.pen" sheets="theme.style tube.style" dark="dark.style" alt="…" />
|
|
6
|
+
//
|
|
7
|
+
// The poster is an image with the figure's size, so the page is laid out before any script runs,
|
|
8
|
+
// offered as WebP where that's smaller, with the PNG behind it,
|
|
9
|
+
// and it shows until the figure's first frame and wherever a figure can't run. The element swaps
|
|
10
|
+
// itself in over it without anything moving. `astro dev` gives the element the sources too, and a
|
|
11
|
+
// figure follows its files as they're edited.
|
|
12
|
+
//
|
|
13
|
+
// `sheets` are always applied. `dark` are added after them when the reader's theme is dark, and
|
|
14
|
+
// `narrow` before those when `narrowMedia` matches, as a sheet that reshapes a figure for a phone.
|
|
15
|
+
// Paths are from the integration's `root`. `alt` says what the figure shows, for the poster and
|
|
16
|
+
// for the figure. `poster` picks another moment than the document's own: `{ time, params }`.
|
|
17
|
+
// `priority` is for a figure a reader sees before scrolling: its poster is likely the largest
|
|
18
|
+
// thing painted first, so it's fetched at once and ahead of the rest. Every other poster waits
|
|
19
|
+
// until it's near, and a page should mark one figure or two, since marking them all marks none.
|
|
20
|
+
// A build knows what such a figure will fetch once its script runs, the compiled figure and the
|
|
21
|
+
// WASM, so a line of script in the page starts on them as it's read, behind the poster.
|
|
22
|
+
// Anything else (`id`, `class`, `params`, `paused`, `gl`, `data-*`) goes on `<pencil-figure>`.
|
|
23
|
+
import { alternates, build } from './build.js';
|
|
24
|
+
import wasm from '../pkg/pencil_web_bg.wasm?url';
|
|
25
|
+
|
|
26
|
+
interface Props {
|
|
27
|
+
src: string;
|
|
28
|
+
sheets?: string | string[];
|
|
29
|
+
dark?: string | string[];
|
|
30
|
+
narrow?: string | string[];
|
|
31
|
+
/** When `narrow` applies: one media condition. */
|
|
32
|
+
narrowMedia?: string;
|
|
33
|
+
alt: string;
|
|
34
|
+
poster?: { time?: number; params?: Record<string, number> };
|
|
35
|
+
/** The figure is in view when the page opens. */
|
|
36
|
+
priority?: boolean;
|
|
37
|
+
[attribute: string]: unknown;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const { src, sheets, dark, narrow, narrowMedia, alt, poster = {}, priority = false, ...attributes } = Astro.props;
|
|
41
|
+
// As in `<picture>`, the first choice that matches wins, so the narrowest case comes first.
|
|
42
|
+
const { sheets: always, others: choices } = alternates({ sheets, dark, narrow, narrowMedia });
|
|
43
|
+
|
|
44
|
+
const [main, ...others] = await Promise.all(
|
|
45
|
+
[{ sheets: always }, ...choices].map((choice) => build({ src, sheets: choice.sheets, ...poster })),
|
|
46
|
+
);
|
|
47
|
+
// A build ships the compiled figure. `astro dev` hands over the sources.
|
|
48
|
+
const from = (built: Awaited<ReturnType<typeof build>>) =>
|
|
49
|
+
built.src ? { src: built.src, sheets: built.sheets.join(' ') } : { compiled: built.compiled };
|
|
50
|
+
|
|
51
|
+
// The poster takes the figure's exact shape, which its own pixels only round to, so nothing
|
|
52
|
+
// moves by even a pixel when the figure takes over. A choice with another shape, as a narrow
|
|
53
|
+
// sheet gives, says so under its media query. Later rules win, so they go in reverse.
|
|
54
|
+
const shape = (built: Awaited<ReturnType<typeof build>>) => (built.info ? built.info.size.join(' / ') : undefined);
|
|
55
|
+
const reshaped = others
|
|
56
|
+
.map((built, i) => ({ media: choices[i].media, shape: shape(built) }))
|
|
57
|
+
.filter((each) => each.shape && each.shape !== shape(main))
|
|
58
|
+
.reverse();
|
|
59
|
+
// What to fetch ahead for a figure in view: the WASM, and the compiled figure for the first
|
|
60
|
+
// choice whose media matches, as `<source>` picks it. A script starts on them as the page is
|
|
61
|
+
// read and leaves them for the element (`ahead`, in host.js). `astro dev` loads the sources, so
|
|
62
|
+
// there it would fetch what's never used.
|
|
63
|
+
const early = priority && main.compiled && !main.src
|
|
64
|
+
? JSON.stringify({ wasm, figures: [...others.map((built, i) => [choices[i].media, built.compiled]), [null, main.compiled]] }).replace(/</g, '\\u003c')
|
|
65
|
+
: undefined;
|
|
66
|
+
const start = `(()=>{const a=${early},s=self.__pencilAhead??={},get=(u)=>fetch(u,{priority:'low'}).catch(()=>null);s.wasm??=get(a.wasm);const f=a.figures.find(([m])=>!m||matchMedia(m).matches);if(f){const u=new URL(f[1],document.baseURI).href;s[u]??=get(u)}})()`;
|
|
67
|
+
const mark = reshaped.length ? main.hash : undefined;
|
|
68
|
+
const rules = reshaped
|
|
69
|
+
.map((each) => `@media ${each.media}{[data-pencil-poster="${mark}"] img{--pencil-shape:${each.shape}}}`)
|
|
70
|
+
.join('');
|
|
71
|
+
---
|
|
72
|
+
{mark && <style is:inline set:html={rules}></style>}
|
|
73
|
+
{early && <script is:inline set:html={start}></script>}
|
|
74
|
+
<pencil-figure {...attributes} {...from(main)} aria-label={alt} data-pencil-poster={mark}>
|
|
75
|
+
{others.map((built, i) => <source media={choices[i].media} {...from(built)} />)}
|
|
76
|
+
{main.poster && (
|
|
77
|
+
<picture style={shape(main) && `--pencil-shape: ${shape(main)}`}>
|
|
78
|
+
{others.map((built, i) => built.poster && (
|
|
79
|
+
<>
|
|
80
|
+
{built.poster.webp && <source media={choices[i].media} type="image/webp" srcset={built.poster.webp} width={built.poster.width} height={built.poster.height} />}
|
|
81
|
+
<source media={choices[i].media} srcset={built.poster.srcset ?? built.poster.src} width={built.poster.width} height={built.poster.height} />
|
|
82
|
+
</>
|
|
83
|
+
))}
|
|
84
|
+
{main.poster.webp && <source type="image/webp" srcset={main.poster.webp} width={main.poster.width} height={main.poster.height} />}
|
|
85
|
+
<img
|
|
86
|
+
src={main.poster.src}
|
|
87
|
+
srcset={main.poster.srcset}
|
|
88
|
+
width={main.poster.width}
|
|
89
|
+
height={main.poster.height}
|
|
90
|
+
alt={alt}
|
|
91
|
+
loading={priority ? 'eager' : 'lazy'}
|
|
92
|
+
fetchpriority={priority ? 'high' : undefined}
|
|
93
|
+
decoding="async"
|
|
94
|
+
style="display: block; width: 100%; height: auto; aspect-ratio: var(--pencil-shape, auto)"
|
|
95
|
+
/>
|
|
96
|
+
</picture>
|
|
97
|
+
)}
|
|
98
|
+
</pencil-figure>
|
|
99
|
+
|
|
100
|
+
<script>
|
|
101
|
+
import './client.js';
|
|
102
|
+
</script>
|
package/astro/build.js
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
// Builds a figure for a page, by running `pencil build`: the compiled figure, its poster, what the
|
|
2
|
+
// page needs to know about it, and on request a card for sharing. `Figure.astro` calls this, and a
|
|
3
|
+
// page can too, for a figure's `info` or its card.
|
|
4
|
+
//
|
|
5
|
+
// Nothing is made twice: what a build wrote is kept in Astro's cache, and used again until one of
|
|
6
|
+
// the files that went into it, or `pencil` itself, is newer. A site can keep it in its own repo
|
|
7
|
+
// instead (the integration's `kept`), and then a build that has no `pencil` uses what was
|
|
8
|
+
// committed, for as long as the sources still hold what they did.
|
|
9
|
+
import { execFile } from 'node:child_process';
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import { cp, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
|
12
|
+
import { existsSync } from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { pack } from '../src/pack.js';
|
|
15
|
+
|
|
16
|
+
/** Where a site serves what a build made, and in `astro dev` the sources under `src/`. */
|
|
17
|
+
export const PUBLIC = '_pencil';
|
|
18
|
+
|
|
19
|
+
/** What the integration worked out, which it leaves in the environment for the pages it renders,
|
|
20
|
+
* since they're bundled and can run apart from it: where the figures are (`root`), the `pencil`
|
|
21
|
+
* command (`bin`), where to keep what's made (`cache`), the folder in the site's repo that holds
|
|
22
|
+
* built figures if it keeps them there (`kept`), which build of the core the package's WASM is
|
|
23
|
+
* (`wasm`), whether this is `astro dev` (`dev`), and the site's `base`. */
|
|
24
|
+
export function config() {
|
|
25
|
+
const text = process.env.PENCIL_FIGURE;
|
|
26
|
+
if (!text) {
|
|
27
|
+
throw new Error(
|
|
28
|
+
"@pencil-lang/figure: add the integration to astro.config (`import pencil from '@pencil-lang/figure/astro'`, then `integrations: [pencil()]`). It says where the figures are and where `pencil` is.",
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
return JSON.parse(text);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const hash = (text) => createHash('sha1').update(text).digest('hex');
|
|
35
|
+
const modified = async (file) => (await stat(file)).mtimeMs;
|
|
36
|
+
|
|
37
|
+
/** A hash of every file a build wrote into `dir`, by its name and its bytes. */
|
|
38
|
+
async function contents(dir) {
|
|
39
|
+
const sum = createHash('sha1');
|
|
40
|
+
for (const file of (await readdir(dir)).sort()) {
|
|
41
|
+
if (file !== STAMP) sum.update(`${file}\0`).update(await readFile(path.join(dir, file)));
|
|
42
|
+
}
|
|
43
|
+
return sum.digest('hex');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// At most this many `pencil` at once: each starts a GPU.
|
|
47
|
+
const ROOM = 4;
|
|
48
|
+
let busy = 0;
|
|
49
|
+
const waiting = [];
|
|
50
|
+
const turn = async (work) => {
|
|
51
|
+
if (busy >= ROOM) await new Promise((go) => waiting.push(go));
|
|
52
|
+
else busy += 1;
|
|
53
|
+
try {
|
|
54
|
+
return await work();
|
|
55
|
+
} finally {
|
|
56
|
+
// The next one waiting takes this place, so no one else can slip in ahead of it.
|
|
57
|
+
const next = waiting.shift();
|
|
58
|
+
if (next) next();
|
|
59
|
+
else busy -= 1;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const run = (bin, args, cwd) =>
|
|
64
|
+
new Promise((resolve, reject) => {
|
|
65
|
+
execFile(bin, args, { cwd, maxBuffer: 1 << 24 }, (error, stdout, stderr) => {
|
|
66
|
+
if (!error) return resolve(stdout);
|
|
67
|
+
if (error.code === 'ENOENT') {
|
|
68
|
+
const missing = new Error(
|
|
69
|
+
`@pencil-lang/figure: couldn't run \`${bin}\`. Build it with \`cargo build --release -p pencil-cli\`, or say where it is with the integration's \`bin\` or PENCIL_BIN.`,
|
|
70
|
+
);
|
|
71
|
+
missing.missing = true;
|
|
72
|
+
return reject(missing);
|
|
73
|
+
}
|
|
74
|
+
// The CLI's own message says the file, the line and what's wrong.
|
|
75
|
+
reject(new Error((stderr || stdout || error.message).trim()));
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
/** In a folder of kept figures, what its sources held when it was built. */
|
|
80
|
+
const STAMP = 'sources.sha1';
|
|
81
|
+
|
|
82
|
+
/** A hash of a figure's sources, by each one's path and what it holds. */
|
|
83
|
+
async function sourcesHash(sources, cfg) {
|
|
84
|
+
const sum = createHash('sha1');
|
|
85
|
+
for (const file of sources) sum.update(`${file}\0`).update(await readFile(path.resolve(cfg.root, file))).update('\0');
|
|
86
|
+
return sum.digest('hex');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** What a build wrote into `dir`, as `{ manifest }` if it's still what a build would write, and
|
|
90
|
+
* otherwise `{ why }`, which says what's the matter with it. */
|
|
91
|
+
async function fresh(dir, stem, cfg) {
|
|
92
|
+
let manifest;
|
|
93
|
+
try {
|
|
94
|
+
manifest = JSON.parse(await readFile(path.join(dir, `${stem}.json`), 'utf8'));
|
|
95
|
+
} catch {
|
|
96
|
+
return { why: 'nothing is built for it' };
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
if (cfg.kept) {
|
|
100
|
+
// A checkout gives every file the time it was checked out, so what's kept in a repo is
|
|
101
|
+
// compared by what its sources hold. A compiled figure is read only by the build of the core
|
|
102
|
+
// that wrote it, so one from another build is as good as none.
|
|
103
|
+
if (manifest.build !== cfg.wasm) return { why: 'what is kept was built by another build of Pencil' };
|
|
104
|
+
const stamp = (await readFile(path.join(dir, STAMP), 'utf8')).trim();
|
|
105
|
+
if (stamp !== (await sourcesHash(manifest.sources, cfg))) return { why: 'a source has changed since it was built' };
|
|
106
|
+
return { manifest };
|
|
107
|
+
}
|
|
108
|
+
const since = await modified(path.join(dir, `${stem}.json`));
|
|
109
|
+
const inputs = [...manifest.sources.map((file) => path.resolve(cfg.root, file))];
|
|
110
|
+
// `pencil` is found on the PATH when it isn't a path, and then its age isn't known.
|
|
111
|
+
if (path.isAbsolute(cfg.bin)) inputs.push(cfg.bin);
|
|
112
|
+
for (const file of inputs) if ((await modified(file)) > since) return { why: 'a source or `pencil` is newer' };
|
|
113
|
+
return { manifest };
|
|
114
|
+
} catch {
|
|
115
|
+
return { why: 'a source has changed since it was built' };
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const list = (value) => (Array.isArray(value) ? value : String(value ?? '').split(/\s+/).filter(Boolean));
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The sets of sheets a reader can get: the figure's own as `sheets`, and as `others` each set that
|
|
123
|
+
* stands in for them under a media query, `{ media, sheets }`. `dark` are added after `sheets`
|
|
124
|
+
* when the reader's theme is dark, and `narrow` before those when `narrowMedia` matches. As in
|
|
125
|
+
* `<picture>` the first that matches wins, so the narrowest case goes first. Each of `sheets`,
|
|
126
|
+
* `dark` and `narrow` is a list, or names with spaces between.
|
|
127
|
+
*/
|
|
128
|
+
export function alternates({ sheets, dark, narrow, narrowMedia = '(max-width: 600px)' }) {
|
|
129
|
+
const [always, whenDark, whenNarrow] = [list(sheets), list(dark), list(narrow)];
|
|
130
|
+
const DARK = '(prefers-color-scheme: dark)';
|
|
131
|
+
const others = [
|
|
132
|
+
whenNarrow.length && whenDark.length
|
|
133
|
+
? { media: `${narrowMedia} and ${DARK}`, sheets: [...always, ...whenNarrow, ...whenDark] }
|
|
134
|
+
: null,
|
|
135
|
+
whenDark.length ? { media: DARK, sheets: [...always, ...whenDark] } : null,
|
|
136
|
+
whenNarrow.length ? { media: narrowMedia, sheets: [...always, ...whenNarrow] } : null,
|
|
137
|
+
].filter((choice) => choice !== null);
|
|
138
|
+
return { sheets: always, others };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** A link into a playground that carries everything the figure was built from, or nothing if
|
|
142
|
+
* the integration wasn't given a playground. */
|
|
143
|
+
async function playgroundLink(cfg, name, doc, sheets, sources) {
|
|
144
|
+
if (!cfg.playground) return null;
|
|
145
|
+
const files = {};
|
|
146
|
+
for (const file of sources) files[file] = await readFile(path.resolve(cfg.root, file), 'utf8');
|
|
147
|
+
return `${cfg.playground}#pen=${await pack({ name, doc, sheets, files })}`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const making = new Map();
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Builds one figure under one set of sheets.
|
|
154
|
+
*
|
|
155
|
+
* - `src`: the document, a path from the integration's `root`.
|
|
156
|
+
* - `sheets`: its sheets, in order, the same way.
|
|
157
|
+
* - `time`, `params`: the poster's moment, if not the document's own `poster`.
|
|
158
|
+
* - `size`: the poster's width, for a figure with no design width.
|
|
159
|
+
* - `card`: also a 1200×630 card for sharing.
|
|
160
|
+
*
|
|
161
|
+
* Gives `{ compiled, poster: { src, srcset, webp, width, height }, card, info, moment, hash }`,
|
|
162
|
+
* with URLs from the site's root. `moment` is the figure as its poster shows it, which is how a
|
|
163
|
+
* page that holds the same params starts it: `{ time, values, ranges }`, the last two for every
|
|
164
|
+
* param by name, so a page can write its controls as they'll be before the figure runs.
|
|
165
|
+
* `playground` is a link that opens the figure's sources in a playground, when the integration
|
|
166
|
+
* was told where one is: the page ships none of them, so the link carries them all. `webp` is a `srcset` of the same poster as WebP, where that's the smaller,
|
|
167
|
+
* and in `astro dev` also `src` and `sheets`, the sources' URLs, which the
|
|
168
|
+
* element is given there so a figure follows its files as they're edited. A document that doesn't
|
|
169
|
+
* compile fails the build with the compiler's message. In `astro dev` it gives the sources alone,
|
|
170
|
+
* and the element says what's wrong.
|
|
171
|
+
*/
|
|
172
|
+
export function build({ src, sheets = [], time, params = {}, size, card = false }) {
|
|
173
|
+
const cfg = config();
|
|
174
|
+
const key = hash(JSON.stringify([src, sheets, time ?? null, Object.entries(params).sort(), size ?? null, card]));
|
|
175
|
+
if (!making.has(key)) {
|
|
176
|
+
const made = make(cfg, key, { src, sheets, time, params, size, card }).finally(() => making.delete(key));
|
|
177
|
+
making.set(key, made);
|
|
178
|
+
}
|
|
179
|
+
return making.get(key);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function make(cfg, key, { src, sheets, time, params, size, card }) {
|
|
183
|
+
const base = `${cfg.base.replace(/\/$/, '')}/${PUBLIC}`;
|
|
184
|
+
const sources = cfg.dev
|
|
185
|
+
? { src: `${base}/src/${src}`, sheets: sheets.map((sheet) => `${base}/src/${sheet}`) }
|
|
186
|
+
: {};
|
|
187
|
+
const stem = path.basename(src).replace(/\.[^.]+$/, '');
|
|
188
|
+
const folder = `${stem}-${key.slice(0, 12)}`;
|
|
189
|
+
const dir = path.join(cfg.kept ?? path.join(cfg.cache, 'made'), folder);
|
|
190
|
+
const manifestFile = path.join(dir, `${stem}.json`);
|
|
191
|
+
// So a build can say afterwards which kept folders nothing asked for.
|
|
192
|
+
if (cfg.kept && !cfg.dev) {
|
|
193
|
+
await mkdir(path.join(cfg.cache, 'used'), { recursive: true });
|
|
194
|
+
await writeFile(path.join(cfg.cache, 'used', folder), '');
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
let { manifest, why } = await fresh(dir, stem, cfg);
|
|
198
|
+
if (!manifest) {
|
|
199
|
+
const args = ['build', src, ...sheets.flatMap((sheet) => ['--style', sheet])];
|
|
200
|
+
if (time != null) args.push('--t', String(time));
|
|
201
|
+
for (const [name, value] of Object.entries(params)) args.push('--param', `${name}=${value}`);
|
|
202
|
+
if (size != null) args.push('--size', String(size));
|
|
203
|
+
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 });
|
|
207
|
+
try {
|
|
208
|
+
await turn(() => run(cfg.bin, args, cfg.root));
|
|
209
|
+
} catch (error) {
|
|
210
|
+
// While a figure is being written it's often broken for a moment.
|
|
211
|
+
if (cfg.dev) {
|
|
212
|
+
console.warn(`[pencil] ${error.message}`);
|
|
213
|
+
return { ...sources, compiled: null, poster: null, card: null, info: null, moment: null, playground: null, hash: null };
|
|
214
|
+
}
|
|
215
|
+
// A site that keeps its figures is built where there's no `pencil`, and then the one thing
|
|
216
|
+
// to say is which figure isn't what was committed, and why.
|
|
217
|
+
if (cfg.kept && error.missing) {
|
|
218
|
+
const kept = path.relative(process.cwd(), cfg.kept) || '.';
|
|
219
|
+
throw new Error(
|
|
220
|
+
`@pencil-lang/figure: \`${src}\`${sheets.length ? ` with ${sheets.join(', ')}` : ''} needs building (${why}), and \`${cfg.bin}\` isn't here to build it. Build the site where \`pencil\` and a GPU are, and commit \`${kept}\`.`,
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
throw error;
|
|
224
|
+
}
|
|
225
|
+
manifest = JSON.parse(await readFile(manifestFile, 'utf8'));
|
|
226
|
+
if (cfg.kept) await writeFile(path.join(dir, STAMP), `${await sourcesHash(manifest.sources, cfg)}\n`);
|
|
227
|
+
}
|
|
228
|
+
|
|
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
|
+
}
|
|
234
|
+
|
|
235
|
+
// What a reader fetches is named for what's in it, so a copy they kept is never a stale one. That's
|
|
236
|
+
// the files' own bytes: a change to the renderer draws the same figure's poster differently, and
|
|
237
|
+
// nothing the build wrote about the figure would say so.
|
|
238
|
+
const name = `${stem}-${(await contents(dir)).slice(0, 12)}`;
|
|
239
|
+
const out = path.join(cfg.cache, 'out', name);
|
|
240
|
+
if (!existsSync(path.join(out, `${stem}.json`))) {
|
|
241
|
+
await mkdir(path.dirname(out), { recursive: true });
|
|
242
|
+
await cp(dir, out, { recursive: true, filter: (file) => path.basename(file) !== STAMP });
|
|
243
|
+
}
|
|
244
|
+
const url = (file) => `${base}/${name}/${file}`;
|
|
245
|
+
const [one, two] = manifest.poster.images;
|
|
246
|
+
// The WebP is offered only when both sizes have one, so a reader gets one kind at any density.
|
|
247
|
+
const lighter = one.webp && (!two || two.webp);
|
|
248
|
+
return {
|
|
249
|
+
...sources,
|
|
250
|
+
compiled: url(manifest.figure),
|
|
251
|
+
poster: {
|
|
252
|
+
src: url(one.src),
|
|
253
|
+
srcset: two ? `${url(one.src)}, ${url(two.src)} 2x` : undefined,
|
|
254
|
+
webp: lighter ? (two ? `${url(one.webp)}, ${url(two.webp)} 2x` : url(one.webp)) : undefined,
|
|
255
|
+
width: one.width,
|
|
256
|
+
height: one.height,
|
|
257
|
+
},
|
|
258
|
+
card: manifest.card ? { src: url(manifest.card.src), width: manifest.card.width, height: manifest.card.height } : null,
|
|
259
|
+
info: manifest.info,
|
|
260
|
+
moment: { time: manifest.poster.time, values: manifest.poster.values, ranges: manifest.poster.ranges },
|
|
261
|
+
playground: await playgroundLink(cfg, stem, src, sheets, manifest.sources),
|
|
262
|
+
hash: manifest.hash,
|
|
263
|
+
};
|
|
264
|
+
}
|
package/astro/client.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// What a page with a `<Figure>` loads: the element, and in `astro dev` word from the integration
|
|
2
|
+
// that a source changed, so each figure fetches its files again where it is.
|
|
3
|
+
import '../src/element.js';
|
|
4
|
+
|
|
5
|
+
if (import.meta.hot) {
|
|
6
|
+
import.meta.hot.on('pencil:change', () => {
|
|
7
|
+
for (const figure of document.querySelectorAll('pencil-figure')) figure.reload();
|
|
8
|
+
});
|
|
9
|
+
}
|