@cn-math-notation/core 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -21,6 +21,15 @@ 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
+ 递等式(脱式计算)返回 TeX,交给 KaTeX、MathJax 等任何 TeX 渲染器:
25
+
26
+ ```ts
27
+ import { buildDengshi, dengshiSteps } from "@cn-math-notation/core";
28
+
29
+ dengshiSteps("25×(40+4)"); // ["25\\times (40+4)", "25\\times 44", "1100"]
30
+ buildDengshi("25×(40+4)"); // "\\begin{aligned}&25\\times (40+4)\\\\[6pt]={}&…\\end{aligned}"
31
+ ```
32
+
24
33
  在网页里配合 KaTeX 使用,请用 [@cn-math-notation/katex](https://www.npmjs.com/package/@cn-math-notation/katex)。
25
34
 
26
35
  完整写法、样式选项与例子见 [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,4 +1,5 @@
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";
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";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cn-math-notation/core",
3
- "version": "0.1.0",
3
+ "version": "0.2.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": "rm -rf dist && tsc -p tsconfig.build.json",
42
- "prepublishOnly": "bun run build"
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",