jpfun 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.
Files changed (104) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +134 -0
  3. package/dist/diagnostic.d.ts +27 -0
  4. package/dist/diagnostic.js +141 -0
  5. package/dist/functions/ASTtypes.d.ts +115 -0
  6. package/dist/functions/ASTtypes.js +187 -0
  7. package/dist/functions/bar/index.d.ts +2 -0
  8. package/dist/functions/bar/index.js +180 -0
  9. package/dist/functions/beam/auto.d.ts +4 -0
  10. package/dist/functions/beam/auto.js +202 -0
  11. package/dist/functions/beam/index.d.ts +2 -0
  12. package/dist/functions/beam/index.js +54 -0
  13. package/dist/functions/beam/layout.d.ts +9 -0
  14. package/dist/functions/beam/layout.js +233 -0
  15. package/dist/functions/box/index.d.ts +2 -0
  16. package/dist/functions/box/index.js +202 -0
  17. package/dist/functions/br/index.d.ts +2 -0
  18. package/dist/functions/br/index.js +83 -0
  19. package/dist/functions/dash/index.d.ts +2 -0
  20. package/dist/functions/dash/index.js +61 -0
  21. package/dist/functions/default.d.ts +2 -0
  22. package/dist/functions/default.js +32 -0
  23. package/dist/functions/div/index.d.ts +50 -0
  24. package/dist/functions/div/index.js +190 -0
  25. package/dist/functions/dot/index.d.ts +2 -0
  26. package/dist/functions/dot/index.js +160 -0
  27. package/dist/functions/grace/index.d.ts +84 -0
  28. package/dist/functions/grace/index.js +464 -0
  29. package/dist/functions/key/index.d.ts +2 -0
  30. package/dist/functions/key/index.js +40 -0
  31. package/dist/functions/note/accidentals.d.ts +10 -0
  32. package/dist/functions/note/accidentals.js +60 -0
  33. package/dist/functions/note/index.d.ts +2 -0
  34. package/dist/functions/note/index.js +284 -0
  35. package/dist/functions/note/noteNameFSM.d.ts +8 -0
  36. package/dist/functions/note/noteNameFSM.js +192 -0
  37. package/dist/functions/over/index.d.ts +2 -0
  38. package/dist/functions/over/index.js +307 -0
  39. package/dist/functions/page/index.d.ts +20 -0
  40. package/dist/functions/page/index.js +63 -0
  41. package/dist/functions/set/index.d.ts +2 -0
  42. package/dist/functions/set/index.js +55 -0
  43. package/dist/functions/stack/index.d.ts +2 -0
  44. package/dist/functions/stack/index.js +164 -0
  45. package/dist/functions/tempo/index.d.ts +2 -0
  46. package/dist/functions/tempo/index.js +37 -0
  47. package/dist/functions/text/index.d.ts +2 -0
  48. package/dist/functions/text/index.js +65 -0
  49. package/dist/functions/tie/index.d.ts +2 -0
  50. package/dist/functions/tie/index.js +301 -0
  51. package/dist/functions/voice/index.d.ts +3 -0
  52. package/dist/functions/voice/index.js +714 -0
  53. package/dist/index.d.ts +17 -0
  54. package/dist/index.js +17 -0
  55. package/dist/layout/default.d.ts +12 -0
  56. package/dist/layout/default.js +27 -0
  57. package/dist/layout/engine.d.ts +47 -0
  58. package/dist/layout/engine.js +410 -0
  59. package/dist/layout/model.d.ts +73 -0
  60. package/dist/layout/model.js +422 -0
  61. package/dist/layout/page.d.ts +27 -0
  62. package/dist/layout/page.js +121 -0
  63. package/dist/layout/types.d.ts +197 -0
  64. package/dist/layout/types.js +1 -0
  65. package/dist/lowering/loweringContext.d.ts +126 -0
  66. package/dist/lowering/loweringContext.js +625 -0
  67. package/dist/lowering/track.d.ts +61 -0
  68. package/dist/lowering/track.js +35 -0
  69. package/dist/lowering/types.d.ts +176 -0
  70. package/dist/lowering/types.js +82 -0
  71. package/dist/parser/grammarType.d.ts +81 -0
  72. package/dist/parser/grammarType.js +1 -0
  73. package/dist/parser/parse-utils/brace-utils.d.ts +1 -0
  74. package/dist/parser/parse-utils/brace-utils.js +29 -0
  75. package/dist/parser/parse-utils/call-utils.d.ts +24 -0
  76. package/dist/parser/parse-utils/call-utils.js +178 -0
  77. package/dist/parser/parse-utils/label-utils.d.ts +4 -0
  78. package/dist/parser/parse-utils/label-utils.js +17 -0
  79. package/dist/parser/parse-utils/length-utils.d.ts +3 -0
  80. package/dist/parser/parse-utils/length-utils.js +20 -0
  81. package/dist/parser/parse-utils/note-utils.d.ts +10 -0
  82. package/dist/parser/parse-utils/note-utils.js +111 -0
  83. package/dist/parser/parserContext.d.ts +93 -0
  84. package/dist/parser/parserContext.js +542 -0
  85. package/dist/parser/preprocess.d.ts +6 -0
  86. package/dist/parser/preprocess.js +193 -0
  87. package/dist/parser/types.d.ts +31 -0
  88. package/dist/parser/types.js +2 -0
  89. package/dist/pipeline.d.ts +36 -0
  90. package/dist/pipeline.js +51 -0
  91. package/dist/render/canvas.d.ts +19 -0
  92. package/dist/render/canvas.js +121 -0
  93. package/dist/render/index.d.ts +5 -0
  94. package/dist/render/index.js +5 -0
  95. package/dist/render/recording.d.ts +46 -0
  96. package/dist/render/recording.js +76 -0
  97. package/dist/render/svg.d.ts +18 -0
  98. package/dist/render/svg.js +126 -0
  99. package/dist/render/text.d.ts +6 -0
  100. package/dist/render/text.js +17 -0
  101. package/dist/render/types.d.ts +86 -0
  102. package/dist/render/types.js +1 -0
  103. package/grammar.md +123 -0
  104. package/package.json +58 -0
