@cn-math-notation/core 0.2.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 +2 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +12 -0
- package/dist/mathml.d.ts +30 -0
- package/dist/mathml.js +214 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -21,6 +21,8 @@ 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
|
+
|
|
24
26
|
递等式(脱式计算)返回 TeX,交给 KaTeX、MathJax 等任何 TeX 渲染器:
|
|
25
27
|
|
|
26
28
|
```ts
|
package/dist/index.d.ts
CHANGED
|
@@ -6,7 +6,13 @@ export { renderLayout, describe, FONT_SIZE, COLORS, type RenderedSvg, type Rende
|
|
|
6
6
|
export { DEFAULT_STYLE, parseOptions, OptionError, type StyleOptions, type CarryAt, type OperatorPlacement, type MulMode, type ProcessMode, } from "./options.ts";
|
|
7
7
|
import { type StyleOptions } from "./options.ts";
|
|
8
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";
|
|
9
11
|
/** 直写布局一步到位:原文 + 选项原文 → SVG。base 是未写选项时的默认样式。 */
|
|
10
12
|
export declare function renderShushiLayout(source: string, options?: string, base?: StyleOptions, render?: RenderOptions): RenderedSvg;
|
|
11
13
|
/** 语义式一步到位:算式(如 `403-167`)+ 选项原文 → SVG。竖式过程由程序算出。 */
|
|
12
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
|
@@ -7,6 +7,8 @@ import { parseLayout } from "./parse-layout.js";
|
|
|
7
7
|
import { buildSemantic } from "./semantic/index.js";
|
|
8
8
|
import { DEFAULT_STYLE, parseOptions } from "./options.js";
|
|
9
9
|
import { renderLayout } from "./render-svg.js";
|
|
10
|
+
import { layoutToMathML } from "./mathml.js";
|
|
11
|
+
export { layoutToMathML } from "./mathml.js";
|
|
10
12
|
/** 直写布局一步到位:原文 + 选项原文 → SVG。base 是未写选项时的默认样式。 */
|
|
11
13
|
export function renderShushiLayout(source, options, base = DEFAULT_STYLE, render = {}) {
|
|
12
14
|
return renderLayout(parseLayout(source), parseOptions(options, base), render);
|
|
@@ -16,3 +18,13 @@ export function renderShushi(expression, options, base = DEFAULT_STYLE, render =
|
|
|
16
18
|
const style = parseOptions(options, base);
|
|
17
19
|
return renderLayout(buildSemantic(expression, style), style, render);
|
|
18
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
|
+
}
|