feat: docx/math, with matrices, cases, equations lined up with numbers, and brackets of any characters (#3553)

This commit is contained in:
Dolan
2026-09-27 17:30:38 +01:00
committed by GitHub
parent e0ff13ee3d
commit 7ada74f6d1
25 changed files with 1724 additions and 19 deletions
+3
View File
@@ -18,6 +18,7 @@
"aiueo",
"arrowok",
"ATLEAST",
"bmatrix",
"chosung",
"clippy",
"coordsize",
@@ -46,6 +47,7 @@
"onfile",
"ooxml",
"panose",
"pmatrix",
"rels",
"rsid",
"sdtdh",
@@ -56,6 +58,7 @@
"twips",
"ungrouping",
"verticies",
"vmatrix",
"Xmlable",
"xmlified",
"xmlify",
+2 -5
View File
@@ -1,8 +1,8 @@
// Simple example to add text to a document
import * as fs from "fs";
import { Document, Packer, Paragraph, TextRun } from "docx";
import {
Document,
Math,
MathAngledBrackets,
MathCurlyBrackets,
@@ -18,12 +18,9 @@ import {
MathSum,
MathIntegral,
MathSuperScript,
Packer,
Paragraph,
TextRun,
MathLimitLower,
MathLimitUpper,
} from "docx";
} from "docx/math";
const doc = new Document({
sections: [
+105
View File
@@ -0,0 +1,105 @@
// Matrices, equations lined up with numbers, cases, and brackets of any characters: LaTeX's pmatrix, bmatrix, vmatrix,
// Vmatrix, align, aligned and cases (issue #2993). See docs/usage/math.md.
import * as fs from "fs";
import { AlignmentType, Document, HeadingLevel, Packer, Paragraph, TextRun } from "docx";
import { Math, MathBrackets, MathCases, type MathComponent, MathEquationArray, MathMatrix, MathRun, MathSuperScript } from "docx/math";
const heading = (text: string): Paragraph => new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun(text)] });
// An equation on a line of its own, centred
const equation = (...children: MathComponent[]): Paragraph =>
new Paragraph({ alignment: AlignmentType.CENTER, children: [new Math({ children })] });
const run = (text: string): MathRun => new MathRun(text);
const words = (text: string): MathRun => new MathRun({ text, normalText: true });
const squared = (...children: MathComponent[]): MathSuperScript => new MathSuperScript({ children, superScript: [run("2")] });
const cells = (...rows: readonly string[][]): readonly (readonly MathComponent[])[][] => rows.map((row) => row.map((text) => [run(text)]));
const doc = new Document({
sections: [
{
children: [
new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("Matrices and alignment")] }),
heading("Matrices"),
new Paragraph("In round brackets (pmatrix), square brackets (bmatrix), bars (vmatrix) and double bars (Vmatrix):"),
equation(new MathMatrix({ brackets: "round", rows: cells(["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]) })),
equation(new MathMatrix({ brackets: "square", rows: cells(["1", "2"], ["3", "4"]) })),
equation(new MathMatrix({ brackets: "verticalBars", rows: cells(["a", "b"], ["c", "d"]) })),
equation(new MathMatrix({ brackets: "doubleVerticalBars", rows: cells(["a", "b"], ["c", "d"]) })),
new Paragraph("Columns lined up on the left and on the right, with a shorter row given empty cells:"),
equation(
run("A="),
new MathMatrix({
brackets: "square",
columnAlignment: ["left", "center", "right"],
rows: cells(["1", "20", "300"], ["4000", "5", "6"], ["7"]),
}),
),
heading("Equations lined up, with numbers"),
new Paragraph("Lined up at the = sign, each with a number (align):"),
equation(
new MathEquationArray({
rows: [
{ parts: [[run("y")], [run("=mx+b")]], equationNumber: "(1)" },
{ parts: [[run("y′")], [run("=m")]], equationNumber: "(2)" },
],
}),
),
new Paragraph("Parts of one equation lined up (aligned), the rows after the first going on from it:"),
equation(
new MathEquationArray({
rows: [
{
parts: [
[squared(new MathBrackets({ children: [run("a+b")] }))],
[run("="), new MathBrackets({ children: [run("a+b")] }), new MathBrackets({ children: [run("a+b")] })],
],
},
{ parts: [[], [run("="), squared(run("a")), run("+ab+ba+"), squared(run("b"))]] },
{ parts: [[], [run("="), squared(run("a")), run("+2ab+"), squared(run("b"))]] },
],
}),
),
heading("Cases"),
equation(
run("f(x)="),
new MathCases({
cases: [
{ value: [run("1,")], condition: [words("if "), run("x>0")] },
{ value: [run("0,")], condition: [words("if "), run("x=0")] },
{ value: [run("−1,")], condition: [words("if "), run("x<0")] },
],
}),
),
equation(
run("f(x)="),
new MathCases({
cases: [
{ value: [squared(run("x")), run(",")], condition: [words("if "), run("x≥0")] },
{ value: [run("−"), squared(run("x")), run(",")], condition: [words("otherwise")] },
],
}),
),
heading("Brackets of any characters"),
equation(
new MathBrackets({ open: "|", close: "|", children: [run("x")] }),
run(", "),
new MathBrackets({ open: "‖", close: "‖", children: [run("v")] }),
run(", "),
new MathBrackets({ open: "⟨", close: "⟩", separator: "|", items: [[run("a")], [run("b")]] }),
run(", "),
new MathBrackets({ open: "[", close: ")", children: [run("0,1")] }),
),
],
},
],
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer);
});
+167
View File
@@ -9,6 +9,19 @@
3. `MathComponents` can have nested `MathComponents` inside. e.g. A fraction where the numerator is a square root, and the denominator as another fraction. More on `MathComponents` below
4. Make sure to add the `Math` object inside a `Paragraph`
## Importing
Math comes with the `docx` package. Import it from `docx/math`, and everything else, such as the document and its paragraphs, from `docx`:
```ts
import { Document, Packer, Paragraph } from "docx";
import { Math, MathFraction, MathRun } from "docx/math";
```
Types such as `IMathOptions` and `MathComponent` come from `docx/math` too. `docx` still exports the math it had before `docx/math`, so code that imports it from `docx` keeps working. The two export the same classes, so they can be mixed. `MathMatrix`, `MathCases`, `MathEquationArray` and `MathBrackets` come from `docx/math` only.
In a page without a bundler, load `dist/math.umd.cjs` after `dist/index.umd.cjs` (or `dist/math.iife.js` after `dist/index.iife.js`). It adds a `docxMath` global, such as `new docxMath.MathRun("2+2")`.
## Example
```ts
@@ -59,6 +72,14 @@ new Math({
}),
```
#### Normal text
Letters in math are drawn in italics, as variables. For words, such as "if" and "otherwise", give the text as normal text, which is upright and in the document's font, with its spaces kept, as Word's "Normal Text" button does (`m:nor`):
```ts
new MathRun({ text: "if ", normalText: true });
```
### Math Fraction
`MathFractions` require a `numerator` and a `denominator`, which are both a list of `MathComponents`
@@ -212,6 +233,29 @@ new MathFunction({
### Brackets
#### Brackets of any characters
`MathBrackets` puts brackets of any single characters around math, such as bars for an absolute value, double bars for a norm, or a brace on one side only (`""` for no bracket). The brackets grow with what they hold. Give `items` instead of `children` for several things with a `separator` between them:
```ts
new MathBrackets({ open: "|", close: "|", children: [new MathRun("x")] }); // |x|
new MathBrackets({ open: "‖", close: "‖", children: [new MathRun("v")] }); // ‖v‖
new MathBrackets({ open: "⟨", close: "⟩", separator: "|", items: [[new MathRun("a")], [new MathRun("b")]] }); // ⟨a|b⟩
new MathBrackets({ open: "[", close: ")", children: [new MathRun("0,1")] }); // [0,1)
new MathBrackets({ open: "{", close: "", children: [new MathRun("x")] }); // a brace on the left only
```
| Option | Type | Default | Notes |
| ----------- | ------------------- | ------- | ------------------------------------------------------------------------------------- |
| `open` | `string` | `"("` | One character, or `""` for none (`m:begChr`) |
| `close` | `string` | `")"` | One character, or `""` for none (`m:endChr`) |
| `children` | `MathComponent[]` | | What goes between the brackets |
| `items` | `MathComponent[][]` | | Instead of `children`: several things, with `separator` between them |
| `separator` | `string` | `"\|"` | One character (`m:sepChr`) |
| `grow` | `boolean` | `true` | Whether the brackets grow with what they hold. LibreOffice and Pages always grow them |
The four kinds below are fixed pairs of these.
#### Square brackets
```ts
@@ -284,8 +328,131 @@ new MathLimitLower({
}),
```
### Matrices
`MathMatrix` writes a matrix (`m:m`): rows of cells, each cell a list of `MathComponents`, in brackets or none. A row shorter than the longest gets empty cells at its end.
```ts
new MathMatrix({
brackets: "round",
rows: [
[[new MathRun("1")], [new MathRun("2")], [new MathRun("3")]],
[[new MathRun("4")], [new MathRun("5")], [new MathRun("6")]],
],
});
```
| Option | Type | Default | Notes |
| ------------------- | ------------------------------------------------------------------------------------------------ | ---------- | ----------------------------------------------------------------------------------------- |
| `rows` | `MathComponent[][][]` | | Rows of cells. Word allows at most 256 rows and 64 cells in a row |
| `brackets` | `"none"`, `"round"`, `"square"`, `"curly"`, `"angled"`, `"verticalBars"`, `"doubleVerticalBars"` | `"none"` | ( ), [ ], { }, ⟨ ⟩, \| \| and ‖ ‖ |
| `columnAlignment` | `"left"`, `"center"`, `"right"`, or one for each column | `"center"` | Where the cells go across their columns (`m:mcJc`). LibreOffice and Pages centre them all |
| `verticalAlignment` | `"top"`, `"center"`, `"bottom"` | `"center"` | Where the matrix sits on its line (`m:baseJc`) |
### Cases
`MathCases` writes values, each with its condition, one to a line, in a brace on the left, as LaTeX's `cases`:
```ts
new Math({
children: [
new MathRun("f(x)="),
new MathCases({
cases: [
{ value: [new MathRun("1,")], condition: [new MathRun({ text: "if ", normalText: true }), new MathRun("x>0")] },
{ value: [new MathRun("0,")], condition: [new MathRun({ text: "otherwise", normalText: true })] },
],
}),
],
});
```
A case's `condition` can be left out. The cases are written as a matrix of two columns, lined up on the left, in a brace with no closing bracket, as pandoc writes them, since LibreOffice draws the `&` of Word's own way. Word allows at most 256 cases.
### Equations lined up, with numbers
`MathEquationArray` writes rows of math, one to a line, lined up at the points between their parts, as LaTeX's `align` and `aligned` (`m:eqArr`). Each row is a list of `parts`: the first, third and every other point between them line up with the same points in the other rows, such as at an `=` sign, and the others are where space goes between columns, as LaTeX's `&`. A part can be empty, such as the first part of a row that goes on from the row before:
```ts
new MathEquationArray({
rows: [
{ parts: [[new MathRun("(a+b)²")], [new MathRun("=(a+b)(a+b)")]] },
{ parts: [[], [new MathRun("=a²+ab+ba+b²")]] },
{ parts: [[], [new MathRun("=a²+2ab+b²")]] },
],
});
```
A row's `equationNumber` is put at the right margin by Word 2016 and later, as Word's own equation numbers (`#` then the number):
```ts
new MathEquationArray({
rows: [
{ parts: [[new MathRun("y")], [new MathRun("=mx+b")]], equationNumber: "(1)" },
{ parts: [[new MathRun("y′")], [new MathRun("=m")]], equationNumber: "(2)" },
],
});
```
| Option | Type | Default | Notes |
| ----------------------- | ------------------------------- | ---------- | --------------------------------------------- |
| `rows` | `MathEquationArrayRow[]` | | Word allows at most 64 |
| `rows[].parts` | `MathComponent[][]` | | At least one, which can be empty |
| `rows[].equationNumber` | `string` | | Such as `"(1)"` |
| `verticalAlignment` | `"top"`, `"center"`, `"bottom"` | `"center"` | Where the array sits on its line (`m:baseJc`) |
?> Word marks the points with an `&`, and the number with a `#`, in the text. So an `&` or a `#` in a `MathRun` inside an equation array is taken as one too.
Word 2013 and older, LibreOffice and Pages show the `#` before the number. For numbers that every application puts at the margin, put the equation in a paragraph with a centre tab stop and a right tab stop, and the number after a tab. Word then draws the equation at the size of inline math:
```ts
new Paragraph({
tabStops: [
{ type: TabStopType.CENTER, position: TabStopPosition.MAX / 2 },
{ type: TabStopType.RIGHT, position: TabStopPosition.MAX },
],
children: [
new TextRun({ children: [new Tab()] }),
new Math({ children: [new MathRun("E=mc²")] }),
new TextRun({ children: [new Tab(), "(1)"] }),
],
});
```
## From LaTeX
| LaTeX | `docx/math` |
| --------------------------------------- | ---------------------------------------------------------------------- |
| `\begin{matrix}` | `new MathMatrix({ rows })` |
| `\begin{pmatrix}` | `new MathMatrix({ brackets: "round", rows })` |
| `\begin{bmatrix}` | `new MathMatrix({ brackets: "square", rows })` |
| `\begin{Bmatrix}` | `new MathMatrix({ brackets: "curly", rows })` |
| `\begin{vmatrix}` | `new MathMatrix({ brackets: "verticalBars", rows })` |
| `\begin{Vmatrix}` | `new MathMatrix({ brackets: "doubleVerticalBars", rows })` |
| `\begin{cases}` | `new MathCases({ cases: [{ value, condition }] })` |
| `\begin{aligned}`, `\begin{align*}` | `new MathEquationArray({ rows: [{ parts }] })` |
| `\begin{align}`, `\tag{1}` | `new MathEquationArray({ rows: [{ parts, equationNumber: "(1)" }] })` |
| `&` in a row | Between two of a row's `parts` |
| `\left\| x \right\|`, `\lVert v \rVert` | `new MathBrackets({ open: "\|", close: "\|", children })`, `open: "‖"` |
| `\langle a \mid b \rangle` | `new MathBrackets({ open: "⟨", close: "⟩", separator: "\|", items })` |
| `\text{if}` | `new MathRun({ text: "if", normalText: true })` |
## Compatibility
Word is the reference. Other applications differ:
- **LibreOffice** centres every column of a matrix, centres the rows of an equation array without lining them up, and shows the `&` between parts and the `#` before equation numbers.
- **Pages** centres every column of a matrix and shows the `#` before equation numbers. It draws all math very small unless the document's default paragraph style has a size, which `docx` doesn't write.
- **Word 2013 and older** show the `#` before equation numbers.
## Demo
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/math/math.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/math/math.ts_
Matrices, equations lined up with numbers, cases, and brackets of any characters:
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/math/matrices-and-alignment.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/math/matrices-and-alignment.ts_
+4 -3
View File
@@ -369,10 +369,11 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
},
// docx's optional entries, docx/shapes (src/shapes), docx/watermarks (src/watermarks) and docx/charts (src/charts), are
// built on docx's public API. They import docx by name, so their builds leave docx out and the package has one copy of
// each class and id counter. docx doesn't import them. Specs may import docx's internals, such as the Formatter
// each class and id counter. docx doesn't import them. Specs may import docx's internals, such as the Formatter.
// docx/math (src/math) re-exports docx's math, which docx still exports and keeps in src/file/paragraph/math
{
files: ["src/**/*.ts"],
ignores: ["src/shapes/**", "src/watermarks/**", "src/charts/**", "**/*.spec.ts"],
ignores: ["src/shapes/**", "src/watermarks/**", "src/charts/**", "src/math/**", "**/*.spec.ts"],
rules: {
"no-restricted-imports": [
"error",
@@ -387,7 +388,7 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
},
},
{
files: ["src/shapes/*.ts", "src/watermarks/*.ts", "src/charts/*.ts"],
files: ["src/shapes/*.ts", "src/watermarks/*.ts", "src/charts/*.ts", "src/math/*.ts"],
ignores: ["**/*.spec.ts"],
rules: {
"no-restricted-imports": [
+15 -2
View File
@@ -46,6 +46,16 @@
"types": "./dist/charts.d.cts",
"default": "./dist/charts.cjs"
}
},
"./math": {
"import": {
"types": "./dist/math.d.ts",
"default": "./dist/math.mjs"
},
"require": {
"types": "./dist/math.d.cts",
"default": "./dist/math.cjs"
}
}
},
"typesVersions": {
@@ -58,6 +68,9 @@
],
"charts": [
"./dist/charts.d.ts"
],
"math": [
"./dist/math.d.ts"
]
}
},
@@ -65,14 +78,14 @@
"dist"
],
"scripts": {
"build": "tsc && vite build && vite build --config vite.entries.config.ts --mode shapes && vite build --config vite.entries.config.ts --mode watermarks && vite build --config vite.entries.config.ts --mode charts",
"build": "tsc && vite build && vite build --config vite.entries.config.ts --mode shapes && vite build --config vite.entries.config.ts --mode watermarks && vite build --config vite.entries.config.ts --mode charts && vite build --config vite.entries.config.ts --mode math",
"test": "vitest --ui --coverage",
"test:ci": "vitest run --coverage",
"prepublishOnly": "npm run build --omit=dev",
"lint": "eslint --config eslint.config.ts",
"predemo": "npm run build",
"demo": "tsx ./demo/index.ts",
"typedoc": "typedoc src/index.ts src/shapes/index.ts src/watermarks/index.ts src/charts/index.ts --tsconfig tsconfig.typedoc.json",
"typedoc": "typedoc src/index.ts src/shapes/index.ts src/watermarks/index.ts src/charts/index.ts src/math/index.ts --tsconfig tsconfig.typedoc.json",
"prettier": "prettier -l \"{src,scripts,demo,docs}/**/*.{ts,html,md}\"",
"prettier:fix": "npm run prettier -- --write",
"cspell": "cspell \"{src,demo,docs,scripts}/**/*.{ts,scss,html,md}\" && cspell \"./*.*\"",
+7 -7
View File
@@ -1,12 +1,12 @@
#!/usr/bin/env bash
# Runs the shape and chart demos, checks where their drawings' Word 2010 extensions are and that their drawing ids are
# unique, and draws each page as a PNG with LibreOffice. The Demos workflow checks them with the Open XML SDK validator.
# Runs the shape, chart and math demos, checks where their drawings' Word 2010 extensions are and that their drawing ids
# are unique, and draws each page as a PNG with LibreOffice. The Demos workflow checks them with the Open XML SDK validator.
#
# Usage: scripts/render-shape-demos.sh [output directory] [demo ...]
#
# Each demo is its topic and name, such as shapes/shape-groups. The output directory (default build/shape-demos) gets
# each demo's .docx, .pdf and one PNG per page, named after the demo. Without demos, all the shape and chart demos are
# run. Needs the package built (npm run build) and perl.
# each demo's .docx, .pdf and one PNG per page, named after the demo. Without demos, all the shape, chart and math demos
# are run. Needs the package built (npm run build) and perl.
#
# The pages are drawn with LibreOffice (set SOFFICE if soffice isn't on the PATH) and pdftoppm from Poppler.
# When SHAPE_RENDER_IMAGE names a Docker image built from scripts/shape-demos/Dockerfile, they are drawn in
@@ -22,7 +22,7 @@ OUT="${1:-build/shape-demos}"
shift || true
DEMOS=("$@")
if [ ${#DEMOS[@]} -eq 0 ]; then
DEMOS=(shapes/inline-shapes shapes/shapes shapes/shape-groups shapes/shape-connectors shapes/shape-styles shapes/shape-diagrams shapes/shape-layout shapes/shape-document-styles shapes/shape-swimlanes shapes/shape-page-layout styles/theme shapes/custom-shapes charts/charts charts/chart-options charts/charts-in-templates charts/chart-data-in-templates charts/more-charts)
DEMOS=(shapes/inline-shapes shapes/shapes shapes/shape-groups shapes/shape-connectors shapes/shape-styles shapes/shape-diagrams shapes/shape-layout shapes/shape-document-styles shapes/shape-swimlanes shapes/shape-page-layout styles/theme shapes/custom-shapes charts/charts charts/chart-options charts/charts-in-templates charts/chart-data-in-templates charts/more-charts math/matrices-and-alignment)
fi
SOFFICE="${SOFFICE:-soffice}"
@@ -50,8 +50,8 @@ for demo in "${DEMOS[@]}"; do
failed=1
fi
# Drawing ids must be unique across the document
repeated="$(grep -ho '\(wp:docPr\|wps:cNvPr\|pic:cNvPr\|wpg:cNvPr\) id="[0-9]*"' "$extracted"/word/*.xml | sed 's/.*id=//' | sort | uniq -d)"
# Drawing ids must be unique across the document. grep finds none in a document without drawings, such as math's
repeated="$( (grep -ho '\(wp:docPr\|wps:cNvPr\|pic:cNvPr\|wpg:cNvPr\) id="[0-9]*"' "$extracted"/word/*.xml || true) | sed 's/.*id=//' | sort | uniq -d)"
if [ -n "$repeated" ]; then
echo "::error::$demo repeats drawing ids: $repeated"
failed=1
Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

+12
View File
@@ -17,5 +17,17 @@ describe("MathRun", () => {
],
});
});
it("takes its text in options too", () => {
expect(new Formatter().format(new MathRun({ text: "2+2" }))).to.deep.equal({ "m:r": [{ "m:t": ["2+2"] }] });
expect(new Formatter().format(new MathRun({ text: "2+2", normalText: false }))).to.deep.equal({ "m:r": [{ "m:t": ["2+2"] }] });
});
it("writes normal text with m:nor, keeping its spaces", () => {
const tree = new Formatter().format(new MathRun({ text: "if ", normalText: true }));
expect(tree).to.deep.equal({
"m:r": [{ "m:rPr": [{ "m:nor": { _attr: { "m:val": 1 } } }] }, { "m:t": [{ _attr: { "xml:space": "preserve" } }, "if "] }],
});
});
});
});
+30 -2
View File
@@ -7,10 +7,24 @@
*
* @module
*/
import { XmlComponent } from "@file/xml-components";
import { BuilderElement, XmlComponent } from "@file/xml-components";
import { MathText } from "./math-text";
/**
* Options for a {@link MathRun}.
*/
export type MathRunOptions = {
/** The text */
readonly text: string;
/**
* Writes the text as ordinary text rather than math, as Word's "Normal Text" button does (`m:nor`): upright and in
* the document's font, with its spaces kept. For words in an equation, such as "if" and "otherwise" in cases.
* @default false
*/
readonly normalText?: boolean;
};
/**
* Represents a run of text within a math equation.
*
@@ -38,12 +52,26 @@ import { MathText } from "./math-text";
* @example
* ```typescript
* new MathRun("x + y");
* new MathRun({ text: "if ", normalText: true });
* ```
*/
export class MathRun extends XmlComponent {
public constructor(text: string) {
public constructor(options: string | MathRunOptions) {
super("m:r");
const { text, normalText } = typeof options === "string" ? { text: options, normalText: false } : options;
if (normalText) {
this.root.push(
new BuilderElement({
name: "m:rPr",
children: [
new BuilderElement<{ readonly on: number }>({ name: "m:nor", attributes: { on: { key: "m:val", value: 1 } } }),
],
}),
);
}
this.root.push(new MathText(text));
}
}
+11
View File
@@ -13,5 +13,16 @@ describe("MathText", () => {
"m:t": ["2+2"],
});
});
it("keeps spaces at either end, and only then marks them", () => {
expect(new Formatter().format(new MathText("if "))).to.deep.equal({ "m:t": [{ _attr: { "xml:space": "preserve" } }, "if "] });
expect(new Formatter().format(new MathText(" x"))).to.deep.equal({ "m:t": [{ _attr: { "xml:space": "preserve" } }, " x"] });
expect(new Formatter().format(new MathText("\tx"))).to.deep.equal({ "m:t": [{ _attr: { "xml:space": "preserve" } }, "\tx"] });
expect(new Formatter().format(new MathText("\u200B"))).to.deep.equal({
"m:t": [{ _attr: { "xml:space": "preserve" } }, "\u200B"],
});
expect(new Formatter().format(new MathText("x + y"))).to.deep.equal({ "m:t": ["x + y"] });
expect(new Formatter().format(new MathText(""))).to.deep.equal({ "m:t": [""] });
});
});
});
+9
View File
@@ -7,8 +7,11 @@
*
* @module
*/
import { SpaceType } from "@file/shared";
import { XmlComponent } from "@file/xml-components";
import { TextAttributes } from "../run/text-attributes";
/**
* Represents text content within a math run.
*
@@ -32,6 +35,12 @@ export class MathText extends XmlComponent {
public constructor(text: string) {
super("m:t");
// Spaces at either end are kept only when marked. LibreOffice drops them otherwise, and zero-width spaces too, which
// docx/math writes in empty arguments. Spaces matter in normal text
if (/^[\s\u200B]|[\s\u200B]$/.test(text)) {
this.root.push(new TextAttributes({ space: SpaceType.PRESERVE }));
}
this.root.push(text);
}
}
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, expectTypeOf, it } from "vitest";
import * as mathModule from "@file/paragraph/math";
import * as docx from "docx";
import * as math from ".";
// docx/math's own components, which docx doesn't export
const OWN = ["MathBrackets", "MathCases", "MathEquationArray", "MathMatrix"];
describe("docx/math", () => {
it("exports docx's own math classes and functions, not copies of them", () => {
for (const [name, value] of Object.entries(math).filter(([key]) => !OWN.includes(key))) {
expect(value, name).toBe(docx[name as keyof typeof docx]);
}
});
it("exports every class and function of docx's math, so a new one isn't left out of docx/math", () => {
// WORKAROUND4 is an empty string, not part of the math API
const names = Object.keys(mathModule).filter((name) => name !== "WORKAROUND4");
expect(Object.keys(math).toSorted()).toEqual([...names, ...OWN].toSorted());
});
it("keeps its own components out of docx, so they don't add to docx's bundle", () => {
for (const name of OWN) {
expect(name in docx, name).toBe(false);
expect(math[name as keyof typeof math], name).toBeTypeOf("function");
}
});
it("gives components that go wherever docx's math and paragraphs take their children", () => {
expectTypeOf<math.MathMatrix>().toExtend<docx.MathComponent>();
expectTypeOf<math.MathBrackets>().toExtend<docx.MathComponent>();
expectTypeOf<math.MathCases>().toExtend<docx.MathComponent>();
expectTypeOf<math.MathEquationArray>().toExtend<docx.MathComponent>();
expectTypeOf<docx.Math>().toExtend<docx.ParagraphChild>();
const paragraph = new docx.Paragraph({
children: [
new math.Math({
children: [
new math.MathFraction({
numerator: [new math.MathMatrix({ rows: [[[new math.MathRun("1")]]] })],
denominator: [new math.MathCases({ cases: [{ value: [new math.MathRun("2")] }] })],
}),
],
}),
],
});
expect(paragraph).toBeInstanceOf(docx.Paragraph);
});
});
+99
View File
@@ -0,0 +1,99 @@
/**
* Math for docx documents: equations, such as fractions, sums, integrals, radicals, scripts, brackets, matrices, cases
* and aligned equations with numbers, written as Office Math, which Word shows and edits as equations.
*
* Math comes with the `docx` package, from `docx/math`. Everything else, such as the document and its paragraphs,
* comes from `docx`. `docx` still exports the math it had before `docx/math`, as the same classes, not copies, so the
* two can be mixed. Matrices, cases, equation arrays and brackets of any characters come from `docx/math` only.
*
* @module
*
* @example
* ```typescript
* import { Document, Packer, Paragraph } from "docx";
* import { Math, MathFraction, MathRun } from "docx/math";
*
* const doc = new Document({
* sections: [
* {
* children: [
* new Paragraph({
* children: [
* new Math({
* children: [
* new MathRun("2+2"),
* new MathFraction({ numerator: [new MathRun("hi")], denominator: [new MathRun("2")] }),
* ],
* }),
* ],
* }),
* ],
* },
* ],
* });
*
* const buffer = await Packer.toBuffer(doc);
* ```
*/
export {
Math,
MathAngledBrackets,
MathCurlyBrackets,
MathDegree,
MathDenominator,
MathFraction,
MathFunction,
MathFunctionName,
MathFunctionProperties,
MathIntegral,
MathLimit,
MathLimitLower,
MathLimitUpper,
MathNumerator,
MathPreSubSuperScript,
MathRadical,
MathRadicalProperties,
MathRoundBrackets,
MathRun,
MathSquareBrackets,
MathSubScript,
MathSubSuperScript,
MathSum,
MathSuperScript,
createMathAccentCharacter,
createMathBase,
createMathLimitLocation,
createMathNAryProperties,
createMathPreSubSuperScriptProperties,
createMathSubScriptElement,
createMathSubScriptProperties,
createMathSubSuperScriptProperties,
createMathSuperScriptElement,
createMathSuperScriptProperties,
} from "docx";
export type {
IMathFractionOptions,
IMathFunctionOptions,
IMathIntegralOptions,
IMathLimitLowerOptions,
IMathLimitUpperOptions,
IMathOptions,
IMathPreSubSuperScriptOptions,
IMathRadicalOptions,
IMathSubScriptOptions,
IMathSubSuperScriptOptions,
IMathSumOptions,
IMathSuperScriptOptions,
MathComponent,
MathRunOptions,
} from "docx";
export { MathBrackets, type MathBracketsOptions } from "./math-brackets";
export { MathCases, type MathCase, type MathCasesOptions } from "./math-cases";
export { MathEquationArray, type MathEquationArrayOptions, type MathEquationArrayRow } from "./math-equation-array";
export {
MathMatrix,
type MathColumnAlignment,
type MathMatrixBrackets,
type MathMatrixOptions,
type MathVerticalAlignment,
} from "./math-matrix";
+110
View File
@@ -0,0 +1,110 @@
import { describe, expect, it } from "vitest";
import xml from "xml";
import { Formatter } from "@export/formatter";
import { Math, MathFraction, MathRun, Paragraph, TextRun } from "docx";
import { MathBrackets } from "./math-brackets";
import { MathMatrix } from "./math-matrix";
const toXml = (component: MathBrackets): string => xml(new Formatter().format(component));
const x = "<m:e><m:r><m:t>x</m:t></m:r></m:e>";
describe("MathBrackets", () => {
it("puts round brackets around its children by default", () => {
expect(toXml(new MathBrackets({ children: [new MathRun("x")] }))).toBe(
`<m:d><m:dPr><m:begChr m:val="("/><m:endChr m:val=")"/></m:dPr>${x}</m:d>`,
);
});
it("takes any single characters, such as bars for an absolute value", () => {
expect(toXml(new MathBrackets({ open: "|", close: "|", children: [new MathRun("x")] }))).toBe(
`<m:d><m:dPr><m:begChr m:val="|"/><m:endChr m:val="|"/></m:dPr>${x}</m:d>`,
);
expect(toXml(new MathBrackets({ open: "‖", close: "‖", children: [new MathRun("x")] }))).toContain('<m:begChr m:val="‖"/>');
});
it("writes an empty character for a side with no bracket", () => {
expect(toXml(new MathBrackets({ open: "{", close: "", children: [new MathRun("x")] }))).toBe(
`<m:d><m:dPr><m:begChr m:val="{"/><m:endChr m:val=""/></m:dPr>${x}</m:d>`,
);
expect(toXml(new MathBrackets({ open: "", close: "}", children: [new MathRun("x")] }))).toContain(
'<m:begChr m:val=""/><m:endChr m:val="}"/>',
);
});
it("writes each item as an argument, with the separator between the two brackets in the schema's order", () => {
expect(toXml(new MathBrackets({ open: "⟨", close: "⟩", separator: "|", items: [[new MathRun("a")], [new MathRun("b")]] }))).toBe(
'<m:d><m:dPr><m:begChr m:val="⟨"/><m:sepChr m:val="|"/><m:endChr m:val="⟩"/></m:dPr>' +
"<m:e><m:r><m:t>a</m:t></m:r></m:e><m:e><m:r><m:t>b</m:t></m:r></m:e></m:d>",
);
});
it("leaves the separator to Word's default when none is given", () => {
const written = toXml(new MathBrackets({ items: [[new MathRun("a")], [new MathRun("b")], [new MathRun("c")]] }));
expect(written).not.toContain("m:sepChr");
expect(written.match(/<m:e>/g)).toHaveLength(3);
});
it("takes one item", () => {
expect(toXml(new MathBrackets({ items: [[new MathRun("x")]] }))).toBe(
`<m:d><m:dPr><m:begChr m:val="("/><m:endChr m:val=")"/></m:dPr>${x}</m:d>`,
);
});
it("writes m:grow only to stop the brackets growing", () => {
expect(toXml(new MathBrackets({ grow: false, children: [new MathRun("x")] }))).toContain(
'<m:endChr m:val=")"/><m:grow m:val="0"/></m:dPr>',
);
expect(toXml(new MathBrackets({ grow: true, children: [new MathRun("x")] }))).not.toContain("m:grow");
});
it("writes a zero-width space in an empty argument, which LibreOffice can't read otherwise", () => {
expect(toXml(new MathBrackets({ children: [] }))).toContain('<m:e><m:r><m:t xml:space="preserve">\u200B</m:t></m:r></m:e>');
expect(toXml(new MathBrackets({ items: [[new MathRun("a")], []] }))).toContain(
'<m:e><m:r><m:t>a</m:t></m:r></m:e><m:e><m:r><m:t xml:space="preserve">\u200B</m:t></m:r></m:e>',
);
});
it("counts characters as code points, so one outside the BMP is one character", () => {
expect(toXml(new MathBrackets({ open: "𝒜", close: "𝒜", separator: "𝒜", items: [[], []] }))).toContain('<m:begChr m:val="𝒜"/>');
});
it("throws for a bracket or separator of more than one character", () => {
expect(() => new MathBrackets({ open: "((", children: [] })).toThrow(
'MathBrackets: open is "((", which is more than one character. Give one character, or "" for none',
);
expect(() => new MathBrackets({ close: "||", children: [] })).toThrow('MathBrackets: close is "||"');
expect(() => new MathBrackets({ separator: ", ", items: [[], []] })).toThrow('MathBrackets: separator is ", "');
});
it("throws for no items", () => {
expect(() => new MathBrackets({ items: [] })).toThrow("MathBrackets: items is empty. Give at least one item, or use children");
});
it("throws for math inside math, a paragraph or a run of document text, naming where it is", () => {
const math = new Math({ children: [new MathRun("x")] });
expect(() => new MathBrackets({ children: [math] })).toThrow(
"MathBrackets: children holds a Math. Word won't open math inside math, so give the Math's children instead",
);
expect(() => new MathBrackets({ items: [[new MathRun("a")], [new MathRun("b"), math]] })).toThrow(
"MathBrackets: item 2 holds a Math",
);
expect(() => new MathBrackets({ children: [new Paragraph("x")] })).toThrow(
"MathBrackets: children holds a Paragraph. Math goes in a paragraph, not a paragraph in math",
);
expect(() => new MathBrackets({ children: [new TextRun("x")] })).toThrow(
"MathBrackets: children holds a TextRun or another run of document text, which can't go in math. Use a MathRun",
);
});
it("goes inside other math, and holds it", () => {
const fraction = new MathFraction({
numerator: [new MathBrackets({ open: "|", close: "|", children: [new MathRun("x")] })],
denominator: [new MathRun("2")],
});
expect(xml(new Formatter().format(fraction))).toContain('<m:num><m:d><m:dPr><m:begChr m:val="|"/>');
expect(toXml(new MathBrackets({ children: [new MathMatrix({ rows: [[[new MathRun("1")]]] })] }))).toContain("<m:e><m:m>");
});
});
+77
View File
@@ -0,0 +1,77 @@
/**
* Brackets of any characters around math, such as |x|, ‖v‖, ⟨a|b⟩ or a brace on one side.
*
* @module
*/
import { BuilderElement, type MathComponent } from "docx";
import { bracketsElement, checkArgument, checkCharacter, createArgument } from "./math-elements";
/**
* Options for {@link MathBrackets}: the brackets, and what goes between them.
*/
export type MathBracketsOptions = {
/**
* The opening bracket: one character, such as `"|"` or `"⟨"`, or `""` for none (`m:begChr`).
* @default "("
*/
readonly open?: string;
/**
* The closing bracket: one character, or `""` for none (`m:endChr`).
* @default ")"
*/
readonly close?: string;
/**
* The character between `items`, such as `","` (`m:sepChr`).
* @default "|"
*/
readonly separator?: string;
/**
* Whether the brackets grow to the height of what they hold (`m:grow`). LibreOffice and Pages always grow them.
* @default true
*/
readonly grow?: boolean;
} & (
| {
/** What goes between the brackets */
readonly children: readonly MathComponent[];
readonly items?: never;
}
| {
/** Several things between the brackets, with `separator` between them, such as ⟨a|b⟩ */
readonly items: readonly (readonly MathComponent[])[];
readonly children?: never;
}
);
/**
* Brackets of any characters around math (`m:d`), such as |x|, ‖v‖, ⟨a|b⟩ or a brace on one side only. They grow
* with what they hold.
*
* `MathRoundBrackets`, `MathSquareBrackets`, `MathCurlyBrackets` and `MathAngledBrackets` are fixed pairs of these.
*
* @example
* ```typescript
* new MathBrackets({ open: "|", close: "|", children: [new MathRun("x")] });
* new MathBrackets({ open: "⟨", close: "⟩", items: [[new MathRun("a")], [new MathRun("b")]] });
* new MathBrackets({ open: "{", close: "", children: [new MathRun("x")] });
* ```
*/
export class MathBrackets extends BuilderElement {
public constructor(options: MathBracketsOptions) {
const { open = "(", close = ")", separator, grow } = options;
const items = options.items ?? [options.children];
checkCharacter("MathBrackets", "open", open);
checkCharacter("MathBrackets", "close", close);
if (separator !== undefined) {
checkCharacter("MathBrackets", "separator", separator);
}
if (items.length === 0) {
throw new Error("MathBrackets: items is empty. Give at least one item, or use children");
}
items.forEach((item, index) => checkArgument("MathBrackets", options.items ? `item ${index + 1}` : "children", item));
super(bracketsElement({ open, close, separator, grow }, items.map(createArgument)));
}
}
+90
View File
@@ -0,0 +1,90 @@
import { describe, expect, it } from "vitest";
import xml from "xml";
import { Formatter } from "@export/formatter";
import { Math, MathRun } from "docx";
import { type MathCase, MathCases } from "./math-cases";
import { MathMatrix } from "./math-matrix";
const toXml = (component: MathCases): string => xml(new Formatter().format(component));
const e = (text: string): string => `<m:e><m:r><m:t>${text}</m:t></m:r></m:e>`;
const EMPTY = '<m:e><m:r><m:t xml:space="preserve">\u200B</m:t></m:r></m:e>';
describe("MathCases", () => {
it("writes a two-column matrix, lined up on the left, in a brace with no closing bracket", () => {
expect(
toXml(
new MathCases({
cases: [
{ value: [new MathRun("1,")], condition: [new MathRun("x>0")] },
{ value: [new MathRun("0,")], condition: [new MathRun("x=0")] },
],
}),
),
).toBe(
'<m:d><m:dPr><m:begChr m:val="{"/><m:endChr m:val=""/></m:dPr><m:e><m:m>' +
'<m:mPr><m:baseJc m:val="center"/><m:plcHide m:val="1"/>' +
'<m:mcs><m:mc><m:mcPr><m:count m:val="2"/><m:mcJc m:val="left"/></m:mcPr></m:mc></m:mcs></m:mPr>' +
`<m:mr>${e("1,")}${e("x&gt;0")}</m:mr><m:mr>${e("0,")}${e("x=0")}</m:mr></m:m></m:e></m:d>`,
);
});
it("keeps the spaces of normal text in a condition", () => {
expect(
toXml(
new MathCases({
cases: [
{ value: [new MathRun("1,")], condition: [new MathRun({ text: "if ", normalText: true }), new MathRun("x>0")] },
],
}),
),
).toContain(
'<m:e><m:r><m:rPr><m:nor m:val="1"/></m:rPr><m:t xml:space="preserve">if </m:t></m:r><m:r><m:t>x&gt;0</m:t></m:r></m:e>',
);
});
it("writes one column when no case has a condition", () => {
const written = toXml(new MathCases({ cases: [{ value: [new MathRun("a")] }, { value: [new MathRun("b")] }] }));
expect(written).toContain('<m:count m:val="1"/>');
expect(written).toContain(`<m:mr>${e("a")}</m:mr><m:mr>${e("b")}</m:mr>`);
});
it("gives a case with no condition an empty one when others have one", () => {
expect(
toXml(new MathCases({ cases: [{ value: [new MathRun("a")], condition: [new MathRun("c")] }, { value: [new MathRun("b")] }] })),
).toContain(`<m:mr>${e("b")}${EMPTY}</m:mr>`);
});
it("writes an empty value or condition with a zero-width space", () => {
expect(toXml(new MathCases({ cases: [{ value: [], condition: [] }] }))).toContain(`<m:mr>${EMPTY}${EMPTY}</m:mr>`);
});
it("takes as many cases as Word allows in a matrix, and throws for more", () => {
const cases = (count: number): readonly MathCase[] =>
Array.from({ length: count }, (_, index) => ({ value: [new MathRun(`${index}`)] }));
expect(toXml(new MathCases({ cases: cases(256) })).match(/<m:mr>/g)).toHaveLength(256);
expect(() => new MathCases({ cases: cases(257) })).toThrow("MathCases: there are 257 cases, but Word allows at most 256");
});
it("throws for no cases", () => {
expect(() => new MathCases({ cases: [] })).toThrow("MathCases: there are no cases. Give at least one");
});
it("throws for math inside math, naming the case and its part", () => {
const math = new Math({ children: [] });
expect(() => new MathCases({ cases: [{ value: [new MathRun("a")] }, { value: [math] }] })).toThrow(
"MathCases: case 2's value holds a Math",
);
expect(() => new MathCases({ cases: [{ value: [new MathRun("a")], condition: [math] }] })).toThrow(
"MathCases: case 1's condition holds a Math",
);
});
it("holds other math", () => {
expect(
toXml(new MathCases({ cases: [{ value: [new MathMatrix({ brackets: "round", rows: [[[new MathRun("1")]]] })] }] })),
).toContain('<m:mr><m:e><m:d><m:dPr><m:begChr m:val="("/>');
});
});
+63
View File
@@ -0,0 +1,63 @@
/**
* Cases, such as LaTeX's `cases`: values, each with its condition, in a brace.
*
* @module
*/
import { BuilderElement, type MathComponent, createMathBase } from "docx";
import { bracketsElement } from "./math-elements";
import { matrixElement } from "./math-matrix";
/**
* One case: a value, and the condition it holds under.
*/
export type MathCase = {
/** The value, such as `−x,` */
readonly value: readonly MathComponent[];
/**
* The condition, such as `if x < 0`. Words such as "if" and "otherwise" read best as normal text:
* `new MathRun({ text: "if ", normalText: true })`.
*/
readonly condition?: readonly MathComponent[];
};
/**
* Options for {@link MathCases}.
*/
export type MathCasesOptions = {
/** The cases, one to a line. Word allows at most 256 */
readonly cases: readonly MathCase[];
};
/**
* Cases, as LaTeX's `cases`: values, each with its condition, one to a line, in a brace on the left. The values and
* the conditions each line up on the left.
*
* They are written as pandoc writes them: a matrix of two columns in a brace with no closing bracket. Word's own
* equation editor lines the conditions up with an `&` instead, which LibreOffice draws.
*
* @example
* ```typescript
* new MathCases({
* cases: [
* { value: [new MathRun("x,")], condition: [new MathRun({ text: "if ", normalText: true }), new MathRun("x≥0")] },
* { value: [new MathRun("−x,")], condition: [new MathRun({ text: "otherwise", normalText: true })] },
* ],
* });
* ```
*/
export class MathCases extends BuilderElement {
public constructor({ cases }: MathCasesOptions) {
const conditions = cases.some((one) => one.condition !== undefined);
const matrix = matrixElement(
"MathCases",
{
rows: cases.map(({ value, condition }) => (conditions ? [value, condition ?? []] : [value])),
columnAlignment: "left",
},
{ rowsName: "cases", cellName: (row, column) => `case ${row + 1}'s ${column === 0 ? "value" : "condition"}` },
);
super(bracketsElement({ open: "{", close: "" }, [createMathBase({ children: [new BuilderElement(matrix)] })]));
}
}
+100
View File
@@ -0,0 +1,100 @@
/**
* What docx/math's components share: the checks on their arguments, and the elements they are made of. Nothing here is
* exported from docx/math.
*
* @module
*/
import { BuilderElement, type MathComponent, MathRun, Math as OfficeMath, Paragraph, Run, type XmlComponent, createMathBase } from "docx";
/** The options of a {@link BuilderElement}, to build an element before its class calls `super` */
export type ElementOptions = {
readonly name: string;
readonly children: readonly XmlComponent[];
};
// Word's limits ([MS-OE376] 7.1.2.34 and 7.1.2.60, [MS-OI29500] 22.1.2.69). The schema has none
export const MAX_MATRIX_ROWS = 256;
export const MAX_MATRIX_COLUMNS = 64;
export const MAX_EQUATION_ARRAY_ROWS = 64;
/**
* A count of things, such as "1 column" or "3 columns".
*/
export const plural = (count: number, thing: string): string => `${count} ${thing}${count === 1 ? "" : "s"}`;
/**
* An element whose value is its `m:val`, such as `<m:begChr m:val="("/>`.
*/
export const createValueElement = (name: string, value: string | number): XmlComponent =>
new BuilderElement<{ readonly value: string | number }>({ name, attributes: { value: { key: "m:val", value } } });
/**
* Throws for what can't go in an argument: a `Math`, which Word won't open inside math, and a paragraph or a run of
* document text, which the schema doesn't allow there. Only an argument's own children can be checked.
*/
export const checkArgument = (owner: string, where: string, children: readonly MathComponent[]): void => {
for (const child of children) {
if (child instanceof OfficeMath) {
throw new Error(`${owner}: ${where} holds a Math. Word won't open math inside math, so give the Math's children instead`);
}
if (child instanceof Paragraph) {
throw new Error(`${owner}: ${where} holds a Paragraph. Math goes in a paragraph, not a paragraph in math`);
}
if (child instanceof Run) {
throw new Error(`${owner}: ${where} holds a TextRun or another run of document text, which can't go in math. Use a MathRun`);
}
}
};
/**
* Throws unless a bracket or separator is one character, or none. Characters are counted as code points, so `𝒜` is one.
*/
export const checkCharacter = (owner: string, option: string, value: string): void => {
if ([...value].length > 1) {
throw new Error(`${owner}: ${option} is "${value}", which is more than one character. Give one character, or "" for none`);
}
};
/**
* Throws unless a value is one of those allowed, for code that isn't type checked.
*/
export const checkOneOf = (owner: string, option: string, value: string, allowed: readonly string[]): void => {
if (!allowed.includes(value)) {
throw new Error(`${owner}: ${option} is "${value}", which isn't one of ${allowed.map((one) => `"${one}"`).join(", ")}`);
}
};
/**
* An argument (`m:e`). An empty one gets a zero-width space, as LibreOffice can't read an equation with an empty
* argument, and draws "¿" in its place.
*/
export const createArgument = (children: readonly MathComponent[]): XmlComponent =>
createMathBase({ children: children.length === 0 ? [new MathRun("​")] : children });
/**
* Brackets (`m:d`) around arguments, with a separator between them. They grow with their content unless `grow` is
* false, as Word's do when `m:grow` isn't written.
*/
export const bracketsElement = (
{
open,
close,
separator,
grow,
}: { readonly open: string; readonly close: string; readonly separator?: string; readonly grow?: boolean },
args: readonly XmlComponent[],
): ElementOptions => ({
name: "m:d",
children: [
new BuilderElement({
name: "m:dPr",
children: [
createValueElement("m:begChr", open),
...(separator === undefined ? [] : [createValueElement("m:sepChr", separator)]),
createValueElement("m:endChr", close),
...(grow === false ? [createValueElement("m:grow", 0)] : []),
],
}),
...args,
],
});
+119
View File
@@ -0,0 +1,119 @@
import { describe, expect, it } from "vitest";
import xml from "xml";
import { Formatter } from "@export/formatter";
import { Math, MathRun, MathSuperScript, TextRun } from "docx";
import { MathCases } from "./math-cases";
import { MathEquationArray, type MathEquationArrayOptions, type MathEquationArrayRow } from "./math-equation-array";
const toXml = (component: MathEquationArray | MathCases): string => xml(new Formatter().format(component));
const r = (text: string): string => `<m:r><m:t>${text}</m:t></m:r>`;
const AMP = r("&amp;");
describe("MathEquationArray", () => {
it("writes each row as an argument, with an & between its parts and a # before its number", () => {
expect(
toXml(
new MathEquationArray({
rows: [
{ parts: [[new MathRun("y")], [new MathRun("=mx+b")]], equationNumber: "(1)" },
{ parts: [[new MathRun("y′")], [new MathRun("=m")]], equationNumber: "(2)" },
],
}),
),
).toBe(
`<m:eqArr><m:e>${r("y")}${AMP}${r("=mx+b")}${r("#")}${r("(1)")}</m:e>` +
`<m:e>${r("y′")}${AMP}${r("=m")}${r("#")}${r("(2)")}</m:e></m:eqArr>`,
);
});
it("writes a row with one part and no number as it is", () => {
expect(toXml(new MathEquationArray({ rows: [{ parts: [[new MathRun("a"), new MathRun("b")]] }] }))).toBe(
`<m:eqArr><m:e>${r("a")}${r("b")}</m:e></m:eqArr>`,
);
});
it("starts a row that goes on from the row before with an &, from an empty first part", () => {
const square = new MathSuperScript({ children: [new MathRun("a")], superScript: [new MathRun("2")] });
expect(toXml(new MathEquationArray({ rows: [{ parts: [[], [new MathRun("="), square]] }] }))).toMatch(
/^<m:eqArr><m:e><m:r><m:t>&amp;<\/m:t><\/m:r><m:r><m:t>=<\/m:t><\/m:r><m:sSup>/,
);
});
it("writes every & for rows lined up at several points, as align's columns", () => {
const row: MathEquationArrayRow = { parts: [[new MathRun("a")], [new MathRun("=b")], [new MathRun("c")], [new MathRun("=d")]] };
expect(toXml(new MathEquationArray({ rows: [row] }))).toBe(
`<m:eqArr><m:e>${r("a")}${AMP}${r("=b")}${AMP}${r("c")}${AMP}${r("=d")}</m:e></m:eqArr>`,
);
});
it("writes an equation number on a row with one part", () => {
expect(toXml(new MathEquationArray({ rows: [{ parts: [[new MathRun("E=mc²")]], equationNumber: "(30)" }] }))).toBe(
`<m:eqArr><m:e>${r("E=mc²")}${r("#")}${r("(30)")}</m:e></m:eqArr>`,
);
});
it("writes no # for an empty equation number", () => {
expect(toXml(new MathEquationArray({ rows: [{ parts: [[new MathRun("a")]], equationNumber: "" }] }))).toBe(
`<m:eqArr><m:e>${r("a")}</m:e></m:eqArr>`,
);
});
it("writes an empty row with a zero-width space, which LibreOffice needs", () => {
expect(toXml(new MathEquationArray({ rows: [{ parts: [[]] }, { parts: [[], []] }] }))).toBe(
`<m:eqArr><m:e><m:r><m:t xml:space="preserve">\u200B</m:t></m:r></m:e><m:e>${AMP}</m:e></m:eqArr>`,
);
});
it("writes where the array sits on its line only when it is given", () => {
const rows: MathEquationArrayOptions["rows"] = [{ parts: [[new MathRun("a")]] }];
expect(toXml(new MathEquationArray({ rows, verticalAlignment: "top" }))).toMatch(
/^<m:eqArr><m:eqArrPr><m:baseJc m:val="top"\/><\/m:eqArrPr><m:e>/,
);
expect(toXml(new MathEquationArray({ rows, verticalAlignment: "center" }))).toContain('<m:baseJc m:val="center"/>');
expect(toXml(new MathEquationArray({ rows }))).not.toContain("m:eqArrPr");
});
it("takes as many rows as Word allows, and throws for more", () => {
const rows = (count: number): MathEquationArrayOptions["rows"] =>
Array.from({ length: count }, (_, index) => ({ parts: [[new MathRun(`${index}`)]] }));
expect(toXml(new MathEquationArray({ rows: rows(64) })).match(/<m:e>/g)).toHaveLength(64);
expect(() => new MathEquationArray({ rows: rows(65) })).toThrow("MathEquationArray: there are 65 rows, but Word allows at most 64");
});
it("throws for no rows, or a row with no parts", () => {
expect(() => new MathEquationArray({ rows: [] })).toThrow("MathEquationArray: there are no rows. Give at least one");
expect(() => new MathEquationArray({ rows: [{ parts: [[new MathRun("a")]] }, { parts: [] }] })).toThrow(
"MathEquationArray: row 2 has no parts. Give at least one, which can be empty",
);
});
it("throws for a vertical alignment it doesn't know", () => {
expect(
() =>
new MathEquationArray({
rows: [{ parts: [[]] }],
verticalAlignment: "middle" as MathEquationArrayOptions["verticalAlignment"],
}),
).toThrow('MathEquationArray: verticalAlignment is "middle", which isn\'t one of "top", "center", "bottom"');
});
it("throws for math inside math, or document text, naming the row and part", () => {
expect(() => new MathEquationArray({ rows: [{ parts: [[new MathRun("a")], [new Math({ children: [] })]] }] })).toThrow(
"MathEquationArray: row 1, part 2 holds a Math",
);
expect(() => new MathEquationArray({ rows: [{ parts: [[]] }, { parts: [[new TextRun("a")]] }] })).toThrow(
"MathEquationArray: row 2, part 1 holds a TextRun",
);
});
it("goes inside cases, and holds them", () => {
const array = new MathEquationArray({ rows: [{ parts: [[new MathRun("a")], [new MathRun("=b")]] }] });
expect(toXml(new MathCases({ cases: [{ value: [array] }] }))).toContain("<m:mr><m:e><m:eqArr>");
expect(
toXml(new MathEquationArray({ rows: [{ parts: [[new MathCases({ cases: [{ value: [new MathRun("x")] }] })]] }] })),
).toContain('<m:eqArr><m:e><m:d><m:dPr><m:begChr m:val="{"/>');
});
});
+93
View File
@@ -0,0 +1,93 @@
/**
* Equation arrays: rows of math lined up at points, such as LaTeX's `align` and `aligned`, with equation numbers.
*
* @module
*/
import { BuilderElement, type MathComponent, MathRun } from "docx";
import { MAX_EQUATION_ARRAY_ROWS, checkArgument, checkOneOf, createArgument, createValueElement } from "./math-elements";
import { type MathVerticalAlignment, VERTICAL_ALIGNMENTS } from "./math-matrix";
/**
* One row of an equation array.
*/
export type MathEquationArrayRow = {
/**
* The row's parts. Word lines up the points between them with the same points in the other rows, as LaTeX's `&`
* does: the first, third and every other point line up (such as at an `=`), and the space goes at the others, as
* between the columns of `align`. A part can be empty, such as the first part of a row that goes on from the row
* before.
*/
readonly parts: readonly (readonly MathComponent[])[];
/**
* The row's equation number, such as `"(1)"`, which Word 2016 and later put at the right margin. Word 2013 and
* older, LibreOffice and Pages show it after a `#`.
*/
readonly equationNumber?: string;
};
/**
* Options for {@link MathEquationArray}.
*/
export type MathEquationArrayOptions = {
/** The rows, one to a line. Word allows at most 64 */
readonly rows: readonly MathEquationArrayRow[];
/**
* Where the array sits on its line.
* @default "center"
*/
readonly verticalAlignment?: MathVerticalAlignment;
};
/**
* An equation array (`m:eqArr`): rows of math, one to a line, lined up at the points between their parts, as LaTeX's
* `align` and `aligned`, with an equation number at the end of any row.
*
* Word marks the points with an `&`, and the number with a `#`, in the text. So an `&` or a `#` in a `MathRun` in the
* array is taken as one too. LibreOffice shows the `&` and `#`, and centres the rows; Pages lines them up, but shows
* the `#`.
*
* @example
* ```typescript
* new MathEquationArray({
* rows: [
* { parts: [[new MathRun("y")], [new MathRun("=mx+b")]], equationNumber: "(1)" },
* { parts: [[new MathRun("y′")], [new MathRun("=m")]], equationNumber: "(2)" },
* ],
* });
* ```
*/
export class MathEquationArray extends BuilderElement {
public constructor({ rows, verticalAlignment }: MathEquationArrayOptions) {
if (rows.length === 0) {
throw new Error("MathEquationArray: there are no rows. Give at least one");
}
if (rows.length > MAX_EQUATION_ARRAY_ROWS) {
throw new Error(`MathEquationArray: there are ${rows.length} rows, but Word allows at most ${MAX_EQUATION_ARRAY_ROWS}`);
}
if (verticalAlignment !== undefined) {
checkOneOf("MathEquationArray", "verticalAlignment", verticalAlignment, VERTICAL_ALIGNMENTS);
}
rows.forEach(({ parts }, row) => {
if (parts.length === 0) {
throw new Error(`MathEquationArray: row ${row + 1} has no parts. Give at least one, which can be empty`);
}
parts.forEach((part, index) => checkArgument("MathEquationArray", `row ${row + 1}, part ${index + 1}`, part));
});
super({
name: "m:eqArr",
children: [
...(verticalAlignment === undefined
? []
: [new BuilderElement({ name: "m:eqArrPr", children: [createValueElement("m:baseJc", verticalAlignment)] })]),
...rows.map(({ parts, equationNumber }) =>
createArgument([
...parts.flatMap((part, index) => (index === 0 ? part : [new MathRun("&"), ...part])),
...(equationNumber ? [new MathRun("#"), new MathRun(equationNumber)] : []),
]),
),
],
});
}
}
+147
View File
@@ -0,0 +1,147 @@
import { describe, expect, it } from "vitest";
import xml from "xml";
import { Formatter } from "@export/formatter";
import { Math, type MathComponent, MathFraction, MathRun } from "docx";
import { type MathColumnAlignment, MathMatrix, type MathMatrixBrackets, type MathMatrixOptions } from "./math-matrix";
const toXml = (component: MathMatrix | MathFraction): string => xml(new Formatter().format(component));
const cell = (text: string): readonly MathComponent[] => [new MathRun(text)];
const e = (text: string): string => `<m:e><m:r><m:t>${text}</m:t></m:r></m:e>`;
const EMPTY = '<m:e><m:r><m:t xml:space="preserve">\u200B</m:t></m:r></m:e>';
const grid = (rows: number, columns: number): MathMatrixOptions["rows"] =>
Array.from({ length: rows }, (_, row) => Array.from({ length: columns }, (__, column) => cell(`${row},${column}`)));
describe("MathMatrix", () => {
it("writes rows of cells, with its properties: centred, placeholders hidden, and one alignment for its columns", () => {
expect(
toXml(
new MathMatrix({
rows: [
[cell("1"), cell("2")],
[cell("3"), cell("4")],
],
}),
),
).toBe(
'<m:m><m:mPr><m:baseJc m:val="center"/><m:plcHide m:val="1"/>' +
'<m:mcs><m:mc><m:mcPr><m:count m:val="2"/><m:mcJc m:val="center"/></m:mcPr></m:mc></m:mcs></m:mPr>' +
`<m:mr>${e("1")}${e("2")}</m:mr><m:mr>${e("3")}${e("4")}</m:mr></m:m>`,
);
});
it("writes a 1×1 matrix", () => {
expect(toXml(new MathMatrix({ rows: [[cell("x")]] }))).toContain(`<m:count m:val="1"/>`);
expect(toXml(new MathMatrix({ rows: [[cell("x")]] }))).toContain(`<m:mr>${e("x")}</m:mr></m:m>`);
});
const brackets: readonly (readonly [MathMatrixBrackets, string, string])[] = [
["round", "(", ")"],
["square", "[", "]"],
["curly", "{", "}"],
["angled", "⟨", "⟩"],
["verticalBars", "|", "|"],
["doubleVerticalBars", "‖", "‖"],
];
it.each(brackets)("writes %s brackets around the matrix as UnicodeMath's characters", (type, open, close) => {
const written = toXml(new MathMatrix({ brackets: type, rows: [[cell("1")]] }));
expect(written).toMatch(new RegExp(`^<m:d><m:dPr><m:begChr m:val="\\${open}"/><m:endChr m:val="\\${close}"/></m:dPr><m:e><m:m>`));
expect(written).toMatch(/<\/m:m><\/m:e><\/m:d>$/);
});
it("writes no brackets for none", () => {
expect(toXml(new MathMatrix({ brackets: "none", rows: [[cell("1")]] }))).toMatch(/^<m:m>/);
});
it("gives shorter rows empty cells, each with a zero-width space, which LibreOffice needs", () => {
const written = toXml(new MathMatrix({ rows: [[cell("1"), cell("2"), cell("3")], [cell("4")], []] }));
expect(written).toContain(`<m:mr>${e("4")}${EMPTY}${EMPTY}</m:mr><m:mr>${EMPTY}${EMPTY}${EMPTY}</m:mr>`);
expect(written).toContain('<m:count m:val="3"/>');
});
it("writes an empty cell given as an empty list with a zero-width space", () => {
expect(toXml(new MathMatrix({ rows: [[cell("1"), []]] }))).toContain(`<m:mr>${e("1")}${EMPTY}</m:mr>`);
});
it("groups columns side by side with the same alignment", () => {
const written = toXml(new MathMatrix({ rows: [grid(1, 5)[0]], columnAlignment: ["left", "left", "right", "center", "center"] }));
expect(written).toContain(
'<m:mcs><m:mc><m:mcPr><m:count m:val="2"/><m:mcJc m:val="left"/></m:mcPr></m:mc>' +
'<m:mc><m:mcPr><m:count m:val="1"/><m:mcJc m:val="right"/></m:mcPr></m:mc>' +
'<m:mc><m:mcPr><m:count m:val="2"/><m:mcJc m:val="center"/></m:mcPr></m:mc></m:mcs>',
);
});
it("gives every column one alignment", () => {
expect(toXml(new MathMatrix({ rows: grid(2, 3), columnAlignment: "right" }))).toContain(
'<m:mcs><m:mc><m:mcPr><m:count m:val="3"/><m:mcJc m:val="right"/></m:mcPr></m:mc></m:mcs>',
);
});
it("alternates alignments column by column", () => {
const alignments: readonly MathColumnAlignment[] = ["right", "left", "right", "left"];
expect(toXml(new MathMatrix({ rows: grid(1, 4), columnAlignment: alignments })).match(/<m:mc>/g)).toHaveLength(4);
});
it("sits on its line as verticalAlignment says", () => {
expect(toXml(new MathMatrix({ rows: grid(1, 1), verticalAlignment: "top" }))).toContain('<m:baseJc m:val="top"/>');
expect(toXml(new MathMatrix({ rows: grid(1, 1), verticalAlignment: "bottom" }))).toContain('<m:baseJc m:val="bottom"/>');
});
it("writes Word's largest matrix: 256 rows of 64 cells", () => {
const written = toXml(new MathMatrix({ rows: grid(256, 64) }));
expect(written.match(/<m:mr>/g)).toHaveLength(256);
expect(written.match(/<m:e>/g)).toHaveLength(256 * 64);
expect(written).toContain('<m:count m:val="64"/>');
});
it("throws for more rows or cells than Word allows", () => {
expect(() => new MathMatrix({ rows: grid(257, 1) })).toThrow("MathMatrix: there are 257 rows, but Word allows at most 256");
expect(() => new MathMatrix({ rows: [[], grid(1, 65)[0]] })).toThrow("MathMatrix: a row has 65 cells, but Word allows at most 64");
});
it("throws for no rows, or no cells", () => {
expect(() => new MathMatrix({ rows: [] })).toThrow("MathMatrix: there are no rows. Give at least one");
expect(() => new MathMatrix({ rows: [[], []] })).toThrow("MathMatrix: every row is empty. Give at least one cell");
});
it("throws unless there is one column alignment for each column", () => {
expect(() => new MathMatrix({ rows: grid(2, 3), columnAlignment: ["left", "right"] })).toThrow(
"MathMatrix: columnAlignment has 2 alignments, but the rows have 3 columns. Give one for each",
);
expect(() => new MathMatrix({ rows: grid(2, 1), columnAlignment: ["left", "right"] })).toThrow(
"MathMatrix: columnAlignment has 2 alignments, but the rows have 1 column. Give one for each",
);
expect(() => new MathMatrix({ rows: grid(1, 1), columnAlignment: [] })).toThrow(
"columnAlignment has 0 alignments, but the rows have 1 column",
);
});
it("throws for values it doesn't know, from code that isn't type checked", () => {
expect(() => new MathMatrix({ rows: grid(1, 1), brackets: "pointy" as MathMatrixBrackets })).toThrow(
'MathMatrix: brackets is "pointy", which isn\'t one of "none", "round", "square", "curly", "angled", "verticalBars", "doubleVerticalBars"',
);
expect(() => new MathMatrix({ rows: grid(1, 2), columnAlignment: ["left", "middle" as MathColumnAlignment] })).toThrow(
'MathMatrix: columnAlignment is "middle", which isn\'t one of "left", "center", "right"',
);
expect(() => new MathMatrix({ rows: grid(1, 1), verticalAlignment: "baseline" as MathMatrixOptions["verticalAlignment"] })).toThrow(
'MathMatrix: verticalAlignment is "baseline", which isn\'t one of "top", "center", "bottom"',
);
});
it("throws for math inside math in a cell, naming the cell", () => {
expect(() => new MathMatrix({ rows: [[cell("1")], [cell("2"), [new Math({ children: [] })]]] })).toThrow(
"MathMatrix: row 2, cell 2 holds a Math",
);
});
it("holds other math, matrices included, and goes inside it", () => {
const inner = new MathMatrix({ brackets: "square", rows: grid(2, 2) });
expect(toXml(new MathMatrix({ brackets: "round", rows: [[[inner], cell("x")]] }))).toContain(
'<m:mr><m:e><m:d><m:dPr><m:begChr m:val="["/>',
);
expect(toXml(new MathFraction({ numerator: [inner], denominator: cell("2") }))).toContain("<m:num><m:d>");
});
});
+190
View File
@@ -0,0 +1,190 @@
/**
* Matrices, such as LaTeX's `pmatrix`, `bmatrix`, `vmatrix` and `Vmatrix`.
*
* @module
*/
import { BuilderElement, type MathComponent, createMathBase } from "docx";
import {
type ElementOptions,
MAX_MATRIX_COLUMNS,
MAX_MATRIX_ROWS,
bracketsElement,
checkArgument,
checkOneOf,
createArgument,
createValueElement,
plural,
} from "./math-elements";
/**
* The brackets around a matrix:
*
* - `"none"`: none, as LaTeX's `matrix`;
* - `"round"`: ( ), as `pmatrix`;
* - `"square"`: [ ], as `bmatrix`;
* - `"curly"`: { }, as `Bmatrix`;
* - `"angled"`: ⟨ ⟩;
* - `"verticalBars"`: | |, as `vmatrix`, for determinants;
* - `"doubleVerticalBars"`: ‖ ‖, as `Vmatrix`, for norms.
*/
export type MathMatrixBrackets = "none" | "round" | "square" | "curly" | "angled" | "verticalBars" | "doubleVerticalBars";
/** Where the cells of a column go across it (`m:mcJc`). LibreOffice and Pages centre them all */
export type MathColumnAlignment = "left" | "center" | "right";
/** Where a matrix or equation array sits on its line (`m:baseJc`): its top, its middle or its bottom on the line */
export type MathVerticalAlignment = "top" | "center" | "bottom";
/**
* Options for {@link MathMatrix}.
*/
export type MathMatrixOptions = {
/**
* The rows, each a list of cells, and each cell the math in it (`m:mr`, `m:e`). A row shorter than the longest gets
* empty cells at its end. Word allows at most 256 rows and 64 cells in a row.
*/
readonly rows: readonly (readonly (readonly MathComponent[])[])[];
/**
* The brackets around the matrix.
* @default "none"
*/
readonly brackets?: MathMatrixBrackets;
/**
* Where the cells go across their columns: one alignment for every column, or one for each column.
* @default "center"
*/
readonly columnAlignment?: MathColumnAlignment | readonly MathColumnAlignment[];
/**
* Where the matrix sits on its line.
* @default "center"
*/
readonly verticalAlignment?: MathVerticalAlignment;
};
// The characters UnicodeMath gives \langle and \norm, which LibreOffice and Pages draw, rather than U+2329 and U+2225
const BRACKETS: Readonly<Record<Exclude<MathMatrixBrackets, "none">, readonly [string, string]>> = {
round: ["(", ")"],
square: ["[", "]"],
curly: ["{", "}"],
angled: ["⟨", "⟩"],
verticalBars: ["|", "|"],
doubleVerticalBars: ["‖", "‖"],
};
const COLUMN_ALIGNMENTS: readonly MathColumnAlignment[] = ["left", "center", "right"];
export const VERTICAL_ALIGNMENTS: readonly MathVerticalAlignment[] = ["top", "center", "bottom"];
/**
* A matrix (`m:m`), without brackets. Its errors name `owner`, its rows as `rowsName`, and each cell as `cellName` does.
*/
export const matrixElement = (
owner: string,
{ rows, columnAlignment = "center", verticalAlignment = "center" }: Omit<MathMatrixOptions, "brackets">,
{
rowsName = "rows",
cellName = (row, column) => `row ${row + 1}, cell ${column + 1}`,
}: { readonly rowsName?: string; readonly cellName?: (row: number, column: number) => string } = {},
): ElementOptions => {
if (rows.length === 0) {
throw new Error(`${owner}: there are no ${rowsName}. Give at least one`);
}
if (rows.length > MAX_MATRIX_ROWS) {
throw new Error(`${owner}: there are ${rows.length} ${rowsName}, but Word allows at most ${MAX_MATRIX_ROWS}`);
}
const columns = Math.max(...rows.map((row) => row.length));
if (columns === 0) {
throw new Error(`${owner}: every row is empty. Give at least one cell`);
}
if (columns > MAX_MATRIX_COLUMNS) {
throw new Error(`${owner}: a row has ${columns} cells, but Word allows at most ${MAX_MATRIX_COLUMNS}`);
}
const alignments = typeof columnAlignment === "string" ? Array.from({ length: columns }, () => columnAlignment) : columnAlignment;
if (alignments.length !== columns) {
throw new Error(
`${owner}: columnAlignment has ${plural(alignments.length, "alignment")}, but the rows have ${plural(columns, "column")}. Give one for each`,
);
}
alignments.forEach((alignment) => checkOneOf(owner, "columnAlignment", alignment, COLUMN_ALIGNMENTS));
checkOneOf(owner, "verticalAlignment", verticalAlignment, VERTICAL_ALIGNMENTS);
rows.forEach((row, rowIndex) => row.forEach((cell, column) => checkArgument(owner, cellName(rowIndex, column), cell)));
// Columns side by side with the same alignment share an m:mc, with their count
const groups = alignments.reduce<readonly { readonly alignment: MathColumnAlignment; readonly count: number }[]>(
(all, alignment) =>
all.length > 0 && all[all.length - 1].alignment === alignment
? [...all.slice(0, -1), { alignment, count: all[all.length - 1].count + 1 }]
: [...all, { alignment, count: 1 }],
[],
);
return {
name: "m:m",
children: [
new BuilderElement({
name: "m:mPr",
children: [
createValueElement("m:baseJc", verticalAlignment),
// Word shows a dotted box in an empty cell unless placeholders are hidden
createValueElement("m:plcHide", 1),
new BuilderElement({
name: "m:mcs",
children: groups.map(
({ alignment, count }) =>
new BuilderElement({
name: "m:mc",
children: [
new BuilderElement({
name: "m:mcPr",
children: [createValueElement("m:count", count), createValueElement("m:mcJc", alignment)],
}),
],
}),
),
}),
],
}),
...rows.map(
(row) =>
new BuilderElement({
name: "m:mr",
children: Array.from({ length: columns }, (_, column) => createArgument(row[column] ?? [])),
}),
),
],
};
};
/**
* A matrix (`m:m`), in brackets or none (`m:d`): LaTeX's `matrix`, `pmatrix`, `bmatrix`, `Bmatrix`, `vmatrix` and
* `Vmatrix`.
*
* Word lines up each column's cells as `columnAlignment` says, and hides the placeholders of empty cells. LibreOffice
* and Pages centre every column.
*
* @example
* ```typescript
* new MathMatrix({
* brackets: "round",
* rows: [
* [[new MathRun("1")], [new MathRun("2")]],
* [[new MathRun("3")], [new MathRun("4")]],
* ],
* });
* ```
*/
export class MathMatrix extends BuilderElement {
public constructor({ brackets = "none", ...options }: MathMatrixOptions) {
checkOneOf("MathMatrix", "brackets", brackets, ["none", ...Object.keys(BRACKETS)]);
const matrix = matrixElement("MathMatrix", options);
super(
brackets === "none"
? matrix
: bracketsElement({ open: BRACKETS[brackets][0], close: BRACKETS[brackets][1] }, [
createMathBase({ children: [new BuilderElement(matrix)] }),
]),
);
}
}
+217
View File
@@ -0,0 +1,217 @@
import { describe, expect, it } from "vitest";
import xml from "xml";
import { type Element, xml2js } from "xml-js";
import { Formatter } from "@export/formatter";
import { Math, type MathComponent, MathFraction, MathRun, MathSuperScript } from "docx";
import { MathBrackets } from "./math-brackets";
import { MathCases } from "./math-cases";
import { MathEquationArray } from "./math-equation-array";
import { MathMatrix, type MathMatrixBrackets } from "./math-matrix";
// @ts-expect-error -- Vite reads the schema as text, which TypeScript has no type for
import mathSchema from "../../ooxml-schemas/ISO-IEC29500-4_2016/shared-math.xsd?raw";
// The math schema, which docx/math's elements are checked against: each element's children are ones its type has, in
// its type's order. The Open XML SDK validator checks this too, for the demos only
const schema = xml2js(mathSchema as string) as Element;
const definitions = new Map(
schema
.elements![0].elements!.filter(({ name }) => name === "xsd:complexType" || name === "xsd:group")
.map((definition) => [`${definition.name}:${definition.attributes!.name}`, definition]),
);
type Child = {
/** Its type, such as CT_D, or a type of another schema, such as s:ST_String */
readonly type: string;
/** Where it comes in its parent: children of one rank come before those of the next, and a choice's are all one rank */
readonly rank: number;
};
/**
* The children a complex type or group has, by name, with their types and ranks, from the rank given. Groups of
* WordprocessingML, such as the run properties a math run can have, are left out: docx/math writes none of them.
*/
const childrenOf = (definition: Element, first = 0): { readonly children: ReadonlyMap<string, Child>; readonly next: number } =>
(definition.elements ?? []).reduce<{ readonly children: ReadonlyMap<string, Child>; readonly next: number }>(
({ children, next }, part) => {
switch (part.name) {
case "xsd:element":
return {
children: new Map([
...children,
[String(part.attributes!.name), { type: String(part.attributes!.type), rank: next }],
]),
next: next + 1,
};
case "xsd:group": {
const ref = String(part.attributes!.ref);
if (ref.includes(":")) {
return { children, next: next + 1 };
}
const group = childrenOf(definitions.get(`xsd:group:${ref}`)!, next);
return { children: new Map([...children, ...group.children]), next: group.next };
}
case "xsd:sequence": {
const sequence = childrenOf(part, next);
return { children: new Map([...children, ...sequence.children]), next: sequence.next };
}
case "xsd:choice": {
// Each of a choice's options takes the same place
const options = (part.elements ?? []).map((option) => childrenOf({ elements: [option] }, next));
return {
children: new Map([...children, ...options.flatMap((option) => [...option.children])]),
next: globalThis.Math.max(next + 1, ...options.map((option) => option.next)),
};
}
default:
return { children, next };
}
},
{ children: new Map(), next: first },
);
/**
* The problems with an element's children and theirs: children its type doesn't have, or children out of order.
*/
const problemsIn = (element: Element, type: string, path: string): readonly string[] => {
const definition = definitions.get(`xsd:complexType:${type}`);
if (definition === undefined) {
return [`${path}: unknown type ${type}`];
}
const { children } = childrenOf(definition);
const elements = (element.elements ?? []).filter((child) => child.type === "element");
return elements.flatMap((child, index) => {
const declared = child.name!.startsWith("m:") ? children.get(child.name!.slice(2)) : undefined;
const at = `${path} > ${child.name}`;
if (declared === undefined) {
return [`${at}: not a child of ${type}`];
}
const before = elements.slice(0, index).map((one) => children.get(one.name!.slice(2))?.rank ?? -1);
const order = before.some((rank) => rank > declared.rank) ? [`${at}: out of the order of ${type}`] : [];
// Simple types, and types of other schemas, have no children to check
return [...order, ...(declared.type.includes(":") || declared.type.startsWith("ST_") ? [] : problemsIn(child, declared.type, at))];
});
};
const problemsOf = (children: readonly MathComponent[]): readonly string[] => {
const written = xml(new Formatter().format(new Math({ children })));
return problemsIn((xml2js(written) as Element).elements![0], "CT_OMath", "m:oMath");
};
const run = (text: string): MathRun => new MathRun(text);
const cell = (text: string): readonly MathComponent[] => [run(text)];
const BRACKETS: readonly MathMatrixBrackets[] = ["none", "round", "square", "curly", "angled", "verticalBars", "doubleVerticalBars"];
const EQUATIONS: readonly (readonly [string, () => readonly MathComponent[]])[] = [
...BRACKETS.map(
(brackets) =>
[
`a matrix in ${brackets} brackets, with every option`,
() => [
new MathMatrix({
brackets,
rows: [[cell("1"), cell("2"), []], [cell("3")], []],
columnAlignment: ["left", "right", "center"],
verticalAlignment: "top",
}),
],
] as const,
),
[
"brackets of every kind",
() => [
new MathBrackets({ open: "|", close: "|", children: [run("x")] }),
new MathBrackets({ open: "⟨", close: "⟩", separator: "|", grow: false, items: [cell("a"), cell("b"), []] }),
new MathBrackets({ open: "{", close: "", items: [cell("x")] }),
new MathBrackets({ children: [] }),
],
],
[
"cases, with normal text, and without conditions",
() => [
new MathCases({
cases: [
{ value: cell("1,"), condition: [new MathRun({ text: "if ", normalText: true }), run("x>0")] },
{ value: cell("0,") },
{ value: [], condition: [new MathRun({ text: "otherwise", normalText: true })] },
],
}),
new MathCases({ cases: [{ value: cell("a") }] }),
],
],
[
"an equation array with numbers, several points and empty parts",
() => [
new MathEquationArray({
verticalAlignment: "bottom",
rows: [
{ parts: [cell("a"), cell("=b"), cell("c"), cell("=d")], equationNumber: "(1)" },
{ parts: [[], cell("=e")], equationNumber: "(2)" },
{ parts: [[]] },
],
}),
],
],
[
"everything inside everything",
() => [
new MathFraction({
numerator: [
new MathMatrix({
brackets: "round",
rows: [[[new MathCases({ cases: [{ value: cell("x"), condition: cell("y") }] })]]],
}),
],
denominator: [
new MathEquationArray({
rows: [
{
parts: [
[
new MathSuperScript({
children: [new MathBrackets({ children: cell("a+b") })],
superScript: cell("2"),
}),
],
[run("="), new MathMatrix({ rows: [[cell("1")]] })],
],
equationNumber: "(3)",
},
],
}),
],
}),
],
],
];
describe("docx/math against the schema", () => {
it.each(EQUATIONS)("writes %s as shared-math.xsd has it", (_, equation) => {
expect(problemsOf(equation())).toEqual([]);
});
it("finds a child out of order, and one its type doesn't have", () => {
// A check of the check: m:sepChr after m:endChr, and m:e in m:dPr
const wrong = {
elements: [
{
type: "element",
name: "m:dPr",
elements: [
{ type: "element", name: "m:endChr" },
{ type: "element", name: "m:sepChr" },
{ type: "element", name: "m:e" },
],
},
],
} as Element;
expect(problemsIn(wrong, "CT_D", "m:d")).toEqual([
"m:d > m:dPr > m:sepChr: out of the order of CT_DPr",
"m:d > m:dPr > m:e: not a child of CT_DPr",
]);
expect(problemsIn(wrong, "CT_Unknown", "m:d")).toEqual(["m:d: unknown type CT_Unknown"]);
});
});
+1
View File
@@ -23,6 +23,7 @@ const ENTRIES: Readonly<Record<string, Entry>> = {
shapes: { name: "shapes", global: "docxShapes" },
watermarks: { name: "watermarks", global: "docxWatermarks" },
charts: { name: "charts", global: "docxCharts" },
math: { name: "math", global: "docxMath" },
};
// API Extractor, which bundles the declarations, copies in those of any module that isn't a library, so it would copy