rapier-math 2.0.0 → 2.2.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 +15 -5
- package/dist/accessible.css +6 -0
- package/dist/accessible.d.ts +10 -0
- package/dist/accessible.mjs +18 -0
- package/dist/classic.d.ts +8 -2
- package/dist/combined.d.ts +4 -0
- package/dist/combined.mjs +2 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.mjs +6 -2980
- package/dist/integration.d.ts +3 -1
- package/dist/integration.mjs +13 -19
- package/dist/markdown-it.mjs +7 -4
- package/dist/mathml.d.ts +5 -0
- package/dist/mathml.mjs +3 -0
- package/dist/rapier-math.js +674 -173
- package/dist/rehype.mjs +13 -3
- package/docs/api.md +42 -4
- package/docs/math-components.json +6 -5
- package/docs/math-resources.json +150 -54
- package/docs/semantics.md +228 -0
- package/examples/README.md +10 -0
- package/examples/accessible.html +27 -0
- package/examples/accessible.mjs +42 -0
- package/examples/semantic.mjs +11 -0
- package/package.json +16 -2
- package/src/math/api.js +16 -55
- package/src/math/browser.js +4 -0
- package/src/math/classic.js +7 -0
- package/src/math/combined.js +13 -0
- package/src/math/fallbacks.js +5 -0
- package/src/math/font.js +3 -0
- package/src/math/layout.js +56 -53
- package/src/math/mathml.js +408 -0
- package/src/math/package-build.mjs +24 -11
- package/src/math/package-layout.mjs +3 -0
- package/src/math/package-readme.mjs +14 -4
- package/src/math/parser.js +36 -20
- package/src/math/responsive.js +4 -0
- package/src/math/semantic-api.js +12 -0
- package/src/math/source.js +67 -0
- package/src/math/symbols.js +6 -3
- package/src/math/variants.js +41 -0
- package/src/tools/build-math.mjs +18 -10
- package/tests/adoption.mjs +34 -0
- package/tests/check.mjs +13 -5
- package/tests/semantics.mjs +340 -0
- package/tests/verify.mjs +3 -3
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
# Structured mathematical output
|
|
2
|
+
|
|
3
|
+
Rapier Math serializes its existing TeX parse into Presentation MathML. Fractions, roots,
|
|
4
|
+
scripts, operators and table cells become mathematical elements that a native MathML consumer
|
|
5
|
+
can inspect. It does not infer theorem meaning, chemical identities or mathematical speech.
|
|
6
|
+
|
|
7
|
+
## Select an output
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
// This import contains the parser and serializer, with no SVG font or layout initialization.
|
|
11
|
+
import {toMathML, parse} from 'rapier-math/mathml';
|
|
12
|
+
const source = String.raw`\frac{12.5}{\sqrt[3]{x^2+1}}`;
|
|
13
|
+
const semantic = toMathML(source, {displayMode: true});
|
|
14
|
+
if (semantic.status === 'refused') console.error(semantic.errors);
|
|
15
|
+
else console.log(semantic.mathml);
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
The main native entry produces SVG without importing the semantic serializer. When both outputs
|
|
19
|
+
are needed, use the explicit combined entry:
|
|
20
|
+
|
|
21
|
+
```js
|
|
22
|
+
import {renderWithMathML} from 'rapier-math/combined';
|
|
23
|
+
const result = renderWithMathML(source, {displayMode: true});
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Its required `semantics` field contains the same result as `toMathML`; the combined call admits
|
|
27
|
+
and parses once. SVG errors and semantic status remain independent: MathML can represent a
|
|
28
|
+
Unicode character absent from the embedded SVG font. A successful SVG does not turn a semantic
|
|
29
|
+
refusal into success. `renderToString` returns SVG. The complete classic `RapierMath` object
|
|
30
|
+
also exposes `toMathML` and `renderWithMathML`.
|
|
31
|
+
|
|
32
|
+
The font-free entry exports `parse` for inspection as well. Parse results are ordinary,
|
|
33
|
+
detached data: changing a returned tree has no effect on subsequent renders. There is no
|
|
34
|
+
public API accepting arbitrary or modified trees for serialization. Local macros are
|
|
35
|
+
expanded by the existing parser; their expanded tree is separate from exact authored TeX.
|
|
36
|
+
|
|
37
|
+
| Result field | Meaning |
|
|
38
|
+
| --- | --- |
|
|
39
|
+
| `mathml` | One namespace-correct `math` element, including independent source annotation when admitted. |
|
|
40
|
+
| `status: "complete"` | Every encountered part has a supported structural mapping. This is a mapping claim, not an AT or mathematical-understanding claim. |
|
|
41
|
+
| `status: "presentation-fallback"` | Structure is emitted with explicit lossy presentation, domain or extension notices in `errors`. |
|
|
42
|
+
| `status: "refused"` | No equivalent expression is claimed. A bounded `merror` and source annotation are returned where possible. |
|
|
43
|
+
| `errors` | Structured fallback notices or refusal diagnostics, with the same bounded diagnostic fields as SVG rendering. |
|
|
44
|
+
| `source.encoding` | `application/x-tex`, `application/x-rapier-tex-utf16`, or `null` for omitted oversized input. |
|
|
45
|
+
| `source.omitted` | True only when source admission refused embedding. The caller still owns the original input. |
|
|
46
|
+
| `metrics` | Semantic work visits, greatest AST traversal depth, final output UTF-16 code units and emitted native link count. These are not peak-memory or DOM counts. |
|
|
47
|
+
|
|
48
|
+
## Mapping by construct
|
|
49
|
+
|
|
50
|
+
The published [MathML Core Candidate Recommendation of 24 June 2025](https://www.w3.org/TR/2025/CR-mathml-core-20250624/)
|
|
51
|
+
is the portable structural target. Extensions and lossy cases are reported explicitly.
|
|
52
|
+
|
|
53
|
+
| TeX/AST family | Mapping and qualification |
|
|
54
|
+
| --- | --- |
|
|
55
|
+
| Rows and groups | `mrow`; explicit groups stay separate. No inferred multiplication or function application is inserted. Explicit U+2061–U+2064 invisible operators remain `mo`. |
|
|
56
|
+
| Identifiers and alphabets | `mi`; a single default or italic letter stays plain, so MathML Core italicizes it and assistive technology reads the ordinary letter. Other alphabets reuse the SVG renderer's pure Unicode mapping. Roman identifiers use `mathvariant="normal"`. Text spaces become no-break spaces because MathML trims token whitespace. |
|
|
57
|
+
| Numbers | `mn` joins Unicode decimal-digit integer/decimal runs within one row and matching style. Unary signs remain `mo`. Explicit groups, spaces and style boundaries stop joining. A final directly scripted digit belongs to the complete preceding numeric token, as in `12^3`; `1{2}^3` stays grouped. Multi-dot runs are not reinterpreted as decimals. |
|
|
58
|
+
| Scientific notation | Authored `1.2e-3` remains a number, identifier and signed expression; there is no inferred exponent grammar. `1.2\times10^{-3}` preserves its explicit structure. The existing units parser's lowering remains reported as a domain fallback. |
|
|
59
|
+
| Named operators and text | Standard names and plain `operatorname` use one `mo`; ordinary multi-character text uses `mtext`. Mixed or styled operator-name content retains its nested structure and gets a fallback notice. |
|
|
60
|
+
| Fractions | `mfrac`, with numerator then denominator; zero-bar fractions and explicit fences are retained. Continued-fraction numerator alignment is a documented presentation fallback. |
|
|
61
|
+
| Roots | `msqrt` or `mroot`, with radicand before degree. |
|
|
62
|
+
| Scripts and limits | `msub`, `msup`, `msubsup`; `munder`, `mover`, `munderover` for applicable explicit/display operator limits. |
|
|
63
|
+
| Fences and accents | Explicit `mo` fences, plus under/over accent relationships. No `mfenced` dependency. |
|
|
64
|
+
| Matrices, aligned equations and cases | `mtable`/`mtr`/`mtd`, the original row/cell order and case/matrix fences. Cell alignment uses fixed CSS. Custom row gaps/baselines are reported as presentation fallback. Array insertion content remains in adjacent cells; decorative row/column rules are omitted with a notice. |
|
|
65
|
+
| Styles and spaces | `mstyle`, safe fixed CSS, Unicode alphabets and `mspace`. Text script/fraktur/double-struck requests use a disclosed MathML 3 `mathvariant` extension. |
|
|
66
|
+
| Phantom, smash and raising | `mphantom`/`mpadded`. Overlay-width adjustments retain their content with a fallback notice. Native presentation may differ from SVG. |
|
|
67
|
+
| Cancellation and generic negation overlay | MathML 3 `menclose`, with an explicit extension notice. Core-only hosts may omit the mark. Already-negated Unicode operators stay ordinary `mo`. |
|
|
68
|
+
| Rules | A decorative `mspace` with an explicit presentation notice; no additional mathematical relationship is inferred. |
|
|
69
|
+
| Explicit `mmlToken` | The authored admitted `mi`/`mn`/`mo`/`mtext` kind and token text are retained before visual literal lowering. Only the parser's admitted font variant is accepted. |
|
|
70
|
+
| Chemistry, physics and units | Existing fractions, scripts, arrows, fences and rows survive. Origin metadata triggers a domain notice; chemical elements/bonds/charges, unit identities and specialized physical meaning are not invented. |
|
|
71
|
+
| Tags and labels | Tags remain following authored content with a notice. Labels remain parser-discarded metadata: there is no equation identity, automatic numbering or cross-formula reference support. |
|
|
72
|
+
| HTTP(S) links | A native XHTML `a` inside MathML `mtext`, containing a nested MathML expression. This is a disclosed host integration fallback; see the composition contract below. Nested links and links inside phantom content refuse the semantic path. |
|
|
73
|
+
|
|
74
|
+
The parser retains only distinctions with live consumers: explicit token kind/text, operator-name
|
|
75
|
+
origin, and chemistry/physics/units/tag origin. Its visual syntax and SVG layout relationships
|
|
76
|
+
remain the same. Unsupported commands still produce parser diagnostics.
|
|
77
|
+
|
|
78
|
+
## Exact source and bounded refusal
|
|
79
|
+
|
|
80
|
+
The first child of `semantics` is the mathematical expression. For XML-valid source without
|
|
81
|
+
CR, a following `annotation encoding="application/x-tex"` keeps exact authored source
|
|
82
|
+
independently. Escaping includes numeric references for tabs and LF; BOM and supplementary
|
|
83
|
+
Unicode characters remain intact. The semantic token text is normalized presentation and is
|
|
84
|
+
never described as the original source. The [XML character and newline rules](https://www.w3.org/TR/xml/)
|
|
85
|
+
explain why ordinary escaping alone is insufficient.
|
|
86
|
+
|
|
87
|
+
Source containing CR uses `source.encoding: "application/x-rapier-tex-utf16"`, with four
|
|
88
|
+
lowercase ASCII hex digits per original UTF-16 code unit. A separate `text/plain` annotation
|
|
89
|
+
is a readable alternative, not an exact-source claim. This preserves CRLF through the actual
|
|
90
|
+
HAST-to-HTML-to-HAST pipeline: an HTML stringifier can write a decoded CR literally, which a
|
|
91
|
+
later HTML parser normalizes. The ASCII carrier survives that boundary. CR alone does not
|
|
92
|
+
make an otherwise supported expression a fallback or refusal. Recover exact source from the
|
|
93
|
+
annotation selected by `source.encoding`; when only markup remains, prefer its UTF-16
|
|
94
|
+
annotation when present, otherwise its TeX annotation. SVG uses the same carrier for CR-bearing source, preserving exact input through host
|
|
95
|
+
reserialization and later browser fitting. The source is admitted and encoded once per operation.
|
|
96
|
+
|
|
97
|
+
XML-invalid input, including isolated UTF-16 surrogates, U+0000 and U+FFFE/U+FFFF, returns
|
|
98
|
+
`refused`. A `text/plain` annotation shows explicit Unicode escapes and a separate
|
|
99
|
+
`application/x-rapier-tex-utf16` annotation contains four lowercase hex digits for every
|
|
100
|
+
original UTF-16 code unit. The same carrier used for CR is an application convention, not a
|
|
101
|
+
standard TeX media type or a claim that the readable alternative is original TeX. Source invalid in XML
|
|
102
|
+
never becomes an invalid character reference. Invalid characters produced by an admitted
|
|
103
|
+
Unicode command likewise refuse while retaining its valid authored command text.
|
|
104
|
+
|
|
105
|
+
Source longer than 1,000,000 UTF-16 code units is refused before scanning, escaping or parsing.
|
|
106
|
+
It is not truncated or embedded; `source.omitted`, the diagnostic's `sourceOmitted`, and
|
|
107
|
+
`data-math-source-omitted` make that explicit. Keep that original input with the host.
|
|
108
|
+
|
|
109
|
+
Existing parser bounds still apply: 100,000 tokens, 50,000 nodes, nesting 192 and 4096 macro
|
|
110
|
+
expansions. Serialization adds fixed limits of 100,000 work visits, traversal depth 512,
|
|
111
|
+
8 Mi presentation code units and 16 Mi complete MathML code units. Array expansions and
|
|
112
|
+
repeated insertion content count against the semantic budget. If source carriers plus
|
|
113
|
+
presentation exceed the complete-output bound, the result refuses, retains the admitted
|
|
114
|
+
source carriers and replaces the partial expression with `merror`. SVG retains its existing
|
|
115
|
+
separate limits. Combined accessible HTML has a 40 Mi code-unit bound. All budgets are local
|
|
116
|
+
to one operation; a refusal cannot poison a later render. These bounds do not measure device
|
|
117
|
+
memory or claim constant-size output.
|
|
118
|
+
|
|
119
|
+
## Usable SVG and MathML composition
|
|
120
|
+
|
|
121
|
+
```js
|
|
122
|
+
import {renderAccessible} from 'rapier-math/accessible';
|
|
123
|
+
// Also include rapier-math/accessible.css in the host's stylesheet pipeline.
|
|
124
|
+
const result = renderAccessible(source, {displayMode: true});
|
|
125
|
+
if (result.errors.length) container.textContent = source;
|
|
126
|
+
else container.innerHTML = result.html; // only freshly generated output reaches this sink
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
`renderAccessible` calls `renderWithMathML` once. It returns full standalone `svg`, the
|
|
130
|
+
semantic result, `html`, and `presentation`:
|
|
131
|
+
|
|
132
|
+
- `svg-mathml`: visual SVG is inside an `aria-hidden` wrapper; native MathML is its clipped
|
|
133
|
+
assistive sibling. There are no authored links in this branch. The semantic tree has no
|
|
134
|
+
image role, raw-TeX aria-label, `aria-hidden`, `display:none` or `visibility:hidden` override.
|
|
135
|
+
- `mathml`: authored links use visible native MathML once. Standalone SVG is still returned
|
|
136
|
+
for consumers choosing that representation, but is not inserted into the combined host.
|
|
137
|
+
Each link uses an HTTP(S) URL, a native HTML anchor, `noopener noreferrer`, and its visible
|
|
138
|
+
content as a nested mathematical expression. The destination title supplies a link-name
|
|
139
|
+
fallback in hosts that do not derive a name from MathML children; it is not generated
|
|
140
|
+
mathematical speech or a claim of a descriptive link purpose. No duplicate or clipped
|
|
141
|
+
focus target is created.
|
|
142
|
+
- `refused`: `html` is empty and `errors` explains the failure. Insert the original source
|
|
143
|
+
through a text sink. A semantic refusal is not silently downgraded to equivalent success.
|
|
144
|
+
|
|
145
|
+
This composition supplies one exposed semantic equation surface structurally. Its actual
|
|
146
|
+
announcements and link navigation still require AT acceptance. Putting an interactive link
|
|
147
|
+
under `aria-hidden` violates the [W3C focus rule](https://www.w3.org/WAI/standards-guidelines/act/rules/6cfa84/).
|
|
148
|
+
The published Core target omits native MathML links; HTML embedding uses its web integration
|
|
149
|
+
rules. A newer editor draft's MathML anchor does not establish support in a target browser.
|
|
150
|
+
Nested, phantom and empty links refuse; the serializer also checks explicit transparency
|
|
151
|
+
while allowing an opaque descendant. Unknown or host-specific color names cannot undo an explicitly transparent ancestor. These are structural checks, not a visibility guarantee
|
|
152
|
+
under arbitrary host CSS, colors or backgrounds.
|
|
153
|
+
|
|
154
|
+
The stylesheet must be retained. If it is absent or blocked, both ordinary representations
|
|
155
|
+
can become visible. Hosts that cannot include it can insert `toMathML(source).mathml` visibly
|
|
156
|
+
as their sole representation instead. Native MathML uses the host's mathematical font;
|
|
157
|
+
it does not inherit Rapier's embedded SVG outlines. Linked formulas therefore use native
|
|
158
|
+
typesetting rather than a guarantee of identical SVG appearance.
|
|
159
|
+
|
|
160
|
+
`fit`/`observe` may operate on ordinary combined output because its SVG source carrier remains
|
|
161
|
+
intact; they adjust only SVG geometry. Linked native MathML has no SVG to fit. Do not change
|
|
162
|
+
source on one side of a combined formula: regenerate the whole result. Stop observations
|
|
163
|
+
before replacement and on unmount; no semantic timers, IDs or retained formula caches exist.
|
|
164
|
+
For SSR, emit the same source/options and stylesheet; initial MathML needs no client code.
|
|
165
|
+
|
|
166
|
+
The [accessible browser example](../examples/accessible.html) keeps editable source and generated
|
|
167
|
+
MathML available and demonstrates both representations, replacement and cleanup. The
|
|
168
|
+
[font-free example](../examples/semantic.mjs) runs in Node, SSR or a module worker.
|
|
169
|
+
|
|
170
|
+
A host HTML link can wrap an ordinary `svg-mathml` result to link the whole formula while
|
|
171
|
+
preserving its SVG appearance. Put the anchor outside both composition siblings and provide
|
|
172
|
+
an authored link-purpose name, such as `aria-label="Open the derivation"`, or a meaningful
|
|
173
|
+
link title. Native MathML children can leave an otherwise unnamed host link blank in a
|
|
174
|
+
browser's accessibility tree. For accessible output the rehype adapter retains an existing
|
|
175
|
+
`aria-label`, `aria-labelledby` or title; otherwise it supplies the existing destination as
|
|
176
|
+
a title fallback. This preserves the native mathematical subtree without synthesizing
|
|
177
|
+
speech. A URL fallback is not a substitute for the author's meaningful link-purpose name.
|
|
178
|
+
Direct `renderAccessible` users must name any containing host anchor themselves. Do not nest
|
|
179
|
+
an internally linked formula inside another link. The adapters retain the outer host link
|
|
180
|
+
and leave such a formula as source with a `nested-link` diagnostic. Host grammar still applies:
|
|
181
|
+
markdown-it keeps math in link labels literal; a remark-math/rehype pipeline can admit it.
|
|
182
|
+
|
|
183
|
+
## Markdown, sanitizer and CSP boundaries
|
|
184
|
+
|
|
185
|
+
The neutral markdown-it and rehype adapters accept `accessible: true`. Include the same CSS.
|
|
186
|
+
Their document output budget counts the complete inserted HTML, including semantic annotations and every cache hit;
|
|
187
|
+
semantic refusal leaves source in the host. Original Markdown and diagnostic `mathSource` remain
|
|
188
|
+
the exact fallback authority: HTML text alone can normalize CR or replace invalid Unicode code units. Their parser grammar and lifetime ownership do not
|
|
189
|
+
change. Each inserted occurrence counts against its document's output budget.
|
|
190
|
+
|
|
191
|
+
For rehype, retain the documented order: host parsing, `rehype-sanitize`, this math adapter,
|
|
192
|
+
then serialization. The adapter materializes only newly generated output. If a host sanitizes
|
|
193
|
+
again afterward, its policy must explicitly retain the required MathML namespace/elements,
|
|
194
|
+
source annotations, generated styles, classes and native links. Do not globally allow arbitrary
|
|
195
|
+
authored SVG or HTML. HTML serialization is not a replacement for retaining original Markdown.
|
|
196
|
+
|
|
197
|
+
The example uses an external stylesheet/module and permits generated style attributes. A CSP
|
|
198
|
+
forbidding all inline style attributes cannot reproduce all SVG or MathML presentation. Core
|
|
199
|
+
structure may survive, but that is not a claim of unchanged presentation. The package creates
|
|
200
|
+
no Trusted Types policy; string insertion and SVG fitting have the same TrustedHTML limitations
|
|
201
|
+
as the existing browser API. Exact HTTP(S) link destinations carry no fetch authority until
|
|
202
|
+
the person activates them; no formula rendering request performs a network fetch.
|
|
203
|
+
|
|
204
|
+
## Assistive-technology acceptance
|
|
205
|
+
|
|
206
|
+
Generated MathML, strict XML parsing, HAST inspection and DOM/ARIA checks establish structure
|
|
207
|
+
and custody. They do not establish speech output, mathematical navigation or screen-reader
|
|
208
|
+
parity. No native browser/screen-reader stack is claimed as tested by these checks.
|
|
209
|
+
|
|
210
|
+
For each supported host, record the actual OS, browser, screen reader, math provider, versions
|
|
211
|
+
and speech/braille settings. Read a sentence with inline math, a nested fraction/root, a matrix
|
|
212
|
+
and cases expression, and a linked fraction. Check reading order, access to numerator and
|
|
213
|
+
denominator, root degree and table cells, a single intended equation announcement, one visible
|
|
214
|
+
link focus target, link activation and source edit/copy. Repeat after replacement and cleanup.
|
|
215
|
+
These steps are manual acceptance, not an automated pass:
|
|
216
|
+
|
|
217
|
+
- [NVDA's mathematical-content guide](https://download.nvaccess.org/documentation/userGuide.html):
|
|
218
|
+
use the installed provider and recorded browser; enter math from browse mode and inspect
|
|
219
|
+
its nested parts, then return to the surrounding sentence.
|
|
220
|
+
- [JAWS Math Viewer guidance](https://support.freedomscientific.com/SurfsUp/24-MathML.htm):
|
|
221
|
+
enter its viewer, inspect peers and nested structure, return and activate the native link.
|
|
222
|
+
- [VoiceOver mathematical-equation guidance for iPhone](https://support.apple.com/en-au/guide/iphone/iphe4ee74be8/27/ios/27):
|
|
223
|
+
explore the expression at different granularities and verify nested math within a link.
|
|
224
|
+
Qualify macOS/Safari separately with its actual VoiceOver controls.
|
|
225
|
+
|
|
226
|
+
Run `node tests/semantics.mjs` from the package for the focused structural/source corpus.
|
|
227
|
+
This optional development check requires Python 3 with `lxml` for strict XML verification;
|
|
228
|
+
the runtime package itself has no dependency on Python, `lxml` or an XML parser.
|
package/examples/README.md
CHANGED
|
@@ -9,6 +9,9 @@ and run `unified.mjs`. The remark example uses remark's syntax; it does not reco
|
|
|
9
9
|
|
|
10
10
|
Serve the package directory over HTTP and open `examples/browser.html`. Its external module imports the
|
|
11
11
|
installed ESM renderer, fits the output and releases observation before replacement and on page exit.
|
|
12
|
+
Keep both `dist/` and `src/` when serving or copying these native-module examples.
|
|
13
|
+
For a one-file alternative, copy `dist/rapier-math.js`, load it with a classic script tag
|
|
14
|
+
and call `globalThis.RapierMath.renderToString(source)`; do not copy only `dist/index.mjs`.
|
|
12
15
|
Start `new Worker('./worker.mjs', {type: 'module'})` from this directory and post `{id, source}`.
|
|
13
16
|
Use an id owned by the current message and ignore stale replies. Workers render SVG; they do not call `observe`.
|
|
14
17
|
|
|
@@ -26,3 +29,10 @@ source for an explicit `finish()` retry; abort in a final cleanup if the host wi
|
|
|
26
29
|
|
|
27
30
|
The examples retain the original source as the editable/copyable authority. Markdown hosts can normalize
|
|
28
31
|
newlines or escapes in their syntax nodes; an HTML serialization is not an exact source archive.
|
|
32
|
+
|
|
33
|
+
## Structured and accessible formulas
|
|
34
|
+
|
|
35
|
+
Run `node examples/semantic.mjs` for font-free MathML. Serve the package root locally and open
|
|
36
|
+
`examples/accessible.html` for source replacement, generated MathML, cleanup, CSP and the two
|
|
37
|
+
link compositions. The external stylesheet must load. General internal links use native MathML;
|
|
38
|
+
a host link around a complete ordinary formula preserves SVG. See [semantic contracts](../docs/semantics.md).
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<meta charset="utf-8">
|
|
4
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
5
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; connect-src 'none'; base-uri 'none'; form-action 'none'">
|
|
6
|
+
<title>Rapier Math: structured output</title>
|
|
7
|
+
<link rel="stylesheet" href="../dist/accessible.css">
|
|
8
|
+
<main>
|
|
9
|
+
<h1>Structured mathematical output</h1>
|
|
10
|
+
<form id="math-example">
|
|
11
|
+
<label for="source">TeX source</label>
|
|
12
|
+
<textarea id="source" rows="4" cols="48">\frac{-b\pm\sqrt{b^2-4ac}}{2a}</textarea>
|
|
13
|
+
<button type="submit">Render</button>
|
|
14
|
+
</form>
|
|
15
|
+
<p id="status" aria-live="polite"></p>
|
|
16
|
+
<div id="equation"></div>
|
|
17
|
+
<details><summary>Generated MathML</summary><pre id="mathml"></pre></details>
|
|
18
|
+
<h2>A link around the complete SVG formula</h2>
|
|
19
|
+
<p><a href="https://www.w3.org/TR/mathml-core/" id="outer-equation"></a></p>
|
|
20
|
+
<p>A host link can wrap the ordinary composition. Its focus target stays outside the hidden SVG.</p>
|
|
21
|
+
<h2>A link inside a formula</h2>
|
|
22
|
+
<p>The link below uses visible native MathML and one keyboard focus target.</p>
|
|
23
|
+
<div id="linked-equation"></div>
|
|
24
|
+
<p>Its source: <code id="linked-source"></code></p>
|
|
25
|
+
</main>
|
|
26
|
+
<script type="module" src="./accessible.mjs"></script>
|
|
27
|
+
</html>
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
import {renderAccessible} from '../dist/accessible.mjs';
|
|
3
|
+
import {observe} from '../dist/index.mjs';
|
|
4
|
+
|
|
5
|
+
const form = document.querySelector('#math-example'), source = document.querySelector('#source');
|
|
6
|
+
const container = document.querySelector('#equation'), status = document.querySelector('#status');
|
|
7
|
+
let stop = () => {};
|
|
8
|
+
function update(event) {
|
|
9
|
+
event?.preventDefault();
|
|
10
|
+
stop(); stop = () => {};
|
|
11
|
+
const exactSource = source.value;
|
|
12
|
+
try {
|
|
13
|
+
const result = renderAccessible(exactSource, {displayMode: true});
|
|
14
|
+
document.querySelector('#mathml').textContent = result.semantics.mathml;
|
|
15
|
+
status.textContent = result.semantics.status + (result.semantics.errors.length
|
|
16
|
+
? ': ' + result.semantics.errors.map(error => error.message).join(' ') : '');
|
|
17
|
+
if (result.errors.length) container.replaceChildren(document.createTextNode(exactSource));
|
|
18
|
+
else {
|
|
19
|
+
// This sink receives only newly generated package output. Authored TeX stays text.
|
|
20
|
+
container.innerHTML = result.html;
|
|
21
|
+
if (result.presentation === 'svg-mathml') stop = observe(container);
|
|
22
|
+
}
|
|
23
|
+
} catch (error) {
|
|
24
|
+
container.replaceChildren(document.createTextNode(exactSource));
|
|
25
|
+
status.textContent = String(error.message);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
const outer = renderAccessible(String.raw`\frac{12}{\sqrt{x}}`);
|
|
29
|
+
const outerElement = document.querySelector('#outer-equation');
|
|
30
|
+
if (!outer.errors.length) outerElement.innerHTML = outer.html;
|
|
31
|
+
else outerElement.textContent = String.raw`\frac{12}{\sqrt{x}}`;
|
|
32
|
+
|
|
33
|
+
const linkedSource = String.raw`\href{https://www.w3.org/TR/mathml-core/}{\frac{12}{\sqrt{x}}}`;
|
|
34
|
+
const linked = renderAccessible(linkedSource);
|
|
35
|
+
document.querySelector('#linked-source').textContent = linkedSource;
|
|
36
|
+
if (!linked.errors.length) document.querySelector('#linked-equation').innerHTML = linked.html;
|
|
37
|
+
else document.querySelector('#linked-equation').textContent = linkedSource;
|
|
38
|
+
|
|
39
|
+
form.addEventListener('submit', update);
|
|
40
|
+
window.addEventListener('pagehide', () => stop());
|
|
41
|
+
window.addEventListener('pageshow', event => { if (event.persisted) update(); });
|
|
42
|
+
update();
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Node/SSR/worker use: this entry does not load or decode the SVG font.
|
|
3
|
+
import {parse, toMathML} from '../dist/mathml.mjs';
|
|
4
|
+
|
|
5
|
+
const source = String.raw`\frac{12.5}{\sqrt[3]{x^2+1}}`;
|
|
6
|
+
const result = toMathML(source, {displayMode: true});
|
|
7
|
+
if (result.status === 'refused') throw new Error(result.errors.map(error => error.message).join('; '));
|
|
8
|
+
console.log(result.mathml);
|
|
9
|
+
console.log(JSON.stringify({status: result.status, metrics: result.metrics, tree: parse(source)}));
|
|
10
|
+
// Retain source separately for edits. SSR can emit result.mathml visibly without CSS
|
|
11
|
+
// or client-side hydration; speech and navigation still depend on the actual AT stack.
|
package/package.json
CHANGED
|
@@ -1,18 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rapier-math",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"description": "Self-contained offline LaTeX-to-SVG rendering with Latin Modern outlines, optional Markdown integrations and streaming helpers.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.mjs",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
8
8
|
"sideEffects": [
|
|
9
|
-
"./dist/rapier-math.js"
|
|
9
|
+
"./dist/rapier-math.js",
|
|
10
|
+
"./dist/accessible.css"
|
|
10
11
|
],
|
|
11
12
|
"exports": {
|
|
12
13
|
".": {
|
|
13
14
|
"types": "./dist/index.d.ts",
|
|
14
15
|
"default": "./dist/index.mjs"
|
|
15
16
|
},
|
|
17
|
+
"./mathml": {
|
|
18
|
+
"types": "./dist/mathml.d.ts",
|
|
19
|
+
"default": "./dist/mathml.mjs"
|
|
20
|
+
},
|
|
21
|
+
"./combined": {
|
|
22
|
+
"types": "./dist/combined.d.ts",
|
|
23
|
+
"default": "./dist/combined.mjs"
|
|
24
|
+
},
|
|
25
|
+
"./accessible": {
|
|
26
|
+
"types": "./dist/accessible.d.ts",
|
|
27
|
+
"default": "./dist/accessible.mjs"
|
|
28
|
+
},
|
|
16
29
|
"./delimiters": {
|
|
17
30
|
"types": "./dist/delimiters.d.ts",
|
|
18
31
|
"default": "./dist/delimiters.mjs"
|
|
@@ -29,6 +42,7 @@
|
|
|
29
42
|
"types": "./dist/stream.d.ts",
|
|
30
43
|
"default": "./dist/stream.mjs"
|
|
31
44
|
},
|
|
45
|
+
"./accessible.css": "./dist/accessible.css",
|
|
32
46
|
"./classic": {
|
|
33
47
|
"types": "./dist/classic.d.ts",
|
|
34
48
|
"default": "./dist/rapier-math.js"
|
package/src/math/api.js
CHANGED
|
@@ -25,43 +25,9 @@ function mathSvg(box,source,error,utf16,options={}) {
|
|
|
25
25
|
return {svg,width,height,depth,lines:box.lines || 1,fitted:!!box.fitted,errors:error?[error]:[]};
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
-
function
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
for(let i=0;i<source.length;i++) {
|
|
32
|
-
const code=source.charCodeAt(i);
|
|
33
|
-
if(code>=0xd800 && code<=0xdbff && i+1<source.length) {
|
|
34
|
-
const next=source.charCodeAt(i+1);
|
|
35
|
-
if(next>=0xdc00 && next<=0xdfff) {i++;continue;}
|
|
36
|
-
}
|
|
37
|
-
if((code>=0x20 && code<=0xd7ff) || (code>=0xe000 && code<=0xfffd) || code===9 || code===10 || code===13)continue;
|
|
38
|
-
if(first<0)first=i;
|
|
39
|
-
if(i>kept)parts.push(source.slice(kept,i));
|
|
40
|
-
parts.push('\\u'+code.toString(16).toUpperCase().padStart(4,'0'));kept=i+1;
|
|
41
|
-
// Flatten small batches instead of retaining one rope node per bad code unit.
|
|
42
|
-
if(parts.length>=1024) {alternatives.push(parts.join(''));parts.length=0;}
|
|
43
|
-
}
|
|
44
|
-
if(first<0)return {alternative:source};
|
|
45
|
-
parts.push(source.slice(kept));alternatives.push(parts.join(''));
|
|
46
|
-
// Only malformed XML text needs a separate carrier; each four hex digits keep one original code unit.
|
|
47
|
-
const encoded=[];parts.length=0;
|
|
48
|
-
for(let i=0;i<source.length;i++) {
|
|
49
|
-
parts.push(source.charCodeAt(i).toString(16).padStart(4,'0'));
|
|
50
|
-
if(parts.length===1024) {encoded.push(parts.join(''));parts.length=0;}
|
|
51
|
-
}
|
|
52
|
-
encoded.push(parts.join(''));
|
|
53
|
-
return {alternative:alternatives.join(''),utf16:encoded.join(''),error:{code:'invalid-source-character',offset:first,
|
|
54
|
-
message:'A source character cannot be embedded in SVG. The text alternative shows Unicode escapes; data-tex-utf16 keeps the original source.'}};
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
function renderMath(source,options={}) {
|
|
58
|
-
const text=String(source ?? '');
|
|
59
|
-
// Reject before scanning, escaping or parsing. Keep the diagnostic-return
|
|
60
|
-
// contract, but explicitly omit refused source instead of expanding it.
|
|
61
|
-
const safe=text.length>1000000?{alternative:'Formula source omitted: source limit exceeded.',error:{
|
|
62
|
-
code:'resource-limit',offset:0,sourceOmitted:true,
|
|
63
|
-
message:'This formula is too long to render safely. Its source was not embedded; retain the original input.'
|
|
64
|
-
}}:mathSourceAlternative(text),context={size:1,level:0,variant:'normal',cramped:false,display:!!options?.displayMode,cache:new WeakMap(),budget:{nodes:0,outlineBytes:0}};
|
|
28
|
+
function mathRenderPrepared(prepared,options={}) {
|
|
29
|
+
const {text,safe,tree,error:parseError}=prepared;
|
|
30
|
+
const context={size:1,level:0,variant:'normal',cramped:false,display:!!options?.displayMode,cache:new WeakMap(),budget:{nodes:0,outlineBytes:0}};
|
|
65
31
|
try {
|
|
66
32
|
if(safe.error)throw safe.error;
|
|
67
33
|
if(options?.screen!==undefined) {
|
|
@@ -72,20 +38,14 @@ function renderMath(source,options={}) {
|
|
|
72
38
|
throw Object.assign(new Error('Screen font size, pixel ratio and device scale must be positive and finite; dark must be a boolean.'),{code:'invalid-screen'});
|
|
73
39
|
context.screen={fontSize:scaled,pixelRatio,dark};
|
|
74
40
|
}
|
|
75
|
-
|
|
41
|
+
if(parseError)throw parseError;
|
|
42
|
+
const natural=mathLayout(tree,context),limit=Number(options?.maxWidth);
|
|
76
43
|
const maxWidth=Number.isFinite(limit) && limit>.1?limit:undefined;
|
|
77
44
|
const box=maxWidth && mathInkWidth(natural)>maxWidth-.05?mathResponsiveLayout(tree,context,maxWidth-.05,natural):natural;
|
|
78
|
-
return mathSvg(box,safe.alternative,undefined,
|
|
45
|
+
return mathSvg(box,safe.alternative,undefined,safe.utf16,{displayMode:context.display,maxWidth,naturalWidth:mathInkWidth(natural)+.05,screen:context.screen});
|
|
79
46
|
}
|
|
80
47
|
catch (cause) {
|
|
81
|
-
const
|
|
82
|
-
const error={code:cause.code || 'invalid-tex',message:message.length>1024?message.slice(0,1024).replace(/[\ud800-\udbff]$/,'')+'…':message,offset:Number.isFinite(cause.offset)?cause.offset:0};
|
|
83
|
-
if(message.length>1024)error.messageTruncated=true;
|
|
84
|
-
if(cause.sourceOmitted)error.sourceOmitted=true;
|
|
85
|
-
if(cause.command) {
|
|
86
|
-
error.command=String(cause.command).slice(0,128);
|
|
87
|
-
if(cause.command.length>128)error.commandTruncated=true;
|
|
88
|
-
}
|
|
48
|
+
const error=mathDiagnostic(cause);
|
|
89
49
|
// A diagnostic is visible, but remains distinct from a successfully typeset formula.
|
|
90
50
|
// Diagnostics have an explicit bound. Exact input stays in the source alternative.
|
|
91
51
|
const label=error.message.length>240?'This formula could not be rendered. The complete diagnostic is in its text description.':error.message.replace(/[^\x20-\x7e]/g,'?');
|
|
@@ -99,11 +59,12 @@ function renderMath(source,options={}) {
|
|
|
99
59
|
}
|
|
100
60
|
}
|
|
101
61
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
}
|
|
62
|
+
function renderMath(source,options={}) {
|
|
63
|
+
return mathRenderPrepared(mathPrepare(source),options);
|
|
64
|
+
}
|
|
65
|
+
function mathRenderToString(source,options) { return renderMath(source,options).svg; }
|
|
66
|
+
|
|
67
|
+
import {mathDiagnostic, mathPrepare} from './source.js';
|
|
68
|
+
import {mathNumber, mathEscape, mathFontRatio, mathText, mathLayout} from './layout.js';
|
|
69
|
+
import {mathInkWidth, mathResponsiveLayout} from './responsive.js';
|
|
70
|
+
export {renderMath, mathRenderPrepared, mathRenderToString};
|
package/src/math/browser.js
CHANGED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
globalThis.RapierMath=Object.freeze({
|
|
3
|
+
version:'2.2.0', parse:parseMathTex,
|
|
4
|
+
render:renderMath, renderToString:mathRenderToString,
|
|
5
|
+
fit:mathFit, observe:mathObserve,
|
|
6
|
+
toMathML:mathToMathML, renderWithMathML:mathRenderWithMathML,
|
|
7
|
+
});
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// The prepared tree never crosses the public boundary. Both outputs consume it
|
|
3
|
+
// within this call, before any result or caller-mutable parse tree is exposed.
|
|
4
|
+
function mathRenderWithMathML(source, options = {}) {
|
|
5
|
+
const prepared = mathPrepare(source), displayMode = !!options?.displayMode;
|
|
6
|
+
const semantics = mathSemanticPrepared(prepared, {displayMode});
|
|
7
|
+
return {...mathRenderPrepared(prepared, {...options, displayMode}), semantics};
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
import {mathPrepare} from './source.js';
|
|
11
|
+
import {mathRenderPrepared} from './api.js';
|
|
12
|
+
import {mathSemanticPrepared} from './semantic-api.js';
|
|
13
|
+
export {mathRenderWithMathML};
|
package/src/math/fallbacks.js
CHANGED
|
@@ -109,3 +109,8 @@ function mathFallbackGlyph(value,c,extra={}) {
|
|
|
109
109
|
}
|
|
110
110
|
return null;
|
|
111
111
|
}
|
|
112
|
+
|
|
113
|
+
import {MATH_FONT} from './font.js';
|
|
114
|
+
import {mathStyledCodePoint} from './variants.js';
|
|
115
|
+
import {mathNumber, mathScale, mathScreenStroke, mathConstant, mathBox, mathCompose, mathGlyphIndex, mathRule, mathStretch} from './layout.js';
|
|
116
|
+
export {mathFallbackGlyph};
|
package/src/math/font.js
CHANGED
|
@@ -545,3 +545,6 @@ complete(r);return remember(profileCache,id,profile,128);
|
|
|
545
545
|
MATH_FONT.glyph=id=>glyphRecord(id)?.glyph;
|
|
546
546
|
MATH_FONT.profile=id=>{const glyph=glyphRecord(id);return glyph&&glyph.profile>=0?profileRecord(glyph.profile):undefined;};
|
|
547
547
|
}
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
export {MATH_FONT};
|