jpfun 0.7.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 (152) 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 +0 -10
  5. package/dist/converter/midi/convert.js +19 -56
  6. package/dist/converter/musicxml/features.d.ts +16 -8
  7. package/dist/converter/musicxml/features.js +88 -19
  8. package/dist/converter/musicxml/index.js +88 -50
  9. package/dist/converter/musicxml/model.d.ts +9 -0
  10. package/dist/converter/source.d.ts +4 -7
  11. package/dist/converter/source.js +11 -9
  12. package/dist/core.d.ts +1 -0
  13. package/dist/core.js +1 -0
  14. package/dist/diagnostic.d.ts +7 -1
  15. package/dist/diagnostic.js +40 -88
  16. package/dist/fraction.js +3 -2
  17. package/dist/functions/ASTtypes.d.ts +3 -32
  18. package/dist/functions/ASTtypes.js +5 -52
  19. package/dist/functions/adjust/index.js +45 -33
  20. package/dist/functions/arpeggio/index.js +50 -55
  21. package/dist/functions/arpeggio/shape.d.ts +2 -3
  22. package/dist/functions/arpeggio/shape.js +20 -50
  23. package/dist/functions/bar/index.d.ts +8 -0
  24. package/dist/functions/bar/index.js +105 -8
  25. package/dist/functions/beam/auto.d.ts +1 -2
  26. package/dist/functions/beam/auto.js +80 -135
  27. package/dist/functions/beam/index.js +6 -12
  28. package/dist/functions/beam/layout.d.ts +1 -1
  29. package/dist/functions/beam/layout.js +1 -1
  30. package/dist/functions/box/index.js +0 -6
  31. package/dist/functions/br/index.d.ts +34 -2
  32. package/dist/functions/br/index.js +5 -4
  33. package/dist/functions/dash/index.js +9 -10
  34. package/dist/functions/default.js +2 -1
  35. package/dist/functions/div/index.d.ts +3 -4
  36. package/dist/functions/div/index.js +18 -14
  37. package/dist/functions/dot/index.js +5 -11
  38. package/dist/functions/dyn/index.js +55 -57
  39. package/dist/functions/gliss/index.js +131 -103
  40. package/dist/functions/grace/index.d.ts +3 -12
  41. package/dist/functions/grace/index.js +52 -102
  42. package/dist/functions/head/index.js +10 -7
  43. package/dist/functions/key/index.js +13 -15
  44. package/dist/functions/meter/index.d.ts +56 -1
  45. package/dist/functions/meter/index.js +15 -10
  46. package/dist/functions/note/index.js +6 -6
  47. package/dist/functions/note/noteName.d.ts +16 -0
  48. package/dist/functions/note/noteName.js +88 -0
  49. package/dist/functions/note/source-transform.js +8 -10
  50. package/dist/functions/ottava/index.js +35 -40
  51. package/dist/functions/page/index.d.ts +1 -0
  52. package/dist/functions/page/index.js +27 -21
  53. package/dist/functions/pagebreak/index.js +2 -2
  54. package/dist/functions/rest/index.js +5 -5
  55. package/dist/functions/set/index.js +4 -4
  56. package/dist/functions/slide/index.js +0 -1
  57. package/dist/functions/stack/index.js +8 -57
  58. package/dist/functions/symbol/index.d.ts +21 -2
  59. package/dist/functions/symbol/index.js +69 -24
  60. package/dist/functions/symbol/ornament.d.ts +1 -2
  61. package/dist/functions/symbol/shape.d.ts +6 -0
  62. package/dist/functions/symbol/shape.js +16 -3
  63. package/dist/functions/symbol/symbols/coda.d.ts +4 -0
  64. package/dist/functions/symbol/symbols/coda.js +56 -0
  65. package/dist/functions/symbol/symbols/dynamics.d.ts +1 -1
  66. package/dist/functions/symbol/symbols/dynamics.js +18 -8
  67. package/dist/functions/symbol/symbols/harmonic.d.ts +2 -0
  68. package/dist/functions/symbol/symbols/harmonic.js +11 -0
  69. package/dist/functions/symbol/symbols/marcato.d.ts +2 -0
  70. package/dist/functions/symbol/symbols/marcato.js +22 -0
  71. package/dist/functions/symbol/symbols/staccato.d.ts +2 -0
  72. package/dist/functions/symbol/symbols/staccato.js +24 -0
  73. package/dist/functions/symbol/symbols/tenuto.d.ts +2 -0
  74. package/dist/functions/symbol/symbols/tenuto.js +11 -0
  75. package/dist/functions/symbol/symbols/tocoda.d.ts +2 -0
  76. package/dist/functions/symbol/symbols/tocoda.js +16 -0
  77. package/dist/functions/symbol/symbols/turn.d.ts +3 -0
  78. package/dist/functions/symbol/symbols/turn.js +50 -0
  79. package/dist/functions/symbol/symbols/wheel.d.ts +2 -0
  80. package/dist/functions/symbol/symbols/wheel.js +36 -0
  81. package/dist/functions/temporal.d.ts +3 -2
  82. package/dist/functions/temporal.js +8 -0
  83. package/dist/functions/text/index.js +38 -35
  84. package/dist/functions/tie/index.js +44 -43
  85. package/dist/functions/tremolo/index.d.ts +2 -0
  86. package/dist/functions/tremolo/index.js +318 -0
  87. package/dist/functions/tuplet/index.js +4 -14
  88. package/dist/functions/up/index.js +81 -85
  89. package/dist/functions/voice/connections.d.ts +2 -1
  90. package/dist/functions/voice/connections.js +48 -10
  91. package/dist/functions/voice/index.d.ts +2 -3
  92. package/dist/functions/voice/index.js +2 -963
  93. package/dist/functions/voice/lyrics.d.ts +30 -0
  94. package/dist/functions/voice/lyrics.js +289 -0
  95. package/dist/functions/voice/voice.d.ts +63 -0
  96. package/dist/functions/voice/voice.js +373 -0
  97. package/dist/functions/voice/voices.d.ts +106 -0
  98. package/dist/functions/voice/voices.js +423 -0
  99. package/dist/functions/volta/index.js +5 -23
  100. package/dist/jpfun.core.min.js +76 -59
  101. package/dist/jpfun.from-midi.min.js +5 -5
  102. package/dist/jpfun.from-musicxml.min.js +8 -8
  103. package/dist/jpfun.min.js +81 -64
  104. package/dist/layout/default.d.ts +0 -1
  105. package/dist/layout/default.js +0 -1
  106. package/dist/layout/engine.js +30 -18
  107. package/dist/layout/model.d.ts +0 -1
  108. package/dist/layout/model.js +1 -4
  109. package/dist/layout/page.d.ts +2 -1
  110. package/dist/layout/page.js +14 -14
  111. package/dist/layout/range.d.ts +7 -6
  112. package/dist/layout/range.js +23 -14
  113. package/dist/layout/types.d.ts +9 -28
  114. package/dist/lowering/loweringContext.d.ts +18 -23
  115. package/dist/lowering/loweringContext.js +33 -46
  116. package/dist/lowering/track.d.ts +8 -1
  117. package/dist/lowering/types.d.ts +13 -11
  118. package/dist/parser/parse-utils/call-utils.d.ts +1 -2
  119. package/dist/parser/parse-utils/call-utils.js +6 -34
  120. package/dist/parser/parse-utils/note-utils.d.ts +3 -3
  121. package/dist/parser/parse-utils/note-utils.js +21 -33
  122. package/dist/parser/parse-utils/string-utils.d.ts +3 -2
  123. package/dist/parser/parse-utils/string-utils.js +20 -5
  124. package/dist/parser/parserContext.d.ts +9 -9
  125. package/dist/parser/parserContext.js +62 -11
  126. package/dist/pipeline.js +2 -3
  127. package/dist/playback/compile.js +131 -82
  128. package/dist/playback/event.d.ts +6 -6
  129. package/dist/playback/event.js +13 -49
  130. package/dist/playback/time.js +42 -31
  131. package/dist/playback/types.d.ts +3 -1
  132. package/dist/render/canvas.js +4 -22
  133. package/dist/render/recording.js +1 -4
  134. package/dist/render/svg.d.ts +0 -1
  135. package/dist/render/svg.js +33 -31
  136. package/dist/render/text.d.ts +36 -1
  137. package/dist/render/text.js +134 -0
  138. package/dist/render/translate.d.ts +0 -1
  139. package/dist/render/translate.js +6 -23
  140. package/dist/render/types.d.ts +0 -2
  141. package/grammar.md +39 -30
  142. package/package.json +3 -3
  143. package/dist/functions/note/noteNameFSM.d.ts +0 -8
  144. package/dist/functions/note/noteNameFSM.js +0 -181
  145. package/dist/iife/core.d.ts +0 -1
  146. package/dist/iife/core.js +0 -3
  147. package/dist/iife/from-midi.d.ts +0 -1
  148. package/dist/iife/from-midi.js +0 -15
  149. package/dist/iife/from-musicxml.d.ts +0 -1
  150. package/dist/iife/from-musicxml.js +0 -3
  151. package/dist/iife/full.d.ts +0 -1
  152. package/dist/iife/full.js +0 -3
