@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/src/fit.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// A figure's canvas takes its shape from the figure and its width from the page, and keeps its
|
|
2
|
+
// pixels matched to that width, so it draws sharp at any size. `<pencil-figure>` shapes it to the
|
|
3
|
+
// design size the sheets give and calls this as the page lays it out again.
|
|
4
|
+
|
|
5
|
+
/** Sizes the canvas's pixels to its laid-out size, in device pixels. Setting a size clears the
|
|
6
|
+
* canvas, even to the size it has, so it's only set when it changes. */
|
|
7
|
+
export function match(canvas) {
|
|
8
|
+
const dpr = window.devicePixelRatio || 1;
|
|
9
|
+
const width = Math.max(1, Math.round(canvas.clientWidth * dpr));
|
|
10
|
+
const height = Math.max(1, Math.round(canvas.clientHeight * dpr));
|
|
11
|
+
if (canvas.width !== width) canvas.width = width;
|
|
12
|
+
if (canvas.height !== height) canvas.height = height;
|
|
13
|
+
return [width, height];
|
|
14
|
+
}
|
package/src/host.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// The host interface: the Rust core, compiled to WASM, as a page calls it. `<pencil-figure>` is
|
|
2
|
+
// built on this and is what most pages want. A page that draws to its own canvas, reads how text
|
|
3
|
+
// parses, or converts LaTeX uses these directly.
|
|
4
|
+
//
|
|
5
|
+
// `ready()` fetches and starts the WASM, once. Everything else here needs it to have resolved:
|
|
6
|
+
//
|
|
7
|
+
// import { ready, Player, gather } from '@pencil-lang/figure/host';
|
|
8
|
+
// await ready();
|
|
9
|
+
// const player = await Player.create(canvas, false);
|
|
10
|
+
//
|
|
11
|
+
// `scripts/build-web.sh` writes `../pkg`, which isn't checked in.
|
|
12
|
+
import init from '../pkg/pencil_web.js';
|
|
13
|
+
|
|
14
|
+
export {
|
|
15
|
+
Player,
|
|
16
|
+
figure_size,
|
|
17
|
+
figure_size_compiled,
|
|
18
|
+
named_colors,
|
|
19
|
+
uses,
|
|
20
|
+
fingerprint,
|
|
21
|
+
inspect,
|
|
22
|
+
functions,
|
|
23
|
+
is_latex,
|
|
24
|
+
from_latex,
|
|
25
|
+
symbols,
|
|
26
|
+
} from '../pkg/pencil_web.js';
|
|
27
|
+
import { uses } from '../pkg/pencil_web.js';
|
|
28
|
+
|
|
29
|
+
let starting = null;
|
|
30
|
+
let started = false;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* What the page began fetching before this script ran, if it did, and hands it over: a response,
|
|
34
|
+
* or nothing. A page that knows what a figure will need can start on it as it's read, in a
|
|
35
|
+
* script of its own, and leave each promise here by name: `wasm`, or a compiled figure's URL.
|
|
36
|
+
*
|
|
37
|
+
* (self.__pencilAhead ??= {}).wasm = fetch(url, { priority: 'low' }).catch(() => null);
|
|
38
|
+
*
|
|
39
|
+
* It's this and not `<link rel="preload" as="fetch">` because WebKit doesn't give a preloaded
|
|
40
|
+
* fetch to the script that asks for it, and downloads the file again.
|
|
41
|
+
*/
|
|
42
|
+
export async function ahead(name) {
|
|
43
|
+
const waiting = globalThis.__pencilAhead;
|
|
44
|
+
const early = waiting?.[name];
|
|
45
|
+
if (!early) return null;
|
|
46
|
+
delete waiting[name];
|
|
47
|
+
try {
|
|
48
|
+
const response = await early;
|
|
49
|
+
return response?.ok ? response : null;
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function start() {
|
|
56
|
+
const early = await ahead('wasm');
|
|
57
|
+
if (early) {
|
|
58
|
+
try {
|
|
59
|
+
const wasm = await init({ module_or_path: early });
|
|
60
|
+
started = true;
|
|
61
|
+
return wasm;
|
|
62
|
+
} catch {
|
|
63
|
+
// One that was cut short, as a tab left in the background can be, is fetched again.
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const wasm = await init();
|
|
67
|
+
started = true;
|
|
68
|
+
return wasm;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Fetches and starts the WASM core, once, and resolves when it can be called. */
|
|
72
|
+
export const ready = () => (starting ??= start());
|
|
73
|
+
|
|
74
|
+
/** Whether the core can be called now, without waiting. */
|
|
75
|
+
export const isReady = () => started;
|
|
76
|
+
|
|
77
|
+
const fetchText = async (url) => {
|
|
78
|
+
const response = await fetch(new URL(url, document.baseURI));
|
|
79
|
+
if (!response.ok) throw new Error(`${url}: ${response.status}`);
|
|
80
|
+
return response.text();
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Reads every file a document and its sheets `use`, and every file those use, for `load`.
|
|
85
|
+
* `names` say where the document and then each sheet came from: URLs, which can be relative to
|
|
86
|
+
* the page. A used file is found from the file that names it, so its own name is a URL too, and
|
|
87
|
+
* `read` is given that. A file that can't be read is left out, and compiling says which line
|
|
88
|
+
* wanted it. `have` are files already at hand, by name, such as ones being edited.
|
|
89
|
+
*/
|
|
90
|
+
export async function gather(names, texts, read = fetchText, have = {}) {
|
|
91
|
+
await ready();
|
|
92
|
+
const files = {};
|
|
93
|
+
const visit = (name, text) =>
|
|
94
|
+
Promise.all(
|
|
95
|
+
uses(name, text).map(async (file) => {
|
|
96
|
+
if (file in files) return;
|
|
97
|
+
files[file] = null;
|
|
98
|
+
try {
|
|
99
|
+
files[file] = have[file] ?? (await read(file));
|
|
100
|
+
} catch {
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
await visit(file, files[file]);
|
|
104
|
+
}),
|
|
105
|
+
);
|
|
106
|
+
await Promise.all(texts.map((text, i) => visit(names[i] ?? '', text)));
|
|
107
|
+
for (const [file, text] of Object.entries(files)) if (text === null) delete files[file];
|
|
108
|
+
return { names, files };
|
|
109
|
+
}
|
package/src/labels.js
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
// Text over a figure, for every page. A settling label's spot comes from the figure, and
|
|
2
|
+
// the same spring `place::spring` runs for video runs here over the page's clock, on its
|
|
3
|
+
// offset from its point: a reader's drag has no time axis, and only the page has its history.
|
|
4
|
+
const RATE = 12;
|
|
5
|
+
const REST = 0.01;
|
|
6
|
+
|
|
7
|
+
// As `frame::LEADER_MARGIN` and `frame::TEXT_HALF_HEIGHT`, which video uses.
|
|
8
|
+
const LEADER_MARGIN = 0.25;
|
|
9
|
+
const TEXT_HALF_HEIGHT = 0.35;
|
|
10
|
+
const SVG = 'http://www.w3.org/2000/svg';
|
|
11
|
+
// The size text is measured at, in pixels.
|
|
12
|
+
const RULER = 100;
|
|
13
|
+
|
|
14
|
+
// The package's own fonts, Libertinus under the SIL Open Font License (`../fonts/OFL.txt`): the
|
|
15
|
+
// files the `pencil` command has built in, so a poster and the figure that takes over from it
|
|
16
|
+
// set the same glyphs at the same widths. A role is a text face with the math font behind it,
|
|
17
|
+
// for what the text face lacks. The math font is registered as italic too, so the browser
|
|
18
|
+
// doesn't slant an `ℝ` it finds there for a label in italics.
|
|
19
|
+
const FILES = {
|
|
20
|
+
sans: new URL('../fonts/LibertinusSans-Regular.otf', import.meta.url),
|
|
21
|
+
italic: new URL('../fonts/LibertinusSerif-Italic.otf', import.meta.url),
|
|
22
|
+
math: new URL('../fonts/LibertinusMath-Regular.otf', import.meta.url),
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
// As `formula::BASELINE`: how far below the middle of a line the fonts' baseline is, in ems.
|
|
26
|
+
const BASELINE = 0.324;
|
|
27
|
+
|
|
28
|
+
export const FAMILY = {
|
|
29
|
+
math: "'Pencil Serif', 'Pencil Math', Charter, 'Bitstream Charter', 'Sitka Text', Cambria, serif",
|
|
30
|
+
sans: "'Pencil Sans', 'Pencil Math', system-ui, -apple-system, sans-serif",
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
// The command sets glyphs one after another by their advances, with no kerning or ligatures, so
|
|
34
|
+
// the page does too.
|
|
35
|
+
export const LABEL_CSS = `
|
|
36
|
+
.label { position: absolute; left: 0; top: 0; white-space: nowrap; font-family: ${FAMILY.sans}; line-height: 1; will-change: transform; font-kerning: none; font-variant-ligatures: none; font-feature-settings: "calt" 0; }
|
|
37
|
+
.label.math { font-family: ${FAMILY.math}; font-style: italic; }
|
|
38
|
+
/* A label with mathematics in it is a point, with each run and rule the core laid out placed from
|
|
39
|
+
it. A run is set from the top of its line, and a stretched one grows about its baseline. */
|
|
40
|
+
.label.laid { width: 0; height: 0; }
|
|
41
|
+
.label .run { position: absolute; white-space: pre; line-height: 1; transform-origin: 0 ${(0.5 + BASELINE) * 100}%; }
|
|
42
|
+
.label .run.formula { font-family: 'Pencil Math', ${FAMILY.math}; font-style: normal; }
|
|
43
|
+
.label .rule { position: absolute; background: var(--rule); outline: var(--grow, 0px) solid var(--rule); }
|
|
44
|
+
`;
|
|
45
|
+
|
|
46
|
+
/** Registers the faces, and resolves when the two text faces are in, or can't be had. The math
|
|
47
|
+
* font is fetched when something is first set in it. */
|
|
48
|
+
function loadFonts() {
|
|
49
|
+
if (typeof document === 'undefined' || typeof FontFace === 'undefined') return Promise.resolve();
|
|
50
|
+
const face = (family, url, style) => {
|
|
51
|
+
const made = new FontFace(family, `url("${url.href}")`, { style });
|
|
52
|
+
document.fonts.add(made);
|
|
53
|
+
return made;
|
|
54
|
+
};
|
|
55
|
+
const text = [face('Pencil Sans', FILES.sans, 'normal'), face('Pencil Serif', FILES.italic, 'italic')];
|
|
56
|
+
face('Pencil Math', FILES.math, 'normal');
|
|
57
|
+
face('Pencil Math', FILES.math, 'italic');
|
|
58
|
+
// A figure without its fonts still draws, in the fallbacks.
|
|
59
|
+
return Promise.allSettled(text.map((made) => made.load())).then(() => {});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export const fonts = loadFonts();
|
|
63
|
+
|
|
64
|
+
export class LabelLayer {
|
|
65
|
+
constructor(stage, dpr) {
|
|
66
|
+
this.stage = stage;
|
|
67
|
+
this.dpr = dpr;
|
|
68
|
+
// Leaders under everything, then every halo under every glyph, so one term's can't eat
|
|
69
|
+
// into its neighbor.
|
|
70
|
+
this.leaders = document.createElementNS(SVG, 'svg');
|
|
71
|
+
this.leaders.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;pointer-events:none;overflow:visible';
|
|
72
|
+
this.stage.append(this.leaders);
|
|
73
|
+
this.halos = this.makeLayer();
|
|
74
|
+
this.glyphs = this.makeLayer();
|
|
75
|
+
this.ruler = document.createElement('canvas').getContext('2d');
|
|
76
|
+
this.items = new Map();
|
|
77
|
+
this.advances = new Map();
|
|
78
|
+
this.last = 0;
|
|
79
|
+
this.still = matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
makeLayer() {
|
|
83
|
+
const layer = document.createElement('div');
|
|
84
|
+
layer.style.cssText = 'position:absolute;inset:0;pointer-events:none';
|
|
85
|
+
this.stage.append(layer);
|
|
86
|
+
return layer;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** For `Player.set_measure`: a width in device pixels, in the same font labels are drawn in.
|
|
90
|
+
* It's the sum of each character's advance, as the command measures, so no kerning. */
|
|
91
|
+
measure = (text, size, math) => {
|
|
92
|
+
const role = math ? 'math' : 'sans';
|
|
93
|
+
let width = 0;
|
|
94
|
+
for (const character of text) {
|
|
95
|
+
const key = role + character;
|
|
96
|
+
let advance = this.advances.get(key);
|
|
97
|
+
if (advance === undefined) {
|
|
98
|
+
// At a large size, so the browser's rounding of a small one doesn't add up.
|
|
99
|
+
this.ruler.font = `${math ? 'italic ' : ''}${RULER}px ${FAMILY[role]}`;
|
|
100
|
+
advance = this.ruler.measureText(character).width / RULER;
|
|
101
|
+
this.advances.set(key, advance);
|
|
102
|
+
}
|
|
103
|
+
width += advance;
|
|
104
|
+
}
|
|
105
|
+
return width * size;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
/** Forgets what was measured, when a font arrives after text was measured without it. */
|
|
109
|
+
remeasure() {
|
|
110
|
+
this.advances.clear();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Takes a frame's labels. One that isn't listed doesn't exist this frame. */
|
|
114
|
+
update(labels) {
|
|
115
|
+
const present = new Set();
|
|
116
|
+
for (const label of labels) {
|
|
117
|
+
present.add(label.id);
|
|
118
|
+
let item = this.items.get(label.id);
|
|
119
|
+
const target = [label.x - label.anchorX, label.y - label.anchorY];
|
|
120
|
+
if (!item) {
|
|
121
|
+
const span = document.createElement('span');
|
|
122
|
+
span.className = 'label';
|
|
123
|
+
const halo = span.cloneNode();
|
|
124
|
+
// Which label it is, for whoever looks: a page's own script, or a test.
|
|
125
|
+
span.dataset.label = label.id;
|
|
126
|
+
this.halos.append(halo);
|
|
127
|
+
this.glyphs.append(span);
|
|
128
|
+
const line = document.createElementNS(SVG, 'line');
|
|
129
|
+
this.leaders.append(line);
|
|
130
|
+
item = { span, halo, line, offset: target.slice(), velocity: [0, 0], shown: false };
|
|
131
|
+
this.items.set(label.id, item);
|
|
132
|
+
}
|
|
133
|
+
const { span, halo } = item;
|
|
134
|
+
// What comes back starts where it belongs, not gliding in from where it went.
|
|
135
|
+
if (!item.shown) {
|
|
136
|
+
item.offset = target.slice();
|
|
137
|
+
item.velocity = [0, 0];
|
|
138
|
+
item.shown = true;
|
|
139
|
+
}
|
|
140
|
+
item.target = target;
|
|
141
|
+
item.anchor = [label.anchorX, label.anchorY];
|
|
142
|
+
item.settles = label.settles;
|
|
143
|
+
item.leader = label.leader;
|
|
144
|
+
item.text = label.text;
|
|
145
|
+
item.size = label.size;
|
|
146
|
+
item.math = label.math;
|
|
147
|
+
item.line.style.stroke = label.color;
|
|
148
|
+
item.line.style.opacity = label.opacity;
|
|
149
|
+
// What's laid out is rebuilt only when it changes, which a label that only moves doesn't.
|
|
150
|
+
const laid = label.laid ? JSON.stringify(label.laid) : '';
|
|
151
|
+
item.half = label.laid ? [label.laid.halfWidth, label.laid.halfHeight] : null;
|
|
152
|
+
for (const part of [span, halo]) {
|
|
153
|
+
if (label.laid) {
|
|
154
|
+
if (part.laid !== laid) this.lay(part, label.laid);
|
|
155
|
+
} else if (part.laid || part.textContent !== label.text) {
|
|
156
|
+
part.textContent = label.text;
|
|
157
|
+
}
|
|
158
|
+
part.laid = laid;
|
|
159
|
+
part.classList.toggle('laid', !!label.laid);
|
|
160
|
+
part.hidden = false;
|
|
161
|
+
part.classList.toggle('math', label.math);
|
|
162
|
+
part.style.fontSize = `${label.size / this.dpr}px`;
|
|
163
|
+
part.style.opacity = label.opacity;
|
|
164
|
+
}
|
|
165
|
+
span.style.color = label.color;
|
|
166
|
+
span.style.setProperty('--rule', label.color);
|
|
167
|
+
halo.style.color = 'transparent';
|
|
168
|
+
halo.style.webkitTextStrokeColor = label.haloColor;
|
|
169
|
+
halo.style.webkitTextStrokeWidth = `${label.halo / this.dpr}px`;
|
|
170
|
+
// A rule's halo is the rule grown by half the halo's width, as a glyph's is its outline's.
|
|
171
|
+
halo.style.setProperty('--rule', label.halo > 0 ? label.haloColor : 'transparent');
|
|
172
|
+
halo.style.setProperty('--grow', `${label.halo / 2 / this.dpr}px`);
|
|
173
|
+
}
|
|
174
|
+
for (const [id, item] of this.items) {
|
|
175
|
+
if (!present.has(id)) {
|
|
176
|
+
item.span.hidden = true;
|
|
177
|
+
item.halo.hidden = true;
|
|
178
|
+
item.line.style.display = 'none';
|
|
179
|
+
item.shown = false;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
this.place();
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Fills a label with what the core laid out: runs of text and rules, in device pixels from the
|
|
186
|
+
* label's point. */
|
|
187
|
+
lay(part, laid) {
|
|
188
|
+
const px = (v) => `${v / this.dpr}px`;
|
|
189
|
+
part.textContent = '';
|
|
190
|
+
for (const run of laid.runs) {
|
|
191
|
+
const piece = document.createElement('span');
|
|
192
|
+
piece.className = run.math ? 'run formula' : 'run';
|
|
193
|
+
piece.textContent = run.text;
|
|
194
|
+
piece.style.cssText = `left:${px(run.x)};top:${px(run.top)};font-size:${px(run.size)}`;
|
|
195
|
+
if (run.stretch !== 1) piece.style.transform = `scaleY(${run.stretch})`;
|
|
196
|
+
part.append(piece);
|
|
197
|
+
}
|
|
198
|
+
for (const rule of laid.rules) {
|
|
199
|
+
const piece = document.createElement('span');
|
|
200
|
+
piece.className = 'rule';
|
|
201
|
+
piece.style.cssText = `left:${px(rule.x)};top:${px(rule.y)};width:${px(rule.width)};height:${px(rule.height)}`;
|
|
202
|
+
part.append(piece);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
place() {
|
|
207
|
+
for (const item of this.items.values()) {
|
|
208
|
+
if (!item.shown) continue;
|
|
209
|
+
const [x, y] = [item.anchor[0] + item.offset[0], item.anchor[1] + item.offset[1]];
|
|
210
|
+
const transform = `translate(${x / this.dpr}px, ${y / this.dpr}px) translate(-50%, -50%)`;
|
|
211
|
+
item.span.style.transform = transform;
|
|
212
|
+
item.halo.style.transform = transform;
|
|
213
|
+
this.placeLeader(item, x, y);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** As `frame::leader_ends`: from its gap off the point to a little short of the text's box. */
|
|
218
|
+
placeLeader(item, x, y) {
|
|
219
|
+
const { line, leader, anchor } = item;
|
|
220
|
+
const [dx, dy] = [x - anchor[0], y - anchor[1]];
|
|
221
|
+
const apart = Math.hypot(dx, dy);
|
|
222
|
+
let end = -Infinity;
|
|
223
|
+
if (leader && apart > 0) {
|
|
224
|
+
const [ux, uy] = [dx / apart, dy / apart];
|
|
225
|
+
const half = item.half ?? [this.measure(item.text, item.size, item.math) / 2, item.size * TEXT_HALF_HEIGHT];
|
|
226
|
+
const toEdge = Math.min(half[0] / Math.max(Math.abs(ux), 1e-9), half[1] / Math.max(Math.abs(uy), 1e-9));
|
|
227
|
+
end = apart - toEdge - LEADER_MARGIN * item.size;
|
|
228
|
+
if (end > leader.gap) {
|
|
229
|
+
const at = (d) => [(anchor[0] + ux * d) / this.dpr, (anchor[1] + uy * d) / this.dpr];
|
|
230
|
+
const [a, b] = [at(leader.gap), at(end)];
|
|
231
|
+
line.setAttribute('x1', a[0]);
|
|
232
|
+
line.setAttribute('y1', a[1]);
|
|
233
|
+
line.setAttribute('x2', b[0]);
|
|
234
|
+
line.setAttribute('y2', b[1]);
|
|
235
|
+
line.style.strokeWidth = `${leader.width / this.dpr}px`;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
line.style.display = leader && end > (leader?.gap ?? 0) ? '' : 'none';
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Moves labels along by the clock. Needs no redraw of the figure. */
|
|
242
|
+
tick(now) {
|
|
243
|
+
const dt = Math.min((now - this.last) / 1000, 0.1);
|
|
244
|
+
this.last = now;
|
|
245
|
+
let moving = false;
|
|
246
|
+
for (const item of this.items.values()) {
|
|
247
|
+
if (!item.shown) continue;
|
|
248
|
+
if (!item.settles || this.still) {
|
|
249
|
+
item.offset = item.target.slice();
|
|
250
|
+
item.velocity = [0, 0];
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
// The exact step of a critically damped spring, so it's the same at any frame rate.
|
|
254
|
+
const decay = Math.exp(-RATE * dt);
|
|
255
|
+
for (let k = 0; k < 2; k++) {
|
|
256
|
+
const error = item.offset[k] - item.target[k];
|
|
257
|
+
const carry = (item.velocity[k] + RATE * error) * dt;
|
|
258
|
+
item.offset[k] = item.target[k] + (error + carry) * decay;
|
|
259
|
+
item.velocity[k] = (item.velocity[k] - RATE * carry) * decay;
|
|
260
|
+
if (Math.abs(item.offset[k] - item.target[k]) > REST || Math.abs(item.velocity[k]) > REST) moving = true;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
this.place();
|
|
264
|
+
return moving;
|
|
265
|
+
}
|
|
266
|
+
}
|
package/src/pack.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// A figure's sources as one string that fits in a link, and back. The playground reads one from
|
|
2
|
+
// the address after `#pen=`, and writes one to share what's in its editor. A build writes one for
|
|
3
|
+
// a figure it compiled, so a page can link a reader from the figure to its sources.
|
|
4
|
+
//
|
|
5
|
+
// const link = `https://pencil-lang.dev/playground/#pen=${await pack(sources)}`;
|
|
6
|
+
//
|
|
7
|
+
// `sources` is `{ name, doc, sheets, files }`: what to call it, the document's name, its sheets'
|
|
8
|
+
// names in order, and every file's text by name, with the document, the sheets and each file they
|
|
9
|
+
// `use`. Names are paths, and a used file is found from the file that names it, as everywhere.
|
|
10
|
+
//
|
|
11
|
+
// It's the JSON, deflated, in the base64 that's safe in an address. Nothing is sent anywhere: what
|
|
12
|
+
// follows a `#` stays in the browser. It runs the same in a page and in Node.
|
|
13
|
+
|
|
14
|
+
const VERSION = 1;
|
|
15
|
+
|
|
16
|
+
// Writing and reading are waited on together, so text that isn't deflate fails here, as one
|
|
17
|
+
// error, and not as a write nobody was listening to.
|
|
18
|
+
const through = async (stream, bytes) => {
|
|
19
|
+
const writer = stream.writable.getWriter();
|
|
20
|
+
const [out] = await Promise.all([
|
|
21
|
+
new Response(stream.readable).arrayBuffer(),
|
|
22
|
+
writer.write(bytes),
|
|
23
|
+
writer.close(),
|
|
24
|
+
]);
|
|
25
|
+
return new Uint8Array(out);
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const toBase64 = (bytes) => {
|
|
29
|
+
let text = '';
|
|
30
|
+
for (let i = 0; i < bytes.length; i += 0x8000) text += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
31
|
+
return btoa(text).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const fromBase64 = (text) => {
|
|
35
|
+
const binary = atob(text.replace(/-/g, '+').replace(/_/g, '/'));
|
|
36
|
+
return Uint8Array.from(binary, (c) => c.charCodeAt(0));
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** Sources as a string for a link. */
|
|
40
|
+
export async function pack({ name = '', doc, sheets = [], files }) {
|
|
41
|
+
const json = JSON.stringify({ v: VERSION, name, doc, sheets, files });
|
|
42
|
+
return toBase64(await through(new CompressionStream('deflate-raw'), new TextEncoder().encode(json)));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Sources back from a link's string. Throws, with a message a reader can be shown, when it isn't
|
|
47
|
+
* one, was cut short, or doesn't hold what it says it does.
|
|
48
|
+
*/
|
|
49
|
+
export async function unpack(text) {
|
|
50
|
+
let sources;
|
|
51
|
+
try {
|
|
52
|
+
const bytes = await through(new DecompressionStream('deflate-raw'), fromBase64(text));
|
|
53
|
+
sources = JSON.parse(new TextDecoder().decode(bytes));
|
|
54
|
+
} catch {
|
|
55
|
+
throw new Error('This link doesn’t hold a figure: it may have been cut short when it was copied.');
|
|
56
|
+
}
|
|
57
|
+
if (sources?.v !== VERSION) throw new Error('This link was made by a newer Pencil than this page has.');
|
|
58
|
+
const { name = '', doc, sheets = [], files } = sources;
|
|
59
|
+
const text_ = (path) => typeof files?.[path] === 'string';
|
|
60
|
+
if (typeof doc !== 'string' || !Array.isArray(sheets) || ![doc, ...sheets].every(text_)) {
|
|
61
|
+
throw new Error('This link doesn’t hold a figure: it names a file it doesn’t carry.');
|
|
62
|
+
}
|
|
63
|
+
for (const [path, body] of Object.entries(files)) {
|
|
64
|
+
if (typeof body !== 'string') throw new Error(`This link doesn’t hold a figure: ${path} isn’t text.`);
|
|
65
|
+
}
|
|
66
|
+
return { name: String(name), doc, sheets, files };
|
|
67
|
+
}
|