jpfun 0.6.0 → 0.8.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 (134) hide show
  1. package/Bravura-LICENSE.txt +93 -0
  2. package/README.md +49 -146
  3. package/dist/Bravura-LICENSE.txt +93 -0
  4. package/dist/converter/midi/convert.d.ts +3 -11
  5. package/dist/converter/midi/convert.js +89 -67
  6. package/dist/converter/musicxml/features.d.ts +34 -12
  7. package/dist/converter/musicxml/features.js +131 -24
  8. package/dist/converter/musicxml/index.js +221 -54
  9. package/dist/converter/musicxml/model.d.ts +24 -0
  10. package/dist/core.d.ts +1 -0
  11. package/dist/core.js +1 -0
  12. package/dist/diagnostic.d.ts +7 -1
  13. package/dist/diagnostic.js +40 -88
  14. package/dist/fraction.js +3 -2
  15. package/dist/functions/ASTtypes.d.ts +2 -18
  16. package/dist/functions/ASTtypes.js +0 -16
  17. package/dist/functions/arpeggio/index.js +17 -22
  18. package/dist/functions/arpeggio/shape.d.ts +1 -1
  19. package/dist/functions/arpeggio/shape.js +27 -21
  20. package/dist/functions/bar/index.d.ts +8 -0
  21. package/dist/functions/bar/index.js +139 -36
  22. package/dist/functions/beam/auto.d.ts +1 -2
  23. package/dist/functions/beam/auto.js +44 -27
  24. package/dist/functions/beam/index.js +2 -3
  25. package/dist/functions/beam/layout.d.ts +1 -1
  26. package/dist/functions/beam/layout.js +16 -24
  27. package/dist/functions/br/index.d.ts +34 -2
  28. package/dist/functions/br/index.js +8 -8
  29. package/dist/functions/dash/index.js +6 -6
  30. package/dist/functions/default.js +10 -5
  31. package/dist/functions/div/index.d.ts +1 -0
  32. package/dist/functions/div/index.js +8 -4
  33. package/dist/functions/dot/index.js +2 -2
  34. package/dist/functions/dyn/index.js +49 -31
  35. package/dist/functions/gliss/index.d.ts +2 -0
  36. package/dist/functions/gliss/index.js +202 -0
  37. package/dist/functions/grace/index.d.ts +1 -7
  38. package/dist/functions/grace/index.js +11 -19
  39. package/dist/functions/head/index.js +41 -60
  40. package/dist/functions/key/index.js +8 -10
  41. package/dist/functions/meter/index.d.ts +56 -1
  42. package/dist/functions/meter/index.js +30 -24
  43. package/dist/functions/note/accidentals.js +10 -16
  44. package/dist/functions/note/index.js +18 -8
  45. package/dist/functions/note/noteName.d.ts +16 -0
  46. package/dist/functions/note/noteName.js +88 -0
  47. package/dist/functions/note/source-transform.js +6 -5
  48. package/dist/functions/ottava/index.d.ts +2 -0
  49. package/dist/functions/ottava/index.js +233 -0
  50. package/dist/functions/page/index.d.ts +1 -0
  51. package/dist/functions/page/index.js +22 -13
  52. package/dist/functions/pagebreak/index.d.ts +2 -0
  53. package/dist/functions/pagebreak/index.js +36 -0
  54. package/dist/functions/rest/index.js +15 -15
  55. package/dist/functions/set/index.js +4 -4
  56. package/dist/functions/slide/index.d.ts +2 -0
  57. package/dist/functions/slide/index.js +132 -0
  58. package/dist/functions/stack/index.js +8 -15
  59. package/dist/functions/symbol/index.d.ts +30 -2
  60. package/dist/functions/symbol/index.js +93 -19
  61. package/dist/functions/symbol/ornament.d.ts +1 -2
  62. package/dist/functions/symbol/ornament.js +14 -19
  63. package/dist/functions/symbol/shape.d.ts +6 -0
  64. package/dist/functions/symbol/shape.js +20 -4
  65. package/dist/functions/symbol/symbols/coda.d.ts +4 -0
  66. package/dist/functions/symbol/symbols/coda.js +56 -0
  67. package/dist/functions/symbol/symbols/dynamics.d.ts +1 -1
  68. package/dist/functions/symbol/symbols/dynamics.js +18 -8
  69. package/dist/functions/symbol/symbols/fine.js +1 -1
  70. package/dist/functions/symbol/symbols/harmonic.d.ts +2 -0
  71. package/dist/functions/symbol/symbols/harmonic.js +11 -0
  72. package/dist/functions/symbol/symbols/marcato.d.ts +2 -0
  73. package/dist/functions/symbol/symbols/marcato.js +22 -0
  74. package/dist/functions/symbol/symbols/staccato.d.ts +2 -0
  75. package/dist/functions/symbol/symbols/staccato.js +24 -0
  76. package/dist/functions/symbol/symbols/tenuto.d.ts +2 -0
  77. package/dist/functions/symbol/symbols/tenuto.js +11 -0
  78. package/dist/functions/symbol/symbols/tocoda.d.ts +2 -0
  79. package/dist/functions/symbol/symbols/tocoda.js +16 -0
  80. package/dist/functions/symbol/symbols/tr.js +46 -1
  81. package/dist/functions/symbol/symbols/turn.d.ts +3 -0
  82. package/dist/functions/symbol/symbols/turn.js +50 -0
  83. package/dist/functions/symbol/symbols/wheel.d.ts +2 -0
  84. package/dist/functions/symbol/symbols/wheel.js +36 -0
  85. package/dist/functions/temporal.d.ts +17 -6
  86. package/dist/functions/temporal.js +17 -6
  87. package/dist/functions/text/index.js +15 -6
  88. package/dist/functions/tie/index.js +64 -30
  89. package/dist/functions/tremolo/index.d.ts +2 -0
  90. package/dist/functions/tremolo/index.js +319 -0
  91. package/dist/functions/tuplet/index.js +4 -8
  92. package/dist/functions/up/index.js +7 -9
  93. package/dist/functions/voice/connections.js +7 -5
  94. package/dist/functions/voice/index.js +19 -11
  95. package/dist/functions/volta/index.js +41 -21
  96. package/dist/jpfun.core.min.js +64 -80
  97. package/dist/jpfun.from-midi.min.js +5 -5
  98. package/dist/jpfun.from-musicxml.min.js +8 -8
  99. package/dist/jpfun.min.js +69 -85
  100. package/dist/layout/default.d.ts +0 -1
  101. package/dist/layout/default.js +0 -1
  102. package/dist/layout/engine.d.ts +1 -0
  103. package/dist/layout/engine.js +42 -11
  104. package/dist/layout/page.d.ts +3 -2
  105. package/dist/layout/page.js +6 -5
  106. package/dist/layout/types.d.ts +4 -0
  107. package/dist/lowering/loweringContext.d.ts +11 -13
  108. package/dist/lowering/loweringContext.js +30 -197
  109. package/dist/lowering/types.d.ts +1 -3
  110. package/dist/parser/parse-utils/note-utils.d.ts +1 -1
  111. package/dist/parser/parse-utils/note-utils.js +8 -9
  112. package/dist/parser/parse-utils/string-utils.d.ts +3 -2
  113. package/dist/parser/parse-utils/string-utils.js +16 -3
  114. package/dist/parser/parserContext.d.ts +2 -0
  115. package/dist/parser/parserContext.js +36 -8
  116. package/dist/pipeline.js +0 -1
  117. package/dist/playback/compile.js +131 -72
  118. package/dist/playback/event.d.ts +1 -1
  119. package/dist/playback/event.js +9 -9
  120. package/dist/playback/time.js +42 -31
  121. package/dist/playback/types.d.ts +7 -3
  122. package/dist/render/canvas.d.ts +2 -0
  123. package/dist/render/canvas.js +25 -22
  124. package/dist/render/recording.js +1 -4
  125. package/dist/render/svg.js +1 -0
  126. package/dist/render/text.d.ts +1 -1
  127. package/dist/render/text.js +3 -2
  128. package/dist/render/translate.d.ts +0 -1
  129. package/dist/render/translate.js +6 -23
  130. package/dist/render/types.d.ts +1 -0
  131. package/grammar.md +52 -25
  132. package/package.json +3 -3
  133. package/dist/functions/note/noteNameFSM.d.ts +0 -8
  134. package/dist/functions/note/noteNameFSM.js +0 -181
