jpfun 0.9.0 → 1.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 (125) hide show
  1. package/README.md +11 -16
  2. package/dist/diagnostic.d.ts +29 -2
  3. package/dist/diagnostic.js +5 -4
  4. package/dist/functions/arpeggio/index.js +2 -3
  5. package/dist/functions/bar/index.d.ts +3 -0
  6. package/dist/functions/bar/index.js +21 -3
  7. package/dist/functions/beam/layout.js +3 -2
  8. package/dist/functions/box/index.js +1 -0
  9. package/dist/functions/dash/index.js +5 -2
  10. package/dist/functions/default.js +2 -1
  11. package/dist/functions/div/index.d.ts +1 -1
  12. package/dist/functions/div/index.js +4 -2
  13. package/dist/functions/dyn/index.js +1 -0
  14. package/dist/functions/gliss/index.js +85 -9
  15. package/dist/functions/grace/index.d.ts +1 -8
  16. package/dist/functions/grace/index.js +23 -53
  17. package/dist/functions/head/index.js +23 -30
  18. package/dist/functions/key/index.js +5 -7
  19. package/dist/functions/meter/index.d.ts +1 -0
  20. package/dist/functions/meter/index.js +3 -0
  21. package/dist/functions/meter/shape.d.ts +1 -1
  22. package/dist/functions/note/accidentals.d.ts +3 -3
  23. package/dist/functions/note/accidentals.js +29 -16
  24. package/dist/functions/note/index.d.ts +5 -2
  25. package/dist/functions/note/index.js +168 -25
  26. package/dist/functions/note/source-transform.d.ts +23 -2
  27. package/dist/functions/note/source-transform.js +95 -74
  28. package/dist/functions/ottava/index.js +1 -0
  29. package/dist/functions/page/index.d.ts +1 -36
  30. package/dist/functions/page/index.js +8 -7
  31. package/dist/functions/rest/index.js +8 -6
  32. package/dist/functions/set/index.js +2 -2
  33. package/dist/functions/slide/index.js +1 -0
  34. package/dist/functions/stack/index.js +6 -4
  35. package/dist/functions/temporal.d.ts +12 -3
  36. package/dist/functions/temporal.js +15 -2
  37. package/dist/functions/text/index.js +2 -2
  38. package/dist/functions/tie/index.js +28 -4
  39. package/dist/functions/tremolo/index.js +1 -0
  40. package/dist/functions/tuplet/index.js +1 -0
  41. package/dist/functions/up/index.js +12 -12
  42. package/dist/functions/voice/connections.d.ts +1 -1
  43. package/dist/functions/voice/connections.js +2 -2
  44. package/dist/functions/voice/lyrics.d.ts +11 -5
  45. package/dist/functions/voice/lyrics.js +151 -47
  46. package/dist/functions/voice/voice.d.ts +6 -2
  47. package/dist/functions/voice/voice.js +51 -19
  48. package/dist/functions/voice/voices.d.ts +2 -1
  49. package/dist/functions/voice/voices.js +4 -3
  50. package/dist/functions/volta/index.js +1 -0
  51. package/dist/index.d.ts +69 -3
  52. package/dist/index.js +69 -3
  53. package/dist/jpfun.min.js +47 -60
  54. package/dist/layout/engine.d.ts +4 -3
  55. package/dist/layout/engine.js +173 -27
  56. package/dist/layout/model.d.ts +13 -4
  57. package/dist/layout/model.js +15 -7
  58. package/dist/layout/page.js +2 -2
  59. package/dist/layout/path.js +1 -1
  60. package/dist/layout/types.d.ts +12 -3
  61. package/dist/lowering/accidentalMemory.d.ts +33 -0
  62. package/dist/lowering/accidentalMemory.js +84 -0
  63. package/dist/lowering/loweringContext.js +4 -0
  64. package/dist/parser/grammarType.d.ts +8 -3
  65. package/dist/parser/parse-utils/brace-utils.js +7 -17
  66. package/dist/parser/parse-utils/call-utils.d.ts +3 -1
  67. package/dist/parser/parse-utils/call-utils.js +17 -32
  68. package/dist/parser/parse-utils/note-utils.d.ts +4 -0
  69. package/dist/parser/parse-utils/note-utils.js +8 -12
  70. package/dist/parser/parse-utils/string-utils.d.ts +1 -1
  71. package/dist/parser/parse-utils/string-utils.js +1 -1
  72. package/dist/parser/parserContext.d.ts +32 -26
  73. package/dist/parser/parserContext.js +104 -194
  74. package/dist/parser/preprocess.d.ts +7 -0
  75. package/dist/parser/preprocess.js +31 -42
  76. package/dist/parser/syntax.d.ts +9 -0
  77. package/dist/parser/syntax.js +109 -0
  78. package/dist/pipeline.d.ts +1 -1
  79. package/dist/pipeline.js +3 -2
  80. package/dist/playback/compile.js +5 -7
  81. package/dist/playback/event.d.ts +1 -2
  82. package/dist/playback/event.js +2 -3
  83. package/dist/render/canvas.js +50 -35
  84. package/dist/render/index.d.ts +2 -1
  85. package/dist/render/index.js +2 -1
  86. package/dist/render/paint.d.ts +7 -0
  87. package/dist/render/paint.js +70 -20
  88. package/dist/render/recording.d.ts +8 -1
  89. package/dist/render/recording.js +12 -0
  90. package/dist/render/svg.d.ts +5 -1
  91. package/dist/render/svg.js +37 -17
  92. package/dist/render/text.d.ts +2 -2
  93. package/dist/render/text.js +7 -6
  94. package/dist/render/translate.d.ts +3 -1
  95. package/dist/render/translate.js +6 -0
  96. package/dist/render/types.d.ts +9 -0
  97. package/grammar.md +7 -5
  98. package/package.json +8 -18
  99. package/dist/converter/midi/convert.d.ts +0 -42
  100. package/dist/converter/midi/convert.js +0 -682
  101. package/dist/converter/midi/index.d.ts +0 -5
  102. package/dist/converter/midi/index.js +0 -11
  103. package/dist/converter/midi/json.d.ts +0 -38
  104. package/dist/converter/midi/json.js +0 -1
  105. package/dist/converter/midi/triplet.d.ts +0 -30
  106. package/dist/converter/midi/triplet.js +0 -75
  107. package/dist/converter/musicxml/dom.d.ts +0 -25
  108. package/dist/converter/musicxml/dom.js +0 -65
  109. package/dist/converter/musicxml/features.d.ts +0 -114
  110. package/dist/converter/musicxml/features.js +0 -501
  111. package/dist/converter/musicxml/index.d.ts +0 -14
  112. package/dist/converter/musicxml/index.js +0 -1285
  113. package/dist/converter/musicxml/model.d.ts +0 -176
  114. package/dist/converter/musicxml/model.js +0 -1
  115. package/dist/converter/musicxml/resolve.d.ts +0 -10
  116. package/dist/converter/musicxml/resolve.js +0 -152
  117. package/dist/converter/source.d.ts +0 -19
  118. package/dist/converter/source.js +0 -53
  119. package/dist/core.d.ts +0 -24
  120. package/dist/core.js +0 -24
  121. package/dist/functions/voice/index.d.ts +0 -2
  122. package/dist/functions/voice/index.js +0 -2
  123. package/dist/jpfun.core.min.js +0 -132
  124. package/dist/jpfun.from-midi.min.js +0 -9
  125. package/dist/jpfun.from-musicxml.min.js +0 -12
