@cn-math-notation/core 0.1.0 → 0.3.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 +11 -0
- package/dist/dengshi/expr.d.ts +21 -0
- package/dist/dengshi/expr.js +156 -0
- package/dist/dengshi/index.d.ts +13 -0
- package/dist/dengshi/index.js +41 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +13 -0
- package/dist/mathml.d.ts +30 -0
- package/dist/mathml.js +214 -0
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -21,6 +21,17 @@ const layout = renderShushiLayout(String.raw`\tui{4} 0 3 \\ - 1 6 7 \\ \hline \e
|
|
|
21
21
|
- `svg`:SVG 字符串,颜色跟随外层文字(`currentColor`),尺寸以 em 计。
|
|
22
22
|
- `label`:给屏幕阅读器的文字描述。
|
|
23
23
|
|
|
24
|
+
竖式导出 MathML(`mstack` / `mlongdiv`):`shushiToMathML("403-167")`、`shushiLayoutToMathML(…)`。
|
|
25
|
+
|
|
26
|
+
递等式(脱式计算)返回 TeX,交给 KaTeX、MathJax 等任何 TeX 渲染器:
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { buildDengshi, dengshiSteps } from "@cn-math-notation/core";
|
|
30
|
+
|
|
31
|
+
dengshiSteps("25×(40+4)"); // ["25\\times (40+4)", "25\\times 44", "1100"]
|
|
32
|
+
buildDengshi("25×(40+4)"); // "\\begin{aligned}&25\\times (40+4)\\\\[6pt]={}&…\\end{aligned}"
|
|
33
|
+
```
|
|
34
|
+
|
|
24
35
|
在网页里配合 KaTeX 使用,请用 [@cn-math-notation/katex](https://www.npmjs.com/package/@cn-math-notation/katex)。
|
|
25
36
|
|
|
26
37
|
完整写法、样式选项与例子见 [GitHub](https://github.com/n7tequila/cn-math-notation) 与[使用说明](https://github.com/n7tequila/cn-math-notation/blob/main/docs/usage.md)。
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export type BinOp = "+" | "-" | "×" | "÷";
|
|
2
|
+
export type Bracket = "(" | "[";
|
|
3
|
+
export type Node = {
|
|
4
|
+
readonly k: "num";
|
|
5
|
+
readonly v: bigint;
|
|
6
|
+
} | {
|
|
7
|
+
readonly k: "op";
|
|
8
|
+
readonly op: BinOp;
|
|
9
|
+
readonly l: Node;
|
|
10
|
+
readonly r: Node;
|
|
11
|
+
} | {
|
|
12
|
+
readonly k: "paren";
|
|
13
|
+
readonly br: Bracket;
|
|
14
|
+
readonly inner: Node;
|
|
15
|
+
};
|
|
16
|
+
/** 递归下降:expr := term (± term)*;term := factor (×÷ factor)*;factor := 数 | (expr) | [expr]。 */
|
|
17
|
+
export declare function parseArith(source: string): Node;
|
|
18
|
+
/** 逐步化简,返回每一步的语法树(第一项是原式,最后一项是结果)。 */
|
|
19
|
+
export declare function simplifySteps(root: Node): Node[];
|
|
20
|
+
/** 语法树 → TeX(括号都来自原式,照原样写回)。 */
|
|
21
|
+
export declare function toTex(n: Node): string;
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 递等式(脱式计算)的算式:解析成语法树、按课本运算顺序逐步化简、写回 TeX。
|
|
3
|
+
*
|
|
4
|
+
* 运算顺序(课本):有括号先算括号里面的(小括号 → 中括号,由里往外);
|
|
5
|
+
* 同一层先乘除、后加减;同级从左往右。互不影响的几处在同一步里一起算
|
|
6
|
+
* (如 25×4+36÷6 → 100+6;(12+8)×(5-3) → 20×2),但括号外的运算要等括号都算完。
|
|
7
|
+
* 第一期只做整数;减法不能出现负数,除法要能整除。
|
|
8
|
+
*/
|
|
9
|
+
import { ExpressionError } from "../semantic/numbers.js";
|
|
10
|
+
const SYMBOLS = [
|
|
11
|
+
[/^\d+/, (m) => ({ t: "num", v: BigInt(m) })],
|
|
12
|
+
[/^\+/, () => ({ t: "op", op: "+" })],
|
|
13
|
+
[/^(?:-|−)/, () => ({ t: "op", op: "-" })],
|
|
14
|
+
[/^(?:\\times|×|\*)/, () => ({ t: "op", op: "×" })],
|
|
15
|
+
[/^(?:\\div|÷|\/)/, () => ({ t: "op", op: "÷" })],
|
|
16
|
+
[/^(?:\\left)?(?:\(|()/, () => ({ t: "open", br: "(" })],
|
|
17
|
+
[/^(?:\\right)?(?:\)|))/, () => ({ t: "close", br: "(" })],
|
|
18
|
+
[/^(?:\\left)?(?:\[|[|\\lbrack)/, () => ({ t: "open", br: "[" })],
|
|
19
|
+
[/^(?:\\right)?(?:\]|]|\\rbrack)/, () => ({ t: "close", br: "[" })],
|
|
20
|
+
];
|
|
21
|
+
function tokenize(source) {
|
|
22
|
+
let rest = source.replace(/\\nobreakspace|~|\s+/g, "");
|
|
23
|
+
if (rest === "")
|
|
24
|
+
throw new ExpressionError("算式是空的");
|
|
25
|
+
const tokens = [];
|
|
26
|
+
while (rest !== "") {
|
|
27
|
+
// 小数要先于整数判断
|
|
28
|
+
const decimal = /^\d+\.\d+/.exec(rest);
|
|
29
|
+
if (decimal !== null)
|
|
30
|
+
throw new ExpressionError("小数的递等式属第二期");
|
|
31
|
+
const hit = SYMBOLS.find(([re]) => re.test(rest));
|
|
32
|
+
if (hit === undefined)
|
|
33
|
+
throw new ExpressionError(`不认识的符号:“${rest}”`);
|
|
34
|
+
const m = hit[0].exec(rest)[0];
|
|
35
|
+
tokens.push(hit[1](m));
|
|
36
|
+
rest = rest.slice(m.length);
|
|
37
|
+
}
|
|
38
|
+
return tokens;
|
|
39
|
+
}
|
|
40
|
+
/** 递归下降:expr := term (± term)*;term := factor (×÷ factor)*;factor := 数 | (expr) | [expr]。 */
|
|
41
|
+
export function parseArith(source) {
|
|
42
|
+
const tokens = tokenize(source);
|
|
43
|
+
let pos = 0;
|
|
44
|
+
const peek = () => tokens[pos];
|
|
45
|
+
const factor = () => {
|
|
46
|
+
const tok = peek();
|
|
47
|
+
if (tok === undefined)
|
|
48
|
+
throw new ExpressionError("算式不完整:结尾少了一个数");
|
|
49
|
+
if (tok.t === "num") {
|
|
50
|
+
pos += 1;
|
|
51
|
+
return { k: "num", v: tok.v };
|
|
52
|
+
}
|
|
53
|
+
if (tok.t === "open") {
|
|
54
|
+
pos += 1;
|
|
55
|
+
const inner = expr();
|
|
56
|
+
const close = peek();
|
|
57
|
+
if (close?.t !== "close" || close.br !== tok.br) {
|
|
58
|
+
throw new ExpressionError(tok.br === "(" ? "小括号没有配对" : "中括号没有配对");
|
|
59
|
+
}
|
|
60
|
+
pos += 1;
|
|
61
|
+
return { k: "paren", br: tok.br, inner };
|
|
62
|
+
}
|
|
63
|
+
throw new ExpressionError(tok.t === "close" ? "多了一个右括号" : "运算符前面少了一个数");
|
|
64
|
+
};
|
|
65
|
+
const chain = (next, ops) => () => {
|
|
66
|
+
let node = next();
|
|
67
|
+
for (let tok = peek(); tok?.t === "op" && ops.includes(tok.op); tok = peek()) {
|
|
68
|
+
pos += 1;
|
|
69
|
+
node = { k: "op", op: tok.op, l: node, r: next() };
|
|
70
|
+
}
|
|
71
|
+
return node;
|
|
72
|
+
};
|
|
73
|
+
const term = chain(factor, ["×", "÷"]);
|
|
74
|
+
const expr = chain(term, ["+", "-"]);
|
|
75
|
+
const root = expr();
|
|
76
|
+
if (pos < tokens.length) {
|
|
77
|
+
const tok = tokens[pos];
|
|
78
|
+
throw new ExpressionError(tok.t === "close" ? "多了一个右括号" : "两个数之间少了运算符");
|
|
79
|
+
}
|
|
80
|
+
return root;
|
|
81
|
+
}
|
|
82
|
+
function compute(op, a, b) {
|
|
83
|
+
switch (op) {
|
|
84
|
+
case "+":
|
|
85
|
+
return a + b;
|
|
86
|
+
case "-":
|
|
87
|
+
if (a < b)
|
|
88
|
+
throw new ExpressionError(`${a}−${b} 得负数,小学递等式不处理负数`);
|
|
89
|
+
return a - b;
|
|
90
|
+
case "×":
|
|
91
|
+
return a * b;
|
|
92
|
+
case "÷":
|
|
93
|
+
if (b === 0n)
|
|
94
|
+
throw new ExpressionError("除数不能是 0");
|
|
95
|
+
if (a % b !== 0n)
|
|
96
|
+
throw new ExpressionError(`${a}÷${b} 除不尽,递等式里的除法要能整除`);
|
|
97
|
+
return a / b;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function containsParen(n) {
|
|
101
|
+
return n.k === "paren" || (n.k === "op" && (containsParen(n.l) || containsParen(n.r)));
|
|
102
|
+
}
|
|
103
|
+
function containsOp(n, ops) {
|
|
104
|
+
return n.k === "op" && (ops.includes(n.op) || containsOp(n.l, ops) || containsOp(n.r, ops));
|
|
105
|
+
}
|
|
106
|
+
/** 把两个子节点都是数、且属于 ops 的运算全部算掉(同一步里互不影响的几处一起算)。 */
|
|
107
|
+
function reduceReady(n, ops) {
|
|
108
|
+
if (n.k !== "op")
|
|
109
|
+
return n;
|
|
110
|
+
if (ops.includes(n.op) && n.l.k === "num" && n.r.k === "num")
|
|
111
|
+
return { k: "num", v: compute(n.op, n.l.v, n.r.v) };
|
|
112
|
+
return { ...n, l: reduceReady(n.l, ops), r: reduceReady(n.r, ops) };
|
|
113
|
+
}
|
|
114
|
+
/** 一层(括号外或某个括号内)往前算一步。 */
|
|
115
|
+
function stepScope(n) {
|
|
116
|
+
if (containsParen(n))
|
|
117
|
+
return stepParens(n);
|
|
118
|
+
return containsOp(n, ["×", "÷"]) ? reduceReady(n, ["×", "÷"]) : reduceReady(n, ["+", "-"]);
|
|
119
|
+
}
|
|
120
|
+
/** 有括号时只算括号里面:各个括号各自往前一步,算成一个数时去掉括号。 */
|
|
121
|
+
function stepParens(n) {
|
|
122
|
+
if (n.k === "paren") {
|
|
123
|
+
const inner = stepScope(n.inner);
|
|
124
|
+
return inner.k === "num" ? inner : { ...n, inner };
|
|
125
|
+
}
|
|
126
|
+
if (n.k === "op")
|
|
127
|
+
return { ...n, l: stepParens(n.l), r: stepParens(n.r) };
|
|
128
|
+
return n;
|
|
129
|
+
}
|
|
130
|
+
const MAX_STEPS = 100;
|
|
131
|
+
/** 逐步化简,返回每一步的语法树(第一项是原式,最后一项是结果)。 */
|
|
132
|
+
export function simplifySteps(root) {
|
|
133
|
+
const steps = [root];
|
|
134
|
+
let cur = root;
|
|
135
|
+
while (cur.k !== "num") {
|
|
136
|
+
if (steps.length > MAX_STEPS)
|
|
137
|
+
throw new ExpressionError("算式太长了");
|
|
138
|
+
cur = stepScope(cur);
|
|
139
|
+
steps.push(cur);
|
|
140
|
+
}
|
|
141
|
+
if (steps.length === 1)
|
|
142
|
+
throw new ExpressionError("只有一个数,不需要递等式");
|
|
143
|
+
return steps;
|
|
144
|
+
}
|
|
145
|
+
const OP_TEX = { "+": "+", "-": "-", "×": "\\times ", "÷": "\\div " };
|
|
146
|
+
/** 语法树 → TeX(括号都来自原式,照原样写回)。 */
|
|
147
|
+
export function toTex(n) {
|
|
148
|
+
switch (n.k) {
|
|
149
|
+
case "num":
|
|
150
|
+
return n.v.toString();
|
|
151
|
+
case "op":
|
|
152
|
+
return `${toTex(n.l)}${OP_TEX[n.op]}${toTex(n.r)}`;
|
|
153
|
+
case "paren":
|
|
154
|
+
return n.br === "(" ? `(${toTex(n.inner)})` : `[${toTex(n.inner)}]`;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export { parseArith, simplifySteps, toTex as arithToTex, type Node as ArithNode } from "./expr.ts";
|
|
2
|
+
/** 把若干行算式(不含等号)排成递等式的 TeX。 */
|
|
3
|
+
export declare function dengshiTex(lines: readonly string[]): string;
|
|
4
|
+
/** 语义式:只写算式,按运算顺序逐步化简,每一步一行。返回每行的 TeX(不含等号)。 */
|
|
5
|
+
export declare function dengshiSteps(expression: string): string[];
|
|
6
|
+
/** 语义式一步到位:算式 → 递等式 TeX。 */
|
|
7
|
+
export declare function buildDengshi(expression: string): string;
|
|
8
|
+
/**
|
|
9
|
+
* 直写:`25\times(40+4) \\ 25\times44 \\ 1100`,用 `\\` 分行,每行一步。
|
|
10
|
+
* 行首写不写等号都可以(写了会去掉,统一由排版加上悬在左边的等号)。
|
|
11
|
+
*/
|
|
12
|
+
export declare function parseDengshiLines(source: string): string[];
|
|
13
|
+
export declare function buildDengshiLayout(source: string): string;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 递等式:等号悬在算式左边(维护者 2026-11-26 定),各行算式左端对齐,第一行不写等号。
|
|
3
|
+
* 排版交给 TeX 的 aligned 环境(第一列放等号、右对齐,第二列放算式、左对齐),
|
|
4
|
+
* 所以本模块只产出 TeX 字符串,KaTeX、MathJax 都能排。
|
|
5
|
+
*/
|
|
6
|
+
import { ExpressionError } from "../semantic/numbers.js";
|
|
7
|
+
import { parseArith, simplifySteps, toTex } from "./expr.js";
|
|
8
|
+
export { parseArith, simplifySteps, toTex as arithToTex } from "./expr.js";
|
|
9
|
+
/** 行距,与课本里每步一行的疏朗程度接近。 */
|
|
10
|
+
const ROW_GAP = "6pt";
|
|
11
|
+
/** 把若干行算式(不含等号)排成递等式的 TeX。 */
|
|
12
|
+
export function dengshiTex(lines) {
|
|
13
|
+
if (lines.length === 0)
|
|
14
|
+
throw new ExpressionError("递等式至少要有一行");
|
|
15
|
+
const rows = lines.map((line, i) => (i === 0 ? `&${line}` : `={}&${line}`));
|
|
16
|
+
return `\\begin{aligned}${rows.join(`\\\\[${ROW_GAP}]`)}\\end{aligned}`;
|
|
17
|
+
}
|
|
18
|
+
/** 语义式:只写算式,按运算顺序逐步化简,每一步一行。返回每行的 TeX(不含等号)。 */
|
|
19
|
+
export function dengshiSteps(expression) {
|
|
20
|
+
return simplifySteps(parseArith(expression)).map(toTex);
|
|
21
|
+
}
|
|
22
|
+
/** 语义式一步到位:算式 → 递等式 TeX。 */
|
|
23
|
+
export function buildDengshi(expression) {
|
|
24
|
+
return dengshiTex(dengshiSteps(expression));
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* 直写:`25\times(40+4) \\ 25\times44 \\ 1100`,用 `\\` 分行,每行一步。
|
|
28
|
+
* 行首写不写等号都可以(写了会去掉,统一由排版加上悬在左边的等号)。
|
|
29
|
+
*/
|
|
30
|
+
export function parseDengshiLines(source) {
|
|
31
|
+
const lines = source
|
|
32
|
+
.split(/\\\\(?:\[[^\]]*\])?/)
|
|
33
|
+
.map((line) => line.trim().replace(/^=\s*/, "").trim())
|
|
34
|
+
.filter((line) => line !== "");
|
|
35
|
+
if (lines.length === 0)
|
|
36
|
+
throw new ExpressionError("递等式至少要有一行");
|
|
37
|
+
return lines;
|
|
38
|
+
}
|
|
39
|
+
export function buildDengshiLayout(source) {
|
|
40
|
+
return dengshiTex(parseDengshiLines(source));
|
|
41
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
export type * from "./model.ts";
|
|
2
|
+
export { buildDengshi, buildDengshiLayout, dengshiSteps, dengshiTex, parseDengshiLines, parseArith, simplifySteps, arithToTex, type ArithNode, } from "./dengshi/index.ts";
|
|
2
3
|
export { buildSemantic, parseExpression, ExpressionError, DIGIT_COLORS, type Expression } from "./semantic/index.ts";
|
|
3
4
|
export { parseLayout, tokenize, assignColumns, LayoutSyntaxError } from "./parse-layout.ts";
|
|
4
5
|
export { renderLayout, describe, FONT_SIZE, COLORS, type RenderedSvg, type RenderOptions, type RootDisplay, } from "./render-svg.ts";
|
|
5
6
|
export { DEFAULT_STYLE, parseOptions, OptionError, type StyleOptions, type CarryAt, type OperatorPlacement, type MulMode, type ProcessMode, } from "./options.ts";
|
|
6
7
|
import { type StyleOptions } from "./options.ts";
|
|
7
8
|
import { type RenderedSvg, type RenderOptions } from "./render-svg.ts";
|
|
9
|
+
import { type MathMLOptions } from "./mathml.ts";
|
|
10
|
+
export { layoutToMathML, type MathMLOptions } from "./mathml.ts";
|
|
8
11
|
/** 直写布局一步到位:原文 + 选项原文 → SVG。base 是未写选项时的默认样式。 */
|
|
9
12
|
export declare function renderShushiLayout(source: string, options?: string, base?: StyleOptions, render?: RenderOptions): RenderedSvg;
|
|
10
13
|
/** 语义式一步到位:算式(如 `403-167`)+ 选项原文 → SVG。竖式过程由程序算出。 */
|
|
11
14
|
export declare function renderShushi(expression: string, options?: string, base?: StyleOptions, render?: RenderOptions): RenderedSvg;
|
|
15
|
+
/** 语义式 → MathML(mstack / mlongdiv)。 */
|
|
16
|
+
export declare function shushiToMathML(expression: string, options?: string, base?: StyleOptions, mathml?: MathMLOptions): string;
|
|
17
|
+
/** 直写布局 → MathML。 */
|
|
18
|
+
export declare function shushiLayoutToMathML(source: string, options?: string, base?: StyleOptions, mathml?: MathMLOptions): string;
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { buildDengshi, buildDengshiLayout, dengshiSteps, dengshiTex, parseDengshiLines, parseArith, simplifySteps, arithToTex, } from "./dengshi/index.js";
|
|
1
2
|
export { buildSemantic, parseExpression, ExpressionError, DIGIT_COLORS } from "./semantic/index.js";
|
|
2
3
|
export { parseLayout, tokenize, assignColumns, LayoutSyntaxError } from "./parse-layout.js";
|
|
3
4
|
export { renderLayout, describe, FONT_SIZE, COLORS, } from "./render-svg.js";
|
|
@@ -6,6 +7,8 @@ import { parseLayout } from "./parse-layout.js";
|
|
|
6
7
|
import { buildSemantic } from "./semantic/index.js";
|
|
7
8
|
import { DEFAULT_STYLE, parseOptions } from "./options.js";
|
|
8
9
|
import { renderLayout } from "./render-svg.js";
|
|
10
|
+
import { layoutToMathML } from "./mathml.js";
|
|
11
|
+
export { layoutToMathML } from "./mathml.js";
|
|
9
12
|
/** 直写布局一步到位:原文 + 选项原文 → SVG。base 是未写选项时的默认样式。 */
|
|
10
13
|
export function renderShushiLayout(source, options, base = DEFAULT_STYLE, render = {}) {
|
|
11
14
|
return renderLayout(parseLayout(source), parseOptions(options, base), render);
|
|
@@ -15,3 +18,13 @@ export function renderShushi(expression, options, base = DEFAULT_STYLE, render =
|
|
|
15
18
|
const style = parseOptions(options, base);
|
|
16
19
|
return renderLayout(buildSemantic(expression, style), style, render);
|
|
17
20
|
}
|
|
21
|
+
/** 语义式 → MathML(mstack / mlongdiv)。 */
|
|
22
|
+
export function shushiToMathML(expression, options, base = DEFAULT_STYLE, mathml = {}) {
|
|
23
|
+
const style = parseOptions(options, base);
|
|
24
|
+
return layoutToMathML(buildSemantic(expression, style), style, mathml);
|
|
25
|
+
}
|
|
26
|
+
/** 直写布局 → MathML。 */
|
|
27
|
+
export function shushiLayoutToMathML(source, options, base = DEFAULT_STYLE, mathml = {}) {
|
|
28
|
+
const style = parseOptions(options, base);
|
|
29
|
+
return layoutToMathML(parseLayout(source), style, mathml);
|
|
30
|
+
}
|
package/dist/mathml.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 布局 → MathML(MathML 3 §3.6 小学算术:mstack / mlongdiv / mscarries / msline)。
|
|
3
|
+
*
|
|
4
|
+
* - 列对齐:每行从自己的最高位写到全竖式的最低列,缺的格子补空 <mrow/>,统一 stackalign="right",
|
|
5
|
+
* 不依赖渲染器对小数点对齐的实现;小数点占一列(与规范一致)。
|
|
6
|
+
* - 进位、退位点:合并成该行前面的一个 <mscarries>,每格用 <mscarry location=…> 指定方位。
|
|
7
|
+
* 进位坐在横线上(课本写法)→ 挂在上一行,location s,并用看不见的占位进位铺满整行(见 mscarries 的 fillTop);
|
|
8
|
+
* carries=above 时改为 location n(画在上一行上方)。进位写在下一行上方 → 挂在下一行,location n;
|
|
9
|
+
* 退位点 → location n,内容“·”。左下写法(carryAt=sw)在 MathML 里不区分。
|
|
10
|
+
* - 补 0 → menclose box;划掉 → menclose updiagonalstrike;错误 → mathbackground;着色、红色强调 → mathcolor。
|
|
11
|
+
* - 数位虚线在 MathML 里没有对应写法,导出时省略。
|
|
12
|
+
*/
|
|
13
|
+
import type { Layout } from "./model.ts";
|
|
14
|
+
import { type StyleOptions } from "./options.ts";
|
|
15
|
+
export interface MathMLOptions {
|
|
16
|
+
/** 外面包不包 <math>。嵌进 KaTeX 等已有 <math> 的场合用 false。默认 true。 */
|
|
17
|
+
readonly wrap?: boolean;
|
|
18
|
+
/** <math display=…>,默认 block。 */
|
|
19
|
+
readonly display?: "block" | "inline";
|
|
20
|
+
/**
|
|
21
|
+
* 进位方位:textbook(默认,按课本写在下方:s / se,或写在下一行上方:n / ne);
|
|
22
|
+
* above(一律写成 MathML 默认的 n,挂在进到的那一行上方)——兼容性更好,但不是课本写法。
|
|
23
|
+
*/
|
|
24
|
+
readonly carries?: "textbook" | "above";
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* 竖式布局 → MathML 字符串。style 目前不影响输出(左下进位写法在 MathML 里不区分),
|
|
28
|
+
* 保留参数以便以后按样式调整导出。
|
|
29
|
+
*/
|
|
30
|
+
export declare function layoutToMathML(layout: Layout, style?: StyleOptions, opts?: MathMLOptions): string;
|
package/dist/mathml.js
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { DEFAULT_STYLE } from "./options.js";
|
|
2
|
+
import { COLORS, describe } from "./render-svg.js";
|
|
3
|
+
const MATHML_NS = "http://www.w3.org/1998/Math/MathML";
|
|
4
|
+
function escapeXml(s) {
|
|
5
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
6
|
+
}
|
|
7
|
+
const EMPTY = "<mrow/>";
|
|
8
|
+
const OPERATOR_TEXT = { "+": "+", "-": "−", "×": "×", "÷": "÷" };
|
|
9
|
+
/** 全竖式的列,从高位到低位(有小数点时含 -0.5 列)。 */
|
|
10
|
+
function allColumns(layout) {
|
|
11
|
+
const cols = new Set();
|
|
12
|
+
for (const row of layout.rows) {
|
|
13
|
+
if (row.kind === "hline")
|
|
14
|
+
continue;
|
|
15
|
+
for (const c of row.cells)
|
|
16
|
+
cols.add(c.col);
|
|
17
|
+
}
|
|
18
|
+
const ints = [...cols].filter((c) => Number.isInteger(c));
|
|
19
|
+
const max = Math.max(0, ...ints);
|
|
20
|
+
const min = Math.min(0, ...ints);
|
|
21
|
+
const out = [];
|
|
22
|
+
for (let c = max; c >= min; c -= 1) {
|
|
23
|
+
out.push(c);
|
|
24
|
+
if (c === 0 && layout.hasDecimal)
|
|
25
|
+
out.push(-0.5);
|
|
26
|
+
}
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
function cellElement(cell) {
|
|
30
|
+
if (cell.content.kind === "blank") {
|
|
31
|
+
return cell.marks.includes("err") ? `<mspace width="0.5em" mathbackground="${COLORS.errBg}"/>` : EMPTY;
|
|
32
|
+
}
|
|
33
|
+
const marks = new Set(cell.marks);
|
|
34
|
+
const attrs = [];
|
|
35
|
+
const color = cell.color ?? (marks.has("hong") ? COLORS.teach : undefined);
|
|
36
|
+
if (color !== undefined)
|
|
37
|
+
attrs.push(`mathcolor="${escapeXml(color)}"`);
|
|
38
|
+
if (marks.has("err"))
|
|
39
|
+
attrs.push(`mathbackground="${COLORS.errBg}"`);
|
|
40
|
+
const text = cell.content.kind === "digit" ? cell.content.text : ".";
|
|
41
|
+
let el = `<mn${attrs.length > 0 ? " " + attrs.join(" ") : ""}>${text}</mn>`;
|
|
42
|
+
if (marks.has("bu"))
|
|
43
|
+
el = `<menclose notation="box" mathcolor="${COLORS.teach}">${el}</menclose>`;
|
|
44
|
+
if (marks.has("hua"))
|
|
45
|
+
el = `<menclose notation="updiagonalstrike">${el}</menclose>`;
|
|
46
|
+
return el;
|
|
47
|
+
}
|
|
48
|
+
/** 一行格子:从这一行的最高位写到全竖式最低列,缺的补空。 */
|
|
49
|
+
function rowCells(cells, cols) {
|
|
50
|
+
const byCol = new Map(cells.map((c) => [c.col, c]));
|
|
51
|
+
const top = Math.max(...cells.map((c) => c.col));
|
|
52
|
+
return cols.filter((c) => c <= top).map((c) => {
|
|
53
|
+
const cell = byCol.get(c);
|
|
54
|
+
return cell === undefined ? EMPTY : cellElement(cell);
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function carryAnnotations(row, location) {
|
|
58
|
+
const out = new Map();
|
|
59
|
+
for (const c of row.cells) {
|
|
60
|
+
if (c.content.kind !== "digit")
|
|
61
|
+
continue;
|
|
62
|
+
const color = c.color ?? COLORS.teach;
|
|
63
|
+
out.set(c.col, { content: `<mn mathcolor="${escapeXml(color)}">${c.content.text}</mn>`, location });
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
function borrowAnnotations(row) {
|
|
68
|
+
const out = new Map();
|
|
69
|
+
for (const c of row.cells) {
|
|
70
|
+
if (c.marks.includes("tui"))
|
|
71
|
+
out.set(c.col, { content: `<mo mathcolor="${COLORS.teach}">·</mo>`, location: "n" });
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
/** 占位进位:看不见,但和真进位一样高(见 fillTop)。 */
|
|
76
|
+
/**
|
|
77
|
+
* 不用 <mphantom>:polyfill 里它比真进位矮约 1px,横线仍有台阶;与真进位同结构、透明着色则差距 < 0.5px(2026-11-26 实测)。
|
|
78
|
+
* aria-hidden 让辅助技术跳过这个占位。
|
|
79
|
+
*/
|
|
80
|
+
const PHANTOM_CARRY = `<mscarry location="s" crossout="none"><mn mathcolor="transparent" aria-hidden="true">0</mn></mscarry>`;
|
|
81
|
+
/**
|
|
82
|
+
* 一行前面的 mscarries。
|
|
83
|
+
* fillTop:课本写法下坐在横线上的进位(location="s")要铺满这一行(含运算符那一列),
|
|
84
|
+
* 没有进位的格子放看不见的占位进位——W3C polyfill 把带进位的格子撑高,横线由各格下边框拼成,
|
|
85
|
+
* 格子高低不一横线就断成几截(2026-11-26 实测);每格都带进位则一样高,横线是一条直线。
|
|
86
|
+
*/
|
|
87
|
+
function mscarries(ann, cols, fillTop) {
|
|
88
|
+
if (ann.size === 0)
|
|
89
|
+
return "";
|
|
90
|
+
const top = Math.max(...ann.keys(), fillTop ?? -Infinity);
|
|
91
|
+
// 运算符单独占的列不在数字列表里:铺满时在左边补上
|
|
92
|
+
const extra = [];
|
|
93
|
+
for (let c = top; c > Math.max(...cols); c -= 1)
|
|
94
|
+
extra.push(c);
|
|
95
|
+
const items = [...extra, ...cols.filter((c) => c <= top)]
|
|
96
|
+
.map((c) => {
|
|
97
|
+
const a = ann.get(c);
|
|
98
|
+
if (a !== undefined)
|
|
99
|
+
return `<mscarry location="${a.location}" crossout="none">${a.content}</mscarry>`;
|
|
100
|
+
return fillTop === undefined ? EMPTY : PHANTOM_CARRY;
|
|
101
|
+
});
|
|
102
|
+
return `<mscarries crossout="none" scriptsizemultiplier="0.6">${items.join("")}</mscarries>`;
|
|
103
|
+
}
|
|
104
|
+
function sitsOnRule(layout, i) {
|
|
105
|
+
const next = layout.rows[i + 1];
|
|
106
|
+
return next === undefined || next.kind === "hline";
|
|
107
|
+
}
|
|
108
|
+
/** 整个竖式最左一列(含运算符单独占的列):polyfill 按全表宽度画横线,占位进位要铺满到这里。 */
|
|
109
|
+
function tableTop(layout) {
|
|
110
|
+
let top = 0;
|
|
111
|
+
for (const row of layout.rows) {
|
|
112
|
+
if (row.kind !== "digits" || row.cells.length === 0)
|
|
113
|
+
continue;
|
|
114
|
+
top = Math.max(top, Math.max(...row.cells.map((c) => c.col)) + (row.operator === undefined ? 0 : 1));
|
|
115
|
+
}
|
|
116
|
+
return top;
|
|
117
|
+
}
|
|
118
|
+
/** 把进位行、退位点归到对应的数字行上,得到“数字行 → 前置 mscarries”的表。 */
|
|
119
|
+
function annotationsByRow(layout, mode) {
|
|
120
|
+
// 左下写法(carryAt=sw)只是同列内的细微偏移,MathML 里不区分;polyfill 对 se / ne / sw 的渲染也有误
|
|
121
|
+
const sitting = mode === "textbook" ? "s" : "n";
|
|
122
|
+
const result = new Map();
|
|
123
|
+
const entry = (rowIndex) => {
|
|
124
|
+
const cur = result.get(rowIndex) ?? { ann: new Map() };
|
|
125
|
+
result.set(rowIndex, cur);
|
|
126
|
+
return cur;
|
|
127
|
+
};
|
|
128
|
+
const add = (rowIndex, ann) => {
|
|
129
|
+
const cur = entry(rowIndex).ann;
|
|
130
|
+
for (const [col, a] of ann)
|
|
131
|
+
if (!cur.has(col))
|
|
132
|
+
cur.set(col, a);
|
|
133
|
+
};
|
|
134
|
+
const digitRowNear = (from, step) => {
|
|
135
|
+
for (let j = from; j >= 0 && j < layout.rows.length; j += step)
|
|
136
|
+
if (layout.rows[j].kind === "digits")
|
|
137
|
+
return j;
|
|
138
|
+
return -1;
|
|
139
|
+
};
|
|
140
|
+
layout.rows.forEach((row, i) => {
|
|
141
|
+
if (row.kind === "digits")
|
|
142
|
+
add(i, borrowAnnotations(row));
|
|
143
|
+
if (row.kind !== "carry")
|
|
144
|
+
return;
|
|
145
|
+
if (sitsOnRule(layout, i)) {
|
|
146
|
+
// 坐在横线上:挂在上一行数字行(课本写法 location=s 画在它下方;above 时 location=n 画在它上方)
|
|
147
|
+
const j = digitRowNear(i - 1, -1);
|
|
148
|
+
if (j < 0)
|
|
149
|
+
return;
|
|
150
|
+
add(j, carryAnnotations(row, sitting));
|
|
151
|
+
if (mode === "textbook")
|
|
152
|
+
entry(j).fillTop = tableTop(layout);
|
|
153
|
+
}
|
|
154
|
+
else {
|
|
155
|
+
// 写在下一行上方:挂在下一行数字行,location=n
|
|
156
|
+
const j = digitRowNear(i + 1, 1);
|
|
157
|
+
if (j >= 0)
|
|
158
|
+
add(j, carryAnnotations(row, "n"));
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
function digitRowElement(row, cols) {
|
|
164
|
+
const cells = rowCells(row.cells, cols);
|
|
165
|
+
const op = row.operator === undefined ? "" : `<mo>${OPERATOR_TEXT[row.operator]}</mo>`;
|
|
166
|
+
return `<msrow>${op}${cells.join("")}</msrow>`;
|
|
167
|
+
}
|
|
168
|
+
function stackBody(layout, skip, mode) {
|
|
169
|
+
const cols = allColumns(layout);
|
|
170
|
+
const ann = annotationsByRow(layout, mode);
|
|
171
|
+
const parts = [];
|
|
172
|
+
layout.rows.forEach((row, i) => {
|
|
173
|
+
if (skip.has(i))
|
|
174
|
+
return;
|
|
175
|
+
if (row.kind === "carry")
|
|
176
|
+
return; // 已并入相邻数字行的 mscarries
|
|
177
|
+
if (row.kind === "hline") {
|
|
178
|
+
parts.push("<msline/>");
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
const carries = ann.get(i);
|
|
182
|
+
if (carries !== undefined)
|
|
183
|
+
parts.push(mscarries(carries.ann, cols, carries.fillTop));
|
|
184
|
+
parts.push(digitRowElement(row, cols));
|
|
185
|
+
});
|
|
186
|
+
return parts.filter((p) => p !== "");
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* 竖式布局 → MathML 字符串。style 目前不影响输出(左下进位写法在 MathML 里不区分),
|
|
190
|
+
* 保留参数以便以后按样式调整导出。
|
|
191
|
+
*/
|
|
192
|
+
export function layoutToMathML(layout, style = DEFAULT_STYLE, opts = {}) {
|
|
193
|
+
void style;
|
|
194
|
+
const quotientIndex = layout.rows.findIndex((r) => r.kind === "digits" && r.quotient === true);
|
|
195
|
+
const dividendIndex = layout.rows.findIndex((r) => r.kind === "digits" && r.divisor !== undefined);
|
|
196
|
+
let body;
|
|
197
|
+
if (dividendIndex >= 0) {
|
|
198
|
+
const dividend = layout.rows[dividendIndex];
|
|
199
|
+
const cols = allColumns(layout);
|
|
200
|
+
const result = quotientIndex >= 0 ? `<msrow>${rowCells(layout.rows[quotientIndex].cells, cols).join("")}</msrow>` : EMPTY;
|
|
201
|
+
const rest = stackBody(layout, new Set([quotientIndex, dividendIndex]), opts.carries ?? "textbook");
|
|
202
|
+
body =
|
|
203
|
+
`<mlongdiv longdivstyle="lefttop" stackalign="right">` +
|
|
204
|
+
`<mn>${escapeXml(dividend.divisor)}</mn>${result}` +
|
|
205
|
+
`<msrow>${rowCells(dividend.cells, cols).join("")}</msrow>${rest.join("")}</mlongdiv>`;
|
|
206
|
+
}
|
|
207
|
+
else {
|
|
208
|
+
body = `<mstack stackalign="right">${stackBody(layout, new Set(), opts.carries ?? "textbook").join("")}</mstack>`;
|
|
209
|
+
}
|
|
210
|
+
if (opts.wrap === false)
|
|
211
|
+
return body;
|
|
212
|
+
const display = opts.display ?? "block";
|
|
213
|
+
return `<math xmlns="${MATHML_NS}" display="${display}" alttext="${escapeXml(describe(layout))}">${body}</math>`;
|
|
214
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cn-math-notation/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "中国中小学数学写法:竖式等课堂写法的模型、解析与 SVG 渲染(不依赖 KaTeX)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "n7tequila",
|
|
@@ -38,8 +38,8 @@
|
|
|
38
38
|
],
|
|
39
39
|
"sideEffects": false,
|
|
40
40
|
"scripts": {
|
|
41
|
-
"build": "
|
|
42
|
-
"prepublishOnly": "
|
|
41
|
+
"build": "tsc -p tsconfig.build.json",
|
|
42
|
+
"prepublishOnly": "rm -rf dist && tsc -p tsconfig.build.json"
|
|
43
43
|
},
|
|
44
44
|
"publishConfig": {
|
|
45
45
|
"access": "public",
|