@@ -3,7 +3,7 @@ import { getLayoutBounds, layoutLocalSequence } from "../../layout/engine.js";
3
3
  import { Fraction } from "../../fraction.js";
4
4
  import { Track } from "../../lowering/track.js";
5
5
  import { transferFunctionAddons, isVisualTemporalNode, TemporalNodeBase, } from "../temporal.js";
6
- import { ASTBraceNode, ASTFunctionNode, ASTLabelNode, ASTTextNode, } from "../ASTtypes.js";
6
+ import { ASTFunctionNode, } from "../ASTtypes.js";
7
7
  import { createBeamLayoutAttachment } from "../beam/layout.js";
8
8
  import { DIV_ADDON_KEY } from "../div/index.js";
9
9
  /** 倚音相对宿主的字号比例 */
@@ -22,9 +22,17 @@ const SHOULDER_PORT = "shoulder";
22
22
  * 所以只能在此刻回头改。这发生在 parse 进行中,不违反「AST parse 后只读」。
23
23
  */
24
24
  function scaleFontSize(node, factor) {
25
+ if (factor === 1)
26
+ return;
25
27
  const sized = node;
26
28
  if (typeof sized.size === "number")
27
29
  sized.size *= factor;
30
+ if (typeof sized.gap === "number")
31
+ sized.gap *= factor;
32
+ if (typeof sized.minGap === "number")
33
+ sized.minGap *= factor;
34
+ sized.aboveGaps?.forEach((_, i, a) => a[i] *= factor);
35
+ sized.belowGaps?.forEach((_, i, a) => a[i] *= factor);
28
36
  for (const child of node.children ?? [])
29
37
  scaleFontSize(child, factor);
30
38
  }