@@ -0,0 +1,193 @@
1
+ /**
2
+ * 预处理核心模块(单次扫描):
3
+ * 1. 构建 lineStarts(用于 offset -> 行列映射)
4
+ * 2. 处理 `%` 行注释:仅在非字符串上下文触发,注释文本等长替换为空格
5
+ * 3. 处理行尾连续反斜杠:
6
+ * - 设行尾连续 `\` 个数为 n;
7
+ * - 第 1/3/5... 个 `\` 替换为空格,第 2/4/6... 个保留;
8
+ * - 若 n 为奇数,则该行换行符也替换为空格(续行)
9
+ */
10
+ const CHAR_LF = 10;
11
+ const CHAR_CR = 13;
12
+ const CHAR_TAB = 9;
13
+ const CHAR_VTAB = 11;
14
+ const CHAR_FF = 12;
15
+ const CHAR_SPACE = 32;
16
+ const CHAR_NBSP = 160;
17
+ const CHAR_OGHAM_SPACE_MARK = 5760;
18
+ const CHAR_NARROW_NO_BREAK_SPACE = 8239;
19
+ const CHAR_MEDIUM_MATHEMATICAL_SPACE = 8287;
20
+ const CHAR_IDEOGRAPHIC_SPACE = 12288;
21
+ const CHAR_BOM = 65279;
22
+ const CHAR_QUOTE_DOUBLE = 34;
23
+ const CHAR_BACKSLASH = 92;
24
+ const CHAR_PERCENT = 37;
25
+ // 高频创建空格串,按长度缓存,减少 repeat 带来的重复分配
26
+ // 考虑到后续会频繁解析 保留此全局量
27
+ const SPACE_CACHE = new Map();
28
+ function getSpaces(length) {
29
+ let cached = SPACE_CACHE.get(length);
30
+ if (cached !== undefined)
31
+ return cached;
32
+ cached = " ".repeat(length);
33
+ SPACE_CACHE.set(length, cached);
34
+ return cached;
35
+ }
36
+ /**
37
+ * 判断 非换行空白
38
+ * 说明:CR/LF 由主循环单独处理,这里只负责可被“行尾回看”忽略的空白
39
+ */
40
+ function isNonLineWhitespace(ch) {
41
+ // 热路径优先处理 ASCII
42
+ if (ch === CHAR_SPACE || ch === CHAR_TAB || ch === CHAR_VTAB || ch === CHAR_FF)
43
+ return true;
44
+ if (ch < 128)
45
+ return false;
46
+ return (ch === CHAR_NBSP ||
47
+ ch === CHAR_OGHAM_SPACE_MARK ||
48
+ (ch >= 8192 && ch <= 8202) ||
49
+ ch === CHAR_NARROW_NO_BREAK_SPACE ||
50
+ ch === CHAR_MEDIUM_MATHEMATICAL_SPACE ||
51
+ ch === CHAR_IDEOGRAPHIC_SPACE ||
52
+ ch === CHAR_BOM);
53
+ }
54
+ export function preprocessSource(source) {
55
+ const sourceLength = source.length;
56
+ const lineStarts = [0];
57
+ const commentSpans = [];
58
+ // 扁平区间表:[start0, end0, start1, end1, ...]
59
+ // 约束:按起点递增写入;相邻/重叠区间会就地合并,减少后续 chunks 数量
60
+ const replaceRanges = [];
61
+ const pushReplaceRange = (start, end) => {
62
+ if (start >= end)
63
+ return;
64
+ const n = replaceRanges.length;
65
+ if (n >= 2 && start <= replaceRanges[n - 1]) {
66
+ if (end > replaceRanges[n - 1])
67
+ replaceRanges[n - 1] = end;
68
+ return;
69
+ }
70
+ replaceRanges.push(start, end);
71
+ };
72
+ const pushTailBackslashMask = (runStart, runCount) => {
73
+ if (runCount <= 0)
74
+ return;
75
+ const runEnd = runStart + runCount;
76
+ for (let p = runStart; p < runEnd; p += 2)
77
+ pushReplaceRange(p, p + 1);
78
+ };
79
+ /**
80
+ * 扫描状态说明:
81
+ * - inQuote:0=不在字符串;其他值为当前引号字符码
82
+ * - escaped:仅在字符串内有效,表示上一个字符是 `\`
83
+ * - pendingCommentStart:>=0 表示已遇到 `%`,等待到行尾/EOF 收口注释
84
+ * - lastSignificantIndex:当前行最后一个“非换行空白”字符位置
85
+ * - tailBackslashRunStart/tailBackslashRunCount:
86
+ * 当前行末尾候选连续 `\` 片段(允许后面跟空白),用于换行处一次性判定
87
+ */
88
+ let inQuote = 0;
89
+ let escaped = false;
90
+ let pendingCommentStart = -1;
91
+ let lastSignificantIndex = -1;
92
+ let tailBackslashRunStart = -1;
93
+ let tailBackslashRunCount = 0;
94
+ const updateLineTailState = (index, ch) => {
95
+ if (ch === CHAR_BACKSLASH) {
96
+ if (tailBackslashRunCount > 0 && lastSignificantIndex + 1 === index)
97
+ tailBackslashRunCount++;
98
+ else {
99
+ tailBackslashRunStart = index;
100
+ tailBackslashRunCount = 1;
101
+ }
102
+ lastSignificantIndex = index;
103
+ return;
104
+ }
105
+ tailBackslashRunStart = -1;
106
+ tailBackslashRunCount = 0;
107
+ lastSignificantIndex = index;
108
+ };
109
+ for (let i = 0; i < sourceLength;) {
110
+ const ch = source.charCodeAt(i);
111
+ // 换行是行内规则的结算点:先处理行尾 `\`,再收口注释,最后决定是否吃换行
112
+ if (ch === CHAR_CR || ch === CHAR_LF) {
113
+ const newlineWidth = ch === CHAR_CR && i + 1 < sourceLength && source.charCodeAt(i + 1) === CHAR_LF ? 2 : 1;
114
+ lineStarts.push(i + newlineWidth);
115
+ // 顺序必须保证区间起点递增:行尾反斜杠 < 注释 < 换行
116
+ const isOddBackslashRun = (tailBackslashRunCount & 1) === 1;
117
+ pushTailBackslashMask(tailBackslashRunStart, tailBackslashRunCount);
118
+ if (pendingCommentStart >= 0) {
119
+ pushReplaceRange(pendingCommentStart, i);
120
+ commentSpans.push({ start: pendingCommentStart, end: i });
121
+ pendingCommentStart = -1;
122
+ }
123
+ if (isOddBackslashRun)
124
+ pushReplaceRange(i, i + newlineWidth);
125
+ // 新行重置行内状态
126
+ lastSignificantIndex = -1;
127
+ tailBackslashRunStart = -1;
128
+ tailBackslashRunCount = 0;
129
+ escaped = false;
130
+ i += newlineWidth;
131
+ continue;
132
+ }
133
+ // 字符串内仅处理转义与闭合;不识别注释
134
+ if (inQuote !== 0) {
135
+ if (escaped)
136
+ escaped = false;
137
+ else if (ch === CHAR_BACKSLASH)
138
+ escaped = true;
139
+ else if (ch === inQuote)
140
+ inQuote = 0;
141
+ if (!isNonLineWhitespace(ch))
142
+ updateLineTailState(i, ch);
143
+ i++;
144
+ continue;
145
+ }
146
+ if (ch === CHAR_QUOTE_DOUBLE) {
147
+ inQuote = ch;
148
+ updateLineTailState(i, ch);
149
+ i++;
150
+ continue;
151
+ }
152
+ // 非字符串上下文下,`%` 到行尾是注释;直接跳到换行,减少无效判断
153
+ if (ch === CHAR_PERCENT) {
154
+ pendingCommentStart = i;
155
+ i++;
156
+ while (i < sourceLength) {
157
+ const c = source.charCodeAt(i);
158
+ if (c === CHAR_CR || c === CHAR_LF)
159
+ break;
160
+ i++;
161
+ }
162
+ continue;
163
+ }
164
+ if (!isNonLineWhitespace(ch))
165
+ updateLineTailState(i, ch);
166
+ i++;
167
+ }
168
+ // EOF 边界:
169
+ // - 注释若未收口,收到文件末尾
170
+ // - 行尾连续 `\` 即使没有换行,也执行“隔位空格化”规则(无续行替换)
171
+ pushTailBackslashMask(tailBackslashRunStart, tailBackslashRunCount);
172
+ if (pendingCommentStart >= 0) {
173
+ pushReplaceRange(pendingCommentStart, sourceLength);
174
+ commentSpans.push({ start: pendingCommentStart, end: sourceLength });
175
+ }
176
+ // 无替换快路径:直接复用原字符串
177
+ if (replaceRanges.length === 0)
178
+ return { maskedSource: source, lineStarts, commentSpans };
179
+ // 分段组装,避免 O(n^2) 拼接
180
+ const chunks = [];
181
+ let lastCopyStart = 0;
182
+ for (let i = 0; i < replaceRanges.length; i += 2) {
183
+ const start = replaceRanges[i];
184
+ const end = replaceRanges[i + 1];
185
+ if (lastCopyStart < start)
186
+ chunks.push(source.slice(lastCopyStart, start));
187
+ chunks.push(getSpaces(end - start));
188
+ lastCopyStart = end;
189
+ }
190
+ if (lastCopyStart < sourceLength)
191
+ chunks.push(source.slice(lastCopyStart));
192
+ return { maskedSource: chunks.join(""), lineStarts, commentSpans };
193
+ }
@@ -0,0 +1,31 @@
1
+ import { GrammarNode } from "./grammarType.js";
2
+ import { ParserContext } from "./parserContext.js";
3
+ /**
4
+ * 源码区间(左闭右开)
5
+ */
6
+ export interface SourceSpan {
7
+ start: number;
8
+ end: number;
9
+ }
10
+ /**
11
+ * 有单位的长度值
12
+ */
13
+ export interface LengthValue {
14
+ value: number;
15
+ unit: "em" | "px";
16
+ }
17
+ /**
18
+ * 原子去糖 只消耗后向的文本 不允许改动ctx
19
+ * 内部一般不报错;实在有就 throw
20
+ * 传 depth 主要是有的语法糖只能在顶层使用
21
+ */
22
+ export type deSugarAtomFunction = (source: string, start: number, end: number, depth: number) => {
23
+ next: number;
24
+ node: GrammarNode;
25
+ } | null;
26
+ /**
27
+ * 传入的列表已经被拆为单字符了 会修改 ctx
28
+ * 返回值是下一个位置 指 nodes 数组;若为null则表示不匹配,需要继续尝试
29
+ * 内部报错需要push到ctx再throw
30
+ */
31
+ export type deSugarRelationFunction = (ctx: ParserContext, nodes: (GrammarNode | number)[], at: number) => number | null;
@@ -0,0 +1,2 @@
1
+ ;
2
+ export {};
@@ -0,0 +1,36 @@
1
+ import { ASTBraceNode, type ASTFunctionClass } from "./functions/ASTtypes.js";
2
+ import { type DocumentLayoutOptions, type DocumentLayoutResult } from "./layout/engine.js";
3
+ import type { LoweringResult } from "./lowering/types.js";
4
+ import { ParserContext } from "./parser/parserContext.js";
5
+ import type { TextMeasurer } from "./render/types.js";
6
+ export interface CompileScoreOptions extends DocumentLayoutOptions {
7
+ functions?: ASTFunctionClass[];
8
+ textMeasurer?: TextMeasurer;
9
+ fontSize?: number;
10
+ }
11
+ export interface CompileScoreResult {
12
+ lineStarts: number[];
13
+ parser: ParserContext;
14
+ ast: ASTBraceNode;
15
+ lowering: LoweringResult;
16
+ layout: DocumentLayoutResult;
17
+ }
18
+ /**
19
+ * 默认的源码到布局流水线
20
+ *
21
+ * 每个中间结果都保留在返回对象中
22
+ * 编辑器可以读取 diagnostics 和 AST(逐次按键的高亮走 analyzeScoreSyntax)
23
+ * 播放器可以读取 lowering
24
+ * 任意 Painter 后端可以直接消费 layout
25
+ */
26
+ export declare function compileScore(source: string, options?: CompileScoreOptions): CompileScoreResult;
27
+ /**
28
+ * 只分析编辑器所需的源码结构,不构造 AST
29
+ *
30
+ * 输入期间(防抖时)源码经常缺少右括号或完整参数;
31
+ * 该入口会把这些问题记录到 diagnostics,并尽量返回已经识别的 call/token,供高亮和补全继续工作
32
+ */
33
+ export declare function analyzeScoreSyntax(source: string, functions?: ASTFunctionClass[]): {
34
+ syntax: import("./index.js").SyntaxAnalysis;
35
+ diagnostics: import("./diagnostic.js").Diagnostic[];
36
+ };
@@ -0,0 +1,51 @@
1
+ import { ASTBraceNode } from "./functions/ASTtypes.js";
2
+ import { defaultFunctions } from "./functions/default.js";
3
+ import { createLayoutPrepareContext } from "./layout/default.js";
4
+ import { layoutDocument, } from "./layout/engine.js";
5
+ import { LoweringContext } from "./lowering/loweringContext.js";
6
+ import { ParserContext } from "./parser/parserContext.js";
7
+ import { preprocessSource } from "./parser/preprocess.js";
8
+ /**
9
+ * 默认的源码到布局流水线
10
+ *
11
+ * 每个中间结果都保留在返回对象中
12
+ * 编辑器可以读取 diagnostics 和 AST(逐次按键的高亮走 analyzeScoreSyntax)
13
+ * 播放器可以读取 lowering
14
+ * 任意 Painter 后端可以直接消费 layout
15
+ */
16
+ export function compileScore(source, options = {}) {
17
+ const { functions = defaultFunctions, textMeasurer, fontSize, ...layoutOptions } = options;
18
+ const { maskedSource, lineStarts } = preprocessSource(source);
19
+ const parser = new ParserContext({ source: maskedSource });
20
+ if (fontSize)
21
+ parser.fontSize = fontSize;
22
+ parser.registerFunctions(functions);
23
+ const ast = new ASTBraceNode({ start: 0, end: source.length }, parser.parse());
24
+ const loweringContext = new LoweringContext(parser.diagnostics);
25
+ loweringContext.registerFunctions(functions);
26
+ const lowering = loweringContext.lowerDocument(ast);
27
+ const layoutContext = createLayoutPrepareContext(functions, { textMeasurer });
28
+ const layout = layoutDocument(lowering, layoutContext, layoutOptions);
29
+ return {
30
+ lineStarts,
31
+ parser,
32
+ ast,
33
+ lowering,
34
+ layout,
35
+ };
36
+ }
37
+ /**
38
+ * 只分析编辑器所需的源码结构,不构造 AST
39
+ *
40
+ * 输入期间(防抖时)源码经常缺少右括号或完整参数;
41
+ * 该入口会把这些问题记录到 diagnostics,并尽量返回已经识别的 call/token,供高亮和补全继续工作
42
+ */
43
+ export function analyzeScoreSyntax(source, functions = defaultFunctions) {
44
+ const { maskedSource, commentSpans } = preprocessSource(source);
45
+ const parser = new ParserContext({ source: maskedSource, commentSpans });
46
+ parser.registerFunctions(functions);
47
+ return {
48
+ syntax: parser.parseSyntax(),
49
+ diagnostics: parser.diagnostics,
50
+ };
51
+ }
@@ -0,0 +1,19 @@
1
+ import { type DocumentLayoutResult } from "../layout/engine.js";
2
+ import type { PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from "./types.js";
3
+ /**
4
+ * CanvasRenderingContext2D 的 Painter 适配器
5
+ *
6
+ * 本类不负责设置 canvas 像素尺寸和 devicePixelRatio
7
+ * 调用方可以在构造前配置 context,再使用同一个布局结果绘制
8
+ */
9
+ export declare class CanvasPainter implements Painter {
10
+ private context;
11
+ constructor(context: CanvasRenderingContext2D);
12
+ drawText(text: string, x: number, y: number, style: TextStyle): void;
13
+ drawLine(x1: number, y1: number, x2: number, y2: number, style?: PaintStyle): void;
14
+ drawRect(x: number, y: number, w: number, h: number, style?: PaintStyle): void;
15
+ drawCircle(cx: number, cy: number, r: number, style?: PaintStyle): void;
16
+ drawPath(commands: readonly PathCommand[], style?: PaintStyle, transform?: PathTransform): void;
17
+ }
18
+ /** 使用 Canvas 后端绘制一个已经完成布局的文档 */
19
+ export declare function renderLayoutToCanvas(result: DocumentLayoutResult, context: CanvasRenderingContext2D): void;
@@ -0,0 +1,121 @@
1
+ import { paintLayout } from "../layout/engine.js";
2
+ function tracePath(context, commands, x = 0, y = 0, scaleX = 1, scaleY = 1) {
3
+ context.beginPath();
4
+ for (const command of commands) {
5
+ if (command.op === "Z") {
6
+ context.closePath();
7
+ continue;
8
+ }
9
+ if (command.op === "M") {
10
+ context.moveTo(x + command.x * scaleX, y + command.y * scaleY);
11
+ continue;
12
+ }
13
+ if (command.op === "L") {
14
+ context.lineTo(x + command.x * scaleX, y + command.y * scaleY);
15
+ continue;
16
+ }
17
+ if (command.op === "Q") {
18
+ context.quadraticCurveTo(x + command.cx * scaleX, y + command.cy * scaleY, x + command.x * scaleX, y + command.y * scaleY);
19
+ continue;
20
+ }
21
+ if (!("cx1" in command))
22
+ continue;
23
+ context.bezierCurveTo(x + command.cx1 * scaleX, y + command.cy1 * scaleY, x + command.cx2 * scaleX, y + command.cy2 * scaleY, x + command.x * scaleX, y + command.y * scaleY);
24
+ }
25
+ }
26
+ function applyOpacity(context, style) {
27
+ if (style?.opacity === void 0)
28
+ return;
29
+ context.globalAlpha *= style.opacity;
30
+ }
31
+ /**
32
+ * CanvasRenderingContext2D 的 Painter 适配器
33
+ *
34
+ * 本类不负责设置 canvas 像素尺寸和 devicePixelRatio
35
+ * 调用方可以在构造前配置 context,再使用同一个布局结果绘制
36
+ */
37
+ export class CanvasPainter {
38
+ context;
39
+ constructor(context) {
40
+ this.context = context;
41
+ }
42
+ drawText(text, x, y, style) {
43
+ this.context.save();
44
+ applyOpacity(this.context, style);
45
+ this.context.fillStyle = style.fill ?? "#000";
46
+ this.context.font = `${style.fontWeight ?? "normal"} ${style.fontSize}px ${style.fontFamily ?? "sans-serif"}`;
47
+ this.context.textAlign = style.textAlign ?? "left";
48
+ this.context.textBaseline = "alphabetic";
49
+ this.context.fillText(text, x, y);
50
+ this.context.restore();
51
+ }
52
+ drawLine(x1, y1, x2, y2, style) {
53
+ this.context.save();
54
+ applyOpacity(this.context, style);
55
+ this.context.beginPath();
56
+ this.context.moveTo(x1, y1);
57
+ this.context.lineTo(x2, y2);
58
+ this.context.strokeStyle = style?.stroke ?? style?.fill ?? "#000";
59
+ this.context.lineWidth = style?.strokeWidth ?? 1;
60
+ this.context.lineCap = "round";
61
+ this.context.stroke();
62
+ this.context.restore();
63
+ }
64
+ drawRect(x, y, w, h, style) {
65
+ if (w < 0 || h < 0)
66
+ return;
67
+ this.context.save();
68
+ applyOpacity(this.context, style);
69
+ if (style?.fill) {
70
+ this.context.fillStyle = style.fill;
71
+ this.context.fillRect(x, y, w, h);
72
+ }
73
+ if (style?.stroke) {
74
+ this.context.strokeStyle = style.stroke;
75
+ this.context.lineWidth = style.strokeWidth ?? 1;
76
+ this.context.strokeRect(x, y, w, h);
77
+ }
78
+ this.context.restore();
79
+ }
80
+ drawCircle(cx, cy, r, style) {
81
+ if (r < 0)
82
+ return;
83
+ this.context.save();
84
+ applyOpacity(this.context, style);
85
+ this.context.beginPath();
86
+ this.context.arc(cx, cy, r, 0, Math.PI * 2);
87
+ if (style?.fill ?? true) {
88
+ this.context.fillStyle = style?.fill ?? "#000";
89
+ this.context.fill();
90
+ }
91
+ if (style?.stroke) {
92
+ this.context.strokeStyle = style.stroke;
93
+ this.context.lineWidth = style.strokeWidth ?? 1;
94
+ this.context.stroke();
95
+ }
96
+ this.context.restore();
97
+ }
98
+ drawPath(commands, style, transform) {
99
+ if (commands.length === 0)
100
+ return;
101
+ this.context.save();
102
+ applyOpacity(this.context, style);
103
+ tracePath(this.context, commands, transform?.x, transform?.y, transform?.scaleX, transform?.scaleY);
104
+ if (style?.fill) {
105
+ this.context.fillStyle = style.fill;
106
+ this.context.fill();
107
+ }
108
+ if (style?.stroke) {
109
+ this.context.strokeStyle = style.stroke;
110
+ this.context.lineWidth = style.strokeWidth ?? 1;
111
+ this.context.lineCap = "round";
112
+ this.context.lineJoin = "round";
113
+ this.context.stroke();
114
+ }
115
+ this.context.restore();
116
+ }
117
+ }
118
+ /** 使用 Canvas 后端绘制一个已经完成布局的文档 */
119
+ export function renderLayoutToCanvas(result, context) {
120
+ paintLayout(result, new CanvasPainter(context));
121
+ }
@@ -0,0 +1,5 @@
1
+ export * from "./types.js";
2
+ export * from "./text.js";
3
+ export * from "./recording.js";
4
+ export * from "./svg.js";
5
+ export * from "./canvas.js";
@@ -0,0 +1,5 @@
1
+ export * from "./types.js";
2
+ export * from "./text.js";
3
+ export * from "./recording.js";
4
+ export * from "./svg.js";
5
+ export * from "./canvas.js";
@@ -0,0 +1,46 @@
1
+ import type { PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from "./types.js";
2
+ export type RecordedPaintCommand = {
3
+ kind: "text";
4
+ text: string;
5
+ x: number;
6
+ y: number;
7
+ style: TextStyle;
8
+ } | {
9
+ kind: "line";
10
+ x1: number;
11
+ y1: number;
12
+ x2: number;
13
+ y2: number;
14
+ style?: PaintStyle;
15
+ } | {
16
+ kind: "rect";
17
+ x: number;
18
+ y: number;
19
+ w: number;
20
+ h: number;
21
+ style?: PaintStyle;
22
+ } | {
23
+ kind: "circle";
24
+ cx: number;
25
+ cy: number;
26
+ r: number;
27
+ style?: PaintStyle;
28
+ } | {
29
+ kind: "path";
30
+ commands: PathCommand[];
31
+ style?: PaintStyle;
32
+ };
33
+ /**
34
+ * 记录通用绘制命令而不产生图像
35
+ *
36
+ * 主要用于后端契约测试、导出中间表示和调试
37
+ * 输入已经是布局完成后的绝对坐标
38
+ */
39
+ export declare class RecordingPainter implements Painter {
40
+ commands: RecordedPaintCommand[];
41
+ drawText(text: string, x: number, y: number, style: TextStyle): void;
42
+ drawLine(x1: number, y1: number, x2: number, y2: number, style?: PaintStyle): void;
43
+ drawRect(x: number, y: number, w: number, h: number, style?: PaintStyle): void;
44
+ drawCircle(cx: number, cy: number, r: number, style?: PaintStyle): void;
45
+ drawPath(commands: readonly PathCommand[], style?: PaintStyle, transform?: PathTransform): void;
46
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * 记录通用绘制命令而不产生图像
3
+ *
4
+ * 主要用于后端契约测试、导出中间表示和调试
5
+ * 输入已经是布局完成后的绝对坐标
6
+ */
7
+ export class RecordingPainter {
8
+ commands = [];
9
+ drawText(text, x, y, style) {
10
+ this.commands.push({
11
+ kind: "text",
12
+ text,
13
+ x, y,
14
+ style,
15
+ });
16
+ }
17
+ drawLine(x1, y1, x2, y2, style) {
18
+ this.commands.push({
19
+ kind: "line",
20
+ x1, y1,
21
+ x2, y2,
22
+ style,
23
+ });
24
+ }
25
+ drawRect(x, y, w, h, style) {
26
+ this.commands.push({
27
+ kind: "rect",
28
+ x, y, w, h,
29
+ style,
30
+ });
31
+ }
32
+ drawCircle(cx, cy, r, style) {
33
+ this.commands.push({
34
+ kind: "circle",
35
+ cx, cy, r,
36
+ style,
37
+ });
38
+ }
39
+ drawPath(commands, style, transform) {
40
+ this.commands.push({
41
+ kind: "path",
42
+ commands: commands.map(command => transformPathCommand(command, transform)),
43
+ style,
44
+ });
45
+ }
46
+ }
47
+ function transformPathCommand(command, transform) {
48
+ if (!transform || command.op === "Z")
49
+ return { ...command };
50
+ const x = (value) => transform.x + value * transform.scaleX;
51
+ const y = (value) => transform.y + value * transform.scaleY;
52
+ if (command.op === "M" || command.op === "L") {
53
+ return { op: command.op, x: x(command.x), y: y(command.y) };
54
+ }
55
+ if (command.op === "Q") {
56
+ return {
57
+ op: "Q",
58
+ cx: x(command.cx),
59
+ cy: y(command.cy),
60
+ x: x(command.x),
61
+ y: y(command.y),
62
+ };
63
+ }
64
+ if (command.op === "C") {
65
+ return {
66
+ op: "C",
67
+ cx1: x(command.cx1),
68
+ cy1: y(command.cy1),
69
+ cx2: x(command.cx2),
70
+ cy2: y(command.cy2),
71
+ x: x(command.x),
72
+ y: y(command.y),
73
+ };
74
+ }
75
+ return { ...command };
76
+ }
@@ -0,0 +1,18 @@
1
+ import { type DocumentLayoutResult } from "../layout/engine.js";
2
+ import type { PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from "./types.js";
3
+ export interface SvgRenderOptions {
4
+ padding?: number;
5
+ background?: string;
6
+ }
7
+ /** 生成独立 SVG 字符串的 Painter;路径直接输出最终坐标 */
8
+ export declare class SvgPainter implements Painter {
9
+ private body;
10
+ drawText(text: string, x: number, y: number, style: TextStyle): void;
11
+ drawLine(x1: number, y1: number, x2: number, y2: number, style?: PaintStyle): void;
12
+ drawRect(x: number, y: number, w: number, h: number, style?: PaintStyle): void;
13
+ drawCircle(cx: number, cy: number, r: number, style?: PaintStyle): void;
14
+ drawPath(commands: readonly PathCommand[], style?: PaintStyle, transform?: PathTransform): void;
15
+ toSvg(bounds: DocumentLayoutResult["bounds"], options?: SvgRenderOptions): string;
16
+ }
17
+ /** 使用 SVG 后端绘制一个已经完成布局的文档 */
18
+ export declare function renderLayoutToSvg(result: DocumentLayoutResult, options?: SvgRenderOptions): string;