@cn-math-notation/core 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +27 -2
- package/dist/index.d.ts +11 -0
- package/dist/index.js +17 -0
- package/dist/model.d.ts +47 -0
- package/dist/model.js +7 -0
- package/dist/options.d.ts +41 -0
- package/dist/options.js +69 -0
- package/dist/parse-layout.d.ts +31 -0
- package/dist/parse-layout.js +273 -0
- package/dist/render-svg.d.ts +29 -0
- package/dist/render-svg.js +219 -0
- package/dist/semantic/add-sub.d.ts +6 -0
- package/dist/semantic/add-sub.js +76 -0
- package/dist/semantic/answer.d.ts +9 -0
- package/dist/semantic/answer.js +35 -0
- package/dist/semantic/div.d.ts +8 -0
- package/dist/semantic/div.js +87 -0
- package/dist/semantic/index.d.ts +10 -0
- package/dist/semantic/index.js +29 -0
- package/dist/semantic/mul.d.ts +14 -0
- package/dist/semantic/mul.js +107 -0
- package/dist/semantic/numbers.d.ts +37 -0
- package/dist/semantic/numbers.js +66 -0
- package/dist/semantic/parse-expr.d.ts +16 -0
- package/dist/semantic/parse-expr.js +40 -0
- package/package.json +46 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 cn-math-notation contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,28 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cn-math-notation/core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
中国中小学数学写法库的核心:把竖式写成几行文字,渲染成和课本一样的 SVG。**不依赖 KaTeX**,可以单独使用,也可以给其他编辑器写插件。
|
|
4
|
+
|
|
5
|
+
<img src="https://raw.githubusercontent.com/n7tequila/cn-math-notation/main/docs/images/sem-sub-zero.svg" alt="403−167 竖式" height="150" /> <img src="https://raw.githubusercontent.com/n7tequila/cn-math-notation/main/docs/images/sem-div.svg" alt="812÷4 竖式" height="250" />
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @cn-math-notation/core
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { renderShushi, renderShushiLayout } from "@cn-math-notation/core";
|
|
13
|
+
|
|
14
|
+
// 语义式:只写算式,程序按课本步骤算出竖式
|
|
15
|
+
const { svg, label } = renderShushi("403-167");
|
|
16
|
+
|
|
17
|
+
// 直写布局:逐行写出,写什么画什么(例如孩子写错的过程)
|
|
18
|
+
const layout = renderShushiLayout(String.raw`\tui{4} 0 3 \\ - 1 6 7 \\ \hline \err{34} 6`);
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
- `svg`:SVG 字符串,颜色跟随外层文字(`currentColor`),尺寸以 em 计。
|
|
22
|
+
- `label`:给屏幕阅读器的文字描述。
|
|
23
|
+
|
|
24
|
+
在网页里配合 KaTeX 使用,请用 [@cn-math-notation/katex](https://www.npmjs.com/package/@cn-math-notation/katex)。
|
|
25
|
+
|
|
26
|
+
完整写法、样式选项与例子见 [GitHub](https://github.com/n7tequila/cn-math-notation) 与[使用说明](https://github.com/n7tequila/cn-math-notation/blob/main/docs/usage.md)。
|
|
27
|
+
|
|
28
|
+
许可:MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export type * from "./model.ts";
|
|
2
|
+
export { buildSemantic, parseExpression, ExpressionError, DIGIT_COLORS, type Expression } from "./semantic/index.ts";
|
|
3
|
+
export { parseLayout, tokenize, assignColumns, LayoutSyntaxError } from "./parse-layout.ts";
|
|
4
|
+
export { renderLayout, describe, FONT_SIZE, COLORS, type RenderedSvg, type RenderOptions, type RootDisplay, } from "./render-svg.ts";
|
|
5
|
+
export { DEFAULT_STYLE, parseOptions, OptionError, type StyleOptions, type CarryAt, type OperatorPlacement, type MulMode, type ProcessMode, } from "./options.ts";
|
|
6
|
+
import { type StyleOptions } from "./options.ts";
|
|
7
|
+
import { type RenderedSvg, type RenderOptions } from "./render-svg.ts";
|
|
8
|
+
/** 直写布局一步到位:原文 + 选项原文 → SVG。base 是未写选项时的默认样式。 */
|
|
9
|
+
export declare function renderShushiLayout(source: string, options?: string, base?: StyleOptions, render?: RenderOptions): RenderedSvg;
|
|
10
|
+
/** 语义式一步到位:算式(如 `403-167`)+ 选项原文 → SVG。竖式过程由程序算出。 */
|
|
11
|
+
export declare function renderShushi(expression: string, options?: string, base?: StyleOptions, render?: RenderOptions): RenderedSvg;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export { buildSemantic, parseExpression, ExpressionError, DIGIT_COLORS } from "./semantic/index.js";
|
|
2
|
+
export { parseLayout, tokenize, assignColumns, LayoutSyntaxError } from "./parse-layout.js";
|
|
3
|
+
export { renderLayout, describe, FONT_SIZE, COLORS, } from "./render-svg.js";
|
|
4
|
+
export { DEFAULT_STYLE, parseOptions, OptionError, } from "./options.js";
|
|
5
|
+
import { parseLayout } from "./parse-layout.js";
|
|
6
|
+
import { buildSemantic } from "./semantic/index.js";
|
|
7
|
+
import { DEFAULT_STYLE, parseOptions } from "./options.js";
|
|
8
|
+
import { renderLayout } from "./render-svg.js";
|
|
9
|
+
/** 直写布局一步到位:原文 + 选项原文 → SVG。base 是未写选项时的默认样式。 */
|
|
10
|
+
export function renderShushiLayout(source, options, base = DEFAULT_STYLE, render = {}) {
|
|
11
|
+
return renderLayout(parseLayout(source), parseOptions(options, base), render);
|
|
12
|
+
}
|
|
13
|
+
/** 语义式一步到位:算式(如 `403-167`)+ 选项原文 → SVG。竖式过程由程序算出。 */
|
|
14
|
+
export function renderShushi(expression, options, base = DEFAULT_STYLE, render = {}) {
|
|
15
|
+
const style = parseOptions(options, base);
|
|
16
|
+
return renderLayout(buildSemantic(expression, style), style, render);
|
|
17
|
+
}
|
package/dist/model.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 竖式布局模型(第一期:整数与小数竖式、长除法)。
|
|
3
|
+
*
|
|
4
|
+
* 列号:个位为 0,向高位为正,向小数位为负;小数点本身占 -0.5 这一“窄列”。
|
|
5
|
+
* 设计依据:docs/design/2026-11-19-设计草案.md §3、§11。
|
|
6
|
+
*/
|
|
7
|
+
export type CellMark = "tui" | "err" | "hong" | "bu" | "hua";
|
|
8
|
+
export type CellContent = {
|
|
9
|
+
readonly kind: "digit";
|
|
10
|
+
readonly text: string;
|
|
11
|
+
} | {
|
|
12
|
+
readonly kind: "point";
|
|
13
|
+
} | {
|
|
14
|
+
readonly kind: "blank";
|
|
15
|
+
};
|
|
16
|
+
export interface Cell {
|
|
17
|
+
readonly col: number;
|
|
18
|
+
readonly content: CellContent;
|
|
19
|
+
readonly marks: readonly CellMark[];
|
|
20
|
+
readonly color?: string;
|
|
21
|
+
}
|
|
22
|
+
export type Operator = "+" | "-" | "×" | "÷";
|
|
23
|
+
/** 普通数字行(加数、部分积、结果、除法各步)。 */
|
|
24
|
+
export interface DigitRow {
|
|
25
|
+
readonly kind: "digits";
|
|
26
|
+
readonly cells: readonly Cell[];
|
|
27
|
+
readonly operator?: Operator;
|
|
28
|
+
/** 长除法:商行。 */
|
|
29
|
+
readonly quotient?: true;
|
|
30
|
+
/** 长除法:被除数行,带除数。 */
|
|
31
|
+
readonly divisor?: string;
|
|
32
|
+
}
|
|
33
|
+
/** 进位行:每个数字记在“进到的那一列”。 */
|
|
34
|
+
export interface CarryRow {
|
|
35
|
+
readonly kind: "carry";
|
|
36
|
+
readonly cells: readonly Cell[];
|
|
37
|
+
}
|
|
38
|
+
/** 横线:画在前一行与后一行之间。 */
|
|
39
|
+
export interface RuleRow {
|
|
40
|
+
readonly kind: "hline";
|
|
41
|
+
}
|
|
42
|
+
export type Row = DigitRow | CarryRow | RuleRow;
|
|
43
|
+
export interface Layout {
|
|
44
|
+
readonly rows: readonly Row[];
|
|
45
|
+
/** 是否出现过小数点(决定按小数点对齐、是否画数位虚线等)。 */
|
|
46
|
+
readonly hasDecimal: boolean;
|
|
47
|
+
}
|
package/dist/model.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 写法样式选项。默认值即沪教版(维护者 2026-11-25 裁决,设计草案 §11.1)。
|
|
3
|
+
*/
|
|
4
|
+
export type CarryAt = "s" | "sw";
|
|
5
|
+
export type OperatorPlacement = "far" | "adjacent";
|
|
6
|
+
/** 一位数乘法:简写(进位小字)或分步式(每位分别乘再相加)。 */
|
|
7
|
+
export type MulMode = "compact" | "expanded";
|
|
8
|
+
/**
|
|
9
|
+
* 语义式是否画计算过程(进位、退位点、补的 0、部分积、除法各步)。
|
|
10
|
+
* auto:没写孩子答案时画;写了孩子答案时不画——程序按正确算法画出的过程会被误当成孩子写的。
|
|
11
|
+
*/
|
|
12
|
+
export type ProcessMode = "auto" | "show" | "hide";
|
|
13
|
+
export interface StyleOptions {
|
|
14
|
+
/** 进位水平位置:s = 进到的那一列正下;sw = 产生进位那一位的左下。 */
|
|
15
|
+
readonly carryAt: CarryAt;
|
|
16
|
+
/** 数位虚线。 */
|
|
17
|
+
readonly guides: boolean;
|
|
18
|
+
/** 多位乘法是否画进位(语义式用;直写布局按写的为准)。 */
|
|
19
|
+
readonly multiCarry: boolean;
|
|
20
|
+
/** 小数位数不够时补 0(语义式用)。 */
|
|
21
|
+
readonly padZero: boolean;
|
|
22
|
+
/** 按乘数位着色(语义式用)。 */
|
|
23
|
+
readonly colorByDigit: boolean;
|
|
24
|
+
/** 运算符放最左(far)还是紧挨数字(adjacent)。 */
|
|
25
|
+
readonly operatorPlacement: OperatorPlacement;
|
|
26
|
+
/** 一位数乘法的写法(语义式用)。 */
|
|
27
|
+
readonly mode: MulMode;
|
|
28
|
+
/** 小数结果末尾的 0 划掉(语义式用,维护者 2026-11-25 定默认开)。 */
|
|
29
|
+
readonly strikeZero: boolean;
|
|
30
|
+
/** 是否画计算过程(语义式用)。 */
|
|
31
|
+
readonly process: ProcessMode;
|
|
32
|
+
}
|
|
33
|
+
export declare const DEFAULT_STYLE: StyleOptions;
|
|
34
|
+
export declare class OptionError extends Error {
|
|
35
|
+
readonly name = "OptionError";
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* 解析方括号里的选项,如 `carryAt=sw, guides=false, multiCarry`。
|
|
39
|
+
* 只写键名表示 true。未知键或非法值抛 OptionError。
|
|
40
|
+
*/
|
|
41
|
+
export declare function parseOptions(source: string | undefined, base?: StyleOptions): StyleOptions;
|
package/dist/options.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 写法样式选项。默认值即沪教版(维护者 2026-11-25 裁决,设计草案 §11.1)。
|
|
3
|
+
*/
|
|
4
|
+
export const DEFAULT_STYLE = {
|
|
5
|
+
carryAt: "s",
|
|
6
|
+
guides: true,
|
|
7
|
+
multiCarry: false,
|
|
8
|
+
padZero: true,
|
|
9
|
+
colorByDigit: false,
|
|
10
|
+
operatorPlacement: "far",
|
|
11
|
+
mode: "compact",
|
|
12
|
+
strikeZero: true,
|
|
13
|
+
process: "auto",
|
|
14
|
+
};
|
|
15
|
+
const BOOLEAN_KEYS = ["guides", "multiCarry", "padZero", "colorByDigit", "strikeZero"];
|
|
16
|
+
export class OptionError extends Error {
|
|
17
|
+
name = "OptionError";
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* 解析方括号里的选项,如 `carryAt=sw, guides=false, multiCarry`。
|
|
21
|
+
* 只写键名表示 true。未知键或非法值抛 OptionError。
|
|
22
|
+
*/
|
|
23
|
+
export function parseOptions(source, base = DEFAULT_STYLE) {
|
|
24
|
+
if (source === undefined || source.trim() === "")
|
|
25
|
+
return base;
|
|
26
|
+
let result = base;
|
|
27
|
+
for (const part of source.split(",")) {
|
|
28
|
+
const item = part.trim();
|
|
29
|
+
if (item === "")
|
|
30
|
+
continue;
|
|
31
|
+
const eq = item.indexOf("=");
|
|
32
|
+
const key = (eq === -1 ? item : item.slice(0, eq)).trim();
|
|
33
|
+
const value = eq === -1 ? "true" : item.slice(eq + 1).trim();
|
|
34
|
+
result = applyOption(result, key, value);
|
|
35
|
+
}
|
|
36
|
+
return result;
|
|
37
|
+
}
|
|
38
|
+
function applyOption(opts, key, value) {
|
|
39
|
+
if (BOOLEAN_KEYS.includes(key)) {
|
|
40
|
+
if (value !== "true" && value !== "false") {
|
|
41
|
+
throw new OptionError(`选项 ${key} 只能是 true 或 false,收到 "${value}"`);
|
|
42
|
+
}
|
|
43
|
+
return { ...opts, [key]: value === "true" };
|
|
44
|
+
}
|
|
45
|
+
if (key === "carryAt") {
|
|
46
|
+
if (value !== "s" && value !== "sw")
|
|
47
|
+
throw new OptionError(`carryAt 只能是 s 或 sw,收到 "${value}"`);
|
|
48
|
+
return { ...opts, carryAt: value };
|
|
49
|
+
}
|
|
50
|
+
if (key === "operatorPlacement") {
|
|
51
|
+
if (value !== "far" && value !== "adjacent") {
|
|
52
|
+
throw new OptionError(`operatorPlacement 只能是 far 或 adjacent,收到 "${value}"`);
|
|
53
|
+
}
|
|
54
|
+
return { ...opts, operatorPlacement: value };
|
|
55
|
+
}
|
|
56
|
+
if (key === "mode") {
|
|
57
|
+
if (value !== "compact" && value !== "expanded") {
|
|
58
|
+
throw new OptionError(`mode 只能是 compact 或 expanded,收到 "${value}"`);
|
|
59
|
+
}
|
|
60
|
+
return { ...opts, mode: value };
|
|
61
|
+
}
|
|
62
|
+
if (key === "process") {
|
|
63
|
+
if (value !== "auto" && value !== "show" && value !== "hide") {
|
|
64
|
+
throw new OptionError(`process 只能是 auto、show 或 hide,收到 "${value}"`);
|
|
65
|
+
}
|
|
66
|
+
return { ...opts, process: value };
|
|
67
|
+
}
|
|
68
|
+
throw new OptionError(`未知选项 "${key}"`);
|
|
69
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 直写布局解析:`\shushi*{…}` 花括号里的原文 → Layout。
|
|
3
|
+
* 语法见 docs/design/2026-11-25-直写布局语法试写.md(R1~R9;R10 的 & 分格属第三期,暂报错)。
|
|
4
|
+
*/
|
|
5
|
+
import type { Cell, CellContent, CellMark, Layout } from "./model.ts";
|
|
6
|
+
export declare class LayoutSyntaxError extends Error {
|
|
7
|
+
readonly name = "LayoutSyntaxError";
|
|
8
|
+
}
|
|
9
|
+
type Token = {
|
|
10
|
+
readonly t: "cmd";
|
|
11
|
+
readonly name: string;
|
|
12
|
+
} | {
|
|
13
|
+
readonly t: "open";
|
|
14
|
+
} | {
|
|
15
|
+
readonly t: "close";
|
|
16
|
+
} | {
|
|
17
|
+
readonly t: "newrow";
|
|
18
|
+
} | {
|
|
19
|
+
readonly t: "char";
|
|
20
|
+
readonly ch: string;
|
|
21
|
+
};
|
|
22
|
+
export declare function tokenize(source: string): Token[];
|
|
23
|
+
interface RawCell {
|
|
24
|
+
readonly content: CellContent;
|
|
25
|
+
readonly marks: readonly CellMark[];
|
|
26
|
+
readonly color?: string;
|
|
27
|
+
}
|
|
28
|
+
/** 给一行的格子编列号:有小数点按小数点,否则按最右一格为个位。 */
|
|
29
|
+
export declare function assignColumns(raw: readonly RawCell[]): Cell[];
|
|
30
|
+
export declare function parseLayout(source: string): Layout;
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
export class LayoutSyntaxError extends Error {
|
|
2
|
+
name = "LayoutSyntaxError";
|
|
3
|
+
}
|
|
4
|
+
const MARK_COMMANDS = {
|
|
5
|
+
tui: "tui",
|
|
6
|
+
borrow: "tui",
|
|
7
|
+
err: "err",
|
|
8
|
+
hong: "hong",
|
|
9
|
+
hl: "hong",
|
|
10
|
+
bu: "bu",
|
|
11
|
+
pad: "bu",
|
|
12
|
+
hua: "hua",
|
|
13
|
+
strike: "hua",
|
|
14
|
+
};
|
|
15
|
+
const OPERATOR_CHARS = {
|
|
16
|
+
"+": "+",
|
|
17
|
+
"-": "-",
|
|
18
|
+
"−": "-",
|
|
19
|
+
"×": "×",
|
|
20
|
+
"÷": "÷",
|
|
21
|
+
};
|
|
22
|
+
const OPERATOR_COMMANDS = { times: "×", div: "÷" };
|
|
23
|
+
export function tokenize(source) {
|
|
24
|
+
const tokens = [];
|
|
25
|
+
let i = 0;
|
|
26
|
+
while (i < source.length) {
|
|
27
|
+
const ch = source[i];
|
|
28
|
+
if (/\s/.test(ch)) {
|
|
29
|
+
i += 1;
|
|
30
|
+
}
|
|
31
|
+
else if (ch === "\\") {
|
|
32
|
+
const next = source[i + 1];
|
|
33
|
+
if (next === "\\") {
|
|
34
|
+
tokens.push({ t: "newrow" });
|
|
35
|
+
i += 2;
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
const m = /^[a-zA-Z]+/.exec(source.slice(i + 1));
|
|
39
|
+
if (m === null)
|
|
40
|
+
throw new LayoutSyntaxError(`第 ${i + 1} 个字符处的反斜杠后面不是命令名`);
|
|
41
|
+
tokens.push({ t: "cmd", name: m[0] });
|
|
42
|
+
i += 1 + m[0].length;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
else if (ch === "{") {
|
|
46
|
+
tokens.push({ t: "open" });
|
|
47
|
+
i += 1;
|
|
48
|
+
}
|
|
49
|
+
else if (ch === "}") {
|
|
50
|
+
tokens.push({ t: "close" });
|
|
51
|
+
i += 1;
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
tokens.push({ t: "char", ch });
|
|
55
|
+
i += 1;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return tokens;
|
|
59
|
+
}
|
|
60
|
+
/** 按顶层的 `\\` 切成行段。 */
|
|
61
|
+
function splitRows(tokens) {
|
|
62
|
+
const segments = [[]];
|
|
63
|
+
let depth = 0;
|
|
64
|
+
for (const tok of tokens) {
|
|
65
|
+
if (tok.t === "open")
|
|
66
|
+
depth += 1;
|
|
67
|
+
if (tok.t === "close")
|
|
68
|
+
depth -= 1;
|
|
69
|
+
if (depth < 0)
|
|
70
|
+
throw new LayoutSyntaxError("多了一个 }");
|
|
71
|
+
if (tok.t === "newrow" && depth === 0) {
|
|
72
|
+
segments.push([]);
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
segments[segments.length - 1].push(tok);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (depth !== 0)
|
|
79
|
+
throw new LayoutSyntaxError("花括号没有配对,少了 }");
|
|
80
|
+
return segments;
|
|
81
|
+
}
|
|
82
|
+
class RowParser {
|
|
83
|
+
tokens;
|
|
84
|
+
pos = 0;
|
|
85
|
+
flags = { carry: false, quotient: false, divisor: undefined, operator: undefined };
|
|
86
|
+
constructor(tokens) {
|
|
87
|
+
this.tokens = tokens;
|
|
88
|
+
}
|
|
89
|
+
parse() {
|
|
90
|
+
return this.items(this.tokens.length, { marks: [], color: undefined }, true);
|
|
91
|
+
}
|
|
92
|
+
/** 读一个 {…} 组,返回组内 token 的范围终点(不含 })。 */
|
|
93
|
+
group(what) {
|
|
94
|
+
const open = this.tokens[this.pos];
|
|
95
|
+
if (open?.t !== "open")
|
|
96
|
+
throw new LayoutSyntaxError(`${what} 后面要跟 {…}`);
|
|
97
|
+
let depth = 0;
|
|
98
|
+
for (let j = this.pos; j < this.tokens.length; j += 1) {
|
|
99
|
+
const tok = this.tokens[j];
|
|
100
|
+
if (tok.t === "open")
|
|
101
|
+
depth += 1;
|
|
102
|
+
if (tok.t === "close") {
|
|
103
|
+
depth -= 1;
|
|
104
|
+
if (depth === 0) {
|
|
105
|
+
const range = { start: this.pos + 1, end: j };
|
|
106
|
+
this.pos = j + 1;
|
|
107
|
+
return range;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
throw new LayoutSyntaxError(`${what} 的花括号没有配对`);
|
|
112
|
+
}
|
|
113
|
+
groupText(what) {
|
|
114
|
+
const { start, end } = this.group(what);
|
|
115
|
+
return this.tokens
|
|
116
|
+
.slice(start, end)
|
|
117
|
+
.map((tok) => (tok.t === "char" ? tok.ch : tok.t === "cmd" ? `\\${tok.name}` : ""))
|
|
118
|
+
.join("");
|
|
119
|
+
}
|
|
120
|
+
subItems(what, ctx) {
|
|
121
|
+
const { start, end } = this.group(what);
|
|
122
|
+
const saved = this.pos;
|
|
123
|
+
this.pos = start;
|
|
124
|
+
const cells = this.items(end, ctx, false);
|
|
125
|
+
this.pos = saved;
|
|
126
|
+
return cells;
|
|
127
|
+
}
|
|
128
|
+
items(end, ctx, rowLevel) {
|
|
129
|
+
const cells = [];
|
|
130
|
+
while (this.pos < end) {
|
|
131
|
+
const tok = this.tokens[this.pos];
|
|
132
|
+
const atRowStart = rowLevel && cells.length === 0 && this.flags.operator === undefined;
|
|
133
|
+
if (tok.t === "char") {
|
|
134
|
+
this.pos += 1;
|
|
135
|
+
cells.push(...this.charCell(tok.ch, ctx, atRowStart));
|
|
136
|
+
}
|
|
137
|
+
else if (tok.t === "cmd") {
|
|
138
|
+
this.pos += 1;
|
|
139
|
+
cells.push(...this.command(tok.name, ctx, atRowStart, cells.length === 0));
|
|
140
|
+
}
|
|
141
|
+
else if (tok.t === "open") {
|
|
142
|
+
cells.push(...this.subItems("{", ctx));
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
throw new LayoutSyntaxError("多了一个 }");
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return cells;
|
|
149
|
+
}
|
|
150
|
+
charCell(ch, ctx, atRowStart) {
|
|
151
|
+
if (/[0-9]/.test(ch))
|
|
152
|
+
return [cell({ kind: "digit", text: ch }, ctx)];
|
|
153
|
+
if (ch === ".")
|
|
154
|
+
return [cell({ kind: "point" }, ctx)];
|
|
155
|
+
if (ch === "~")
|
|
156
|
+
return [cell({ kind: "blank" }, ctx)];
|
|
157
|
+
const op = OPERATOR_CHARS[ch];
|
|
158
|
+
if (op !== undefined)
|
|
159
|
+
return this.operator(op, atRowStart);
|
|
160
|
+
if (ch === "&")
|
|
161
|
+
throw new LayoutSyntaxError("& 分格(多字符的项)属第三期,暂不支持");
|
|
162
|
+
throw new LayoutSyntaxError(`不认识的字符 "${ch}"`);
|
|
163
|
+
}
|
|
164
|
+
operator(op, atRowStart) {
|
|
165
|
+
if (this.flags.carry)
|
|
166
|
+
throw new LayoutSyntaxError("进位行(\\jin)里不能有运算符");
|
|
167
|
+
if (!atRowStart)
|
|
168
|
+
throw new LayoutSyntaxError(`运算符 ${op} 只能写在一行的开头`);
|
|
169
|
+
this.flags.operator = op;
|
|
170
|
+
return [];
|
|
171
|
+
}
|
|
172
|
+
command(name, ctx, atRowStart, noCellsYet) {
|
|
173
|
+
const mark = MARK_COMMANDS[name];
|
|
174
|
+
if (mark !== undefined) {
|
|
175
|
+
return this.subItems(`\\${name}`, { ...ctx, marks: [...ctx.marks, mark] });
|
|
176
|
+
}
|
|
177
|
+
const op = OPERATOR_COMMANDS[name];
|
|
178
|
+
if (op !== undefined)
|
|
179
|
+
return this.operator(op, atRowStart);
|
|
180
|
+
switch (name) {
|
|
181
|
+
case "textcolor": {
|
|
182
|
+
const color = this.groupText("\\textcolor 的颜色").trim();
|
|
183
|
+
if (!/^[#a-zA-Z0-9]+$/.test(color))
|
|
184
|
+
throw new LayoutSyntaxError(`颜色写法不对:"${color}"`);
|
|
185
|
+
return this.subItems("\\textcolor", { ...ctx, color });
|
|
186
|
+
}
|
|
187
|
+
case "jin":
|
|
188
|
+
case "carry":
|
|
189
|
+
this.flags.carry = true;
|
|
190
|
+
return this.subItems(`\\${name}`, ctx);
|
|
191
|
+
case "shang":
|
|
192
|
+
if (!noCellsYet)
|
|
193
|
+
throw new LayoutSyntaxError("\\shang 只能写在一行的开头");
|
|
194
|
+
this.flags.quotient = true;
|
|
195
|
+
return [];
|
|
196
|
+
case "chu": {
|
|
197
|
+
if (!noCellsYet)
|
|
198
|
+
throw new LayoutSyntaxError("\\chu 只能写在一行的开头");
|
|
199
|
+
const divisor = this.groupText("\\chu").trim();
|
|
200
|
+
if (!/^[0-9.]+$/.test(divisor))
|
|
201
|
+
throw new LayoutSyntaxError(`除数只能是数字,收到 "${divisor}"`);
|
|
202
|
+
this.flags.divisor = divisor;
|
|
203
|
+
return [];
|
|
204
|
+
}
|
|
205
|
+
case "hline":
|
|
206
|
+
throw new LayoutSyntaxError("\\hline 要单独放在两行之间(写在 \\\\ 之后、下一行之前)");
|
|
207
|
+
default:
|
|
208
|
+
throw new LayoutSyntaxError(`不认识的命令 \\${name}`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
function cell(content, ctx) {
|
|
213
|
+
return ctx.color === undefined ? { content, marks: ctx.marks } : { content, marks: ctx.marks, color: ctx.color };
|
|
214
|
+
}
|
|
215
|
+
/** 给一行的格子编列号:有小数点按小数点,否则按最右一格为个位。 */
|
|
216
|
+
export function assignColumns(raw) {
|
|
217
|
+
const points = raw.flatMap((c, i) => (c.content.kind === "point" ? [i] : []));
|
|
218
|
+
if (points.length > 1)
|
|
219
|
+
throw new LayoutSyntaxError("一行里出现了两个小数点");
|
|
220
|
+
const p = points[0];
|
|
221
|
+
return raw.map((c, i) => {
|
|
222
|
+
let col;
|
|
223
|
+
if (p === undefined)
|
|
224
|
+
col = raw.length - 1 - i;
|
|
225
|
+
else if (i < p)
|
|
226
|
+
col = p - 1 - i;
|
|
227
|
+
else if (i === p)
|
|
228
|
+
col = -0.5;
|
|
229
|
+
else
|
|
230
|
+
col = -(i - p);
|
|
231
|
+
return { col, ...c };
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
function buildRow(raw, flags) {
|
|
235
|
+
const cells = assignColumns(raw);
|
|
236
|
+
if (flags.carry) {
|
|
237
|
+
if (flags.operator !== undefined || flags.quotient || flags.divisor !== undefined) {
|
|
238
|
+
throw new LayoutSyntaxError("进位行(\\jin)里不能再有运算符、\\shang 或 \\chu");
|
|
239
|
+
}
|
|
240
|
+
if (cells.some((c) => c.content.kind === "point"))
|
|
241
|
+
throw new LayoutSyntaxError("进位行里不能有小数点");
|
|
242
|
+
return { kind: "carry", cells };
|
|
243
|
+
}
|
|
244
|
+
if (cells.length === 0)
|
|
245
|
+
throw new LayoutSyntaxError("这一行没有数字");
|
|
246
|
+
return {
|
|
247
|
+
kind: "digits",
|
|
248
|
+
cells,
|
|
249
|
+
...(flags.operator === undefined ? {} : { operator: flags.operator }),
|
|
250
|
+
...(flags.quotient ? { quotient: true } : {}),
|
|
251
|
+
...(flags.divisor === undefined ? {} : { divisor: flags.divisor }),
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
export function parseLayout(source) {
|
|
255
|
+
const rows = [];
|
|
256
|
+
for (const segment of splitRows(tokenize(source))) {
|
|
257
|
+
let k = 0;
|
|
258
|
+
while (segment[k]?.t === "cmd" && segment[k].name === "hline") {
|
|
259
|
+
rows.push({ kind: "hline" });
|
|
260
|
+
k += 1;
|
|
261
|
+
}
|
|
262
|
+
const rest = segment.slice(k);
|
|
263
|
+
if (rest.length === 0)
|
|
264
|
+
continue;
|
|
265
|
+
const parser = new RowParser(rest);
|
|
266
|
+
const raw = parser.parse();
|
|
267
|
+
rows.push(buildRow(raw, parser.flags));
|
|
268
|
+
}
|
|
269
|
+
if (!rows.some((r) => r.kind === "digits"))
|
|
270
|
+
throw new LayoutSyntaxError("竖式里至少要有一行数字");
|
|
271
|
+
const hasDecimal = rows.some((r) => r.kind !== "hline" && r.cells.some((c) => c.content.kind === "point"));
|
|
272
|
+
return { rows, hasDecimal };
|
|
273
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 布局 → SVG 字符串。几何单位是 px,1em = FONT_SIZE px;对外同时给出 em 尺寸,便于嵌入 KaTeX。
|
|
3
|
+
* 画法依据沪教版样本(设计草案 §11)。
|
|
4
|
+
*/
|
|
5
|
+
import type { Layout } from "./model.ts";
|
|
6
|
+
import { type StyleOptions } from "./options.ts";
|
|
7
|
+
export declare const FONT_SIZE = 24;
|
|
8
|
+
export declare const COLORS: {
|
|
9
|
+
readonly ink: "currentColor";
|
|
10
|
+
readonly teach: "#d4402b";
|
|
11
|
+
readonly guide: "#8fa9c2";
|
|
12
|
+
readonly errBg: "#ffd866";
|
|
13
|
+
};
|
|
14
|
+
export interface RenderedSvg {
|
|
15
|
+
readonly svg: string;
|
|
16
|
+
readonly width: number;
|
|
17
|
+
readonly height: number;
|
|
18
|
+
readonly widthEm: number;
|
|
19
|
+
readonly heightEm: number;
|
|
20
|
+
/** 朗读用的文字描述。 */
|
|
21
|
+
readonly label: string;
|
|
22
|
+
}
|
|
23
|
+
export declare function describe(layout: Layout): string;
|
|
24
|
+
/** inline-block:单独使用(默认);block:嵌进外层盒子(如 KaTeX 插件),避免基线错位撑出空白。 */
|
|
25
|
+
export type RootDisplay = "inline-block" | "block";
|
|
26
|
+
export interface RenderOptions {
|
|
27
|
+
readonly display?: RootDisplay;
|
|
28
|
+
}
|
|
29
|
+
export declare function renderLayout(layout: Layout, style?: StyleOptions, render?: RenderOptions): RenderedSvg;
|