@@ -97,51 +105,17 @@ class GraceFunction extends ASTFunctionNode {
97
105
  if (n.kind !== "sugar" || n.data?.class !== GraceFunction)
98
106
  return null;
99
107
  const side = n.data.side;
100
- // 找上一个非文本节点 实现忽略中间内容的作用
101
- let left = ctx.nodes.length - 1;
102
- while (left >= 0 && ctx.nodes[left] instanceof ASTTextNode)
103
- left--;
104
- if (left < 0) {
108
+ const leftNode = ctx.takeLeftOperand();
109
+ if (!leftNode) {
105
110
  throw new ErrorDiagnostic("E_GRACE_NO_TARGET", "@grace语法糖错误: 左边没有找到目标", n.span);
106
111
  }
107
- let leftNode = ctx.nodes[left];
108
- /** 左操作数在 ctx.nodes 中的起点;只有这一段会被 grace 吞并 */
109
- let replaceFrom = left;
110
- // 对 label 的特判: 目标变为label到被标记的节点范围内的所有节点
111
- if (leftNode instanceof ASTLabelNode) {
112
- let tgt = leftNode.target;
113
- while (tgt && !ctx.nodes.includes(tgt))
114
- tgt = tgt.parent;
115
- for (let j = left - 1; j >= 0; j--) {
116
- if (ctx.nodes[j] === tgt) {
117
- leftNode = new ASTBraceNode({
118
- start: tgt.sourceSpan.start,
119
- end: leftNode.sourceSpan.end,
120
- }, ctx.nodes.slice(j, left + 1), null);
121
- replaceFrom = j;
122
- break;
123
- }
124
- }
125
- }
126
- // 找到下一个非文本节点 通过全量后续解析的方式进行
127
- const storage = ctx.nodes;
128
- ctx.nodes = [];
129
- ctx.makeNodes(nodes, at);
130
- for (let i = 0; i < ctx.nodes.length; i++) {
131
- const right = ctx.nodes[i];
132
- if (right instanceof ASTTextNode)
133
- continue;
134
- // '<' 的倚音在右侧,右结合的解析结果本来就是嵌套语义,不必像 '>' 那样重排
135
- const node = side === "pre"
136
- ? GraceFunction.attachPre(leftNode, right, n.span, ctx)
137
- : GraceFunction.create(ctx, n.span, "post", leftNode, right);
138
- storage.length = replaceFrom;
139
- storage.push(node);
140
- while (++i < ctx.nodes.length)
141
- storage.push(ctx.nodes[i]);
142
- ctx.nodes = storage;
143
- return nodes.length;
144
- }
112
+ const next = ctx.consumeRightOperand(nodes, at, right =>
113
+ // '<' 的倚音在右侧,右结合的解析结果本来就是嵌套语义,不必像 '>' 那样重排
114
+ side === "pre"
115
+ ? GraceFunction.attachPre(leftNode, right, n.span, ctx)
116
+ : GraceFunction.create(ctx, n.span, "post", leftNode, right));
117
+ if (next !== null)
118
+ return next;
145
119
  throw new ErrorDiagnostic("E_GRACE_NO_TARGET", "@grace语法糖错误: 右边没有找到目标", n.span);
146
120
  }
147
121
  host;
@@ -161,33 +135,25 @@ class GraceFunction extends ASTFunctionNode {
161
135
  deepest = deepest.grace;
162
136
  depth++;
163
137
  }
164
- const argMap = new Map();
165
- argMap.set(0, deepest.grace);
166
- argMap.set(1, left);
167
138
  const scale = GRACE_SCALE ** depth;
168
- const inner = new GraceFunction(span, argMap, ctx, null, GRACE_SCALE * scale);
139
+ const inner = GraceFunction.create(ctx, span, "pre", deepest.grace, left, GRACE_SCALE * scale);
169
140
  inner.size *= scale;
170
141
  deepest.setGrace(inner, 1); // inner 内部已按深度缩放,不能再缩
171
142
  return right;
172
143
  }
173
144
  return GraceFunction.create(ctx, span, "pre", right, left);
174
145
  }