@@ -0,0 +1,109 @@
1
+ import { Diagnostic } from "../diagnostic.js";
2
+ import { resolveArgType } from "../functions/ASTtypes.js";
3
+ import { callArgName } from "./parse-utils/call-utils.js";
4
+ import { parseLength } from "./parse-utils/length-utils.js";
5
+ import { BOOL_RE, ParserContext } from "./parserContext.js";
6
+ /** 有函数参数契约时直接用声明类型;未知参数回落到真正的字面量解析器,不另写一套正则 */
7
+ function classifySyntaxValue(type, text) {
8
+ if (type)
9
+ return type === "content" ? undefined : type;
10
+ if (BOOL_RE.test(text))
11
+ return "boolean";
12
+ if (text.startsWith('"'))
13
+ return "string";
14
+ if (!isNaN(Number(text)))
15
+ return "number";
16
+ if (!(parseLength(text) instanceof Diagnostic))
17
+ return "length";
18
+ return undefined;
19
+ }
20
+ /**
21
+ * 编辑器语法视图:以词法层模式观察 parseGrammar,收集着色 token 与调用结构,不构造 AST
22
+ * 节点按源码顺序发出、子区间就地递归,所以 tokens 有序且互不重叠,calls 按起点严格递增,无需排序;
23
+ * 注释在预处理阶段已被掩码,最后从 commentSpans 归并回来
24
+ */
25
+ export function collectSyntax(parser, commentSpans) {
26
+ const { source, functions } = parser;
27
+ const tokens = [];
28
+ const calls = [];
29
+ // 词法层不构造 AST,识别阶段的 span 没有其他读写者,可直接引用
30
+ const add = (kind, span) => {
31
+ if (span && span.start < span.end)
32
+ tokens.push({ kind, span });
33
+ };
34
+ /**
35
+ * 把已识别的 GrammarNode 映射为源码 token;content/brace 在子上下文中继续递归,作用域深度随之加一
36
+ * 总是返回 true 接管节点:输入途中的语法错误只记诊断,继续扫描以保留已识别的结构
37
+ */
38
+ const record = (node, ctx) => {
39
+ if (node.kind === "brace") {
40
+ add("punctuation", { start: node.span.start, end: node.span.start + 1 });
41
+ const close = Math.min(source.length, node.span.end - 1);
42
+ new ParserContext(ctx).parseGrammar(node.span.start + 1, close, record);
43
+ if (source[close] === "}")
44
+ add("punctuation", { start: close, end: close + 1 });
45
+ return true;
46
+ }
47
+ if (node.kind === "label") {
48
+ add("label", node.span);
49
+ return true;
50
+ }
51
+ if (node.kind === "sugar" || node.typed) {
52
+ if (Array.isArray(node.syntaxKind)) {
53
+ for (const token of node.syntaxKind)
54
+ add(token.kind, token.span);
55
+ }
56
+ else
57
+ add(node.syntaxKind ?? "operator", node.span);
58
+ return true;
59
+ }
60
+ // calls 只暴露源码结构,不带 grammar 阶段的字段
61
+ const { kind, typed, syntaxKind, ...call } = node;
62
+ calls.push(call);
63
+ add("function", call.nameSpan);
64
+ add("punctuation", call.openParenSpan);
65
+ const def = functions.get(call.name.toLowerCase())?.def;
66
+ for (let index = 0; index < call.args.length; index++) {
67
+ const arg = call.args[index];
68
+ add("property", arg.nameSpan);
69
+ add("punctuation", arg.equalsSpan);
70
+ const type = def && resolveArgType(def, callArgName(source, arg), index);
71
+ if (type === "content") {
72
+ new ParserContext(ctx).parseGrammar(arg.valueSpan.start, arg.valueSpan.end, record);
73
+ }
74
+ else {
75
+ const valueKind = classifySyntaxValue(type, source.slice(arg.valueSpan.start, arg.valueSpan.end));
76
+ if (valueKind)
77
+ add(valueKind, arg.valueSpan);
78
+ }
79
+ add("punctuation", arg.commaSpan);
80
+ }
81
+ add("punctuation", call.closeParenSpan);
82
+ return true;
83
+ };
84
+ parser.parseGrammar(0, source.length, record);
85
+ return { tokens: interleaveComments(tokens, commentSpans), calls };
86
+ }
87
+ /** 线性归并注释;未裁剪的值(如歌词行)会跨过注释,在注释处切开,保证输出有序且互不重叠 */
88
+ function interleaveComments(tokens, comments) {
89
+ if (comments.length === 0)
90
+ return tokens;
91
+ const out = [];
92
+ let c = 0;
93
+ for (const token of tokens) {
94
+ const { kind, span } = token;
95
+ let start = span.start;
96
+ for (; c < comments.length && comments[c].start < span.end; c++) {
97
+ const comment = comments[c];
98
+ if (start < comment.start)
99
+ out.push({ kind, span: { start, end: comment.start } });
100
+ out.push({ kind: "comment", span: comment });
101
+ start = Math.max(start, comment.end);
102
+ }
103
+ if (start < span.end)
104
+ out.push(start === span.start ? token : { kind, span: { start, end: span.end } });
105
+ }
106
+ for (; c < comments.length; c++)
107
+ out.push({ kind: "comment", span: comments[c] });
108
+ return out;
109
+ }
@@ -32,6 +32,6 @@ export declare function compileScore(source: string, options?: CompileScoreOptio
32
32
  * 该入口会把这些问题记录到 diagnostics,并尽量返回已经识别的 call/token,供高亮和补全继续工作
33
33
  */
34
34
  export declare function analyzeScoreSyntax(source: string, functions?: ASTFunctionClass[]): {
35
- syntax: import("./core.js").SyntaxAnalysis;
35
+ syntax: import("./index.js").SyntaxAnalysis;
36
36
  diagnostics: Diagnostic[];
37
37
  };
package/dist/pipeline.js CHANGED
@@ -5,6 +5,7 @@ import { layoutDocument, } from "./layout/engine.js";
5
5
  import { LoweringContext } from "./lowering/loweringContext.js";
6
6
  import { ParserContext } from "./parser/parserContext.js";
7
7
  import { preprocessSource } from "./parser/preprocess.js";
8
+ import { collectSyntax } from "./parser/syntax.js";
8
9
  /**
9
10
  * 默认的源码到布局流水线
10
11
  *
@@ -40,10 +41,10 @@ export function compileScore(source, options = {}) {
40
41
  */
41
42
  export function analyzeScoreSyntax(source, functions = defaultFunctions) {
42
43
  const { maskedSource, commentSpans } = preprocessSource(source);
43
- const parser = new ParserContext({ source: maskedSource, commentSpans });
44
+ const parser = new ParserContext({ source: maskedSource });
44
45
  parser.registerFunctions(functions);
45
46
  return {
46
- syntax: parser.parseSyntax(),
47
+ syntax: collectSyntax(parser, commentSpans),
47
48
  diagnostics: parser.diagnostics,
48
49
  };
49
50
  }
@@ -8,7 +8,7 @@ import { isPlaybackRelation } from "./types.js";
8
8
  * 按控制流声明展开出实际访问的列顺序
9
9
  *
10
10
  * 核心只维护游标、到达次数和标记表,跳转规则全部由函数在自己的 `playbackFlow` 里写:
11
- * 反复线找最近的段起点标记,房子按段起点被访问过几次决定本遍演不演。
11
+ * 反复线找最近的段起点标记,房子按本段已回跳过几次决定本遍演不演。
12
12
  * 本阶段只产生列索引;游标计数和标记索引每次编译重新建立,不会回写 lowering。
13
13
  */
14
14
  function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
@@ -172,7 +172,6 @@ export function compilePlayback(lowering, options) {
172
172
  const notes = [];
173
173
  const transforms = new Map();
174
174
  const activePrograms = new Map();
175
- let nextEventOrder = 0;
176
175
  let nextNoteId = 0;
177
176
  const changes = [{ kind: "initial", at: new Fraction(), origins: [] }];
178
177
  const factors = new Map();
@@ -228,7 +227,7 @@ export function compilePlayback(lowering, options) {
228
227
  const program = node.playbackState?.program;
229
228
  if (program !== undefined && activePrograms.get(track) !== program) {
230
229
  activePrograms.set(track, program);
231
- events.push({ kind: "program-change", at: start.clone(), order: nextEventOrder++, track, program });
230
+ events.push({ kind: "program-change", at: start.clone(), track, program });
232
231
  }
233
232
  const bpm = node.playbackState?.bpm;
234
233
  if (bpm !== undefined)
@@ -267,7 +266,7 @@ export function compilePlayback(lowering, options) {
267
266
  spanScales.set(span, scales);
268
267
  span.end.add(duration);
269
268
  },
270
- emit: event => events.push({ ...event, at: event.at.clone(), order: nextEventOrder++ }),
269
+ emit: event => events.push({ ...event, at: event.at.clone() }),
271
270
  control: (at, apply) => scheduleControl(at, lineage, apply),
272
271
  /** 只登记效果身份和比例,范围等结构与连接确定后再计算 */
273
272
  scaleFollowingBpm(key, numerator, denominator = 1, options) {
@@ -437,7 +436,6 @@ export function compilePlayback(lowering, options) {
437
436
  kind: "tempo",
438
437
  at: at.clone(),
439
438
  bpm: snapshot.effectiveBpm,
440
- order: nextEventOrder++,
441
439
  });
442
440
  }
443
441
  }
@@ -519,12 +517,12 @@ export function compilePlayback(lowering, options) {
519
517
  const { start, end, track, midi, velocity, percussion, sourceSpans } = sound;
520
518
  const noteId = nextNoteId++;
521
519
  const on = {
522
- kind: "note-on", at: start.clone(), noteId, order: nextEventOrder++,
520
+ kind: "note-on", at: start.clone(), noteId,
523
521
  track, midi, velocity, percussion,
524
522
  sourceSpans: [...sourceSpans],
525
523
  };
526
524
  const off = {
527
- kind: "note-off", at: end.clone(), noteId, order: nextEventOrder++,
525
+ kind: "note-off", at: end.clone(), noteId,
528
526
  track, midi,
529
527
  };
530
528
  audible.add(track);
@@ -45,7 +45,6 @@ export interface PlaybackOrigin {
45
45
  }
46
46
  interface PlaybackDraftEventBase {
47
47
  at: Fraction;
48
- order: number;
49
48
  }
50
49
  /** 声音展开后生成的点事件;最终输出前压实轨道编号并剥离编译期字段 */
51
50
  export interface PlaybackDraftNoteOnEvent extends PlaybackDraftEventBase {
@@ -84,7 +83,7 @@ export interface PlaybackEventInput {
84
83
  numerator: number;
85
84
  denominator: number;
86
85
  }
87
- /** 同刻先处理系统状态,再关音和开音;相同类别保持原发布次序 */
86
+ /** 同刻先处理系统状态,再关音和开音;相同类别依赖稳定排序保持原发布次序 */
88
87
  export declare function comparePlaybackDraftEvents(left: PlaybackDraftEvent, right: PlaybackDraftEvent): number;
89
88
  /**
90
89
  * 压实发声 Track 编号并剥掉编译期字段,得到稳定、可序列化的公开事件
@@ -5,10 +5,9 @@ const EVENT_PRIORITY = {
5
5
  "note-off": 3,
6
6
  "note-on": 4,
7
7
  };
8
- /** 同刻先处理系统状态,再关音和开音;相同类别保持原发布次序 */
8
+ /** 同刻先处理系统状态,再关音和开音;相同类别依赖稳定排序保持原发布次序 */
9
9
  export function comparePlaybackDraftEvents(left, right) {
10
- const byTime = left.at.compare(right.at);
11
- return byTime || EVENT_PRIORITY[left.kind] - EVENT_PRIORITY[right.kind] || left.order - right.order;
10
+ return left.at.compare(right.at) || EVENT_PRIORITY[left.kind] - EVENT_PRIORITY[right.kind];
12
11
  }
13
12
  /**
14
13
  * 压实发声 Track 编号并剥掉编译期字段,得到稳定、可序列化的公开事件
@@ -3,27 +3,31 @@ import { canvasFont } from "./text.js";
3
3
  function tracePath(context, commands, x = 0, y = 0, scaleX = 1, scaleY = 1) {
4
4
  context.beginPath();
5
5
  for (const command of commands) {
6
- if (command.op === "Z") {
7
- context.closePath();
8
- continue;
6
+ switch (command.op) {
7
+ case "M":
8
+ context.moveTo(x + command.x * scaleX, y + command.y * scaleY);
9
+ break;
10
+ case "L":
11
+ context.lineTo(x + command.x * scaleX, y + command.y * scaleY);
12
+ break;
13
+ case "Q":
14
+ context.quadraticCurveTo(x + command.cx * scaleX, y + command.cy * scaleY, x + command.x * scaleX, y + command.y * scaleY);
15
+ break;
16
+ case "C":
17
+ 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);
18
+ break;
19
+ case "Z":
20
+ context.closePath();
21
+ break;
22
+ default:
23
+ command;
9
24
  }
10
- if (command.op === "M") {
11
- context.moveTo(x + command.x * scaleX, y + command.y * scaleY);
12
- continue;
13
- }
14
- if (command.op === "L") {
15
- context.lineTo(x + command.x * scaleX, y + command.y * scaleY);
16
- continue;
17
- }
18
- if (command.op === "Q") {
19
- context.quadraticCurveTo(x + command.cx * scaleX, y + command.cy * scaleY, x + command.x * scaleX, y + command.y * scaleY);
20
- continue;
21
- }
22
- if (!("cx1" in command))
23
- continue;
24
- 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);
25
25
  }
26
26
  }
27
+ /** Canvas 会忽略 "none" 这类非法颜色并沿用上一次的样式,因此按“不绘制”处理 */
28
+ function paint(color) {
29
+ return color === "none" ? undefined : color;
30
+ }
27
31
  /**
28
32
  * CanvasRenderingContext2D 的 Painter 适配器
29
33
  *
@@ -36,17 +40,23 @@ export class CanvasPainter {
36
40
  this.context = context;
37
41
  }
38
42
  drawText(text, x, y, style) {
39
- this.context.fillStyle = style.fill ?? "#000";
43
+ const fill = paint(style.fill ?? "#000");
44
+ if (!fill)
45
+ return;
46
+ this.context.fillStyle = fill;
40
47
  this.context.font = canvasFont(style);
41
48
  this.context.textAlign = style.textAlign ?? "left";
42
49
  this.context.textBaseline = "alphabetic";
43
50
  this.context.fillText(text, x, y);
44
51
  }
45
52
  drawLine(x1, y1, x2, y2, style) {
53
+ const stroke = paint(style?.stroke ?? style?.fill ?? "#000");
54
+ if (!stroke)
55
+ return;
46
56
  this.context.beginPath();
47
57
  this.context.moveTo(x1, y1);
48
58
  this.context.lineTo(x2, y2);
49
- this.context.strokeStyle = style?.stroke ?? style?.fill ?? "#000";
59
+ this.context.strokeStyle = stroke;
50
60
  this.context.lineWidth = style?.strokeWidth ?? 1;
51
61
  this.context.lineCap = "round";
52
62
  this.context.stroke();
@@ -54,13 +64,15 @@ export class CanvasPainter {
54
64
  drawRect(x, y, w, h, style) {
55
65
  if (w < 0 || h < 0)
56
66
  return;
57
- if (style?.fill) {
58
- this.context.fillStyle = style.fill;
67
+ const fill = paint(style?.fill);
68
+ if (fill) {
69
+ this.context.fillStyle = fill;
59
70
  this.context.fillRect(x, y, w, h);
60
71
  }
61
- if (style?.stroke) {
62
- this.context.strokeStyle = style.stroke;
63
- this.context.lineWidth = style.strokeWidth ?? 1;
72
+ const stroke = paint(style?.stroke);
73
+ if (stroke) {
74
+ this.context.strokeStyle = stroke;
75
+ this.context.lineWidth = style?.strokeWidth ?? 1;
64
76
  this.context.lineJoin = "miter";
65
77
  this.context.strokeRect(x, y, w, h);
66
78
  }
@@ -70,14 +82,15 @@ export class CanvasPainter {
70
82
  return;
71
83
  this.context.beginPath();
72
84
  this.context.arc(cx, cy, r, 0, Math.PI * 2);
73
- const fill = style?.fill ?? "#000";
74
- if (fill && fill !== "none") {
85
+ const fill = paint(style?.fill ?? "#000");
86
+ if (fill) {
75
87
  this.context.fillStyle = fill;
76
88
  this.context.fill();
77
89
  }
78
- if (style?.stroke) {
79
- this.context.strokeStyle = style.stroke;
80
- this.context.lineWidth = style.strokeWidth ?? 1;
90
+ const stroke = paint(style?.stroke);
91
+ if (stroke) {
92
+ this.context.strokeStyle = stroke;
93
+ this.context.lineWidth = style?.strokeWidth ?? 1;
81
94
  this.context.stroke();
82
95
  }
83
96
  }
@@ -85,13 +98,15 @@ export class CanvasPainter {
85
98
  if (commands.length === 0)
86
99
  return;
87
100
  tracePath(this.context, commands, transform?.x, transform?.y, transform?.scaleX, transform?.scaleY);
88
- if (style?.fill) {
89
- this.context.fillStyle = style.fill;
101
+ const fill = paint(style?.fill);
102
+ if (fill) {
103
+ this.context.fillStyle = fill;
90
104
  this.context.fill();
91
105
  }
92
- if (style?.stroke) {
93
- this.context.strokeStyle = style.stroke;
94
- this.context.lineWidth = style.strokeWidth ?? 1;
106
+ const stroke = paint(style?.stroke);
107
+ if (stroke) {
108
+ this.context.strokeStyle = stroke;
109
+ this.context.lineWidth = style?.strokeWidth ?? 1;
95
110
  this.context.lineCap = "round";
96
111
  this.context.lineJoin = "round";
97
112
  this.context.stroke();
@@ -1,6 +1,7 @@
1
1
  export * from "./types.js";
2
- export { layoutPageBounds, paintLayout, paintLayoutPages } from "./paint.js";
2
+ export { layoutPageBounds, paintLayout, paintLayoutPages, paintVisual } from "./paint.js";
3
3
  export * from "./text.js";
4
4
  export * from "./recording.js";
5
5
  export * from "./svg.js";
6
6
  export * from "./canvas.js";
7
+ export * from "./translate.js";
@@ -1,6 +1,7 @@
1
1
  export * from "./types.js";
2
- export { layoutPageBounds, paintLayout, paintLayoutPages } from "./paint.js";
2
+ export { layoutPageBounds, paintLayout, paintLayoutPages, paintVisual } from "./paint.js";
3
3
  export * from "./text.js";
4
4
  export * from "./recording.js";
5
5
  export * from "./svg.js";
6
6
  export * from "./canvas.js";
7
+ export * from "./translate.js";
@@ -1,7 +1,14 @@
1
1
  import type { DocumentLayoutResult } from "../layout/engine.js";
2
2
  import type { Rect } from "../layout/types.js";
3
+ import type { VisualTemporalNode } from "../functions/temporal.js";
3
4
  import type { Painter } from "./types.js";
4
5
  export declare function layoutPageBounds(result: DocumentLayoutResult): readonly Rect[];
6
+ /**
7
+ * 绘制一个可见时值对象:主体后接装饰,整体放进 node.kind 分组
8
+ *
9
+ * up、grace、arpeggio 等容器绘制成员时也应调用它,成员的组因此嵌套在容器组内
10
+ */
11
+ export declare function paintVisual(painter: Painter, node: VisualTemporalNode): void;
5
12
  /** 按固定层级把布局结果绘制到一个 Painter */
6
13
  export declare function paintLayout(result: DocumentLayoutResult, painter: Painter): void;
7
14
  /** 用一个代理 Painter 把一次完整绘制分发到多个页面 Painter */
@@ -3,29 +3,68 @@ export function layoutPageBounds(result) {
3
3
  ? result.pages.map(page => page.bounds)
4
4
  : [result.bounds];
5
5
  }
6
+ /**
7
+ * 绘制一个可见时值对象:主体后接装饰,整体放进 node.kind 分组
8
+ *
9
+ * up、grace、arpeggio 等容器绘制成员时也应调用它,成员的组因此嵌套在容器组内
10
+ */
11
+ export function paintVisual(painter, node) {
12
+ const kind = node.kind;
13
+ if (kind)
14
+ painter.beginGroup?.({ kind });
15
+ node.paint(painter);
16
+ for (const decoration of node.decorations)
17
+ decoration.paint?.(painter);
18
+ if (kind)
19
+ painter.endGroup?.();
20
+ }
21
+ function paintAttachments(painter, attachments, layer) {
22
+ for (const attachment of attachments) {
23
+ if (attachment.layer !== layer)
24
+ continue;
25
+ const kind = attachment.kind;
26
+ if (kind)
27
+ painter.beginGroup?.({ kind });
28
+ attachment.paint(painter);
29
+ if (kind)
30
+ painter.endGroup?.();
31
+ }
32
+ }
6
33
  /** 按固定层级把布局结果绘制到一个 Painter */
7
34
  export function paintLayout(result, painter) {
8
- for (const attachment of result.attachments) {
9
- if (attachment.layer === "background")
10
- attachment.paint(painter);
11
- }
12
- for (const node of result.objects) {
13
- node.paint(painter);
14
- for (const decoration of node.decorations)
15
- decoration.paint?.(painter);
16
- }
17
- for (const attachment of result.attachments) {
18
- if (attachment.layer === "foreground")
19
- attachment.paint(painter);
20
- }
35
+ paintAttachments(painter, result.attachments, "background");
36
+ for (const node of result.objects)
37
+ paintVisual(painter, node);
38
+ paintAttachments(painter, result.attachments, "foreground");
21
39
  }
22
40
  class PagePainter {
23
41
  pages;
24
42
  painters;
43
+ /** 当前打开的分组,由外到内 */
44
+ groups = [];
45
+ /** 页下标 → 该页已补开的层数;只记录有未结束分组的页,没有图元的页不开组 */
46
+ opened = new Map();
25
47
  constructor(pages, painters) {
26
48
  this.pages = pages;
27
49
  this.painters = painters;
28
50
  }
51
+ beginGroup(group) {
52
+ this.groups.push(group);
53
+ }
54
+ endGroup() {
55
+ const depth = this.groups.length;
56
+ this.groups.pop();
57
+ // 各页层数不超过 depth,等于 depth 的页才打开过这一组
58
+ for (const [index, opened] of this.opened) {
59
+ if (opened < depth)
60
+ continue;
61
+ this.painters[index].endGroup?.();
62
+ if (depth > 1)
63
+ this.opened.set(index, depth - 1);
64
+ else
65
+ this.opened.delete(index);
66
+ }
67
+ }
29
68
  route(top, bottom, paint) {
30
69
  let low = 0;
31
70
  let high = this.pages.length;
@@ -37,8 +76,16 @@ class PagePainter {
37
76
  else
38
77
  high = middle;
39
78
  }
79
+ const depth = this.groups.length;
40
80
  for (let index = low; index < this.pages.length && this.pages[index].y <= bottom; index++) {
41
- paint(this.painters[index]);
81
+ const painter = this.painters[index];
82
+ const opened = this.opened.get(index) ?? 0;
83
+ if (opened < depth) {
84
+ for (let level = opened; level < depth; level++)
85
+ painter.beginGroup?.(this.groups[level]);
86
+ this.opened.set(index, depth);
87
+ }
88
+ paint(painter);
42
89
  }
43
90
  }
44
91
  drawText(text, x, y, style) {
@@ -62,15 +109,11 @@ class PagePainter {
62
109
  drawPath(commands, style, transform) {
63
110
  if (commands.length === 0)
64
111
  return;
65
- const y = transform
66
- ? (value) => transform.y + value * transform.scaleY
67
- : (value) => value;
68
112
  let top = Infinity;
69
113
  let bottom = -Infinity;
70
114
  const include = (value) => {
71
- const transformed = y(value);
72
- top = Math.min(top, transformed);
73
- bottom = Math.max(bottom, transformed);
115
+ top = Math.min(top, value);
116
+ bottom = Math.max(bottom, value);
74
117
  };
75
118
  for (const command of commands) {
76
119
  if (command.op === "Z")
@@ -83,6 +126,13 @@ class PagePainter {
83
126
  }
84
127
  include(command.y);
85
128
  }
129
+ if (transform) {
130
+ // 仿射变换单调,变换端点即可;scaleY 为负时上下互换
131
+ const a = transform.y + top * transform.scaleY;
132
+ const b = transform.y + bottom * transform.scaleY;
133
+ top = Math.min(a, b);
134
+ bottom = Math.max(a, b);
135
+ }
86
136
  if (!Number.isFinite(top))
87
137
  return;
88
138
  const halfStroke = style?.stroke ? (style.strokeWidth ?? 1) / 2 : 0;
@@ -1,4 +1,4 @@
1
- import type { PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from "./types.js";
1
+ import type { PaintGroup, PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from "./types.js";
2
2
  export type RecordedPaintCommand = {
3
3
  kind: "text";
4
4
  text: string;
@@ -29,6 +29,11 @@ export type RecordedPaintCommand = {
29
29
  kind: "path";
30
30
  commands: PathCommand[];
31
31
  style?: PaintStyle;
32
+ } | {
33
+ kind: "begin-group";
34
+ group: PaintGroup;
35
+ } | {
36
+ kind: "end-group";
32
37
  };
33
38
  /**
34
39
  * 记录通用绘制命令而不产生图像
@@ -39,6 +44,8 @@ export type RecordedPaintCommand = {
39
44
  export declare class RecordingPainter implements Painter {
40
45
  commands: RecordedPaintCommand[];
41
46
  replay(painter: Painter): void;
47
+ beginGroup(group: PaintGroup): void;
48
+ endGroup(): void;
42
49
  drawText(text: string, x: number, y: number, style: TextStyle): void;
43
50
  drawLine(x1: number, y1: number, x2: number, y2: number, style?: PaintStyle): void;
44
51
  drawRect(x: number, y: number, w: number, h: number, style?: PaintStyle): void;
@@ -24,9 +24,21 @@ export class RecordingPainter {
24
24
  case "path":
25
25
  painter.drawPath(command.commands, command.style);
26
26
  break;
27
+ case "begin-group":
28
+ painter.beginGroup?.(command.group);
29
+ break;
30
+ case "end-group":
31
+ painter.endGroup?.();
32
+ break;
27
33
  }
28
34
  }
29
35
  }
36
+ beginGroup(group) {
37
+ this.commands.push({ kind: "begin-group", group });
38
+ }
39
+ endGroup() {
40
+ this.commands.push({ kind: "end-group" });
41
+ }
30
42
  drawText(text, x, y, style) {
31
43
  this.commands.push({
32
44
  kind: "text",
@@ -1,11 +1,15 @@
1
1
  import type { DocumentLayoutResult } from "../layout/engine.js";
2
- import type { PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from "./types.js";
2
+ import type { PaintGroup, PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from "./types.js";
3
3
  export interface SvgRenderOptions {
4
4
  background?: string;
5
5
  }
6
6
  /** 生成独立 SVG 字符串的 Painter;路径直接输出最终坐标 */
7
7
  export declare class SvgPainter implements Painter {
8
8
  private body;
9
+ /** 未结束分组的开标签在 body 中的下标 */
10
+ private groupStarts;
11
+ beginGroup(group: PaintGroup): void;
12
+ endGroup(): void;
9
13
  drawText(text: string, x: number, y: number, style: TextStyle): void;
10
14
  drawLine(x1: number, y1: number, x2: number, y2: number, style?: PaintStyle): void;
11
15
  drawRect(x: number, y: number, w: number, h: number, style?: PaintStyle): void;