@@ -0,0 +1,319 @@
1
+ import { ErrorDiagnostic } from "../../diagnostic.js";
2
+ import { pathBounds } from "../../layout/path.js";
3
+ import { ASTFunctionNode, } from "../ASTtypes.js";
4
+ import { isVisualTemporalNode } from "../temporal.js";
5
+ const MAX_SUBNOTES = 256;
6
+ function isDash(node) {
7
+ return node.ast instanceof ASTFunctionNode && node.ast.callName === "dash";
8
+ }
9
+ function isAudibleNote(item) {
10
+ return "midi" in item;
11
+ }
12
+ function collectNoteAxes(node, axes = []) {
13
+ if ("host" in node && isVisualTemporalNode(node.host)) {
14
+ return collectNoteAxes(node.host, axes);
15
+ }
16
+ if ("members" in node && Array.isArray(node.members)) {
17
+ for (const member of node.members)
18
+ collectNoteAxes(member, axes);
19
+ return axes;
20
+ }
21
+ if (typeof node.resolvedMidi === "number"
22
+ || node.ast.name === "9") {
23
+ axes.push(node.box.y + node.box.visualAxis);
24
+ }
25
+ return axes;
26
+ }
27
+ function visualCenterY(node) {
28
+ const axes = collectNoteAxes(node);
29
+ return (Math.min(...axes) + Math.max(...axes)) / 2;
30
+ }
31
+ function collectVisitSpans(list, target, endAt) {
32
+ let targetOrigin;
33
+ const matched = [];
34
+ for (let i = list.length - 1; i >= 0; i--) {
35
+ const item = list[i];
36
+ if (item.origins.at(-1).node.track !== target.track)
37
+ continue;
38
+ const origin = item.origins.find(entry => entry.node === target);
39
+ if (!targetOrigin) {
40
+ if (!origin)
41
+ continue;
42
+ if (endAt && !item.end.equals(endAt))
43
+ return [];
44
+ targetOrigin = origin;
45
+ }
46
+ else if (origin !== targetOrigin) {
47
+ break;
48
+ }
49
+ if (endAt && !item.end.equals(endAt))
50
+ return [];
51
+ matched.push(item);
52
+ }
53
+ return matched;
54
+ }
55
+ function singleTremoloTransform(n) {
56
+ const rate = 1 << n;
57
+ return (_context, owned) => {
58
+ const result = [];
59
+ for (const note of owned) {
60
+ const duration = note.end.clone().sub(note.start);
61
+ const count = Math.min(MAX_SUBNOTES, Math.max(2, Math.round(duration.toNumber() * rate)));
62
+ const step = duration.div(count);
63
+ for (let i = 0; i < count; i++) {
64
+ const start = step.clone().mul(i).add(note.start);
65
+ result.push({
66
+ ...note,
67
+ start,
68
+ end: start.clone().add(step),
69
+ });
70
+ }
71
+ }
72
+ return result;
73
+ };
74
+ }
75
+ class TremoloFunction extends ASTFunctionNode {
76
+ static def = {
77
+ name: ["tremolo"],
78
+ description: "震音(同音震音与双音交替震音)",
79
+ details: `\
80
+ ~~~jpfun
81
+ @tremolo(5, n=3)
82
+ @tremolo({#5,^7, 2^4}, n=3)
83
+ ~~~
84
+ - **单音震音**:内容为单个音符或和弦(后可接增时线 \`-\`),斜杠记在最末元素右下角,播放时按 \`1 / 2^n\` 四分音符时值同音重复。
85
+ - **双音震音**:内容为两个同轨、等时值的相邻音符或和弦,斜杠记在两音之间,播放时在两音总时值内按 \`1 / 2^n\` 四分音符时值交替发声。`,
86
+ allowExtraArgs: false,
87
+ args: [
88
+ { type: "content", default: null, description: "单个音符(可带增时线)或两个等时值的音符/和弦" },
89
+ { name: "n", type: "number", default: 3, description: "斜杠数量,取 1..3 的整数" },
90
+ ],
91
+ };
92
+ content;
93
+ n;
94
+ get children() { return [this.content]; }
95
+ timeFlowModel() { return { children: [this.content], mode: "sequence" }; }
96
+ constructor(span, args, ctx, parent = null) {
97
+ super(span, parent);
98
+ const [content, n] = this.getArgValue(args, ctx);
99
+ if (!Number.isSafeInteger(n) || n < 1 || n > 3) {
100
+ throw new ErrorDiagnostic("E_TREMOLO_INVALID_N", "@tremolo 的斜杠数 n 必须是 1 到 3 的整数", span);
101
+ }
102
+ this.content = content;
103
+ this.n = n;
104
+ content.parent = this;
105
+ }
106
+ loweringEnter(ctx) {
107
+ for (let ancestor = this.parent; ancestor; ancestor = ancestor.parent) {
108
+ if (ancestor instanceof TremoloFunction) {
109
+ throw new ErrorDiagnostic("E_TREMOLO_CONTENT", "@tremolo 不能嵌套 @tremolo", this.sourceSpan);
110
+ }
111
+ }
112
+ const group = {
113
+ nodes: [],
114
+ onTemporal(node) { if (isVisualTemporalNode(node))
115
+ group.nodes.push(node); },
116
+ };
117
+ ctx.beginLoweringGroup(this, group);
118
+ return [];
119
+ }
120
+ loweringExit(ctx) {
121
+ const { nodes } = ctx.endLoweringGroup(this);
122
+ const isSingle = nodes.length >= 1 && !isDash(nodes[0]) && nodes.slice(1).every(isDash);
123
+ const isPair = nodes.length === 2 && !isDash(nodes[0]) && !isDash(nodes[1]);
124
+ if ((!isSingle && !isPair) || nodes.some(node => node.T.compare(0) <= 0)) {
125
+ throw new ErrorDiagnostic("E_TREMOLO_CONTENT", "@tremolo 的内容必须是单个音符(可带增时线)或两个等时值的音符/和弦", this.sourceSpan);
126
+ }
127
+ if (nodes.some(node => node.track !== nodes[0].track)) {
128
+ throw new ErrorDiagnostic("E_TREMOLO_CROSS_TRACK", "@tremolo 的内容必须位于同一音轨", this.sourceSpan);
129
+ }
130
+ const attachment = new TremoloAttachment(nodes, this);
131
+ ctx.addAttachment(attachment);
132
+ ctx.deferFinalize(() => attachment.finalize());
133
+ const anchorHost = isSingle ? nodes.at(-1) : nodes[0];
134
+ const prepare = anchorHost.prepareHorizontal;
135
+ anchorHost.prepareHorizontal = line => {
136
+ prepare?.call(anchorHost, line);
137
+ attachment.registerHorizontal(line);
138
+ };
139
+ return [];
140
+ }
141
+ toString(source) {
142
+ return `@tremolo(${this.content.toString(source)}, n=${this.n})`;
143
+ }
144
+ }
145
+ export const TremoloNode = TremoloFunction;
146
+ class TremoloAttachment {
147
+ nodes;
148
+ owner;
149
+ layer = "foreground";
150
+ endPoints;
151
+ get sourceSpan() { return this.owner.sourceSpan; }
152
+ constructor(nodes, owner) {
153
+ this.nodes = nodes;
154
+ this.owner = owner;
155
+ const isSingle = nodes.length === 1 || isDash(nodes[1]);
156
+ this.endPoints = isSingle ? [nodes.at(-1)] : [nodes[0], nodes[1]];
157
+ }
158
+ finalize() {
159
+ const { nodes, owner, endPoints } = this;
160
+ const single = endPoints.length === 1;
161
+ const line = nodes[0].layoutLine;
162
+ if (nodes.some(node => node.layoutLine !== line)) {
163
+ throw new ErrorDiagnostic("E_TREMOLO_CROSS_LINE", "@tremolo 不支持跨谱面行", owner.sourceSpan);
164
+ }
165
+ if (collectNoteAxes(nodes[0]).length === 0 || (!single && collectNoteAxes(nodes[1]).length === 0)) {
166
+ throw new ErrorDiagnostic("E_TREMOLO_CONTENT", "@tremolo 的目标必须包含发声音符", owner.sourceSpan);
167
+ }
168
+ if (single) {
169
+ const target = nodes[0];
170
+ const transform = singleTremoloTransform(owner.n);
171
+ const emit = target.emitPlayback;
172
+ target.emitPlayback = emitter => {
173
+ emit?.call(target, emitter);
174
+ emitter.defer(context => {
175
+ for (const span of collectVisitSpans(context.spans, target)) {
176
+ if (isAudibleNote(span))
177
+ context.transform(span, transform);
178
+ }
179
+ });
180
+ };
181
+ return;
182
+ }
183
+ const [first, second] = nodes;
184
+ if (!first.T.equals(second.T))
185
+ throw new ErrorDiagnostic("E_TREMOLO_DURATION_MISMATCH", "@tremolo 双音震音的两个目标时值必须相等", owner.sourceSpan);
186
+ const emitSecond = second.emitPlayback;
187
+ second.emitPlayback = emitter => {
188
+ emitSecond?.call(second, emitter);
189
+ const { start: secondStart, end: t2 } = emitter;
190
+ emitter.defer(context => {
191
+ const firstSpans = collectVisitSpans(context.spans, first, secondStart);
192
+ const secondSpans = collectVisitSpans(context.spans, second);
193
+ if (firstSpans.length === 0 || secondSpans.length === 0)
194
+ return;
195
+ const t0 = firstSpans.reduce((min, s) => s.start.compare(min) < 0 ? s.start : min, firstSpans[0].start).clone();
196
+ const total = t2.clone().sub(t0);
197
+ const pairs = Math.min(MAX_SUBNOTES / 2, Math.max(2, Math.round(total.toNumber() * (1 << (owner.n - 1)))));
198
+ const step = total.clone().div(pairs * 2);
199
+ const slice = (divisor, extendTail) => (_ctx, owned) => owned.flatMap(item => {
200
+ const baseEnd = item.end.compare(t2) > 0 ? t2 : item.end;
201
+ const sliceStep = baseEnd.clone().sub(item.start).div(divisor);
202
+ const out = [];
203
+ for (let k = 0; k < pairs; k++) {
204
+ const start = sliceStep.clone().mul(2 * k).add(item.start);
205
+ const end = extendTail && k === pairs - 1 && item.end.compare(t2) > 0
206
+ ? item.end.clone()
207
+ : start.clone().add(sliceStep);
208
+ out.push({ ...item, start, end });
209
+ }
210
+ return out;
211
+ });
212
+ const evenTransform = slice(pairs * 2, false);
213
+ const oddTransform = slice(pairs * 2 - 1, true);
214
+ for (const span of firstSpans) {
215
+ span.start.copyFrom(t0);
216
+ span.end.copyFrom(t2);
217
+ if (isAudibleNote(span))
218
+ context.transform(span, evenTransform);
219
+ }
220
+ for (const span of secondSpans) {
221
+ span.start.copyFrom(t0).add(step);
222
+ span.end.copyFrom(t2);
223
+ if (isAudibleNote(span))
224
+ context.transform(span, oddTransform);
225
+ }
226
+ });
227
+ };
228
+ }
229
+ registerHorizontal(line) {
230
+ if (this.endPoints.length === 1) {
231
+ const host = this.endPoints[0];
232
+ if (line.columnOf(host) < 0)
233
+ return;
234
+ const size = host.ast.size;
235
+ const space = host.box.w - host.box.anchor + size * 0.6;
236
+ line.registerHorizontalLayoutHook(host, host, ({ columns, start }) => {
237
+ for (const element of columns[start]) {
238
+ if (element.box !== host.box)
239
+ continue;
240
+ element.WR = Math.max(element.WR, space);
241
+ }
242
+ });
243
+ return;
244
+ }
245
+ const [from, to] = this.endPoints;
246
+ const start = line.columnOf(from);
247
+ const end = line.columnOf(to);
248
+ if (start < 0 || end < 0)
249
+ return;
250
+ if (end <= start || line.trackIndexOf(to) !== line.trackIndexOf(from) + 1) {
251
+ throw new ErrorDiagnostic("E_TREMOLO_ADJACENT", "@tremolo 双音震音的两个端点必须在同一谱面行相邻", this.owner.sourceSpan);
252
+ }
253
+ const size = Math.max(from.ast.size, to.ast.size);
254
+ const right = from.box.w - from.box.anchor + size * 0.84;
255
+ line.registerHorizontalLayoutHook(from, to, ({ columns }) => {
256
+ for (const element of columns[start])
257
+ element.WR = Math.max(element.WR, right);
258
+ });
259
+ }
260
+ createGeometry() {
261
+ const { n } = this.owner;
262
+ const host = this.endPoints[0];
263
+ let size = host.ast.size;
264
+ let left;
265
+ let right;
266
+ let centerY;
267
+ let rise;
268
+ let stepY;
269
+ if (this.endPoints.length === 1) {
270
+ left = host.box.x + host.box.w + size * 0.1;
271
+ right = left + size * 0.34;
272
+ centerY = host.box.y + host.box.visualAxis + size * 0.14;
273
+ rise = size * 0.18;
274
+ stepY = size * 0.12;
275
+ }
276
+ else {
277
+ const [from, to] = this.endPoints;
278
+ size = Math.max(from.ast.size, to.ast.size);
279
+ const gap = size * 0.12;
280
+ const availLeft = from.box.x + from.box.w + gap;
281
+ const availRight = to.box.x - gap;
282
+ if (availRight <= availLeft) {
283
+ throw new ErrorDiagnostic("E_TREMOLO_SPACE", "@tremolo 的端点之间没有可用的水平绘制空间", this.owner.sourceSpan);
284
+ }
285
+ const spanX = Math.min(availRight - availLeft, size * 1.2);
286
+ const midX = (availLeft + availRight) / 2;
287
+ left = midX - spanX / 2;
288
+ right = midX + spanX / 2;
289
+ centerY = (visualCenterY(from) + visualCenterY(to)) / 2;
290
+ rise = Math.min(size * 0.26, Math.max(size * 0.16, spanX * 0.32));
291
+ stepY = size * 0.13;
292
+ }
293
+ const strokeWidth = Math.max(1, size * 0.06);
294
+ const commands = buildSlashCommands(n, left, right, centerY, rise, stepY);
295
+ const bounds = pathBounds(commands);
296
+ const region = {
297
+ x: bounds.x - strokeWidth / 2,
298
+ y: bounds.y - strokeWidth / 2,
299
+ w: bounds.w + strokeWidth,
300
+ h: bounds.h + strokeWidth,
301
+ line: host.layoutLine,
302
+ track: host.track,
303
+ };
304
+ return {
305
+ regions: [region],
306
+ paint(painter) {
307
+ painter.drawPath(commands, { fill: "none", stroke: "#000", strokeWidth });
308
+ },
309
+ };
310
+ }
311
+ }
312
+ function buildSlashCommands(n, left, right, centerY, rise, stepY) {
313
+ const commands = [];
314
+ for (let i = 0; i < n; i++) {
315
+ const midY = centerY + (i - (n - 1) / 2) * stepY;
316
+ commands.push({ op: "M", x: left, y: midY + rise / 2 }, { op: "L", x: right, y: midY - rise / 2 });
317
+ }
318
+ return commands;
319
+ }
@@ -31,12 +31,6 @@ class TupletFunction extends ASTFunctionNode {
31
31
  },