175
- static create(ctx, span, side, host, grace) {
146
+ static create(ctx, span, side, host, grace, scale = GRACE_SCALE) {
176
147
  const argMap = new Map();
177
148
  argMap.set(0, host);
178
149
  argMap.set(1, grace);
179
150
  argMap.set("side", side);
180
- return new GraceFunction(span, argMap, ctx);
151
+ return new GraceFunction(span, argMap, ctx, null, scale);
181
152
  }
182
- /** 宿主在前:findActiveDivs 下潜子树时要先命中宿主的 @div,而不是倚音的 */
183
153
  get children() {
184
- const out = [];
185
- if (this.host)
186
- out.push(this.host);
187
- if (this.grace)
188
- out.push(this.grace);
189
- return out;
154
+ return [this.host, this.grace];
190
155
  }
156
+ timeFlowModel() { return null; }
191
157
  constructor(span, args, ctx, parent = null, scale = GRACE_SCALE) {
192
158
  super(span, parent);
193
159
  this.size = ctx.variables.fontsize;
@@ -210,11 +176,7 @@ class GraceFunction extends ASTFunctionNode {
210
176
  }
211
177
  /** 宿主收敛成一个可见 Temporal,倚音展开成局部时间列,然后整体折叠进一个复合节点 */
212
178
  loweringEnter(ctx, track) {
213
- const host = this.host;
214
- const grace = this.grace;
215
- if (!host || !grace) {
216
- throw new ErrorDiagnostic("E_GRACE_MISSING_ARGS", "@grace 需要同时给出宿主和倚音", this.sourceSpan);
217
- }
179
+ const { host, grace } = this;
218
180
  // 倚音内容是一个子域:在私有根轨上展开,根轨不挂进宿主轨的分组,其中的并行结构另开声部
219
181
  const root = new Track(track);
220
182
  let hostEvents = [];
@@ -240,20 +202,10 @@ class GraceFunction extends ASTFunctionNode {
240
202
  if (!events.some(isVisualTemporalNode) || events.some(event => (event.addon?.breakBefore ?? 0) > 0)) {
241
203
  throw new ErrorDiagnostic("E_GRACE_INVALID_CONTENT", "@grace 的倚音至少产生一个可见对象,且不能换行", grace.sourceSpan);
242
204
  }
243
- const composite = new GraceTemporal(this, hostNode, columns, root, attachments, this.side);
244
- // 倚音同段无条件全部相连,只被零时长标记切断,所以 grace 一定认识 beam,允许耦合
245
- // 折叠成员不进全局时间列,autobeam 看不到它们,要手动调用且强制连接
246
- for (const run of composite.graceRuns) {
247
- if (run.length < 2)
248
- continue;
249
- ctx.addAttachment(createBeamLayoutAttachment([...run], false, grace.sourceSpan));
250
- }
251
- return [composite];
205
+ return [new GraceTemporal(this, hostNode, columns, root, attachments, ctx)];
252
206
  }
253
207
  toString(source) {
254
- const host = this.host?.toString(source) ?? "";
255
- const grace = this.grace?.toString(source) ?? "";
256
- return `@grace(${host}, ${grace}, side=${this.side})`;
208
+ return `@grace(${this.host.toString(source)}, ${this.grace.toString(source)}, side=${this.side})`;
257
209
  }
258
210
  }
259
211
  export const GraceNode = GraceFunction;
@@ -267,8 +219,6 @@ const HOOK_COMMANDS = [
267
219
  const HOOK_WIDTH = 0.07;
268
220
  /** 倚音块底边到宿主肩线的视觉间隙;倚音线会探进这段空间指向宿主 */
269
221
  const GRACE_RISE = 0.18;
270
- /** 倚音向宿主借时值的上限,防止宿主被偷光;只读 */
271
- const MAX_STEAL_RATIO = new Fraction(3, 4);
272
222
  /** 倚音复合体:宿主与倚音都折叠在这一个盒子里,对外只是一个可见事件 */
273
223
  export class GraceTemporal extends TemporalNodeBase {
274
224
  host;
@@ -276,9 +226,6 @@ export class GraceTemporal extends TemporalNodeBase {
276
226
  graceColumns;
277
227
  /** graceColumns 按列展开 */
278
228
  graces;
279
- /** 承担节奏的倚音成员,按声部与零时长标记切段;同段视觉上首尾相接,无条件连成一束减时线 */
280
- graceRuns;
281
- side;
282
229
  /** 倚音子域的根轨:由宿主轨分出,不挂进它的分组,子域之外不可见 */
283
230
  root;
284
231
  /** 倚音内容里声明的附件,随子域排版 */
@@ -292,13 +239,12 @@ export class GraceTemporal extends TemporalNodeBase {
292
239
  graceOffsets = [];
293
240
  /** 倚音线起点,同样是局部偏移 */
294
241
  hookOrigin = null;
295
- constructor(ast, host, columns, root, attachments, side) {
242
+ constructor(ast, host, columns, root, attachments, ctx) {
296
243
  super();
297
244
  this.ast = ast;
298
245
  this.host = host;
299
246
  this.root = root;
300
247
  this.attachments = attachments;
301
- this.side = side;
302
248
  this.T.copyFrom(host.T);
303
249
  this.mergeKey = host.mergeKey;
304
250
  this.initLayoutBox();
@@ -329,6 +275,8 @@ export class GraceTemporal extends TemporalNodeBase {
329
275
  this.graces = graceColumns.flat();
330
276
  this.events = events;
331
277
  this.starts = starts;
278
+ // 承担节奏的倚音成员按声部与零时长标记切段;同段视觉上首尾相接,无条件连成一束减时线
279
+ // 折叠成员不进全局时间列,autobeam 看不到它们,要手动调用且强制连接
332
280
  const runs = new Map();
333
281
  const graceRuns = [];
334
282
  for (const grace of this.graces) {
@@ -348,14 +296,17 @@ export class GraceTemporal extends TemporalNodeBase {
348
296
  addon[DIV_ADDON_KEY] = (Number(addon[DIV_ADDON_KEY]) || 0) + 1;
349
297
  grace.T.divPow2();
350
298
  }
351
- this.graceRuns = graceRuns;
299
+ for (const run of graceRuns) {
300
+ if (run.length >= 2)
301
+ ctx.addAttachment(createBeamLayoutAttachment(run, false, ast.grace.sourceSpan));
302
+ }
352
303
  }
353
304
  /** 成员共享全局时间状态,按发声顺序固化 */
354
305
  onTimeState(state) {
355
306
  // 同步时间的修改。比如tuplet修改的是GraceTemporal.T,这里要把它传给成员
356
307
  this.host.T.copyFrom(this.T);
357
308
  let offset = undefined;
358
- for (const member of this.side === "pre" ? [...this.events, this.host] : [this.host, ...this.events]) {
309
+ for (const member of this.ast.side === "pre" ? [...this.events, this.host] : [this.host, ...this.events]) {
359
310
  member.t.copyFrom(this.t);
360
311
  member.layoutLine = this.layoutLine;
361
312
  const result = member.onTimeState?.(state);
@@ -369,13 +320,7 @@ export class GraceTemporal extends TemporalNodeBase {
369
320
  prepareHorizontal(line) {
370
321
  this.host.prepareHorizontal?.(line);
371
322
  }
372
- /**
373
- * 播放时倚音从宿主借走的时值(前倚音从开头、后倚音从末尾)
374
- *
375
- * 比例 = 倚音块字面时长 / 四分音符,而四分音符 T=1,所以直接取各声部最晚的局部终点。
376
- * 基准取宿主经过 div 与 dot 后的实际时值;延时线是独立事件、tie 不改 T,天然不计入。
377
- * 局部时间按同一比例映射进借走的时值,各声部因此同时起奏。
378
- */
323
+ /** 按最长声部的书写时长 × 1/4 借时,最多占宿主一半;前倚音借开头,后倚音借末尾。 */
379
324
  emitPlayback(emitter) {
380
325
  const written = new Fraction();
381
326
  const end = new Fraction();
@@ -384,19 +329,23 @@ export class GraceTemporal extends TemporalNodeBase {
384
329
  if (end.compare(written) > 0)
385
330
  written.copyFrom(end);
386
331
  });
387
- const ratio = written.compare(MAX_STEAL_RATIO) > 0 ? MAX_STEAL_RATIO : written;
388
332
  const total = emitter.end.clone().sub(emitter.start);
389
- const steal = total.clone().mul(ratio);
333
+ const scale = new Fraction(1, 4);
334
+ const steal = written.clone().mul(scale);
335
+ const limit = total.clone().divPow2();
336
+ if (steal.compare(limit) > 0) {
337
+ scale.copyFrom(limit).div(written);
338
+ steal.copyFrom(limit);
339
+ }
390
340
  const hostDuration = total.sub(steal);
391
- // 全是零时长标记时块长为 0,成员都落在借时起点
392
- const scale = written.isZero() ? new Fraction() : steal.clone().div(written);
393
- const base = this.side === "pre" ? emitter.start.clone() : emitter.start.clone().add(hostDuration);
394
- if (this.side === "post")
341
+ const pre = this.ast.side === "pre";
342
+ const base = pre ? emitter.start.clone() : emitter.start.clone().add(hostDuration);
343
+ if (!pre)
395
344
  emitter.play(this.host, emitter.start.clone(), hostDuration);
396
345
  this.events.forEach((event, index) => {
397
346
  emitter.play(event, this.starts[index].clone().mul(scale).add(base), event.T.clone().mul(scale));
398
347
  });
399
- if (this.side === "pre")
348
+ if (pre)
400
349
  emitter.play(this.host, base.add(steal), hostDuration);
401
350
  }
402
351
  /**
@@ -411,19 +360,20 @@ export class GraceTemporal extends TemporalNodeBase {
411
360
  transferFunctionAddons(this, this.host);
412
361
  const block = context.layoutSubdomain(this, this.graceColumns, this.root, this.attachments);
413
362
  const hostWidth = layoutLocalSequence([this.host], context);
414
- this.springConfig = { ...this.host.springConfig, ...this.springConfig };
363
+ this.springConfig = { ...this.host.springConfig };
415
364
  const graceEm = this.ast.size * GRACE_SCALE;
416
365
  const sideGap = graceEm * 0.2;
417
366
  const rise = graceEm * GRACE_RISE;
367
+ const pre = this.ast.side === "pre";
418
368
  // 倚音贴着宿主的肩线而不是宿主盒顶:宿主本身也是复合体时,
419
369
  // 肩线由它转发上来,所以两侧倚音会落在同一高度而不是层层叠高
420
370
  const shoulder = this.host.ports[SHOULDER_PORT]?.y ?? 0;
421
371
  const graceTop = shoulder - rise - block.height;
422
372
  const hostBounds = getLayoutBounds(this.host);
423
373
  const lift = Math.max(0, -graceTop, -hostBounds.y);
424
- const graceX = this.side === "pre" ? 0 : hostWidth + sideGap;
374
+ const graceX = pre ? 0 : hostWidth + sideGap;
425
375
  this.hostOffset = {
426
- x: this.host.box.x + (this.side === "pre" ? block.width + sideGap : 0),
376
+ x: this.host.box.x + (pre ? block.width + sideGap : 0),
427
377
  y: lift,
428
378
  };
429
379
  this.graceOffsets = block.positions.map(position => ({
@@ -447,7 +397,7 @@ export class GraceTemporal extends TemporalNodeBase {
447
397
  this.ports[SHOULDER_PORT] ??= { x: this.box.anchor, y: this.hostOffset.y };
448
398
  // 钩形曲线挂在靠近宿主的那个倚音成员下方,零时长标记不承接它;高度取成员的最低下沿,不含块内附件
449
399
  const rhythmic = this.graces.filter(grace => !grace.T.isZero());
450
- const near = this.side === "pre" ? rhythmic.at(-1) : rhythmic[0];
400
+ const near = pre ? rhythmic.at(-1) : rhythmic[0];
451
401
  this.hookOrigin = near ? {
452
402
  x: this.graceOffsets[this.graces.indexOf(near)].x + near.box.anchor,
453
403
  y: Math.max(...this.graces.map((grace, index) => this.graceOffsets[index].y + grace.box.h)),
@@ -474,7 +424,7 @@ export class GraceTemporal extends TemporalNodeBase {
474
424
  return;
475
425
  const graceEm = this.ast.size * GRACE_SCALE;
476
426
  const hookOrigin = this.hookOrigin;
477
- const dir = this.side === "pre" ? 1 : -1;
427
+ const dir = this.ast.side === "pre" ? 1 : -1;
478
428
  painter.drawPath(HOOK_COMMANDS, { stroke: "#000", strokeWidth: Math.max(0.8, graceEm * HOOK_WIDTH) }, {
479
429
  x: this.box.x + hookOrigin.x,
480
430
  y: this.box.y + hookOrigin.y,
@@ -57,6 +57,7 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
57
57
  members = [];
58
58
  slots = [];
59
59
  titleBottom = 0;
60
+ aligned = false; // 侧栏横向重排在一轮布局中只执行一次,避免二次 onPlaced 把成员微调后的 box.x 当成未偏移基准
60
61
  sideExtents = { left: null, right: null };
61
62
  constructor(ast) {
62
63
  super();
@@ -70,15 +71,20 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
70
71
  }
71
72
  }
72
73
  }
73
- prepareLayout() { this.box.w = this.box.h = this.box.anchor = this.box.visualAxis = 0; }
74
+ prepareLayout() {
75
+ this.box.w = this.box.h = this.box.anchor = this.box.visualAxis = 0;
76
+ this.aligned = false;
77
+ }
74
78
  prepareHorizontal(line) {
75
79
  // 只由第一个边界协调一次整块 Head,避免六个边界重复改弹簧
76
80
  if (this.slots.length > 0)
77
81
  this.prepareHead(line);
78
82
  }
79
83
  onPlaced() {
80
- if (this.slots.length > 0)
84
+ if (this.slots.length > 0 && !this.aligned) {
85
+ this.aligned = true;
81
86
  this.alignHead();
87
+ }
82
88
  }
83
89
  onTemporal(node) { this.members.push(node); }
84
90
  createTracks(slot) {
@@ -152,7 +158,7 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
152
158
  cells.set(cell, [member]);
153
159
  }
154
160
  const [left, , right] = this.slots;
155
- this.packRows(left.ast, left.start.box.x, cells);
161
+ this.packRows(left.ast, left.start.box.x - (left.start.placementOffset?.x ?? 0), cells);
156
162
  this.packRows(right.ast, right.end.box.x, cells);
157
163
  }
158
164
  stretch(node, side) {
@@ -325,9 +331,6 @@ H.tempo: 94
325
331
  gap;
326
332
  createdBySugar = false;
327
333
  get children() { return this.slots; }
328
- timeFlowModel() {
329
- return { mode: "sequence", children: this.slots };
330
- }
331
334
  static deSugarAtom(source, start, end) {
332
335
  if (source[start] !== "H" || source[start + 1] !== ".")
333
336
  return null;
@@ -382,7 +385,7 @@ H.tempo: 94
382
385
  const last = skipSpacesBack(ctx.source, boundary - 1, start);
383
386
  const span = { start, end: Math.max(start, last + 1) };
384
387
  if (span.start >= span.end) {
385
- throw new ErrorDiagnostic("E_HEAD_EMPTY_DECLARATION", `H.${field}: 后必须有内容`, sugar.span);
388
+ throw new ErrorDiagnostic("E_HEAD_EMPTY_DECLARATION", "H.{field}: 后必须有内容", sugar.span, { field });
386
389
  }
387
390
  const text = ctx.source.slice(span.start, span.end).trim();
388
391
  let parsed;
@@ -1,23 +1,19 @@
1
1
  import { DEFAULT_TONALITY, TemporalNodeBase } from "../temporal.js";
2
2
  import { ASTFunctionNode } from "../ASTtypes.js";
3
- import { Diagnostic, ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
4
- import { parseNoteName } from "../note/noteNameFSM.js";
5
- import { acc2Offset, NoteNameMap, tonality2Midi } from "../../parser/parse-utils/note-utils.js";
3
+ import { ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
4
+ import { parseNoteName } from "../note/noteName.js";
5
+ import { acc2Offset, NoteNameMap } from "../../parser/parse-utils/note-utils.js";
6
6
  import { paintAccidental, placeAccidentals } from "../note/accidentals.js";
7
7
  /**
8
8
  * 把宽松的调性写法收敛成 tonality2Midi 认得的 [音名][最多一个 #b][绝对八度]
9
9
  *
10
- * 本来就合法就原样返回,彻底读不懂返回 null
10
+ * 彻底读不懂返回 null
11
11
  * `C###` 这种超过一个变音记号的写法按实际音高换字母(→ D#4),落在黑键上则跟随原来的升降方向拼写
12
12
  */
13
13
  function normalizeTonality(tonality) {
14
- try {
15
- tonality2Midi(tonality, 4);
16
- return tonality;
17
- }
18
- catch { /* 落到下面归一化 */ }
19
- const parsed = parseNoteName(tonality.replace(/^[a-g]/, letter => letter.toUpperCase()));
20
- if (parsed instanceof Diagnostic || parsed.next !== tonality.length)
14
+ const normalizedInput = tonality.replace(/^[a-g]/, letter => letter.toUpperCase());
15
+ const parsed = parseNoteName(normalizedInput, 0, normalizedInput.length, false);
16
+ if (!parsed || parsed.next !== normalizedInput.length)
21
17
  return null;
22
18
  const pitchClass = NoteNameMap[parsed.name];
23
19
  if (pitchClass === undefined)
@@ -25,6 +21,8 @@ function normalizeTonality(tonality) {
25
21
  const offset = acc2Offset(parsed.acc ?? "", false);
26
22
  const octave = parsed.absOctave ? parsed.octave ?? 4 : 4 + (parsed.octave ?? 0);
27
23
  const midi = (octave + 1) * 12 + pitchClass + offset;
24
+ if (!Number.isSafeInteger(midi))
25
+ return null;
28
26
  // NoteNameMap 里同一音高的升号拼写在前、降号在后,正好用来挑方向;数字音名不参与拼写
29
27
  const spellings = Object.keys(NoteNameMap).filter(name => NoteNameMap[name] === ((midi % 12) + 12) % 12 && /^[A-G]/.test(name));
30
28
  return (offset < 0 ? spellings.at(-1) : spellings[0]) + (Math.floor(midi / 12) - 1);
@@ -70,11 +68,11 @@ class KeyFunction extends ASTFunctionNode {
70
68
  this.tonality = tonality;
71
69
  this.size = ctx.length2px(size);
72
70
  const normalized = normalizeTonality(tonality);
73
- if (normalized !== tonality) {
71
+ this.tonality = normalized ?? DEFAULT_TONALITY;
72
+ if (normalized !== tonality && normalized !== `${tonality}4`) {
74
73
  if (ctx.variables.strict)
75
- throw new ErrorDiagnostic("E_KEY_TONALITY", `@key 无法解析调性 "${tonality}"`, sourceSpan);
76
- this.tonality = normalized ?? DEFAULT_TONALITY;
77
- ctx.diagnostics.push(new WarningDiagnostic("W_KEY_TONALITY", `@key 的调性 "${tonality}" 不是规范写法,已自动切换到 ${this.tonality}`, sourceSpan));
74
+ throw new ErrorDiagnostic("E_KEY_TONALITY", '@key 无法解析调性 "{tonality}"', sourceSpan, { tonality });
75
+ ctx.diagnostics.push(new WarningDiagnostic("W_KEY_TONALITY", '@key 的调性 "{input}" 不是规范写法,已自动切换到 {tonality}', sourceSpan, { input: tonality, tonality: this.tonality }));
78
76
  }
79
77
  // 归一化保证了格式是 [音名][最多一个 #b][八度]
80
78
  this.displayName = this.tonality[0];
@@ -1,2 +1,57 @@
1
- import { type ASTFunctionClass } from "../ASTtypes.js";
1
+ import { Fraction } from "../../fraction.js";
2
+ import type { LayoutBox, LayoutPrepareContext } from "../../layout/types.js";
3
+ import { TemporalNodeBase, type TimeState } from "../temporal.js";
4
+ import type { LoweringContext } from "../../lowering/loweringContext.js";
5
+ import type { Painter } from "../../render/types.js";
6
+ import type { PlaybackEmitter } from "../../playback/types.js";
7
+ import { ASTFunctionNode, type ASTFunctionClass, type ASTNodeBase, type FunctionArgs, type LengthValue, type ParserContext, type SourceSpan } from "../ASTtypes.js";
8
+ export declare function meterChangeAt(node: TemporalNodeBase): MeterFunction | undefined;
9
+ declare class MeterFunction extends ASTFunctionNode {
10
+ static def: {
11
+ name: string[];
12
+ description: string;
13
+ details: string;
14
+ allowExtraArgs: boolean;
15
+ args: ({
16
+ name: string;
17
+ description: string;
18
+ type: "number";
19
+ default: null;
20
+ } | {
21
+ name: string;
22
+ description: string;
23
+ type: "length";
24
+ default: LengthValue;
25
+ })[];
26
+ };
27
+ readonly numerator: number;
28
+ readonly denominator: number;
29
+ readonly measureDuration: Fraction | undefined;
30
+ readonly size: number;
31
+ readonly strict: boolean;
32
+ readonly font: string;
33
+ constructor(span: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent?: ASTNodeBase | null);
34
+ loweringEnter(ctx: LoweringContext): MeterTemporal[];
35
+ /**
36
+ * 校验小节拍数
37
+ * 第一小节特殊规则:只允许不满拍,但不能超拍
38
+ */
39
+ private static loweringFinalize;
40
+ toString(): string;
41
+ }
2
42
  export declare const MeterNode: ASTFunctionClass;
43
+ declare class MeterTemporal extends TemporalNodeBase {
44
+ ast: MeterFunction;
45
+ box: LayoutBox;
46
+ private readonly style;
47
+ private numeratorBaseline;
48
+ private denominatorBaseline;
49
+ private lineY;
50
+ private lineHeight;
51
+ constructor(ast: MeterFunction);
52
+ onTimeState(state: TimeState): void;
53
+ emitPlayback(emitter: PlaybackEmitter): void;
54
+ prepareLayout(context: LayoutPrepareContext): void;
55
+ paint(painter: Painter): void;
56
+ }
57
+ export {};
@@ -4,10 +4,13 @@ import { ANCHOR_KEY, TemporalNodeBase } from "../temporal.js";
4
4
  import { paintSymbol } from "../symbol/shape.js";
5
5
  import { sanbanBounds, sanbanShapes } from "./shape.js";
6
6
  import { ASTFunctionNode, } from "../ASTtypes.js";
7
- // 同一执行位置只关闭一次旧小节,保留最终拍号和最后源码边界。
7
+ // 同一执行位置只关闭一次旧小节,保留最终拍号和最后源码边界
8
8
  const changesByPosition = new WeakMap();
9
- function recordMeasureChange(state, node, meter) {
10
- const position = state.currentEvent ?? node;
9
+ export function meterChangeAt(node) {
10
+ return changesByPosition.get(node)?.meter;
11
+ }
12
+ function recordMeasureChange(node, meter) {
13
+ const position = node.rootHost;
11
14
  const span = node.ast.sourceSpan;
12
15
  let change = changesByPosition.get(position);
13
16
  if (!change)
@@ -73,14 +76,15 @@ class MeterFunction extends ASTFunctionNode {
73
76
  this.size = ctx.length2px(size);
74
77
  this.strict = ctx.variables.strict;
75
78
  }
76
- loweringEnter() {
79
+ loweringEnter(ctx) {
80
+ ctx.deferFinalize(MeterFunction.loweringFinalize);
77
81
  return [new MeterTemporal(this)];
78
82
  }
79
83
  /**
80
84
  * 校验小节拍数
81
85
  * 第一小节特殊规则:只允许不满拍,但不能超拍
82
86
  */
83
- static loweringFinalize = (result) => {
87
+ static loweringFinalize(result) {
84
88
  const measureStart = new Fraction();
85
89
  const measureLength = new Fraction();
86
90
  let active = null;
@@ -94,11 +98,12 @@ class MeterFunction extends ASTFunctionNode {
94
98
  measureLength.copyFrom(end).sub(measureStart);
95
99
  if (!measureLength.equals(active.measureDuration)
96
100
  && (validationStarted || measureLength.compare(active.measureDuration) > 0)) {
97
- const message = `小节时长为 ${measureLength} QN,不满足 ${active.numerator}/${active.denominator} 拍号`;
101
+ const message = "小节时长为 {duration} QN,不满足 {num}/{den} 拍号";
98
102
  const span = { start: sourceStart, end: sourceEnd };
103
+ const params = { duration: measureLength, num: active.numerator, den: active.denominator };
99
104
  if (active.strict)
100
- throw new ErrorDiagnostic("E_METER_MISMATCH", message, span);
101
- result.diagnostics.push(new WarningDiagnostic("W_METER_MISMATCH", message, span));
105
+ throw new ErrorDiagnostic("E_METER_MISMATCH", message, span, params);
106
+ result.diagnostics.push(new WarningDiagnostic("W_METER_MISMATCH", message, span, params));
102
107
  }
103
108
  measureStart.copyFrom(end);
104
109
  };
@@ -124,7 +129,7 @@ class MeterFunction extends ASTFunctionNode {
124
129
  const span = result.columns.at(-1)?.at(-1)?.ast.sourceSpan ?? active.sourceSpan;
125
130
  closeMeasure(result.duration, span.end);
126
131
  }
127
- };
132
+ }
128
133
  toString() {
129
134
  return `@meter(${this.numerator}, ${this.denominator})`;
130
135
  }
@@ -149,7 +154,7 @@ class MeterTemporal extends TemporalNodeBase {
149
154
  }
150
155
  onTimeState(state) {
151
156
  state.meter = this.ast.measureDuration;
152
- recordMeasureChange(state, this, this.ast);
157
+ recordMeasureChange(this, this.ast);
153
158
  }
154
159
  emitPlayback(emitter) {
155
160
  if (!this.ast.measureDuration)
@@ -1,6 +1,6 @@
1
1
  import { ASTTextNode, ASTFunctionNode } from "../ASTtypes.js";
2
2
  import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
3
- import { parseNoteName } from "./noteNameFSM.js";
3
+ import { parseNoteName } from "./noteName.js";
4
4
  import { getLayoutBounds } from "../../layout/engine.js";
5
5
  import { paintAccidental, placeAccidentals } from "./accidentals.js";
6
6
  import { rewriteNotes } from "./source-transform.js";
@@ -83,8 +83,8 @@ class NoteFunction extends ASTFunctionNode {
83
83
  },
84
84
  };
85
85
  // 解析音符名
86
- const parseResult = parseNoteName(source, start, end);
87
- if (parseResult instanceof Diagnostic)
86
+ const parseResult = parseNoteName(source, start, end, false);
87
+ if (!parseResult)
88
88
  return null;
89
89
  const argMap = new Map();
90
90
  argMap.set("name", parseResult.name);
@@ -140,13 +140,13 @@ class NoteFunction extends ASTFunctionNode {
140
140
  throw parseResult;
141
141
  }
142
142
  if (parseResult.next !== this.name.length)
143
- throw new ErrorDiagnostic("E_WRONG_NOTE_NAME", `函数 @note 的参数 [0]:"name" 格式错误: 无法解析尾部 "${this.name.slice(parseResult.next)}"`, sourceSpan);
143
+ throw new ErrorDiagnostic("E_WRONG_NOTE_NAME", '函数 @note 的参数 [0]:"name" 格式错误: 无法解析尾部 "{tail}"', sourceSpan, { tail: this.name.slice(parseResult.next) });
144
144
  this.name = parseResult.name === "X" ? "9" : parseResult.name === "Z" ? "0" : parseResult.name;
145
145
  // 校验octave
146
146
  const inputOctave = args.get("octave") ?? args.get(2);
147
147
  if (inputOctave !== void 0) {
148
148
  if (parseResult.octave !== null && parseResult.octave != inputOctave)
149
- throw new ErrorDiagnostic("E_NOTE_OCTAVE_CONFLICT", `函数 @note 的参数 "octave" 与音符名称中的八度信息冲突: ${inputOctave} != ${parseResult.octave}`, sourceSpan);
149
+ throw new ErrorDiagnostic("E_NOTE_OCTAVE_CONFLICT", '函数 @note 的参数 "octave" 与音符名称中的八度信息冲突: {inputOctave} != {noteOctave}', sourceSpan, { inputOctave: String(inputOctave), noteOctave: parseResult.octave });
150
150
  }
151
151
  else {
152
152
  // 没有单独传入 octave 时,优先采用音名中的八度;数字音名缺省为相对 0。
@@ -275,7 +275,6 @@ class NoteTemporalNode extends TemporalNodeBase {
275
275
  const keySignature = this.keySignature = state.keySignature;
276
276
  this.playbackState = { bpm: state.bpm, velocity: state.velocity, program: state.program };
277
277
  this.resolvedMidi = resolveNoteMidi(this.name, this.acc, this.octave, keySignature);
278
- this.transposeDiatonic = createDiatonicTranspose(this.name, this.acc, this.octave, keySignature);
279
278
  // 数字音名本身就是简谱显示形式,直接保留原始数字和相对八度
280
279
  if (this.name >= "0" && this.name <= "9") {
281
280
  if (this.name === "0" || this.name >= "8") {
@@ -292,6 +291,7 @@ class NoteTemporalNode extends TemporalNodeBase {
292
291
  this.octave = jianpuPitch.renderOctave;
293
292
  }
294
293
  }
294
+ this.transposeDiatonic = createDiatonicTranspose(this.name, this.octave, keySignature);
295
295
  }
296
296
  /** 发布完整音段或无声区间,实际 NoteOn/NoteOff 留到声音展开完成后生成 */
297
297
  emitPlayback(emitter) {
@@ -0,0 +1,16 @@
1
+ import { Diagnostic } from "../../diagnostic.js";
2
+ export interface ParsedNoteName {
3
+ name: string;
4
+ next: number;
5
+ acc: string | null;
6
+ octave: number | null;
7
+ absOctave: boolean;
8
+ }
9
+ /**
10
+ * 解析音符名称,支持三种语法分支:
11
+ * 1. 字母音名:`[A-GXZ]` + (`[绝对八度][后置升降号]` | `[升降号][绝对八度]`)
12
+ * 2. 数字音名:`[0-9]` + `[后置升降号]` + `[相对八度 ,']`
13
+ * 3. 前置升降号数字音名:`[#bn]+` + `[0-9]` + `[相对八度 ,']`
14
+ */
15
+ export declare function parseNoteName(str: string, start?: number, end?: number, diagnose?: true): ParsedNoteName | Diagnostic;
16
+ export declare function parseNoteName(str: string, start: number, end: number, diagnose: false): ParsedNoteName | null;