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
@@ -53,30 +53,11 @@ function layoutHeadSlot({ columns, rows, start, end, X, fixed, options }, occupi
53
53
  else
54
54
  X[end] = X[start];
55
55
  }
56
- /** 行从上到下按 gap 排列;capture 让 Head 在同一遍测量里取得整组范围 */
57
- function measureRows(members, gap, capture) {
58
- const placements = [];
59
- let top;
60
- let cursor;
61
- for (const extent of members) {
62
- if (!extent) {
63
- placements.push(null);
64
- continue;
65
- }
66
- const offset = cursor === void 0 ? 0 : cursor + gap - extent.top;
67
- placements.push({ offset, extent });
68
- top ??= offset + extent.top;
69
- cursor = offset + extent.bottom;
70
- }
71
- capture?.(top === void 0 || cursor === void 0 ? null : { top, bottom: cursor });
72
- return placements;
73
- }
74
56
  class HeadBoundaryTemporal extends TemporalNodeBase {
75
57
  members = [];
76
58
  slots = [];
77
59
  titleBottom = 0;
78
- leftExtent = null;
79
- rightExtent = null;
60
+ sideExtents = { left: null, right: null };
80
61
  constructor(ast) {
81
62
  super();
82
63
  this.ast = ast;
@@ -99,31 +80,40 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
99
80
  if (this.slots.length > 0)
100
81
  this.alignHead();
101
82
  }
83
+ onTemporal(node) { this.members.push(node); }
102
84
  createTracks(slot) {
103
85
  const { name, owner } = slot;
104
86
  return {
105
87
  laneKey: `head/rows/${owner.sourceSpan.start}/${name}`,
106
88
  hostIndex: null,
107
89
  measure: members => {
108
- if (name === "center") {
109
- const placements = measureRows(members, owner.gap);
110
- const first = placements.find(placement => placement !== null);
111
- this.titleBottom = first ? first.offset + first.extent.bottom : 0;
112
- return placements;
113
- }
114
- return measureRows(members, owner.gap, extent => {
115
- if (name === "left")
116
- this.leftExtent = extent;
117
- else
118
- this.rightExtent = extent;
90
+ // 行从上到下排列,同一遍取得标题首行底边和侧栏整组范围
91
+ let top;
92
+ let bottom;
93
+ if (name === "center")
94
+ this.titleBottom = 0;
95
+ const placements = members.map(extent => {
96
+ if (!extent)
97
+ return null;
98
+ const offset = bottom === void 0 ? 0 : bottom + owner.gap - extent.top;
99
+ if (bottom === void 0 && name === "center")
100
+ this.titleBottom = extent.bottom;
101
+ top ??= offset + extent.top;
102
+ bottom = offset + extent.bottom;
103
+ return { offset, extent };
119
104
  });
105
+ if (name !== "center") {
106
+ this.sideExtents[name] = top === void 0 || bottom === void 0 ? null : { top, bottom };
107
+ }
108
+ return placements;
120
109
  },
121
110
  place: name === "center" ? undefined : () => {
122
- const extent = name === "left" ? this.leftExtent : this.rightExtent;
111
+ const extent = this.sideExtents[name];
123
112
  if (!extent)
124
113
  return this.titleBottom;
125
- const leftHeight = this.leftExtent ? this.leftExtent.bottom - this.leftExtent.top : 0;
126
- const rightHeight = this.rightExtent ? this.rightExtent.bottom - this.rightExtent.top : 0;
114
+ const { left, right } = this.sideExtents;
115
+ const leftHeight = left ? left.bottom - left.top : 0;
116
+ const rightHeight = right ? right.bottom - right.top : 0;
127
117
  // 两侧共享底边;以较高侧定总高度,使它的顶部恰好贴标题底边
128
118
  const targetBottom = this.titleBottom + Math.max(leftHeight, rightHeight);
129
119
  return targetBottom - extent.bottom;
@@ -162,8 +152,8 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
162
152
  cells.set(cell, [member]);
163
153
  }
164
154
  const [left, , right] = this.slots;
165
- this.packRows(left.ast, left.start.box.x, "left", cells);
166
- this.packRows(right.ast, right.end.box.x, "right", cells);
155
+ this.packRows(left.ast, left.start.box.x, cells);
156
+ this.packRows(right.ast, right.end.box.x, cells);
167
157
  }
168
158
  stretch(node, side) {
169
159
  const alpha = side === "L" ? "alpha_L" : "alpha_R";
@@ -172,9 +162,9 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
172
162
  node.springConfig[alpha] = node.springConfig[alpha] * HEAD_STRETCH;
173
163
  node.springConfig[beta] = node.springConfig[beta] * 3 / HEAD_STRETCH;
174
164
  }
175
- packRows(slot, target, side, cells) {
165
+ packRows(slot, target, cells) {
176
166
  const gap = this.ast.owner.size * ITEM_GAP_EM;
177
- const fromLeft = side === "left";
167
+ const fromLeft = slot.name === "left";
178
168
  const direction = fromLeft ? 1 : -1;
179
169
  for (const row of slot.rows) {
180
170
  const rowCells = row instanceof ASTBraceNode ? row.content : [row];
@@ -242,8 +232,12 @@ class HeadSlotNode extends ASTNodeBase {
242
232
  tracks: head.createTracks(this),
243
233
  };
244
234
  }
245
- loweringEnter() {
246
- return [new HeadBoundaryTemporal(this)];
235
+ loweringEnter(ctx) {
236
+ const boundary = new HeadBoundaryTemporal(this);
237
+ // 首边界收集真实全局事件,供末边界校验和放置后的对齐
238
+ if (this.name === "left")
239
+ ctx.beginLoweringGroup(this.owner, boundary);
240
+ return [boundary];
247
241
  }
248
242
  loweringExit() {
249
243
  return [new HeadBoundaryTemporal(this)];
@@ -388,7 +382,7 @@ H.tempo: 94
388
382
  const last = skipSpacesBack(ctx.source, boundary - 1, start);
389
383
  const span = { start, end: Math.max(start, last + 1) };
390
384
  if (span.start >= span.end) {
391
- throw new ErrorDiagnostic("E_HEAD_EMPTY_DECLARATION", `H.${field}: 后必须有内容`, sugar.span);
385
+ throw new ErrorDiagnostic("E_HEAD_EMPTY_DECLARATION", "H.{field}: 后必须有内容", sugar.span, { field });
392
386
  }
393
387
  const text = ctx.source.slice(span.start, span.end).trim();
394
388
  let parsed;
@@ -403,7 +397,8 @@ H.tempo: 94
403
397
  ? previous
404
398
  : new HeadFunction(sugar.span, new Map(), ctx, null);
405
399
  head.createdBySugar = true;
406
- head.addSugarRow(FIELD_SLOT[field], HeadFunction.parseSugarRow(ctx, field, span, text, parsed));
400
+ head.slots.find(slot => slot.name === FIELD_SLOT[field])
401
+ .addRow(HeadFunction.parseSugarRow(ctx, field, span, text, parsed));
407
402
  head.sourceSpan.end = span.end;
408
403
  if (head !== previous)
409
404
  ctx.pushNode(head);
@@ -461,19 +456,8 @@ H.tempo: 94
461
456
  new HeadSlotNode(span, this, "right", rows("right", 2)),
462
457
  ];
463
458
  }
464
- loweringEnter(ctx) {
465
- // 收集真实全局事件,供末边界校验时值和放置后的横向对齐
466
- const group = {
467
- members: [],
468
- onTemporal(node) { this.members.push(node); },
469
- };
470
- ctx.beginLoweringGroup(this, group);
471
- return [];
472
- }
473
459
  loweringExit(ctx) {
474
- const { members } = ctx.endLoweringGroup(this);
475
- const head = ctx.getTemporalNodes(this.slots[0])[0];
476
- head.members = members;
460
+ const head = ctx.endLoweringGroup(this);
477
461
  head.slots = this.slots.map(ast => {
478
462
  const [start, end] = ctx.getTemporalNodes(ast);
479
463
  return { ast, start, end };
@@ -481,16 +465,13 @@ H.tempo: 94
481
465
  // right.end 是整个 Head 的末边界,按三槽的 sequence 排在所有内容之后
482
466
  // 此时 rest 等延迟时值已固化,只检查当前 Head 的成员,无须再扫描全谱索引
483
467
  head.slots[2].end.onTimeState = () => head.validateDuration();
484
- for (const node of members) {
485
- if (node.breakBefore > 0) {
486
- throw new ErrorDiagnostic("E_HEAD_INTERNAL_BREAK", "@head 的内部不能使用 @br;第一层内容已经表示视觉行", node.ast.sourceSpan);
468
+ for (const node of head.members) {
469
+ if ((node.addon?.breakBefore ?? 0) > 0) {
470
+ throw new ErrorDiagnostic("E_HEAD_INTERNAL_BREAK", "@head 的内部不能换行或换页;第一层内容已经表示视觉行", node.ast.sourceSpan);
487
471
  }
488
472
  }
489
473
  return [];
490
474
  }
491
- addSugarRow(name, row) {
492
- this.slots.find(slot => slot.name === name).addRow(row);
493
- }
494
475
  toString(source) {
495
476
  const slots = this.slots
496
477
  .filter(slot => slot.rows.length > 0)
@@ -1,7 +1,7 @@
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";
3
+ import { ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
4
+ import { parseNoteName } from "../note/noteName.js";
5
5
  import { acc2Offset, NoteNameMap, tonality2Midi } from "../../parser/parse-utils/note-utils.js";
6
6
  import { paintAccidental, placeAccidentals } from "../note/accidentals.js";
7
7
  /**
@@ -11,13 +11,11 @@ import { paintAccidental, placeAccidentals } from "../note/accidentals.js";
11
11
  * `C###` 这种超过一个变音记号的写法按实际音高换字母(→ D#4),落在黑键上则跟随原来的升降方向拼写
12
12
  */
13
13
  function normalizeTonality(tonality) {
14
- try {
15
- tonality2Midi(tonality, 4);
14
+ if (tonality2Midi(tonality) !== null)
16
15
  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)
16
+ const normalizedInput = tonality.replace(/^[a-g]/, letter => letter.toUpperCase());
17
+ const parsed = parseNoteName(normalizedInput, 0, normalizedInput.length, false);
18
+ if (!parsed || parsed.next !== normalizedInput.length)
21
19
  return null;
22
20
  const pitchClass = NoteNameMap[parsed.name];
23
21
  if (pitchClass === undefined)
@@ -72,9 +70,9 @@ class KeyFunction extends ASTFunctionNode {
72
70
  const normalized = normalizeTonality(tonality);
73
71
  if (normalized !== tonality) {
74
72
  if (ctx.variables.strict)
75
- throw new ErrorDiagnostic("E_KEY_TONALITY", `@key 无法解析调性 "${tonality}"`, sourceSpan);
73
+ throw new ErrorDiagnostic("E_KEY_TONALITY", '@key 无法解析调性 "{tonality}"', sourceSpan, { tonality });
76
74
  this.tonality = normalized ?? DEFAULT_TONALITY;
77
- ctx.diagnostics.push(new WarningDiagnostic("W_KEY_TONALITY", `@key 的调性 "${tonality}" 不是规范写法,已自动切换到 ${this.tonality}`, sourceSpan));
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,6 +4,20 @@ 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
+ // 同一执行位置只关闭一次旧小节,保留最终拍号和最后源码边界
8
+ const changesByPosition = new WeakMap();
9
+ export function meterChangeAt(node) {
10
+ return changesByPosition.get(node)?.meter;
11
+ }
12
+ function recordMeasureChange(state, node, meter) {
13
+ const position = state.currentEvent ?? node;
14
+ const span = node.ast.sourceSpan;
15
+ let change = changesByPosition.get(position);
16
+ if (!change)
17
+ changesByPosition.set(position, change = { start: span.start, end: span.end, meter });
18
+ change.end = span.end;
19
+ change.meter = meter;
20
+ }
7
21
  class MeterFunction extends ASTFunctionNode {
8
22
  static def = {
9
23
  name: ["meter"],
@@ -62,14 +76,15 @@ class MeterFunction extends ASTFunctionNode {
62
76
  this.size = ctx.length2px(size);
63
77
  this.strict = ctx.variables.strict;
64
78
  }
65
- loweringEnter() {
79
+ loweringEnter(ctx) {
80
+ ctx.deferFinalize(MeterFunction.loweringFinalize);
66
81
  return [new MeterTemporal(this)];
67
82
  }
68
83
  /**
69
84
  * 校验小节拍数
70
85
  * 第一小节特殊规则:只允许不满拍,但不能超拍
71
86
  */
72
- static loweringFinalize = (result) => {
87
+ static loweringFinalize(result) {
73
88
  const measureStart = new Fraction();
74
89
  const measureLength = new Fraction();
75
90
  let active = null;
@@ -83,35 +98,25 @@ class MeterFunction extends ASTFunctionNode {
83
98
  measureLength.copyFrom(end).sub(measureStart);
84
99
  if (!measureLength.equals(active.measureDuration)
85
100
  && (validationStarted || measureLength.compare(active.measureDuration) > 0)) {
86
- const message = `小节时长为 ${measureLength} QN,不满足 ${active.numerator}/${active.denominator} 拍号`;
101
+ const message = "小节时长为 {duration} QN,不满足 {num}/{den} 拍号";
87
102
  const span = { start: sourceStart, end: sourceEnd };
103
+ const params = { duration: measureLength, num: active.numerator, den: active.denominator };
88
104
  if (active.strict)
89
- throw new ErrorDiagnostic("E_METER_MISMATCH", message, span);
90
- 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));
91
107
  }
92
108
  measureStart.copyFrom(end);
93
109
  };
94
- const metersByHost = new Map();
95
- for (const nodes of result.astToTemporal.values()) {
96
- for (const node of nodes) {
97
- if (!(node instanceof MeterTemporal))
98
- continue;
99
- let host = node;
100
- while (host.foldedInto)
101
- host = host.foldedInto;
102
- if (!metersByHost.has(host))
103
- metersByHost.set(host, node);
104
- }
105
- }
106
110
  for (const column of result.columns) {
107
111
  const time = column[0].t;
108
- const host = column.find(node => metersByHost.has(node));
109
- const meter = host && metersByHost.get(host);
110
- if (meter) {
111
- closeMeasure(time, meter.ast.sourceSpan.start);
112
- active = meter.ast;
112
+ for (const node of column) {
113
+ const change = changesByPosition.get(node);
114
+ if (!change)
115
+ continue;
116
+ closeMeasure(time, change.start);
117
+ active = change.meter;
113
118
  measureStart.copyFrom(time);
114
- sourceStart = meter.ast.sourceSpan.end;
119
+ sourceStart = change.end;
115
120
  }
116
121
  const anchor = column.find(node => node.mergeKey === ANCHOR_KEY);
117
122
  if (anchor) {
@@ -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,6 +154,7 @@ class MeterTemporal extends TemporalNodeBase {
149
154
  }
150
155
  onTimeState(state) {
151
156
  state.meter = this.ast.measureDuration;
157
+ recordMeasureChange(state, this, this.ast);
152
158
  }
153
159
  emitPlayback(emitter) {
154
160
  if (!this.ast.measureDuration)
@@ -46,20 +46,6 @@ const ACCIDENTALS = {
46
46
  ],
47
47
  },
48
48
  };
49
- /** size 是数字字号,升降号自己决定缩小多少 */
50
- function prepareAccidental(symbol, size) {
51
- const definition = ACCIDENTALS[symbol];
52
- if (!definition)
53
- return null;
54
- const glyphSize = size * GLYPH_SCALE;
55
- return {
56
- w: definition.w * glyphSize,
57
- h: definition.h * glyphSize,
58
- baseline: definition.baseline * glyphSize,
59
- strokeWidth: size * STROKE_RATIO,
60
- commands: definition.commands,
61
- };
62
- }
63
49
  /**
64
50
  * 把升降号串按同一基线依次排在 x 右侧
65
51
  * @param size 宿主数字的字号
@@ -69,13 +55,21 @@ function prepareAccidental(symbol, size) {
69
55
  */
70
56
  export function placeAccidentals(symbols, size, x, baselineY, gap) {
71
57
  const placed = [];
58
+ const glyphSize = size * GLYPH_SCALE;
72
59
  const raise = size * RAISE_RATIO;
73
60
  let right = x;
74
61
  let top = 0;
75
62
  for (const symbol of symbols) {
76
- const shape = prepareAccidental(symbol, size);
77
- if (!shape)
63
+ const definition = ACCIDENTALS[symbol];
64
+ if (!definition)
78
65
  continue;
66
+ const shape = {
67
+ w: definition.w * glyphSize,
68
+ h: definition.h * glyphSize,
69
+ baseline: definition.baseline * glyphSize,
70
+ strokeWidth: size * STROKE_RATIO,
71
+ commands: definition.commands,
72
+ };
79
73
  const y = baselineY - shape.baseline - raise;
80
74
  placed.push({ shape, x: right, y });
81
75
  if (y < top)
@@ -1,6 +1,7 @@
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
+ import { getLayoutBounds } from "../../layout/engine.js";
4
5
  import { paintAccidental, placeAccidentals } from "./accidentals.js";
5
6
  import { rewriteNotes } from "./source-transform.js";
6
7
  /** 根据同一源码的 lowering 生成局部修改;传入 ranges 时只处理完整落入任一选区的音符 */
@@ -82,8 +83,8 @@ class NoteFunction extends ASTFunctionNode {
82
83
  },
83
84
  };
84
85
  // 解析音符名
85
- const parseResult = parseNoteName(source, start, end);
86
- if (parseResult instanceof Diagnostic)
86
+ const parseResult = parseNoteName(source, start, end, false);
87
+ if (!parseResult)
87
88
  return null;
88
89
  const argMap = new Map();
89
90
  argMap.set("name", parseResult.name);
@@ -139,13 +140,13 @@ class NoteFunction extends ASTFunctionNode {
139
140
  throw parseResult;
140
141
  }
141
142
  if (parseResult.next !== this.name.length)
142
- 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) });
143
144
  this.name = parseResult.name === "X" ? "9" : parseResult.name === "Z" ? "0" : parseResult.name;
144
145
  // 校验octave
145
146
  const inputOctave = args.get("octave") ?? args.get(2);
146
147
  if (inputOctave !== void 0) {
147
148
  if (parseResult.octave !== null && parseResult.octave != inputOctave)
148
- 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 });
149
150
  }
150
151
  else {
151
152
  // 没有单独传入 octave 时,优先采用音名中的八度;数字音名缺省为相对 0。
@@ -170,7 +171,7 @@ import { createDiatonicTranspose, resolveLetterNameToJianpu, resolveNoteMidi, }
170
171
  const NOTE_GLYPH = { "8": "", "9": "X" };
171
172
  class NoteTemporalNode extends TemporalNodeBase {
172
173
  // 时间固化后的参数
173
- resolvedMidi = null; // MIDI音高 name是数字则需要在onTimeState中基于当前调性偏移 播放的音高
174
+ resolvedMidi = null; // 按调性解析的记谱音高,不含播放偏移
174
175
  keySignature = "C4"; // 用于转调时记录大环境
175
176
  transposeDiatonic;
176
177
  name; // 数字
@@ -253,6 +254,12 @@ class NoteTemporalNode extends TemporalNodeBase {
253
254
  }
254
255
  finalizeLayout() {
255
256
  this.ports["lyric"] = { x: this.box.anchor, y: this.box.h };
257
+ if (this.octave > 0) { // 八度点上方留空间
258
+ this.ports["tie.top"] = {
259
+ x: this.box.anchor,
260
+ y: getLayoutBounds(this, true).y - this.box.y - this.ast.size * 0.05,
261
+ };
262
+ }
256
263
  }
257
264
  paint(painter) {
258
265
  const color = this.ast.color;
@@ -290,6 +297,8 @@ class NoteTemporalNode extends TemporalNodeBase {
290
297
  emitPlayback(emitter) {
291
298
  const percussion = this.ast.name === "9";
292
299
  const midi = percussion ? 37 : this.resolvedMidi;
300
+ const shift = percussion ? 0 : this.playbackState?.pitchShift ?? 0;
301
+ const transpose = this.transposeDiatonic;
293
302
  if (emitter.end.compare(emitter.start) <= 0)
294
303
  return;
295
304
  // 休止符和占位符也要保留结构边界,速度效果与后续延长才能覆盖这段时间。
@@ -301,9 +310,10 @@ class NoteTemporalNode extends TemporalNodeBase {
301
310
  emitter.note({
302
311
  start: emitter.start,
303
312
  end: emitter.end,
304
- midi,
313
+ midi: midi + shift,
305
314
  velocity: this.playbackState?.velocity ?? DEFAULT_VELOCITY,
306
- ...(percussion ? { percussion: true } : { transpose: this.transposeDiatonic }),
315
+ ...(percussion ? { percussion: true }
316
+ : { transpose: shift && transpose ? steps => transpose(steps) + shift : transpose }),
307
317
  });
308
318
  }
309
319
  }
@@ -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;
@@ -0,0 +1,88 @@
1
+ import { ErrorDiagnostic } from "../../diagnostic.js";
2
+ function isLetterNote(ch) {
3
+ return (ch >= "A" && ch <= "G") || ch === "X" || ch === "Z";
4
+ }
5
+ function isDigit(ch) {
6
+ return ch >= "0" && ch <= "9";
7
+ }
8
+ function isAccidentalChar(ch) {
9
+ return ch === "#" || ch === "b" || ch === "n";
10
+ }
11
+ function readAccidental(str, pos, end) {
12
+ while (pos < end && isAccidentalChar(str[pos]))
13
+ pos++;
14
+ return pos;
15
+ }
16
+ /** 后置升降号不能紧接数字音名(例如 `C4#1` 或 `1#2` 中的 `#1`/`#2` 属于下一个音符) */
17
+ function readTrailingAccidental(str, pos, end) {
18
+ const accEnd = readAccidental(str, pos, end);
19
+ return accEnd > pos && !isDigit(str[accEnd] ?? "") ? str.slice(pos, accEnd) : null;
20
+ }
21
+ function readAbsOctave(str, pos, end) {
22
+ if (pos < end && (str[pos] === "+" || str[pos] === "-"))
23
+ pos++;
24
+ const digitStart = pos;
25
+ while (pos < end && isDigit(str[pos]))
26
+ pos++;
27
+ return pos > digitStart ? pos : -1;
28
+ }
29
+ function finishRelative(str, pos, end, name, acc) {
30
+ let octave = 0;
31
+ let next = pos;
32
+ while (next < end && (str[next] === "," || str[next] === "'")) {
33
+ octave += str[next++] === "'" ? 1 : -1;
34
+ }
35
+ return { name, next, acc, octave: next > pos ? octave : null, absOctave: false };
36
+ }
37
+ export function parseNoteName(str, start = 0, end = str.length, diagnose = true) {
38
+ if (end - start === 0) {
39
+ return diagnose ? new ErrorDiagnostic("E_WRONG_NOTE_NAME", '函数 @note 的参数 [0]:"name" 不能为空', { start, end }) : null;
40
+ }
41
+ const ch = str[start];
42
+ // 分支 1:字母音名(使用绝对八度)
43
+ if (isLetterNote(ch)) {
44
+ let pos = start + 1;
45
+ let acc = null;
46
+ let octave = null;
47
+ const octEnd = readAbsOctave(str, pos, end);
48
+ if (octEnd > 0) {
49
+ octave = parseInt(str.slice(pos, octEnd), 10);
50
+ pos = octEnd;
51
+ acc = readTrailingAccidental(str, pos, end);
52
+ if (acc)
53
+ pos += acc.length;
54
+ }
55
+ else {
56
+ const accEnd = readAccidental(str, pos, end);
57
+ if (accEnd > pos) {
58
+ acc = str.slice(pos, accEnd);
59
+ const oct2 = readAbsOctave(str, accEnd, end);
60
+ if (oct2 > 0) {
61
+ octave = parseInt(str.slice(accEnd, oct2), 10);
62
+ pos = oct2;
63
+ }
64
+ else
65
+ pos = accEnd;
66
+ }
67
+ }
68
+ return { name: ch, next: pos, acc, octave, absOctave: true };
69
+ }
70
+ // 分支 2:数字音名(使用相对八度)
71
+ if (isDigit(ch)) {
72
+ const acc = readTrailingAccidental(str, start + 1, end);
73
+ return finishRelative(str, start + 1 + (acc ? acc.length : 0), end, ch, acc);
74
+ }
75
+ // 分支 3:前置升降号 + 数字音名
76
+ if (isAccidentalChar(ch)) {
77
+ const accEnd = readAccidental(str, start, end);
78
+ if (accEnd >= end) {
79
+ return diagnose ? new ErrorDiagnostic("E_WRONG_NOTE_NAME", '函数 @note 的参数 [0]:"name" 格式错误: 在升降号开头时,应该接数字音名,但输入已结束', { start, end }) : null;
80
+ }
81
+ const noteCh = str[accEnd];
82
+ if (!isDigit(noteCh)) {
83
+ return diagnose ? new ErrorDiagnostic("E_WRONG_NOTE_NAME", '函数 @note 的参数 [0]:"name" 格式错误: 在升降号开头时,应该接数字音名,但发现字符 "{ch}"', { start: accEnd, end: accEnd + 1 }, { ch: noteCh }) : null;
84
+ }
85
+ return finishRelative(str, accEnd + 1, end, noteCh, str.slice(start, accEnd));
86
+ }
87
+ return diagnose ? new ErrorDiagnostic("E_WRONG_NOTE_NAME", '函数 @note 的参数 [0]:"name" 格式错误: 首字符 "{ch}" 不合法,期望 A-G (a-g)、0-9、X 或 Z 开头,或在开头直接使用升降号(#/b/n)', { start, end: start + 1 }, { ch }) : null;
88
+ }
@@ -1,9 +1,9 @@
1
- import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
1
+ import { ErrorDiagnostic } from "../../diagnostic.js";
2
2
  import { preprocessSource } from "../../parser/preprocess.js";
3
3
  import { readCall } from "../../parser/parse-utils/call-utils.js";
4
4
  import { findClosingQuote, quote } from "../../parser/parse-utils/string-utils.js";
5
5
  import { NoteNameMap, SHARP_NOTE_NAMES, FLAT_NOTE_NAMES, resolveLetterNameToJianpu, tonality2Midi } from "../../parser/parse-utils/note-utils.js";
6
- import { parseNoteName } from "./noteNameFSM.js";
6
+ import { parseNoteName } from "./noteName.js";
7
7
  const LETTERS = "CDEFGAB";
8
8
  const mod = (value, base) => ((value % base) + base) % base;
9
9
  const accidental = (offset) => offset < 0 ? "b".repeat(-offset) : "#".repeat(offset);
@@ -15,7 +15,7 @@ function targetPitch(note, operation) {
15
15
  const absolute = operation === "to-absolute"
16
16
  || operation !== "to-relative" && LETTERS.includes(note.ast.name);
17
17
  const midi = note.resolvedMidi + (operation === "semitone-up" ? 1 : operation === "semitone-down" ? -1 : 0);
18
- const tonic = tonality2Midi(note.keySignature, 4);
18
+ const tonic = tonality2Midi(note.keySignature);
19
19
  if (![midi, tonic, note.ast.octave, note.ast.jeOctaveOffset].every(Number.isSafeInteger))
20
20
  fail(note.ast.sourceSpan);
21
21
  const spelling = operation === "semitone-down" ? FLAT_NOTE_NAMES : SHARP_NOTE_NAMES;
@@ -145,8 +145,9 @@ export function rewriteNotes(source, notes, operation, ranges) {
145
145
  const left = tokens[index], right = tokens[index + 1];
146
146
  if (left.span.end !== right.span.start || left.text.endsWith("}"))
147
147
  continue;
148
- const parsed = parseNoteName(left.text + right.text);
149
- if (parsed instanceof Diagnostic || parsed.next !== left.text.length) {
148
+ const merged = left.text + right.text;
149
+ const parsed = parseNoteName(merged, 0, merged.length, false);
150
+ if (!parsed || parsed.next !== left.text.length) {
150
151
  if (left.text !== source.slice(left.span.start, left.span.end))
151
152
  left.text += " ";
152
153
  else
@@ -0,0 +1,2 @@
1
+ import { type ASTFunctionClass } from "../ASTtypes.js";
2
+ export declare const OttavaNode: ASTFunctionClass;