32
32
  ],
33
33
  };
34
- static loweringFinalize = (result) => {
35
- for (const attachment of result.attachments) {
36
- if (attachment instanceof TupletLayoutAttachment)
37
- attachment.validate();
38
- }
39
- };
40
34
  content;
41
35
  normal;
42
36
  font;
@@ -83,7 +77,7 @@ class TupletFunction extends ASTFunctionNode {
83
77
  throw new ErrorDiagnostic("E_TUPLET_NON_INTEGRAL_UNITS", "@tuplet 的总时值必须是最短正时值的整数倍,且至少包含2个单位", this.sourceSpan);
84
78
  }
85
79
  if (this.normal === actual) {
86
- throw new ErrorDiagnostic("E_TUPLET_INVALID_RATIO", `@tuplet 的 normal 不能等于推导出的 actual (${actual})`, this.sourceSpan);
80
+ throw new ErrorDiagnostic("E_TUPLET_INVALID_RATIO", "@tuplet 的 normal 不能等于推导出的 actual ({actual})", this.sourceSpan, { actual });
87
81
  }
88
82
  // 以作用域最早时间为仿射缩放原点,不能直接缩放绝对 t,否则嵌套位置会漂移。
89
83
  let start = content.nodes[0].t;
@@ -103,7 +97,9 @@ class TupletFunction extends ASTFunctionNode {
103
97
  // 括线只依附可见主体;时值缩放本身仍覆盖所有收集到的事件。
104
98
  const visible = positive.filter(isVisualTemporalNode);
105
99
  if (visible.length >= 2) {
106
- ctx.addAttachment(new TupletLayoutAttachment(visible, actual, this.sourceSpan, this.font, content));
100
+ const attachment = new TupletLayoutAttachment(visible, actual, this.sourceSpan, this.font, content);
101
+ ctx.addAttachment(attachment);
102
+ ctx.deferFinalize(() => attachment.validate());
107
103
  }
108
104
  return [];
109
105
  }
