@altpsyche/maths 0.5.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 +37 -2
- package/dist/figure/equation.d.ts +40 -0
- package/dist/figure/equation.js +178 -0
- package/dist/figure/typeset.d.ts +18 -0
- package/dist/figure/typeset.js +43 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/package.json +4 -1
package/README.md
CHANGED
|
@@ -20,11 +20,12 @@ svgMarkup(at(figure, 0.5), viewMatrix(figure.extent, 'contain', 640, 360), 640,
|
|
|
20
20
|
|
|
21
21
|
## Axes and a plotted function
|
|
22
22
|
|
|
23
|
-
<img src="docs/tangent.svg" width="720" alt="A parabola on a labelled grid, the region under it shaded to a point on the curve, the tangent at that point drawn, and the slope written as a number.">
|
|
23
|
+
<img src="docs/tangent.svg" width="720" alt="A parabola on a labelled grid, the region under it shaded to a point on the curve, the tangent at that point drawn, and the slope written as a number under the typeset rule it comes from.">
|
|
24
24
|
|
|
25
25
|
The picture arrives rather than appearing. The grid fades, the axes draw on, their labels come in one
|
|
26
26
|
after another, the curve draws, the dot grows out of the origin, and the dot is pointed at where the
|
|
27
|
-
slope is nothing. Then it walks the curve at one speed and flashes at the top.
|
|
27
|
+
slope is nothing. Then it walks the curve at one speed and flashes at the top. The number in the
|
|
28
|
+
corner is a value of the typeset rule under it.
|
|
28
29
|
|
|
29
30
|
```ts
|
|
30
31
|
import { axes, coordsOf, group, interval, numberPlane, plot, scaleOf, shape } from '@altpsyche/maths';
|
|
@@ -63,6 +64,40 @@ Four times of one figure, side by side: the picture arrived, the beat at the sta
|
|
|
63
64
|
way up, and the top. A moving picture in a README needs a GIF and this package has no encoder, so the
|
|
64
65
|
strip shows the motion in a still.
|
|
65
66
|
|
|
67
|
+
## Equations
|
|
68
|
+
|
|
69
|
+
`equationFromTex` typesets an expression with MathJax and reads the SVG the typesetter wrote back as
|
|
70
|
+
marks, one per glyph. `equationNode` places those marks in a figure, fitted inside a box and centred
|
|
71
|
+
on a point. It fits the width as well as the height, because an expression six times wider than it is
|
|
72
|
+
tall runs off the sides of a figure the moment the height alone decides its size.
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import { equationFromTex, equationNode, vec2 } from '@altpsyche/maths';
|
|
76
|
+
|
|
77
|
+
const rule = await equationFromTex('\\frac{dy}{dx} = 2x');
|
|
78
|
+
|
|
79
|
+
equationNode('rule', rule, {
|
|
80
|
+
at: vec2(-4.27, 1.74),
|
|
81
|
+
width: 1.2,
|
|
82
|
+
height: 0.6,
|
|
83
|
+
fill: { colour: '#1b1b1b' },
|
|
84
|
+
});
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
An equation is paths on the page as well as in a recording, which is what stops one expression having
|
|
88
|
+
two pictures free to disagree. A glyph is an outline rather than a letter, so no font has to be
|
|
89
|
+
installed anywhere and the LaTeX is the label the picture carries for a reader.
|
|
90
|
+
|
|
91
|
+
MathJax is the one runtime dependency and the typesetting call is what loads it. Importing the door
|
|
92
|
+
reaches none of it, so a consumer who draws figures and typesets nothing pays nothing. What that
|
|
93
|
+
costs is that typesetting answers with a promise.
|
|
94
|
+
|
|
95
|
+
Three things stop a typeset expression rather than being drawn, and each names what it found. A TeX
|
|
96
|
+
error carries the typesetter's own message. A character the font has no outline for arrives as text,
|
|
97
|
+
which would draw with whatever font a browser had and draw nothing at all in a recording. An
|
|
98
|
+
undefined macro is not an error at all, because MathJax draws the macro's own name in red, so a typo
|
|
99
|
+
would otherwise ship as a red word inside the picture.
|
|
100
|
+
|
|
66
101
|
## The animations
|
|
67
102
|
|
|
68
103
|
`fadeIn`, `fadeOut`, `fadeTo`, `draw`, `morph`, `moveBy`, `rotate`, `scale`, `growFrom`, `moveAlong`,
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type Vec2 } from '../values/vec2.js';
|
|
2
|
+
import { type GroupNode } from './node.js';
|
|
3
|
+
import { type EquationElement } from './typeset.js';
|
|
4
|
+
import type { Fill, PathMark } from './mark.js';
|
|
5
|
+
/** Where the typesetter put the expression, in the marks' own units and with y
|
|
6
|
+
* counted upward, so `y` is the bottom edge and `y + height` the top. */
|
|
7
|
+
export interface EquationBox {
|
|
8
|
+
readonly x: number;
|
|
9
|
+
readonly y: number;
|
|
10
|
+
readonly width: number;
|
|
11
|
+
readonly height: number;
|
|
12
|
+
}
|
|
13
|
+
export interface Equation {
|
|
14
|
+
readonly marks: readonly PathMark[];
|
|
15
|
+
readonly box: EquationBox;
|
|
16
|
+
}
|
|
17
|
+
export declare function equationMarks(root: EquationElement): Equation;
|
|
18
|
+
/** One expression typeset and read, which is the two halves above in the order
|
|
19
|
+
* they are always used in. */
|
|
20
|
+
export declare function equationFromTex(tex: string): Promise<Equation>;
|
|
21
|
+
export interface EquationOptions {
|
|
22
|
+
/** Where the middle of the expression sits, in the figure's own units. */
|
|
23
|
+
readonly at: Vec2;
|
|
24
|
+
/** The box the expression is fitted inside, in the figure's own units. */
|
|
25
|
+
readonly width: number;
|
|
26
|
+
readonly height: number;
|
|
27
|
+
readonly fill: Fill;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* A typeset expression placed in a figure: one shape per glyph, fitted inside a
|
|
31
|
+
* box and centred on a point.
|
|
32
|
+
*
|
|
33
|
+
* It fits inside both measurements rather than being sized by the height alone.
|
|
34
|
+
* An expression two units wide for every one it is tall runs off the sides of a
|
|
35
|
+
* narrow figure the moment its height is what decides its size.
|
|
36
|
+
*
|
|
37
|
+
* The group carries the transform rather than the geometry, so the glyphs stay
|
|
38
|
+
* the typesetter's own numbers and moving the expression is one matrix.
|
|
39
|
+
*/
|
|
40
|
+
export declare function equationNode(name: string, equation: Equation, options: EquationOptions): GroupNode;
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A typeset expression read out of the SVG a typesetter wrote.
|
|
3
|
+
*
|
|
4
|
+
* MathJax describes an expression as nested groups with a transform on each,
|
|
5
|
+
* every glyph as an outline and a fraction bar or a root's rule as a rectangle.
|
|
6
|
+
* A figure holds a flat list of marks with every transform already applied, so
|
|
7
|
+
* this walks the tree, carries the transform stack down it, and hands back the
|
|
8
|
+
* marks with the box the typesetter measured the expression into.
|
|
9
|
+
*
|
|
10
|
+
* The stack starts turned over, because SVG counts y downward and a figure
|
|
11
|
+
* counts it upward. Doing it here means the whole expression arrives in the
|
|
12
|
+
* figure's own space and nothing downstream has to know which way up the
|
|
13
|
+
* typesetter works.
|
|
14
|
+
*
|
|
15
|
+
* A mark comes back with no fill and its id is a leaf name, because both arrive
|
|
16
|
+
* when the equation is placed in a figure: a figure's node tree builds an id out
|
|
17
|
+
* of the names on the way down it, so a full path written here would be a second
|
|
18
|
+
* naming of the same mark. The colour arrives there too, since a figure is handed
|
|
19
|
+
* its palette as it is drawn rather than reading one.
|
|
20
|
+
*
|
|
21
|
+
* An id carries the glyph's own code point, which is what a match between two
|
|
22
|
+
* expressions has to be made on.
|
|
23
|
+
*
|
|
24
|
+
* Three things stop the walk instead of being drawn, and each names what it
|
|
25
|
+
* found. They are written up on `refuse` below.
|
|
26
|
+
*/
|
|
27
|
+
import { mat3 } from '../values/mat3.js';
|
|
28
|
+
import { vec2 } from '../values/vec2.js';
|
|
29
|
+
import { rect, transformPath } from './path.js';
|
|
30
|
+
import { group, shape } from './node.js';
|
|
31
|
+
import { pathFromData } from './path-data.js';
|
|
32
|
+
import { typesetElement } from './typeset.js';
|
|
33
|
+
/** Both transforms a typeset expression uses. Anything else refuses rather than
|
|
34
|
+
* being ignored, which would leave a glyph sitting at the origin. */
|
|
35
|
+
function transformOf(text) {
|
|
36
|
+
let matrix = mat3.IDENTITY;
|
|
37
|
+
for (const match of text.matchAll(/([A-Za-z]+)\s*\(([^)]*)\)/g)) {
|
|
38
|
+
const name = match[1] ?? '';
|
|
39
|
+
const numbers = (match[2] ?? '')
|
|
40
|
+
.split(/[,\s]+/)
|
|
41
|
+
.filter(Boolean)
|
|
42
|
+
.map(Number);
|
|
43
|
+
if (numbers.length === 0 || numbers.some((value) => !Number.isFinite(value)))
|
|
44
|
+
throw new Error(`the transform "${text}" carries something that is not a number`);
|
|
45
|
+
const [first = 0, second] = numbers;
|
|
46
|
+
if (name === 'translate')
|
|
47
|
+
matrix = mat3.multiply(matrix, mat3.translation(vec2(first, second ?? 0)));
|
|
48
|
+
else if (name === 'scale')
|
|
49
|
+
matrix = mat3.multiply(matrix, mat3.scaling(vec2(first, second ?? first)));
|
|
50
|
+
else
|
|
51
|
+
throw new Error(`the transform "${text}" asks for "${name}", which this does not apply`);
|
|
52
|
+
}
|
|
53
|
+
return matrix;
|
|
54
|
+
}
|
|
55
|
+
function attribute(element, name) {
|
|
56
|
+
const value = element.attributes[name];
|
|
57
|
+
if (value === undefined)
|
|
58
|
+
throw new Error(`a "${element.tag}" element in the typeset expression has no ${name}`);
|
|
59
|
+
return value;
|
|
60
|
+
}
|
|
61
|
+
function numberAttribute(element, name, fallback) {
|
|
62
|
+
const written = element.attributes[name];
|
|
63
|
+
if (written === undefined && fallback !== undefined)
|
|
64
|
+
return fallback;
|
|
65
|
+
const value = Number(attribute(element, name));
|
|
66
|
+
if (!Number.isFinite(value))
|
|
67
|
+
throw new Error(`a "${element.tag}" element has ${name}="${written}", which is not a number`);
|
|
68
|
+
return value;
|
|
69
|
+
}
|
|
70
|
+
function svgIn(element) {
|
|
71
|
+
if (element.tag === 'svg')
|
|
72
|
+
return element;
|
|
73
|
+
for (const child of element.children) {
|
|
74
|
+
const found = svgIn(child);
|
|
75
|
+
if (found)
|
|
76
|
+
return found;
|
|
77
|
+
}
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
function svgOf(element) {
|
|
81
|
+
const found = svgIn(element);
|
|
82
|
+
if (!found)
|
|
83
|
+
throw new Error('the typesetter returned no svg element');
|
|
84
|
+
return found;
|
|
85
|
+
}
|
|
86
|
+
/** The colour the `noundefined` extension draws a macro the typesetter does not
|
|
87
|
+
* know, which is the only sign that it did not typeset one. */
|
|
88
|
+
const UNKNOWN = 'red';
|
|
89
|
+
/** The characters under an element, read off the code point each glyph carries.
|
|
90
|
+
* It is what names a run the typesetter drew instead of typesetting. */
|
|
91
|
+
function charactersOf(element) {
|
|
92
|
+
const code = element.tag === 'path' ? Number.parseInt(element.attributes['data-c'] ?? '', 16) : NaN;
|
|
93
|
+
const own = Number.isInteger(code) ? String.fromCodePoint(code) : '';
|
|
94
|
+
return own + element.children.map(charactersOf).join('');
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The three things that stop the walk rather than being drawn, each naming what
|
|
98
|
+
* it found.
|
|
99
|
+
*
|
|
100
|
+
* A TeX error carries its message on the group MathJax puts the error box in. A
|
|
101
|
+
* character the font has no outline for arrives as a text element, which draws
|
|
102
|
+
* in a browser with whatever font it found and draws nothing at all in a
|
|
103
|
+
* recording. And an undefined macro is not an error under `AllPackages`, since
|
|
104
|
+
* the `noundefined` extension in it draws the macro's own name in red, so a typo
|
|
105
|
+
* would otherwise ship as a red word inside the picture.
|
|
106
|
+
*/
|
|
107
|
+
function refuse(element) {
|
|
108
|
+
const error = element.attributes['data-mjx-error'];
|
|
109
|
+
if (error !== undefined)
|
|
110
|
+
throw new Error(`the typesetter refused the expression: ${error}`);
|
|
111
|
+
if (element.attributes.fill === UNKNOWN)
|
|
112
|
+
throw new Error(`the typesetter does not know "${charactersOf(element)}" and drew it in ${UNKNOWN}`);
|
|
113
|
+
if (element.tag === 'text')
|
|
114
|
+
throw new Error(`the typesetter has no outline for "${element.text ?? ''}" and wrote it as text`);
|
|
115
|
+
}
|
|
116
|
+
/** The four numbers of the `viewBox`, turned over the way the marks are. */
|
|
117
|
+
function boxOf(svg) {
|
|
118
|
+
const numbers = attribute(svg, 'viewBox')
|
|
119
|
+
.split(/[,\s]+/)
|
|
120
|
+
.filter(Boolean)
|
|
121
|
+
.map(Number);
|
|
122
|
+
if (numbers.length !== 4 || numbers.some((value) => !Number.isFinite(value)))
|
|
123
|
+
throw new Error(`the svg has viewBox="${svg.attributes.viewBox}", which is not four numbers`);
|
|
124
|
+
const [x = 0, y = 0, width = 0, height = 0] = numbers;
|
|
125
|
+
return { x, y: -(y + height), width, height };
|
|
126
|
+
}
|
|
127
|
+
export function equationMarks(root) {
|
|
128
|
+
const svg = svgOf(root);
|
|
129
|
+
const marks = [];
|
|
130
|
+
const mark = (path, stack, suffix) => {
|
|
131
|
+
marks.push({ kind: 'path', id: `${marks.length}-${suffix}`, path: transformPath(path, stack) });
|
|
132
|
+
};
|
|
133
|
+
const walk = (element, stack) => {
|
|
134
|
+
for (const child of element.children) {
|
|
135
|
+
refuse(child);
|
|
136
|
+
const written = child.attributes.transform;
|
|
137
|
+
const own = written ? mat3.multiply(stack, transformOf(written)) : stack;
|
|
138
|
+
switch (child.tag) {
|
|
139
|
+
case 'g':
|
|
140
|
+
walk(child, own);
|
|
141
|
+
break;
|
|
142
|
+
case 'path':
|
|
143
|
+
mark(pathFromData(attribute(child, 'd')), own, child.attributes['data-c'] ?? 'glyph');
|
|
144
|
+
break;
|
|
145
|
+
case 'rect':
|
|
146
|
+
mark(rect(vec2(numberAttribute(child, 'x', 0), numberAttribute(child, 'y', 0)), numberAttribute(child, 'width'), numberAttribute(child, 'height')), own, 'rule');
|
|
147
|
+
break;
|
|
148
|
+
default:
|
|
149
|
+
throw new Error(`the typeset expression holds a "${child.tag}" element, which this does not draw`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
walk(svg, mat3.scaling(vec2(1, -1)));
|
|
154
|
+
return { marks, box: boxOf(svg) };
|
|
155
|
+
}
|
|
156
|
+
/** One expression typeset and read, which is the two halves above in the order
|
|
157
|
+
* they are always used in. */
|
|
158
|
+
export async function equationFromTex(tex) {
|
|
159
|
+
return equationMarks(await typesetElement(tex));
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* A typeset expression placed in a figure: one shape per glyph, fitted inside a
|
|
163
|
+
* box and centred on a point.
|
|
164
|
+
*
|
|
165
|
+
* It fits inside both measurements rather than being sized by the height alone.
|
|
166
|
+
* An expression two units wide for every one it is tall runs off the sides of a
|
|
167
|
+
* narrow figure the moment its height is what decides its size.
|
|
168
|
+
*
|
|
169
|
+
* The group carries the transform rather than the geometry, so the glyphs stay
|
|
170
|
+
* the typesetter's own numbers and moving the expression is one matrix.
|
|
171
|
+
*/
|
|
172
|
+
export function equationNode(name, equation, options) {
|
|
173
|
+
const { box } = equation;
|
|
174
|
+
const fit = Math.min(options.width / box.width, options.height / box.height);
|
|
175
|
+
const centre = vec2(box.x + box.width / 2, box.y + box.height / 2);
|
|
176
|
+
const transform = mat3.multiply(mat3.translation(options.at), mat3.multiply(mat3.scaling(vec2(fit, fit)), mat3.translation(vec2(-centre.x, -centre.y))));
|
|
177
|
+
return group(name, equation.marks.map((mark) => shape(mark.id, mark.path, { fill: options.fill })), { transform });
|
|
178
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One element of the tree a typesetter wrote, with its attributes as written.
|
|
3
|
+
*
|
|
4
|
+
* The walk that turns this into marks takes this shape rather than the
|
|
5
|
+
* typesetter's own, which is what lets the walk be tested by building a tree by
|
|
6
|
+
* hand with no typesetter behind it.
|
|
7
|
+
*/
|
|
8
|
+
export interface EquationElement {
|
|
9
|
+
readonly tag: string;
|
|
10
|
+
readonly attributes: Readonly<Record<string, string>>;
|
|
11
|
+
readonly children: readonly EquationElement[];
|
|
12
|
+
/** A text element's own characters, which is what names it when it is
|
|
13
|
+
* refused. Nothing else here carries any. */
|
|
14
|
+
readonly text?: string;
|
|
15
|
+
}
|
|
16
|
+
/** One expression typeset, as the tree the typesetter wrote it. `display: true`
|
|
17
|
+
* is the centred form rather than the one that sits inside a line of prose. */
|
|
18
|
+
export declare function typesetElement(tex: string): Promise<EquationElement>;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Held as the promise rather than the value: two calls arriving together share
|
|
2
|
+
// one load, and registering the handler twice leaves MathJax with two of them.
|
|
3
|
+
let shared;
|
|
4
|
+
async function load() {
|
|
5
|
+
const [{ mathjax }, { TeX }, { SVG }, { liteAdaptor }, { RegisterHTMLHandler }, { AllPackages }] = await Promise.all([
|
|
6
|
+
import('mathjax-full/js/mathjax.js'),
|
|
7
|
+
import('mathjax-full/js/input/tex.js'),
|
|
8
|
+
import('mathjax-full/js/output/svg.js'),
|
|
9
|
+
import('mathjax-full/js/adaptors/liteAdaptor.js'),
|
|
10
|
+
import('mathjax-full/js/handlers/html.js'),
|
|
11
|
+
import('mathjax-full/js/input/tex/AllPackages.js'),
|
|
12
|
+
]);
|
|
13
|
+
const adaptor = liteAdaptor();
|
|
14
|
+
RegisterHTMLHandler(adaptor);
|
|
15
|
+
const document = mathjax.document('', {
|
|
16
|
+
InputJax: new TeX({ packages: AllPackages }),
|
|
17
|
+
OutputJax: new SVG({ fontCache: 'none' }),
|
|
18
|
+
});
|
|
19
|
+
return { adaptor, document };
|
|
20
|
+
}
|
|
21
|
+
/** MathJax's own tree read into the shape above, with a text node's characters
|
|
22
|
+
* gathered onto the element that holds them. */
|
|
23
|
+
function elementOf(adaptor, node) {
|
|
24
|
+
const children = [];
|
|
25
|
+
let text = '';
|
|
26
|
+
for (const child of adaptor.childNodes(node)) {
|
|
27
|
+
if (adaptor.kind(child) === '#text')
|
|
28
|
+
text += adaptor.value(child);
|
|
29
|
+
else
|
|
30
|
+
children.push(elementOf(adaptor, child));
|
|
31
|
+
}
|
|
32
|
+
const attributes = {};
|
|
33
|
+
for (const { name, value } of adaptor.allAttributes(node))
|
|
34
|
+
attributes[name] = value;
|
|
35
|
+
return { tag: adaptor.kind(node), attributes, children, text };
|
|
36
|
+
}
|
|
37
|
+
/** One expression typeset, as the tree the typesetter wrote it. `display: true`
|
|
38
|
+
* is the centred form rather than the one that sits inside a line of prose. */
|
|
39
|
+
export async function typesetElement(tex) {
|
|
40
|
+
shared ??= load();
|
|
41
|
+
const { adaptor, document } = await shared;
|
|
42
|
+
return elementOf(adaptor, document.convert(tex, { display: true }));
|
|
43
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -53,3 +53,7 @@ export { paintCanvas } from './paint/canvas.js';
|
|
|
53
53
|
export type { CanvasLike } from './paint/canvas.js';
|
|
54
54
|
export { arrow, callout, dot } from './figure/annotate.js';
|
|
55
55
|
export type { ArrowOptions, CalloutOptions } from './figure/annotate.js';
|
|
56
|
+
export { typesetElement } from './figure/typeset.js';
|
|
57
|
+
export type { EquationElement } from './figure/typeset.js';
|
|
58
|
+
export { equationFromTex, equationMarks, equationNode } from './figure/equation.js';
|
|
59
|
+
export type { Equation, EquationBox, EquationOptions } from './figure/equation.js';
|
package/dist/index.js
CHANGED
|
@@ -32,3 +32,5 @@ export { at, durationOf, loops, sameMarks } from './figure/figure.js';
|
|
|
32
32
|
export { pathData, paintSvg, svgElements, svgMarkup } from './paint/svg.js';
|
|
33
33
|
export { paintCanvas } from './paint/canvas.js';
|
|
34
34
|
export { arrow, callout, dot } from './figure/annotate.js';
|
|
35
|
+
export { typesetElement } from './figure/typeset.js';
|
|
36
|
+
export { equationFromTex, equationMarks, equationNode } from './figure/equation.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@altpsyche/maths",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "The mathematics AltPsyche's figures are drawn from: vectors, matrices, curves, and a value walked over time.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Siva",
|
|
@@ -47,5 +47,8 @@
|
|
|
47
47
|
},
|
|
48
48
|
"engines": {
|
|
49
49
|
"node": ">=20"
|
|
50
|
+
},
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"mathjax-full": "^3.2.1"
|
|
50
53
|
}
|
|
51
54
|
}
|