jpfun 0.8.0 → 0.9.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 (97) hide show
  1. package/dist/converter/midi/convert.js +8 -55
  2. package/dist/converter/musicxml/features.d.ts +1 -1
  3. package/dist/converter/musicxml/features.js +1 -1
  4. package/dist/converter/musicxml/index.js +8 -18
  5. package/dist/converter/source.d.ts +4 -7
  6. package/dist/converter/source.js +11 -9
  7. package/dist/functions/ASTtypes.d.ts +1 -14
  8. package/dist/functions/ASTtypes.js +5 -36
  9. package/dist/functions/adjust/index.js +45 -33
  10. package/dist/functions/arpeggio/index.js +42 -45
  11. package/dist/functions/arpeggio/shape.d.ts +2 -3
  12. package/dist/functions/arpeggio/shape.js +20 -50
  13. package/dist/functions/bar/index.js +3 -8
  14. package/dist/functions/beam/auto.js +54 -123
  15. package/dist/functions/beam/index.js +4 -9
  16. package/dist/functions/box/index.js +0 -6
  17. package/dist/functions/dash/index.js +3 -4
  18. package/dist/functions/div/index.d.ts +2 -4
  19. package/dist/functions/div/index.js +10 -10
  20. package/dist/functions/dot/index.js +3 -9
  21. package/dist/functions/dyn/index.js +6 -26
  22. package/dist/functions/gliss/index.js +95 -89
  23. package/dist/functions/grace/index.d.ts +2 -5
  24. package/dist/functions/grace/index.js +44 -89
  25. package/dist/functions/head/index.js +9 -6
  26. package/dist/functions/key/index.js +6 -6
  27. package/dist/functions/meter/index.js +3 -3
  28. package/dist/functions/note/index.js +1 -1
  29. package/dist/functions/note/source-transform.js +2 -5
  30. package/dist/functions/ottava/index.js +11 -32
  31. package/dist/functions/page/index.js +13 -16
  32. package/dist/functions/rest/index.js +2 -4
  33. package/dist/functions/slide/index.js +0 -1
  34. package/dist/functions/stack/index.js +8 -57
  35. package/dist/functions/temporal.d.ts +2 -2
  36. package/dist/functions/temporal.js +7 -0
  37. package/dist/functions/text/index.js +24 -30
  38. package/dist/functions/tie/index.js +14 -37
  39. package/dist/functions/tremolo/index.js +0 -1
  40. package/dist/functions/tuplet/index.js +0 -6
  41. package/dist/functions/up/index.js +79 -83
  42. package/dist/functions/voice/connections.d.ts +2 -1
  43. package/dist/functions/voice/connections.js +48 -10
  44. package/dist/functions/voice/index.d.ts +2 -3
  45. package/dist/functions/voice/index.js +2 -970
  46. package/dist/functions/voice/lyrics.d.ts +30 -0
  47. package/dist/functions/voice/lyrics.js +289 -0
  48. package/dist/functions/voice/voice.d.ts +63 -0
  49. package/dist/functions/voice/voice.js +373 -0
  50. package/dist/functions/voice/voices.d.ts +106 -0
  51. package/dist/functions/voice/voices.js +423 -0
  52. package/dist/functions/volta/index.js +5 -23
  53. package/dist/jpfun.core.min.js +65 -56
  54. package/dist/jpfun.from-midi.min.js +5 -5
  55. package/dist/jpfun.from-musicxml.min.js +7 -7
  56. package/dist/jpfun.min.js +68 -59
  57. package/dist/layout/engine.js +30 -18
  58. package/dist/layout/model.d.ts +0 -1
  59. package/dist/layout/model.js +1 -4
  60. package/dist/layout/page.d.ts +2 -1
  61. package/dist/layout/page.js +14 -14
  62. package/dist/layout/range.d.ts +7 -6
  63. package/dist/layout/range.js +23 -14
  64. package/dist/layout/types.d.ts +9 -28
  65. package/dist/lowering/loweringContext.d.ts +8 -11
  66. package/dist/lowering/loweringContext.js +7 -13
  67. package/dist/lowering/track.d.ts +8 -1
  68. package/dist/lowering/types.d.ts +12 -8
  69. package/dist/parser/parse-utils/call-utils.d.ts +1 -2
  70. package/dist/parser/parse-utils/call-utils.js +6 -34
  71. package/dist/parser/parse-utils/note-utils.d.ts +3 -3
  72. package/dist/parser/parse-utils/note-utils.js +17 -28
  73. package/dist/parser/parse-utils/string-utils.d.ts +1 -1
  74. package/dist/parser/parse-utils/string-utils.js +8 -6
  75. package/dist/parser/parserContext.d.ts +9 -9
  76. package/dist/parser/parserContext.js +54 -10
  77. package/dist/pipeline.js +2 -2
  78. package/dist/playback/compile.js +13 -14
  79. package/dist/playback/event.d.ts +6 -6
  80. package/dist/playback/event.js +13 -49
  81. package/dist/render/canvas.d.ts +0 -2
  82. package/dist/render/canvas.js +0 -21
  83. package/dist/render/svg.d.ts +0 -1
  84. package/dist/render/svg.js +33 -31
  85. package/dist/render/text.d.ts +36 -1
  86. package/dist/render/text.js +134 -0
  87. package/dist/render/types.d.ts +0 -2
  88. package/grammar.md +16 -13
  89. package/package.json +1 -1
  90. package/dist/iife/core.d.ts +0 -1
  91. package/dist/iife/core.js +0 -3
  92. package/dist/iife/from-midi.d.ts +0 -1
  93. package/dist/iife/from-midi.js +0 -15
  94. package/dist/iife/from-musicxml.d.ts +0 -1
  95. package/dist/iife/from-musicxml.js +0 -3
  96. package/dist/iife/full.d.ts +0 -1
  97. package/dist/iife/full.js +0 -3