@@ -1,6 +1,6 @@
1
1
  import { ASTNodeBase, ASTFunctionNode, ASTTextNode, ASTLabelNode, ASTBraceNode } from "../ASTtypes.js";
2
2
  import { ErrorDiagnostic } from "../../diagnostic.js";
3
- import { ANCHOR_KEY, DEFAULT_KEY, isVisualTemporalNode, TemporalNodeBase, } from "../temporal.js";
3
+ import { ANCHOR_KEY, DEFAULT_KEY, transferFunctionAddons, isVisualTemporalNode, TemporalNodeBase, } from "../temporal.js";
4
4
  import { Fraction } from "../../fraction.js";
5
5
  import { getLayoutBounds, layoutLocalSequence } from "../../layout/engine.js";
6
6
  /**
@@ -60,8 +60,8 @@ class FoldFunction extends ASTFunctionNode {
60
60
  for (const content of this.children) {
61
61
  const columns = ctx.trackedEvents(content, new Fraction(), track);
62
62
  const member = columns.length === 1 && columns[0].length === 1 ? columns[0][0] : undefined;
63
- if (!member || !isVisualTemporalNode(member)) {
64
- throw new ErrorDiagnostic("E_UP_INVALID_CHILD", "@up 的每个参数必须恰好产生一个可见 Temporal,且不能包含多声部结构", content.sourceSpan);
63
+ if (!member || !isVisualTemporalNode(member) || (member.addon?.breakBefore ?? 0) > 0) {
64
+ throw new ErrorDiagnostic("E_UP_INVALID_CHILD", "@up 的每个参数必须恰好产生一个可见 Temporal,且不能换行或包含多声部结构", content.sourceSpan);
65
65
  }
66
66
  members.push(member);
67
67
  }
@@ -121,7 +121,7 @@ class FoldFunction extends ASTFunctionNode {
121
121
  while (left >= 0 && ctx.nodes[left] instanceof ASTTextNode)
122
122
  left--;
123
123
  if (left < 0) {
124
- throw new ErrorDiagnostic("E_FOLD_NO_TARGET", `${label}语法糖错误: 左边没有找到可叠加的目标`, n.span);
124
+ throw new ErrorDiagnostic("E_FOLD_NO_TARGET", "{fn}语法糖错误: 左边没有找到可叠加的目标", n.span, { fn: label });
125
125
  }
126
126
  let leftNode = ctx.nodes[left];
127
127
  /** 左操作数在 ctx.nodes 中的起点;只有这一段会被折叠体吞并,更早的节点必须保留 */