@@ -13,7 +13,7 @@ const CALL_NAME_CHAR_RE = /[A-Za-z0-9_./-]/;
13
13
  * - 正确处理字符串字面量(支持转义)
14
14
  * - 支持嵌套小括号 `(...)`,但被大括号 `{...}` 包裹的小括号不会影响外层匹配
15
15
  * - 忽略大括号内的小括号深度变化
16
- * - 在顶层小括号内以逗号分割参数,记录每个参数的原始文本及其在 `source` 中的起始/结束位置
16
+ * - 在顶层小括号内以逗号分割参数,同时记录每个参数的首个顶层 `=` 及其在 `source` 中的起始/结束位置
17
17
  * - 若找到匹配右括号,记录 closeParenSpan;否则在 end 处结束,让上层决定诊断/恢复策略
18
18
  */
19
19
  export function readCall(source, atPos, end) {
@@ -35,13 +35,13 @@ export function readCall(source, atPos, end) {
35
35
  // 参数相关
36
36
  const argInfo = [];
37
37
  let lastCommaPos = openPos + 1;
38
+ let equals = -1;
38
39
  // 按照 `key = value` 或者 `value` 的模式匹配各个token的span
39
40
  // keepEmpty=true 用于保留 @func(,key=val) 这种情况的空参数
40
41
  const pushArg = (end, commaPos, keepEmpty = false) => {
41
42
  const span = trimRange(source, lastCommaPos, end);
42
43
  if (!keepEmpty && span.start >= span.end)
43
44
  return;
44
- const equals = findTopLevelEquals(source, span.start, span.end);
45
45
  const nameSpan = equals > span.start ? trimRange(source, span.start, equals) : undefined;
46
46
  const valueSpan = equals > span.start ? trimRange(source, equals + 1, span.end) : span;
47
47
  argInfo.push({
@@ -95,6 +95,10 @@ export function readCall(source, atPos, end) {
95
95
  pushArg(i, i, true); // 即使为空也有位置信息
96
96
  // 跳过逗号
97
97
  lastCommaPos = i + 1;
98
+ equals = -1;
99
+ }
100
+ else if (ch === "=" && equals === -1 && parenDepth === 1 && braceDepth === 0) {
101
+ equals = i;
98
102
  }
99
103
  }
100
104
  // 未闭合调用仍保留已有结构;ParserContext 根据 closeParenSpan 生成诊断
@@ -111,38 +115,6 @@ export function trimRange(source, start, end) {
111
115
  e -= 1;
112
116
  return { start: s, end: e };
113
117
  }
114
- export function findTopLevelEquals(text, start = 0, end = text.length) {
115
- let parenDepth = 0;
116
- let braceDepth = 0;
117
- let quote = null;
118
- let escaped = false;
119
- for (let i = start; i < end; i++) {
120
- const ch = text[i];
121
- if (quote) {
122
- if (escaped)
123
- escaped = false;
124
- else if (ch === "\\")
125
- escaped = true;
126
- else if (ch === quote)
127
- quote = null;
128
- continue;
129
- }
130
- if (ch === '"')
131
- quote = ch;
132
- // 依旧忽略大括号里面的小括号
133
- else if (ch === "(" && braceDepth === 0)
134
- parenDepth++;
135
- else if (ch === ")" && braceDepth === 0)
136
- parenDepth = Math.max(0, parenDepth - 1);
137
- else if (ch === "{")
138
- braceDepth++;
139
- else if (ch === "}")
140
- braceDepth = Math.max(0, braceDepth - 1);
141
- else if (ch === "=" && parenDepth === 0 && braceDepth === 0)
142
- return i;
143
- }
144
- return -1;
145
- }
146
118
  // 不管大括号 适用于小括号里传递字符串但没加引号的情况
147
119
  export function findRightParen(source, start, end) {
148
120
  let parenDepth = 1;
@@ -7,14 +7,14 @@ export interface RelativeJianpuPitch {
7
7
  renderAcc: string;
8
8
  renderOctave: number;
9
9
  }
10
- export declare function tonality2Midi(tonality: string, defaultOctave?: number): number | null;
10
+ export declare function tonality2Midi(tonality: string): number | null;
11
11
  export declare function acc2Offset(acc: string, ignoreNatural?: boolean, initOffset?: number): number;
12
12
  export declare function resolveNoteMidi(name: string, acc: string, octave: number, keySignature: string): number | null;
13
13
  /**
14
14
  * 固化音符在当前大调中的位置,返回“沿调内音级移动”的闭包
15
15
  *
16
16
  * 交出闭包而不是数据结构,播放层因此无需认识任何调性模型。
17
- * 基准位置不包含主体的临时升降号。
17
+ * 基准位置基于已归一化的简谱级数与相对八度,不包含主体的临时升降号。
18
18
  */
19
- export declare function createDiatonicTranspose(name: string, acc: string, octave: number, keySignature: string): ((steps: number) => number) | undefined;
19
+ export declare function createDiatonicTranspose(name: string, octave: number, keySignature: string): ((steps: number) => number) | undefined;
20
20
  export declare function resolveLetterNameToJianpu(name: string, acc: string, octave: number, keySignature: string): RelativeJianpuPitch | null;
@@ -24,31 +24,31 @@ export const NoteNameMap = {
24
24
  };
25
25
  const LETTER_ORDER = ["C", "D", "E", "F", "G", "A", "B"];
26
26
  const MAJOR_SCALE_OFFSETS = [0, 2, 4, 5, 7, 9, 11];
27
- // 输入 C4 D#3 B3b G, A 等音符字符串,输出 MIDI 数值;格式不合法返回 null
28
- // 要求非常严格:必须 [大写字母或数字][升降号#bn只能一个][绝对八度]
29
- export function tonality2Midi(tonality, defaultOctave = 4) {
27
+ // 输入 C4 D#3 Bb3 等调性字符串,输出 MIDI 数值;格式不合法返回 null
28
+ // 要求非常严格:必须 [大写字母][最多一个 #b][绝对八度]
29
+ export function tonality2Midi(tonality) {
30
30
  // 解析音名
31
31
  const note = tonality[0];
32
+ if (!note || note < "A" || note > "G")
33
+ return null;
32
34
  let acc = "";
33
35
  let i = 1;
34
36
  // 解析升降号
35
- if (i < tonality.length && (tonality[i] === '#' || tonality[i] === 'b' || tonality[i] === 'n')) {
37
+ if (i < tonality.length && (tonality[i] === "#" || tonality[i] === "b")) {
36
38
  acc = tonality[i];
37
39
  i++;
38
40
  }
39
41
  // 组合音名和升降号
40
- let noteValue = NoteNameMap[note + acc];
42
+ const noteValue = NoteNameMap[note + acc];
41
43
  if (noteValue === undefined)
42
44
  return null;
43
45
  // 解析八度
44
- if (i < tonality.length) {
45
- const octave = tonality.slice(i);
46
- defaultOctave = Number(octave);
47
- if (!/^-?\d+$/.test(octave) || !Number.isSafeInteger(defaultOctave)) {
48
- return null;
49
- }
46
+ const octaveText = tonality.slice(i);
47
+ const octave = Number(octaveText);
48
+ if (!/^-?\d+$/.test(octaveText) || !Number.isSafeInteger(octave)) {
49
+ return null;
50
50
  }
51
- return (defaultOctave + 1) * 12 + noteValue;
51
+ return (octave + 1) * 12 + noteValue;
52
52
  }
53
53
  // ignoreNatural: 是否忽略还原号对升降号的重置作用。默认为true,即默认自然音符不重置acc
54
54
  // initOffset: 该小节累加的升降号偏移量 仅在ignoreNatural=false时有意义
@@ -77,24 +77,13 @@ export function resolveNoteMidi(name, acc, octave, keySignature) {
77
77
  * 固化音符在当前大调中的位置,返回“沿调内音级移动”的闭包
78
78
  *
79
79
  * 交出闭包而不是数据结构,播放层因此无需认识任何调性模型。
80
- * 基准位置不包含主体的临时升降号。
80
+ * 基准位置基于已归一化的简谱级数与相对八度,不包含主体的临时升降号。
81
81
  */
82
- export function createDiatonicTranspose(name, acc, octave, keySignature) {
83
- let degreeIndex;
84
- let relativeOctave;
85
- if (name >= "1" && name <= "7") {
86
- degreeIndex = Number(name) - 1;
87
- relativeOctave = octave;
88
- }
89
- else {
90
- const relative = resolveLetterNameToJianpu(name, acc, octave, keySignature);
91
- if (!relative)
92
- return undefined;
93
- degreeIndex = Number(relative.renderName) - 1;
94
- relativeOctave = relative.renderOctave;
95
- }
82
+ export function createDiatonicTranspose(name, octave, keySignature) {
83
+ if (name < "1" || name > "7")
84
+ return undefined;
96
85
  const tonicMidi = tonality2Midi(keySignature);
97
- const base = relativeOctave * 7 + degreeIndex;
86
+ const base = octave * 7 + Number(name) - 1;
98
87
  return steps => {
99
88
  const total = base + steps;
100
89
  const shift = Math.floor(total / 7);
@@ -5,7 +5,7 @@
5
5
  import { Diagnostic } from "../../diagnostic.js";
6
6
  /** 找与 quotePos 处开引号配对的闭引号;找不到返回 -1 */
7
7
  export declare function findClosingQuote(source: string, quotePos: number, end: number): number;
8
- /** 剥掉成对的双引号并反转义;解码失败时返回相对 source 的诊断,裸参数原样返回 */
8
+ /** 剥掉成对的双引号(若有)并解码编码/定界级转义(`\"`、`\\`、`\uXXXX`);其余 `\X` 原样保留给具体函数解析 */
9
9
  export declare function parseString(source: string): string | Diagnostic;
10
10
  /** 生成双引号包裹的 jpFun 源码,仅转义反斜杠和双引号;与 JSON.stringify 不同,保留真实换行和制表符 */
11
11
  export declare function quote(value: string): string;
@@ -13,17 +13,19 @@ export function findClosingQuote(source, quotePos, end) {
13
13
  }
14
14
  return -1;
15
15
  }
16
- /** 剥掉成对的双引号并反转义;解码失败时返回相对 source 的诊断,裸参数原样返回 */
16
+ /** 剥掉成对的双引号(若有)并解码编码/定界级转义(`\"`、`\\`、`\uXXXX`);其余 `\X` 原样保留给具体函数解析 */
17
17
  export function parseString(source) {
18
- if (source.length < 2 || !source.startsWith('"') || !source.endsWith('"'))
19
- return source;
18
+ const quoted = source.length >= 2 && source.startsWith('"') && source.endsWith('"');
19
+ const raw = quoted ? source.slice(1, -1) : source;
20
20
  let diagnostic;
21
21
  // 连同不完整转义一起匹配以便诊断;替换结果不会被再次扫描
22
- const text = source.slice(1, -1).replace(/\\(u.{0,4}|.)/gs, (escape, body, offset) => {
23
- if (body[0] !== "u")
22
+ const text = raw.replace(/\\(u.{0,4}|.)/gs, (escape, body, offset) => {
23
+ if (body === '"' || body === "\\")
24
24
  return body;
25
+ if (body[0] !== "u")
26
+ return escape;
25
27
  if (!/^u[0-9a-f]{4}$/i.test(body)) {
26
- const start = offset + 1;
28
+ const start = offset + (quoted ? 1 : 0);
27
29
  diagnostic ??= Diagnostic.warning.InvalidUnicodeEscape({ start, end: start + escape.length });
28
30
  return escape;
29
31
  }
@@ -3,7 +3,6 @@ import { Diagnostic } from "../diagnostic.js";
3
3
  import { GrammarCallNode, GrammarNode, type SyntaxAnalysis } from "./grammarType.js";
4
4
  import { ASTFunctionClass, ASTFunctionNode, ASTNodeBase, paramType, paramValue } from "../functions/ASTtypes.js";
5
5
  export declare const DEFAULT_FONT_SIZE = 22;
6
- export declare const DEFAULT_OCTAVE = 4;
7
6
  export declare class ParserContext {
8
7
  /** 系统变量,供 `@set` 读取 */
9
8
  static systemVariables: Record<string, {
@@ -62,17 +61,18 @@ export declare class ParserContext {
62
61
  private addSyntax;
63
62
  /** 把已识别的 GrammarNode 映射为源码 token;content/brace 在这里继续递归 */
64
63
  private recordSyntax;
64
+ /**
65
+ * 向前寻找最后一个非文本节点下标;
66
+ * 若末尾是标签,则将“被标注节点..标签”原位打包为 ASTBraceNode
67
+ */
68
+ findLastOperandIndex(): number;
69
+ /** 摘出末尾最后一个操作数(含其后置标签) */
70
+ takeLeftOperand(): ASTNodeBase | null;
71
+ /** 解析右侧剩余序列,将首个非文本节点交给 combine 合成后连同后续节点写回 this.nodes */
72
+ consumeRightOperand(nodes: (GrammarNode | number)[], at: number, combine: (right: ASTNodeBase) => ASTNodeBase): number | null;
65
73
  /**
66
74
  * 第二轮去糖 & 函数节点创建
67
75
  * 有副作用 会修改 nodes 和 labelableNodes 等上下文属性
68
- * 对于需要后面Node的语法糖(没有终止符),可以调用此函数,具体做法为:
69
- * 1. 先用构造函数开启子上下文
70
- * 2. 再用新的上下文解析剩余的nodes
71
- * 3. 选取需要的,利用老的ctx构建函数节点
72
- * 4. 将新ctx的有用信息合并回老的ctx
73
- * 之所以这么麻烦,是因为创建语法糖对应节点时需要保留当前上下文
74
- *
75
- * 对于有终止符的直接搜索后面的终止符即可。扫过的地方普通文本会再次被合并
76
76
  */
77
77
  makeNodes(nodes: (GrammarNode | number)[], i?: number, end?: number): number;
78
78
  /**
@@ -23,7 +23,6 @@ function classifySyntaxValue(type, text) {
23
23
  return undefined;
24
24
  }
25
25
  export const DEFAULT_FONT_SIZE = 22;
26
- export const DEFAULT_OCTAVE = 4;
27
26
  // 解析上下文
28
27
  export class ParserContext {
29
28
  /** 系统变量,供 `@set` 读取 */
@@ -231,17 +230,62 @@ export class ParserContext {
231
230
  }
232
231
  this.addSyntax("punctuation", call.closeParenSpan);
233
232
  }
233
+ /**
234
+ * 向前寻找最后一个非文本节点下标;
235
+ * 若末尾是标签,则将“被标注节点..标签”原位打包为 ASTBraceNode
236
+ */
237
+ findLastOperandIndex() {
238
+ let left = this.nodes.length - 1;
239
+ while (left >= 0 && this.nodes[left] instanceof ASTTextNode)
240
+ left--;
241
+ if (left < 0)
242
+ return -1;
243
+ const node = this.nodes[left];
244
+ if (node instanceof ASTLabelNode) {
245
+ let tgt = node.target;
246
+ while (tgt.parent)
247
+ tgt = tgt.parent;
248
+ const j = this.nodes.lastIndexOf(tgt, left - 1);
249
+ if (j < 0)
250
+ return -1;
251
+ this.nodes.splice(j, left - j + 1, new ASTBraceNode({ start: tgt.sourceSpan.start, end: node.sourceSpan.end }, this.nodes.slice(j, left + 1), null));
252
+ return j;
253
+ }
254
+ return left;
255
+ }
256
+ /** 摘出末尾最后一个操作数(含其后置标签) */
257
+ takeLeftOperand() {
258
+ const index = this.findLastOperandIndex();
259
+ if (index < 0)
260
+ return null;
261
+ const node = this.nodes[index];
262
+ this.nodes.length = index;
263
+ return node;
264
+ }
265
+ /** 解析右侧剩余序列,将首个非文本节点交给 combine 合成后连同后续节点写回 this.nodes */
266
+ consumeRightOperand(nodes, at, combine) {
267
+ const storage = this.nodes;
268
+ this.nodes = [];
269
+ try {
270
+ this.makeNodes(nodes, at);
271
+ for (let i = 0; i < this.nodes.length; i++) {
272
+ const right = this.nodes[i];
273
+ if (right instanceof ASTTextNode)
274
+ continue;
275
+ storage.push(combine(right));
276
+ while (++i < this.nodes.length)
277
+ storage.push(this.nodes[i]);
278
+ return nodes.length;
279
+ }
280
+ return null;
281
+ }
282
+ finally {
283
+ this.nodes = storage;
284
+ }
285
+ }
234
286
  /**
235
287
  * 第二轮去糖 & 函数节点创建
236
288
  * 有副作用 会修改 nodes 和 labelableNodes 等上下文属性
237
- * 对于需要后面Node的语法糖(没有终止符),可以调用此函数,具体做法为:
238
- * 1. 先用构造函数开启子上下文
239
- * 2. 再用新的上下文解析剩余的nodes
240
- * 3. 选取需要的,利用老的ctx构建函数节点
241
- * 4. 将新ctx的有用信息合并回老的ctx
242
- * 之所以这么麻烦,是因为创建语法糖对应节点时需要保留当前上下文
243
- *
244
- * 对于有终止符的直接搜索后面的终止符即可。扫过的地方普通文本会再次被合并
245
289
  */
246
290
  makeNodes(nodes, i = 0, end = nodes.length) {
247
291
  outer: for (; i < end; i++) {
@@ -534,7 +578,7 @@ export class ParserContext {
534
578
  s.span.start += start;
535
579
  s.span.end += start;
536
580
  this.diagnostics.push(s);
537
- return text.slice(1, -1);
581
+ return text.length >= 2 && text.startsWith('"') && text.endsWith('"') ? text.slice(1, -1) : text;
538
582
  }
539
583
  return s;
540
584
  }
package/dist/pipeline.js CHANGED
@@ -19,8 +19,8 @@ export function compileScore(source, options = {}) {
19
19
  const parser = new ParserContext({ source: maskedSource, variables });
20
20
  parser.registerFunctions(functions);
21
21
  const ast = new ASTBraceNode({ start: 0, end: source.length }, parser.parse());
22
- const loweringContext = new LoweringContext(parser.diagnostics);
23
- const lowering = loweringContext.lowerDocument(ast);
22
+ const loweringContext = new LoweringContext();
23
+ const lowering = loweringContext.lowerDocument(ast, parser.diagnostics);
24
24
  const layoutContext = createLayoutPrepareContext(functions, { textMeasurer });
25
25
  const layout = layoutDocument(lowering, layoutContext, layoutOptions);
26
26
  return {
@@ -228,8 +228,7 @@ export function compilePlayback(lowering, options) {
228
228
  const program = node.playbackState?.program;
229
229
  if (program !== undefined && activePrograms.get(track) !== program) {
230
230
  activePrograms.set(track, program);
231
- events.push({ kind: "program-change", at: start.clone(), order: nextEventOrder++,
232
- origins: lineage, track, program });
231
+ events.push({ kind: "program-change", at: start.clone(), order: nextEventOrder++, track, program });
233
232
  }
234
233
  const bpm = node.playbackState?.bpm;
235
234
  if (bpm !== undefined)
@@ -268,8 +267,7 @@ export function compilePlayback(lowering, options) {
268
267
  spanScales.set(span, scales);
269
268
  span.end.add(duration);
270
269
  },
271
- emit: event => events.push({ ...event, at: event.at.clone(),
272
- order: nextEventOrder++, origins: lineage }),
270
+ emit: event => events.push({ ...event, at: event.at.clone(), order: nextEventOrder++ }),
273
271
  control: (at, apply) => scheduleControl(at, lineage, apply),
274
272
  /** 只登记效果身份和比例,范围等结构与连接确定后再计算 */
275
273
  scaleFollowingBpm(key, numerator, denominator = 1, options) {
@@ -401,12 +399,11 @@ export function compilePlayback(lowering, options) {
401
399
  // 结构与连接全部确定后,只扫描一次状态;后续声音变换统一读取这份最终结果
402
400
  while (changeIndex < changes.length) {
403
401
  const at = changes[changeIndex].at;
404
- const origins = new Set();
402
+ let lastOrigin;
405
403
  // 同刻控制和效果边界全部应用后才生成快照,避免输出由扫描顺序造成的瞬时速度
406
404
  while (changeIndex < changes.length && changes[changeIndex].at.equals(at)) {
407
405
  const change = changes[changeIndex++];
408
- for (const origin of change.origins)
409
- origins.add(origin);
406
+ lastOrigin = change.origins.at(-1) ?? lastOrigin;
410
407
  if (change.kind === "control")
411
408
  change.apply(system);
412
409
  else if (change.kind === "scale") {
@@ -428,7 +425,7 @@ export function compilePlayback(lowering, options) {
428
425
  effectiveBpm: system.bpm * bpmScale.toNumber(),
429
426
  };
430
427
  if (!Number.isFinite(snapshot.effectiveBpm) || snapshot.effectiveBpm <= 0) {
431
- throw new ErrorDiagnostic("E_PLAYBACK_BPM", "系统控制产生了无效速度", [...origins].at(-1)?.node.ast.sourceSpan ?? { start: 0, end: 0 });
428
+ throw new ErrorDiagnostic("E_PLAYBACK_BPM", "系统控制产生了无效速度", lastOrigin?.node.ast.sourceSpan ?? { start: 0, end: 0 });
432
429
  }
433
430
  const previous = statePoints.at(-1)?.state;
434
431
  if (!previous || previous.bpm !== snapshot.bpm || !previous.bpmScale.equals(bpmScale)) {
@@ -441,7 +438,6 @@ export function compilePlayback(lowering, options) {
441
438
  at: at.clone(),
442
439
  bpm: snapshot.effectiveBpm,
443
440
  order: nextEventOrder++,
444
- origins: [...origins],
445
441
  });
446
442
  }
447
443
  }
@@ -465,6 +461,7 @@ export function compilePlayback(lowering, options) {
465
461
  };
466
462
  const canAbsorb = (from, to) => !transforms.has(to)
467
463
  && from.track === to.track && from.midi === to.midi && from.percussion === to.percussion;
464
+ const audible = new Set();
468
465
  const realized = new Map();
469
466
  // 后继无独立变换时直接并入前驱音段,使首段装饰与奏法覆盖连续连音;有新变换时从该处分段并在交界处合并同音
470
467
  for (const note of notes) {
@@ -519,16 +516,18 @@ export function compilePlayback(lowering, options) {
519
516
  ? []
520
517
  : undefined;
521
518
  for (const sound of owned) {
522
- const { start, end, track, midi, velocity, percussion, origins, sourceSpans } = sound;
519
+ const { start, end, track, midi, velocity, percussion, sourceSpans } = sound;
523
520
  const noteId = nextNoteId++;
524
521
  const on = {
525
522
  kind: "note-on", at: start.clone(), noteId, order: nextEventOrder++,
526
523
  track, midi, velocity, percussion,
527
- origins, sourceSpans: [...sourceSpans],
524
+ sourceSpans: [...sourceSpans],
528
525
  };
529
526
  const off = {
530
- kind: "note-off", at: end.clone(), noteId, order: nextEventOrder++, origins,
527
+ kind: "note-off", at: end.clone(), noteId, order: nextEventOrder++,
528
+ track, midi,
531
529
  };
530
+ audible.add(track);
532
531
  events.push(on, off);
533
532
  pairs?.push({ on, off });
534
533
  }
@@ -566,9 +565,9 @@ export function compilePlayback(lowering, options) {
566
565
  on.sourceSpans.push(...next.sourceSpans);
567
566
  }
568
567
  }
569
- // 稳定排序后,由统一出口检查配对、压实轨道编号并剥离编译期字段
568
+ // 稳定排序后,由统一出口压实轨道编号并剥离编译期字段
570
569
  const finalEvents = (removed.size ? events.filter(event => !removed.has(event)) : events).sort(comparePlaybackDraftEvents);
571
- const output = finalizePlaybackEvents(finalEvents, lowering.tracks);
570
+ const output = finalizePlaybackEvents(finalEvents, lowering.tracks, audible);
572
571
  const eventEnd = finalEvents.at(-1)?.at;
573
572
  if (eventEnd && eventEnd.compare(performanceEnd) > 0)
574
573
  performanceEnd.copyFrom(eventEnd);
@@ -46,9 +46,8 @@ export interface PlaybackOrigin {
46
46
  interface PlaybackDraftEventBase {
47
47
  at: Fraction;
48
48
  order: number;
49
- origins: readonly PlaybackOrigin[];
50
49
  }
51
- /** 声音展开后生成的点事件;最终输出前会校验并剥离内部字段 */
50
+ /** 声音展开后生成的点事件;最终输出前压实轨道编号并剥离编译期字段 */
52
51
  export interface PlaybackDraftNoteOnEvent extends PlaybackDraftEventBase {
53
52
  kind: "note-on";
54
53
  noteId: PlaybackNoteId;
@@ -56,12 +55,13 @@ export interface PlaybackDraftNoteOnEvent extends PlaybackDraftEventBase {
56
55
  midi: number;
57
56
  velocity: number;
58
57
  percussion?: true;
59
- transpose?: (steps: number) => number;
60
58
  sourceSpans: SourceSpan[];
61
59
  }
62
60
  export interface PlaybackDraftNoteOffEvent extends PlaybackDraftEventBase {
63
61
  kind: "note-off";
64
62
  noteId: PlaybackNoteId;
63
+ track: Track;
64
+ midi: number;
65
65
  }
66
66
  export interface PlaybackDraftTempoEvent extends PlaybackDraftEventBase {
67
67
  kind: "tempo";
@@ -87,10 +87,10 @@ export interface PlaybackEventInput {
87
87
  /** 同刻先处理系统状态,再关音和开音;相同类别保持原发布次序 */
88
88
  export declare function comparePlaybackDraftEvents(left: PlaybackDraftEvent, right: PlaybackDraftEvent): number;
89
89
  /**
90
- * 校验配对、压实发声 Track 编号并剥掉编译期字段,得到稳定、可序列化的公开事件
91
- * 输入已经稳定排序;这里保留次序,将编译期的 Track 对象和音符配对转换为公开字段
90
+ * 压实发声 Track 编号并剥掉编译期字段,得到稳定、可序列化的公开事件
91
+ * 输入已经稳定排序;这里保留次序,将编译期的 Track 对象转换为公开通道编号
92
92
  */
93
- export declare function finalizePlaybackEvents(events: readonly PlaybackDraftEvent[], trackOrder: readonly Track[]): {
93
+ export declare function finalizePlaybackEvents(events: readonly PlaybackDraftEvent[], trackOrder: readonly Track[], audible: ReadonlySet<Track>): {
94
94
  events: PlaybackEvent[];
95
95
  tracks: Track[];
96
96
  };
@@ -11,44 +11,10 @@ export function comparePlaybackDraftEvents(left, right) {
11
11
  return byTime || EVENT_PRIORITY[left.kind] - EVENT_PRIORITY[right.kind] || left.order - right.order;
12
12
  }
13
13
  /**
14
- * 校验配对、压实发声 Track 编号并剥掉编译期字段,得到稳定、可序列化的公开事件
15
- * 输入已经稳定排序;这里保留次序,将编译期的 Track 对象和音符配对转换为公开字段
14
+ * 压实发声 Track 编号并剥掉编译期字段,得到稳定、可序列化的公开事件
15
+ * 输入已经稳定排序;这里保留次序,将编译期的 Track 对象转换为公开通道编号
16
16
  */
17
- export function finalizePlaybackEvents(events, trackOrder) {
18
- const noteOns = new Map();
19
- const noteOffs = new Map();
20
- // 同一音符的两端不一定相邻,先按 noteId 建立索引并拒绝重复的开音或关音
21
- for (const event of events) {
22
- if (event.kind === "note-on") {
23
- if (noteOns.has(event.noteId))
24
- throw new Error(`Duplicate NoteOn ${event.noteId}`);
25
- noteOns.set(event.noteId, event);
26
- }
27
- else if (event.kind === "note-off") {
28
- if (noteOffs.has(event.noteId))
29
- throw new Error(`Duplicate NoteOff ${event.noteId}`);
30
- noteOffs.set(event.noteId, event);
31
- }
32
- }
33
- const audible = new Set();
34
- // 物理合并完成后仍必须一一配对,并保留正时值和可追溯的来源;同时收集实际发声轨道
35
- for (const [noteId, on] of noteOns) {
36
- const off = noteOffs.get(noteId);
37
- if (!off)
38
- throw new Error(`Note ${noteId} has no NoteOff`);
39
- if (off.at.compare(on.at) <= 0)
40
- throw new Error(`Note ${noteId} has a non-positive duration`);
41
- if (on.origins.length === 0 || off.origins.length === 0)
42
- throw new Error(`Note ${noteId} has no origin`);
43
- audible.add(on.track);
44
- }
45
- // 仅当关音数量多于开音时反查孤立的 NoteOff
46
- if (noteOffs.size !== noteOns.size) {
47
- for (const noteId of noteOffs.keys()) {
48
- if (!noteOns.has(noteId))
49
- throw new Error(`NoteOff ${noteId} has no NoteOn`);
50
- }
51
- }
17
+ export function finalizePlaybackEvents(events, trackOrder, audible) {
52
18
  // 保留 lowering 的稳定轨道顺序,只过滤未实际发声的轨道
53
19
  const trackIds = new Map();
54
20
  for (const track of trackOrder) {
@@ -76,20 +42,18 @@ export function finalizePlaybackEvents(events, trackOrder) {
76
42
  });
77
43
  continue;
78
44
  }
45
+ const track = trackIds.get(event.track);
46
+ if (track === undefined)
47
+ continue;
79
48
  if (event.kind === "program-change") {
80
- const track = trackIds.get(event.track);
81
- if (track !== undefined)
82
- output.push({
83
- kind: "program-change",
84
- at: event.at,
85
- track,
86
- program: event.program,
87
- });
49
+ output.push({
50
+ kind: "program-change",
51
+ at: event.at,
52
+ track,
53
+ program: event.program,
54
+ });
88
55
  continue;
89
56
  }
90
- // NoteOff 从配对的 NoteOn 取得轨道和键号,保证两端始终使用相同的最终身份
91
- const on = event.kind === "note-on" ? event : noteOns.get(event.noteId);
92
- const track = trackIds.get(on.track);
93
57
  if (event.kind === "note-on") {
94
58
  output.push({
95
59
  kind: "note-on",
@@ -108,7 +72,7 @@ export function finalizePlaybackEvents(events, trackOrder) {
108
72
  at: event.at,
109
73
  noteId: event.noteId,
110
74
  track,
111
- midi: on.midi,
75
+ midi: event.midi,
112
76
  });
113
77
  }
114
78
  return { events: output, tracks: [...trackIds.keys()] };
@@ -9,8 +9,6 @@ import type { PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from
9
9
  export declare class CanvasPainter implements Painter {
10
10
  private readonly context;
11
11
  constructor(context: CanvasRenderingContext2D);
12
- private beginOpacity;
13
- private endOpacity;
14
12
  drawText(text: string, x: number, y: number, style: TextStyle): void;
15
13
  drawLine(x1: number, y1: number, x2: number, y2: number, style?: PaintStyle): void;
16
14
  drawRect(x: number, y: number, w: number, h: number, style?: PaintStyle): void;
@@ -35,28 +35,14 @@ export class CanvasPainter {
35
35
  constructor(context) {
36
36
  this.context = context;
37
37
  }
38
- beginOpacity(style) {
39
- if (style?.opacity === void 0)
40
- return void 0;
41
- const previous = this.context.globalAlpha;
42
- this.context.globalAlpha = previous * style.opacity;
43
- return previous;
44
- }
45
- endOpacity(previous) {
46
- if (previous !== void 0)
47
- this.context.globalAlpha = previous;
48
- }
49
38
  drawText(text, x, y, style) {
50
- const previousAlpha = this.beginOpacity(style);
51
39
  this.context.fillStyle = style.fill ?? "#000";
52
40
  this.context.font = canvasFont(style);
53
41
  this.context.textAlign = style.textAlign ?? "left";
54
42
  this.context.textBaseline = "alphabetic";
55
43
  this.context.fillText(text, x, y);
56
- this.endOpacity(previousAlpha);
57
44
  }
58
45
  drawLine(x1, y1, x2, y2, style) {
59
- const previousAlpha = this.beginOpacity(style);
60
46
  this.context.beginPath();
61
47
  this.context.moveTo(x1, y1);
62
48
  this.context.lineTo(x2, y2);
@@ -64,12 +50,10 @@ export class CanvasPainter {
64
50
  this.context.lineWidth = style?.strokeWidth ?? 1;
65
51
  this.context.lineCap = "round";
66
52
  this.context.stroke();
67
- this.endOpacity(previousAlpha);
68
53
  }
69
54
  drawRect(x, y, w, h, style) {
70
55
  if (w < 0 || h < 0)
71
56
  return;
72
- const previousAlpha = this.beginOpacity(style);
73
57
  if (style?.fill) {
74
58
  this.context.fillStyle = style.fill;
75
59
  this.context.fillRect(x, y, w, h);
@@ -80,12 +64,10 @@ export class CanvasPainter {
80
64
  this.context.lineJoin = "miter";
81
65
  this.context.strokeRect(x, y, w, h);
82
66
  }
83
- this.endOpacity(previousAlpha);
84
67
  }
85
68
  drawCircle(cx, cy, r, style) {
86
69
  if (r < 0)
87
70
  return;
88
- const previousAlpha = this.beginOpacity(style);
89
71
  this.context.beginPath();
90
72
  this.context.arc(cx, cy, r, 0, Math.PI * 2);
91
73
  const fill = style?.fill ?? "#000";
@@ -98,12 +80,10 @@ export class CanvasPainter {
98
80
  this.context.lineWidth = style.strokeWidth ?? 1;
99
81
  this.context.stroke();
100
82
  }
101
- this.endOpacity(previousAlpha);
102
83
  }
103
84
  drawPath(commands, style, transform) {
104
85
  if (commands.length === 0)
105
86
  return;
106
- const previousAlpha = this.beginOpacity(style);
107
87
  tracePath(this.context, commands, transform?.x, transform?.y, transform?.scaleX, transform?.scaleY);
108
88
  if (style?.fill) {
109
89
  this.context.fillStyle = style.fill;
@@ -116,7 +96,6 @@ export class CanvasPainter {
116
96
  this.context.lineJoin = "round";
117
97
  this.context.stroke();
118
98
  }
119
- this.endOpacity(previousAlpha);
120
99
  }
121
100
  }
122
101
  /** 使用 Canvas 后端把一个布局结果一次绘制到独立页面 context */
@@ -1,7 +1,6 @@
1
1
  import type { DocumentLayoutResult } from "../layout/engine.js";
2
2
  import type { PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from "./types.js";
3
3
  export interface SvgRenderOptions {
4
- padding?: number;
5
4
  background?: string;
6
5
  }
7
6
  /** 生成独立 SVG 字符串的 Painter;路径直接输出最终坐标 */