@@ -171,7 +171,7 @@ class FoldFunction extends ASTFunctionNode {
171
171
  ctx.labelableNodes.push(merged.labelable());
172
172
  return nodes.length;
173
173
  }
174
- throw new ErrorDiagnostic("E_FOLD_NO_TARGET", `${label}语法糖错误: 右边没有找到可叠加的目标`, n.span);
174
+ throw new ErrorDiagnostic("E_FOLD_NO_TARGET", "{fn}语法糖错误: 右边没有找到可叠加的目标", n.span, { fn: label });
175
175
  }
176
176
  }
177
177
  class UpFunction extends FoldFunction {
@@ -318,10 +318,8 @@ class FoldTemporal extends TemporalNodeBase {
318
318
  prepareLayout(context) {
319
319
  // lowering 期间修饰挂在折叠体上(augmenter 要看到整体节奏),渲染时交给宿主:
320
320
  // 减时线要落在它的数字与下八度点之间,而不是压在整个盒子下面
321
- if (this.addon && this.members[0]) {
322
- this.members[0].addon = this.addon;
323
- this.addon = void 0;
324
- }
321
+ if (this.members[0])
322
+ transferFunctionAddons(this, this.members[0]);
325
323
  const first = this.members[0];
326
324
  if (!first) {
327
325
  this.box.w = this.box.h = 0;
@@ -48,20 +48,22 @@ export const BRACKET_HOOK_COMMANDS = [
48
48
  { op: "Z" },
49
49
  ];
50
50
  function invalidConnection(span) {
51
- return new ErrorDiagnostic("E_VOICES_CONNECT", '@voices 的 connect 必须是 [起点-终点] 或 {起点-终点} 的组合;端点可省略,否则须为有效声部编号。空字符串表示只有连谱线。', span);
51
+ return new ErrorDiagnostic("E_VOICES_CONNECT", '@voices 的 connect 必须是 [起点-终点]、{起点-终点}、[编号] 或 {编号} 的组合;范围端点可省略,否则须为有效声部编号。空字符串表示只有连谱线。', span);
52
52
  }
53
53
  export function parseConnections(value, span) {
54
54
  const source = value.trim();
55
55
  // 粘连匹配必须消费整串,不能跳过非法字符
56
56
  // 非空数字与其后空白一起可选,避免省略端点时重复回溯
57
- const pattern = /\s*([\[{])\s*(?:(\d+)\s*)?-\s*(?:(\d+)\s*)?([\]}])\s*/y;
57
+ const pattern = /\s*([\[{])\s*(?:(?:(\d+)\s*)?-\s*(?:(\d+)\s*)?|(\d+)\s*)([\]}])\s*/y;
58
58
  const result = [];
59
59
  while (pattern.lastIndex < source.length) {
60
60
  const match = pattern.exec(source);
61
- if (!match || match[4] !== (match[1] === "[" ? "]" : "}"))
61
+ if (!match || match[5] !== (match[1] === "[" ? "]" : "}"))
62
62
  throw invalidConnection(span);
63
- const from = match[2] ? Number(match[2]) : undefined;
64
- const to = match[3] ? Number(match[3]) : undefined;
63
+ const fromText = match[4] ?? match[2];
64
+ const toText = match[4] ?? match[3];
65
+ const from = fromText ? Number(fromText) : undefined;
66
+ const to = toText ? Number(toText) : undefined;
65
67
  for (const endpoint of [from, to]) {
66
68
  if (endpoint !== undefined && (!Number.isSafeInteger(endpoint) || endpoint < 1)) {
67
69
  throw invalidConnection(span);
@@ -1,7 +1,7 @@
1
1
  import { ASTNodeBase, ASTBraceNode, ASTFunctionNode, ASTTextNode } from "../ASTtypes.js";
2
2
  import { Diagnostic, ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
3
3
  import { findRightParen } from "../../parser/parse-utils/call-utils.js";
4
- import { findClosingQuote, quote, removeQuote } from "../../parser/parse-utils/string-utils.js";
4
+ import { findClosingQuote, quote } from "../../parser/parse-utils/string-utils.js";
5
5
  import { ParserContext, skipSpaces } from "../../parser/parserContext.js";
6
6
  import { isLayoutAttachment } from "../../layout/types.js";
7
7
  import { getLayoutBounds } from "../../layout/engine.js";
@@ -93,13 +93,13 @@ L: la la la
93
93
  if (source[start] !== 'N' && source[start] !== 'L')
94
94
  return null;
95
95
  let pos = start + 1;
96
- let name = '';
96
+ let name = { start: pos, end: pos };
97
97
  if (source[pos] === '(') {
98
98
  // `X(name)` 提取括号
99
99
  const at = findRightParen(source, pos + 1, end);
100
100
  if (at < 0)
101
101
  return null; // 没有找到匹配的右括号 不去糖
102
- name = removeQuote(source.slice(pos + 1, at).trim());
102
+ name = { start: pos + 1, end: at };
103
103
  pos = at + 1;
104
104
  }
105
105
  if (source[pos++] !== ':')
@@ -129,7 +129,7 @@ L: la la la
129
129
  const close = findClosingQuote(source, pos, end);
130
130
  if (close < 0)
131
131
  return null;
132
- lyric = removeQuote(source.slice(pos, close + 1));
132
+ lyric = { start: pos, end: close + 1 };
133
133
  pos = close + 1;
134
134
  }
135
135
  else {
@@ -137,7 +137,7 @@ L: la la la
137
137
  const from = pos;
138
138
  while (pos < end && source[pos] !== '\n')
139
139
  pos++;
140
- lyric = source.slice(from, pos).trim();
140
+ lyric = { start: from, end: pos };
141
141
  }
142
142
  const node = {
143
143
  kind: "sugar",
@@ -155,6 +155,7 @@ L: la la la
155
155
  const n = nodes[at++];
156
156
  if (n.data?.class !== VoiceFunction)
157
157
  return null;
158
+ const parseStr = (span) => ctx.parseArgWithType(span, "string") ?? "";
158
159
  if (n.data?.lyric !== void 0) {
159
160
  // 歌词 需要找到最近的voice节点并添加歌词
160
161
  let voiceNode = null;
@@ -176,13 +177,14 @@ L: la la la
176
177
  if (voiceNode === null) {
177
178
  throw new ErrorDiagnostic("E_LYRICS_WITHOUT_VOICE_NOTES", `语法糖 'L:' 或 'L(name):' 必须跟在 @voice(或 N:)之后,但没有找到符合要求的 voice;请检查语法或直接使用 @voice 函数`, n.span);
178
179
  }
179
- voiceNode.addLyric(n.data.name, n.data.lyric, n.span, ctx);
180
+ voiceNode.addLyric(parseStr(n.data.name), parseStr(n.data.lyric), n.span, ctx);
180
181
  ctx.nodes.length = voiceNodeAt + 1; // 清除voiceNodeAt之后的TextNode 因为被夹在N和L之间
181
182
  // 消费后面可能的换行符 只消费一个
182
183
  if (at < nodes.length && typeof nodes[at] === "number" && ctx.source[nodes[at]] === '\n')
183
184
  at++;
184
185
  return at;
185
186
  }
187
+ const name = parseStr(n.data.name);
186
188
  // 当前层的换行或 N/L/V 声明结束音符内容,不能把下一组吞进声部
187
189
  let breakAt = at;
188
190
  let endWithBr = 0;
@@ -214,7 +216,7 @@ L: la la la
214
216
  // 复制一份:voice 的 span 之后会被歌词撑大,内容 brace 不该跟着长
215
217
  else
216
218
  argMap.set(0, new ASTBraceNode({ ...span }, newCtx.nodes));
217
- argMap.set("name", n.data.name);
219
+ argMap.set("name", name);
218
220
  const newVoice = new VoiceFunction(span, argMap, ctx, null);
219
221
  // V 声明直接收集成员,最后统一组装,避免创建临时 voices
220
222
  if (members) {
@@ -327,7 +329,7 @@ L: la la la
327
329
  const arg = value;
328
330
  const v = ctx.parseArgWithType(arg.valueSpan, "string", span.start);
329
331
  if (v === null) {
330
- ctx.diagnostics.push(new WarningDiagnostic("W_VOICE_INVALID_LYRIC", `@voice 的歌词参数值解析失败, 参数[${key}]将被忽略`, arg.valueSpan));
332
+ ctx.diagnostics.push(new WarningDiagnostic("W_VOICE_INVALID_LYRIC", "@voice 的歌词参数值解析失败, 参数[{key}]将被忽略", arg.valueSpan, { key }));
331
333
  }
332
334
  else
333
335
  this.addLyric(key, v);
@@ -338,7 +340,7 @@ L: la la la
338
340
  name = "";
339
341
  const tokens = VoiceFunction.parseLyric(lyric);
340
342
  if (tokens.length === 0 && ctx && span) {
341
- ctx.diagnostics.push(new WarningDiagnostic("W_EMPTY_LYRIC", `@voice的歌词${name}是空的`, span));
343
+ ctx.diagnostics.push(new WarningDiagnostic("W_EMPTY_LYRIC", "@voice的歌词{name}是空的", span, { name }));
342
344
  }
343
345
  this.lyrics.push({ name, tokens });
344
346
  if (span) {
@@ -463,6 +465,7 @@ class VoicesFunction extends ASTFunctionNode {
463
465
 
464
466
  **视觉连接**:仅命名参数 \`connect\` 使用字符串,如 \`connect="[1-4]{5-7}"\`。
465
467
  \`[]\` 是现有括线,\`{}\` 是弯曲大括号;编号从 1 开始,省略起点/终点表示首/末声部。
468
+ \`[3]\` 等价于 \`[3-3]\`,\`{3}\` 等价于 \`{3-3}\`,用于单个声部。
466
469
  默认 \`"[-]"\` 连接全部声部;\`""\` 只保留公共细连谱线。未指定的声部仍有细线,范围可以重叠,不改变声部或播放关系。
467
470
  用 \`@set(voices.connect="{1-2}[3-]")\` 设置后续多声部块的默认方案,显式参数写在所有声部之后。
468
471
 
@@ -493,7 +496,7 @@ N(女低): 1 2 3
493
496
  namedOnly: true,
494
497
  type: "string",
495
498
  default: "[-]",
496
- description: '视觉连接:[1-4] 为现有括线,{5-7} 为弯曲大括号;省略端点表示首/末声部,空字符串只保留公共连谱线。',
499
+ description: '视觉连接:[1-4] 为现有括线,{5-7} 为弯曲大括号;[3]、{3} 表示单个声部,省略范围端点表示首/末声部,空字符串只保留公共连谱线。',
497
500
  }]
498
501
  };
499
502
  static deSugarAtom(source, start, end) {
@@ -625,7 +628,7 @@ N(女低): 1 2 3
625
628
  const valueSpan = value instanceof ASTNodeBase ? value.sourceSpan : value.valueSpan;
626
629
  const voice = value instanceof ASTNodeBase ? value : ctx.parseArgWithType(valueSpan, "content", span.start);
627
630
  if (!(voice instanceof VoiceFunction)) {
628
- throw new ErrorDiagnostic("E_VOICES_INVALID_CHILD", `@voices 的参数必须是 @voice 函数,但发现了其他类型 ${voice?.constructor.name}`, valueSpan);
631
+ throw new ErrorDiagnostic("E_VOICES_INVALID_CHILD", "@voices 的参数必须是 @voice 函数,但发现了其他类型 {actual}", valueSpan, { actual: String(voice?.constructor.name) });
629
632
  }
630
633
  this.addVoice(voice);
631
634
  }
@@ -787,6 +790,11 @@ class VoicesBraceAttachment {
787
790
  }
788
791
  }
789
792
  bars.push(line);
793
+ // 在首声部名称宿主上发布连谱号细竖线顶端坐标,供行首小节号直接居中对齐
794
+ this.names[0].ports["bar.number"] = {
795
+ x: x + stem * 1.33 - first.x,
796
+ y: Math.min(top, ...regions.map(region => region.y)) - first.y,
797
+ };
790
798
  return {
791
799
  regions,
792
800
  paint(painter) {