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
@@ -11,7 +11,7 @@
11
11
  import { Fraction } from "../../fraction.js";
12
12
  import { NoteNameMap } from "../../parser/parse-utils/note-utils.js";
13
13
  import { child, children, nameOf, number, text, } from "./dom.js";
14
- import { MusicXmlReader, acceptTuplets, directionDynamic, directionTexts, endingPasses, metronomeBpm, mergeArpeggio, noteArpeggio, noteLyrics, noteModifiers, parsePitch, parseTimeSignature, partMeasures, readInstrument, reportDiagnostic, scoreMetadata, timeModification, transposePitch, } from "./features.js";
14
+ import { MusicXmlReader, acceptTuplets, directionDynamic, directionTexts, endingPasses, metronomeBpm, mergeArpeggio, noteArpeggio, noteGlissandi, noteLyrics, noteModifiers, parsePitch, parseTimeSignature, partMeasures, readInstrument, reportDiagnostic, scoreMetadata, soundRepeats, timeModification, transposePitch, } from "./features.js";
15
15
  import { attachAbove, quote, renderHead, renderPitch, renderSystems } from "../source.js";
16
16
  import { matchingLanes, resolveRelations, resolveVoices } from "./resolve.js";
17
17
  const MAJOR_KEYS = ["Cb", "Gb", "Db", "Ab", "Eb", "Bb", "F", "C", "G", "D", "A", "E", "B", "F#", "C#"];
@@ -67,7 +67,7 @@ function setBar(bars, at, token) {
67
67
  else if (token === "|:" && current.includes(":|")) {
68
68
  bars.set(key, current === ":|" ? ":|:" : `${current} |:`);
69
69
  }
70
- else if (token === "||" && !current.includes("|:") && !current.includes(":|")) {
70
+ else if (token === "|||" && !current.includes("|:") && !current.includes(":|")) {
71
71
  bars.set(key, token);
72
72
  }
73
73
  }
@@ -102,14 +102,21 @@ function parseScore(root, diagnostics) {
102
102
  const meters = new Map();
103
103
  const keys = new Map();
104
104
  const tempos = new Map();
105
+ const repeats = new Map();
105
106
  const directions = [];
106
107
  const wedgePoints = [];
107
108
  const endingPoints = new Map();
108
109
  const bars = new Map();
109
110
  const measureBoundaries = new Set();
110
111
  const lineBreaks = new Set();
112
+ const multipleRests = [];
111
113
  let scoreEnd = new Fraction();
112
114
  let order = 0;
115
+ const recordRepeat = (point) => {
116
+ const key = `${keyOf(point.at)}\0${point.symbol}`;
117
+ if (!repeats.has(key))
118
+ repeats.set(key, point);
119
+ };
113
120
  // 主时间解析:逐 part、逐小节扫描 attributes/direction/note/barline
114
121
  const measuresByPart = partMeasures(root);
115
122
  const partOrder = new Map([...measuresByPart.keys()].map((id, index) => [id, index]));
@@ -128,6 +135,8 @@ function parseScore(root, diagnostics) {
128
135
  const pitches = [];
129
136
  const instrumentChanges = [];
130
137
  const eventInstruments = new Map();
138
+ const measureStarts = [];
139
+ const firstRest = multipleRests.length;
131
140
  const instrumentAt = (id, at) => {
132
141
  const value = { ...(partInstruments?.byId.get(id) ?? partInstruments?.fallback) };
133
142
  for (const change of instrumentChanges) {
@@ -138,6 +147,7 @@ function parseScore(root, diagnostics) {
138
147
  };
139
148
  // 小节游标从零开始,partTime 保存当前小节在全谱中的绝对起点
140
149
  for (let measureIndex = 0; measureIndex < measures.length; measureIndex++) {
150
+ measureStarts.push(partTime.clone());
141
151
  const { body: measure, container: measureContainer } = measures[measureIndex];
142
152
  const measureLocation = {
143
153
  partId, measureIndex: measureIndex + 1,
@@ -171,7 +181,7 @@ function parseScore(root, diagnostics) {
171
181
  setBar(bars, at, new Array(times - 1).fill(":|").join(" "));
172
182
  }
173
183
  else if (text(barline, "bar-style") === "light-heavy")
174
- setBar(bars, at, "||");
184
+ setBar(bars, at, "|||");
175
185
  const ending = child(barline, "ending");
176
186
  const endingType = ending?.getAttribute("type");
177
187
  if (ending && (endingType === "start" || endingType === "stop" || endingType === "discontinue")) {
@@ -184,6 +194,16 @@ function parseScore(root, diagnostics) {
184
194
  passes,
185
195
  });
186
196
  }
197
+ for (const tag of ["segno", "coda"]) {
198
+ const mark = child(barline, tag);
199
+ if (mark)
200
+ recordRepeat({
201
+ at: at.clone(),
202
+ symbol: tag,
203
+ placement: mark.getAttribute("placement") === "below" ? "below" : "above",
204
+ location: { ...measureLocation, element: tag },
205
+ });
206
+ }
187
207
  };
188
208
  // 必须按 XML 原始顺序扫描,backup forward 和 chord 都依赖当前游标或前一事件
189
209
  for (const item of measureItems) {
@@ -221,6 +241,20 @@ function parseScore(root, diagnostics) {
221
241
  mode: text(key, "mode") || "major",
222
242
  });
223
243
  }
244
+ for (const style of children(item, "measure-style")) {
245
+ if (!child(style, "multiple-rest"))
246
+ continue;
247
+ const count = number(style, "multiple-rest");
248
+ if (!Number.isSafeInteger(count) || count <= 0 || count > 0xffffffff) {
249
+ throw new RangeError("MusicXML multiple-rest must be a positive integer in 1..4294967295");
250
+ }
251
+ multipleRests.push({
252
+ location: { ...measureLocation, element: "multiple-rest",
253
+ staff: style.getAttribute("number") || undefined },
254
+ start: at.clone(),
255
+ count,
256
+ });
257
+ }
224
258
  continue;
225
259
  }
226
260
  // backup 和 forward 只重定位当前小节游标,用于交错 voice
@@ -264,38 +298,44 @@ function parseScore(root, diagnostics) {
264
298
  ...measureLocation, element: metronome && markedBpm === bpm ? "metronome" : "sound",
265
299
  } });
266
300
  }
267
- if (!reader)
268
- continue;
269
- if (bpm !== undefined && markedBpm === bpm)
270
- reader.accept(metronome);
301
+ const placement = item.getAttribute("placement") === "below" ? "below" : "above";
271
302
  const staff = text(item, "staff") || "1";
272
303
  const voice = text(item, "voice");
273
304
  const location = { ...measureLocation, element: tag, staff, voice: voice || undefined };
274
- const dynamics = reader.read("dynamics", true);
275
- const dynamic = directionDynamic(dynamics, diagnostics, location);
276
- reader.accept(dynamics);
277
- const texts = directionTexts(reader);
278
- if (dynamic || texts.length > 0)
279
- directions.push({
280
- location,
281
- at,
282
- placement: item.getAttribute("placement") === "below" ? "below" : "above",
283
- dynamic,
284
- texts,
285
- });
286
- const wedge = reader.read("wedge", true);
287
- const wedgeType = wedge?.getAttribute("type");
288
- if (wedgeType === "crescendo" || wedgeType === "diminuendo" || wedgeType === "stop") {
289
- wedgePoints.push({
290
- location: { ...location, element: "wedge" },
291
- at,
292
- number: wedge?.getAttribute("number") || "1",
293
- type: wedgeType,
294
- });
295
- reader.accept(wedge);
305
+ if (reader) {
306
+ if (bpm !== undefined && markedBpm === bpm)
307
+ reader.accept(metronome);
308
+ const dynamics = reader.read("dynamics", true);
309
+ const dynamic = directionDynamic(dynamics, diagnostics, location);
310
+ reader.accept(dynamics);
311
+ const { texts, repeats: dirRepeats } = directionTexts(reader, placement, location);
312
+ for (const repeat of dirRepeats)
313
+ recordRepeat({ ...repeat, at: at.clone() });
314
+ if (dynamic || texts.length > 0)
315
+ directions.push({
316
+ location,
317
+ at,
318
+ placement,
319
+ dynamic,
320
+ texts,
321
+ });
322
+ const wedge = reader.read("wedge", true);
323
+ const wedgeType = wedge?.getAttribute("type");
324
+ if (wedgeType === "crescendo" || wedgeType === "diminuendo" || wedgeType === "stop") {
325
+ wedgePoints.push({
326
+ location: { ...location, element: "wedge" },
327
+ at,
328
+ number: wedge?.getAttribute("number") || "1",
329
+ type: wedgeType,
330
+ });
331
+ reader.accept(wedge);
332
+ }
333
+ for (const directionType of children(item, "direction-type")) {
334
+ reader.report(diagnostics, location, directionType);
335
+ }
296
336
  }
297
- for (const directionType of children(item, "direction-type")) {
298
- reader.report(diagnostics, location, directionType);
337
+ for (const repeat of soundRepeats(sound, placement, { ...measureLocation, element: "sound" })) {
338
+ recordRepeat({ ...repeat, at: at.clone() });
299
339
  }
300
340
  continue;
301
341
  }
@@ -318,6 +358,7 @@ function parseScore(root, diagnostics) {
318
358
  const notationElements = children(item, "notations");
319
359
  const notations = notationElements.length ? new MusicXmlReader(notationElements) : undefined;
320
360
  const pitch = parsePitch(item, location, notations);
361
+ noteGlissandi(notations, pitch, diagnostics);
321
362
  const rest = child(item, "rest") !== undefined;
322
363
  if (!pitch && !rest) {
323
364
  throw new TypeError("MusicXML note must contain pitch, unpitched, or rest");
@@ -391,7 +432,7 @@ function parseScore(root, diagnostics) {
391
432
  throw new RangeError("MusicXML non-grace notes require a positive duration");
392
433
  let event = chord ? previousEvent : undefined;
393
434
  const lyrics = noteLyrics(item);
394
- const modifiers = noteModifiers(notations, diagnostics, location);
435
+ const { modifiers, slides } = noteModifiers(notations, diagnostics, location);
395
436
  const arpeggio = noteArpeggio(notations, location);
396
437
  const tuplets = notations?.readAll("tuplet");
397
438
  // chord 成员只有起点和时值都一致时才合并到前一事件
@@ -408,6 +449,7 @@ function parseScore(root, diagnostics) {
408
449
  postGraces: [],
409
450
  lyrics,
410
451
  arpeggio,
452
+ slides,
411
453
  timeModification: timeModification(item, tuplets),
412
454
  };
413
455
  pendingGraces.delete(laneKey);
@@ -417,6 +459,11 @@ function parseScore(root, diagnostics) {
417
459
  }
418
460
  else {
419
461
  event.arpeggio = mergeArpeggio(event.arpeggio, arpeggio);
462
+ for (const slide of slides) {
463
+ if (!event.slides?.some(item => item.side === slide.side && item.direction === slide.direction)) {
464
+ (event.slides ??= []).push(slide);
465
+ }
466
+ }
420
467
  for (const modifier of modifiers) {
421
468
  if (!event.modifiers.some(item => item.name === modifier.name && item.placement === modifier.placement)) {
422
469
  event.modifiers.push(modifier);
@@ -463,6 +510,10 @@ function parseScore(root, diagnostics) {
463
510
  if (scoreEnd.compare(partTime) < 0)
464
511
  scoreEnd = partTime.clone();
465
512
  }
513
+ measureStarts.push(partTime.clone());
514
+ for (const rest of multipleRests.slice(firstRest)) {
515
+ rest.end = measureStarts[rest.location.measureIndex - 1 + rest.count];
516
+ }
466
517
  for (const groups of pendingGraces.values())
467
518
  for (const group of groups)
468
519
  for (const pitch of group) {
@@ -476,7 +527,7 @@ function parseScore(root, diagnostics) {
476
527
  }
477
528
  for (const [event, id] of eventInstruments)
478
529
  event.program = instrumentAt(id, event.start).program;
479
- setBar(bars, partTime, "||");
530
+ setBar(bars, partTime, "|||");
480
531
  }
481
532
  const laneList = [...lanes.values()];
482
533
  const { wedges, endings } = resolveRelations(wedgePoints, [...endingPoints.values()], diagnostics);
@@ -499,11 +550,13 @@ function parseScore(root, diagnostics) {
499
550
  meters: [...meters.values()].sort((left, right) => left.at.compare(right.at)),
500
551
  keys: [...keys.values()].sort((left, right) => left.at.compare(right.at)),
501
552
  tempos: [...tempos.values()].sort((left, right) => left.at.compare(right.at)),
553
+ repeats: [...repeats.values()].sort((left, right) => left.at.compare(right.at)),
502
554
  wedges,
503
555
  endings,
504
556
  bars,
505
557
  measureBoundaries,
506
558
  lineBreaks,
559
+ multipleRests,
507
560
  end: scoreEnd,
508
561
  };
509
562
  }
@@ -580,6 +633,9 @@ function eventSource(event, mode, key, metadata, diagnostics, suffix = "") {
580
633
  else
581
634
  reportDiagnostic(diagnostics, "arpeggioOutput", event.arpeggio.location);
582
635
  }
636
+ for (const slide of event.slides ?? []) {
637
+ source = `@slide(${source}, side=${slide.side}, direction=${slide.direction})`;
638
+ }
583
639
  const graceSource = (groups) => groups.map(group => group.length === 1
584
640
  ? pitchSource(group[0], mode, key, metadata)
585
641
  : `{${group.map(pitch => pitchSource(pitch, mode, key, metadata)).join(" ^ ")}}`);
@@ -796,12 +852,36 @@ function labelRelations(score, diagnostics) {
796
852
  endpoint.label = `mx${labelIndex++}`;
797
853
  return `${source}@${endpoint.label}`;
798
854
  },
855
+ labelRest(source, events, end) {
856
+ const labeled = events.find(event => metadata.labels.has(event));
857
+ const endpoint = endingLabels.get(keyOf(end));
858
+ if (!labeled && !endpoint)
859
+ return source;
860
+ const label = labelOf(labeled ?? events[0]);
861
+ for (const event of events)
862
+ if (metadata.labels.has(event))
863
+ metadata.labels.set(event, label);
864
+ if (endpoint) {
865
+ endpoint.at = events[0].start;
866
+ endpoint.label = label;
867
+ }
868
+ return `${source}@${label}`;
869
+ },
799
870
  };
800
871
  const labelOf = (target) => {
801
872
  const label = metadata.labels.get(target) ?? `mx${labelIndex++}`;
802
873
  metadata.labels.set(target, label);
803
874
  return label;
804
875
  };
876
+ const appendRelation = (event, source) => {
877
+ let after = metadata.afterSources.get(event);
878
+ if (!after)
879
+ metadata.afterSources.set(event, after = []);
880
+ after.push(source);
881
+ };
882
+ const activeGlissandi = new Map();
883
+ const glissLineBreaks = [...score.lineBreaks].map(fractionFromKey);
884
+ const glissandi = [];
805
885
  const active = new Map();
806
886
  const unmatchedTies = new Set();
807
887
  const endingActive = new Map();
@@ -826,13 +906,13 @@ function labelRelations(score, diagnostics) {
826
906
  ...event.postGraces.flat(),
827
907
  ];
828
908
  for (const pitch of orderedPitches) {
909
+ if (pitch.glissandi?.length)
910
+ glissandi.push({ event, pitch });
829
911
  const key = `${lane.partId}\0${lane.staff}\0${lane.voice}\0${pitch.step}\0${pitch.alter}\0${pitch.octave}`;
830
912
  const previous = localActive.get(key) ?? (ending ? active.get(key) : undefined);
831
913
  if (pitch.tieStop && previous) {
832
914
  unmatchedTies.delete(previous);
833
- const after = metadata.afterSources.get(event) ?? [];
834
- after.push(`@tie(${labelOf(previous)}, ${labelOf(pitch)})`);
835
- metadata.afterSources.set(event, after);
915
+ appendRelation(event, `@tie(${labelOf(previous)}, ${labelOf(pitch)})`);
836
916
  }
837
917
  else if (pitch.tieStop) {
838
918
  reportDiagnostic(diagnostics, "tieStart", pitch.location);
@@ -848,6 +928,28 @@ function labelRelations(score, diagnostics) {
848
928
  }
849
929
  for (const pitch of unmatchedTies)
850
930
  reportDiagnostic(diagnostics, "tieStop", pitch.location);
931
+ // 复用上面的音高遍历,仅排序滑音端点;无滑音时不额外遍历或排序全谱
932
+ for (const { event, pitch } of glissandi.sort((a, b) => a.event.start.compare(b.event.start) || a.event.order - b.event.order))
933
+ for (const mark of pitch.glissandi ?? []) {
934
+ const key = `${pitch.location.partId}\0${mark.kind}\0${mark.number}`;
935
+ const previous = activeGlissandi.get(key);
936
+ if (mark.type === "start") {
937
+ if (previous)
938
+ reportDiagnostic(diagnostics, "glissReplaced", previous.pitch.location);
939
+ activeGlissandi.set(key, { pitch, event });
940
+ continue;
941
+ }
942
+ activeGlissandi.delete(key);
943
+ if (!previous)
944
+ reportDiagnostic(diagnostics, "glissStart", pitch.location);
945
+ else if (previous.event.start.equals(event.start) || glissLineBreaks.some(time => time.compare(previous.event.start) > 0 && time.compare(event.start) <= 0)) {
946
+ reportDiagnostic(diagnostics, "glissEndpoints", pitch.location);
947
+ }
948
+ else
949
+ appendRelation(event, `@gliss(${labelOf(previous.pitch)}, ${labelOf(pitch)})`);
950
+ }
951
+ for (const { pitch } of activeGlissandi.values())
952
+ reportDiagnostic(diagnostics, "glissStop", pitch.location);
851
953
  const eventLabel = (event) => labelOf(event.pitches.length === 1 ? event.pitches[0] : event);
852
954
  for (const wedge of score.wedges) {
853
955
  // 连续楔形区间落到实际起音端点后再输出离散的 dyn 关系
@@ -887,10 +989,10 @@ function labelRelations(score, diagnostics) {
887
989
  }
888
990
  const from = events[fromIndex];
889
991
  const to = events[toIndex - 1];
890
- const fromLabel = eventLabel(from);
992
+ eventLabel(from);
891
993
  const endpoint = endingLabels.get(keyOf(ending.end)) ?? { at: to.start, label: eventLabel(to) };
892
994
  endingLabels.set(keyOf(ending.end), endpoint);
893
- relations.push(() => `@volta(${fromLabel}, ${endpoint.label}, ${ending.from.passes.join(", ")})`);
995
+ relations.push(() => `@volta(${eventLabel(from)}, ${endpoint.label}, ${ending.from.passes.join(", ")})`);
894
996
  }
895
997
  return { relations, metadata };
896
998
  }
@@ -914,6 +1016,7 @@ function renderScore(score, options, diagnostics) {
914
1016
  : score.tempos;
915
1017
  // 初始状态进入 head;中途状态作为精确时间点只写在最上方 lane
916
1018
  const scoreAdjustments = new Map();
1019
+ const barAdjustments = new Map();
917
1020
  const addAdjustment = (adjustments, at, source, location, placement = "above") => {
918
1021
  const key = keyOf(at);
919
1022
  const point = adjustments.get(key) ?? { at, sources: [], pendingLocations: [] };
@@ -931,6 +1034,10 @@ function renderScore(score, options, diagnostics) {
931
1034
  addAdjustment(scoreAdjustments, item.at, `@meter(${item.numerator}, ${item.denominator})`);
932
1035
  for (const item of tempos.slice(1))
933
1036
  addAdjustment(scoreAdjustments, item.at, `@tempo(${item.bpm})`, item.location);
1037
+ for (const item of score.repeats) {
1038
+ const target = item.symbol === "segno" || item.symbol === "coda" ? scoreAdjustments : barAdjustments;
1039
+ addAdjustment(target, item.at, `$${item.symbol}`, item.location, item.placement);
1040
+ }
934
1041
  const adjustmentsByLane = score.lanes.map((lane, index) => {
935
1042
  const adjustments = index === 0 ? scoreAdjustments : new Map();
936
1043
  for (const dynamic of lane.dynamics ?? []) {
@@ -950,8 +1057,6 @@ function renderScore(score, options, diagnostics) {
950
1057
  }
951
1058
  return programs;
952
1059
  });
953
- // 关系先分配标签,随后 eventSource 才能把标签写进正确音符
954
- const { relations, metadata } = labelRelations(score, diagnostics);
955
1060
  const barTimes = [...score.bars.keys()].map(fractionFromKey)
956
1061
  .sort((left, right) => left.compare(right));
957
1062
  const measureBars = [...score.measureBoundaries].map(fractionFromKey)
@@ -965,28 +1070,71 @@ function renderScore(score, options, diagnostics) {
965
1070
  }
966
1071
  }
967
1072
  }
1073
+ // 换行确定后分配关系标签,随后 eventSource 写进正确音符
1074
+ const { relations, metadata } = labelRelations(score, diagnostics);
968
1075
  const page = score.page
969
1076
  ? `@page(width=${score.page.width}px, height=${score.page.height}px, top=${score.page.top}px, bottom=${score.page.bottom}px, left=${score.page.left}px, right=${score.page.right}px)\n`
970
1077
  : "";
971
- // 明确的 MusicXML 换行优先;若会切开 tuplet,则丢弃该断点以保持时值组完整
1078
+ // 明确的 MusicXML 换行优先;若会切开 tuplet 或多小节休止,则保留完整块
972
1079
  const blocksByLane = score.lanes.map((lane, index) => renderBlocks(lane, pitchMode, score, keys, adjustmentsByLane[index], programsByLane[index], metadata, diagnostics));
973
- const tupletSpans = blocksByLane.flatMap(blocks => blocks
1080
+ const acceptedRests = new Set();
1081
+ for (const rest of score.multipleRests) {
1082
+ const { start, end, count } = rest;
1083
+ const id = `${start}:${end}:${count}`;
1084
+ if (acceptedRests.has(id))
1085
+ continue;
1086
+ const interior = (at) => !!end && at.compare(start) > 0 && at.compare(end) < 0;
1087
+ const meter = pointAt(meters, start);
1088
+ const measureDuration = new Fraction(meter.numerator * 4, meter.denominator);
1089
+ // @rest 是全局休止列,只有所有声部同步休止才不会把其他声部的起音推迟。
1090
+ const covered = blocksByLane.map(blocks => blocks.slice(lowerBoundAt(blocks, start, block => block.start), lowerBoundAt(blocks, end ?? start, block => block.start)));
1091
+ const safe = end && end.clone().sub(start).equals(measureDuration.clone().mul(count))
1092
+ && !meters.some(point => interior(point.at))
1093
+ && ![...score.bars].some(([at, bar]) => interior(fractionFromKey(at)) && bar !== "|")
1094
+ && !score.endings.some(span => interior(span.from.at) || interior(span.end))
1095
+ && ![...barAdjustments.values()].some(point => interior(point.at))
1096
+ && adjustmentsByLane.every(points => ![...points.values()].some(point => interior(point.at)))
1097
+ && programsByLane.every(points => ![...points.keys()].some(at => interior(fractionFromKey(at))))
1098
+ && covered.length > 0 && covered.every(blocks => blocks.length === count
1099
+ && blocks.every((block, index) => {
1100
+ const event = block.event;
1101
+ return event?.rest && event.pitches.length === 0 && !event.arpeggio && !event.slides?.length
1102
+ && event.modifiers.length === 0 && event.annotations.length === 0
1103
+ && event.preGraces.length === 0 && event.postGraces.length === 0
1104
+ && event.lyrics.size === 0 && !metadata.afterSources.has(event)
1105
+ && block.start.equals(start.clone().add(measureDuration.clone().mul(index)))
1106
+ && block.end.clone().sub(block.start).equals(measureDuration);
1107
+ }));
1108
+ if (!safe || !end) {
1109
+ reportDiagnostic(diagnostics, "multipleRest", rest.location);
1110
+ continue;
1111
+ }
1112
+ acceptedRests.add(id);
1113
+ for (const [lane, blocks] of blocksByLane.entries()) {
1114
+ const program = programsByLane[lane].get(keyOf(start));
1115
+ const events = covered[lane].map(block => block.event);
1116
+ const source = (program === undefined ? "" : `@program(${program}) `)
1117
+ + attachAdjustment(metadata.labelRest(`@rest(${count})`, events, end), adjustmentsByLane[lane].get(keyOf(start)));
1118
+ blocks.splice(lowerBoundAt(blocks, start, block => block.start), count, { start, end, source });
1119
+ }
1120
+ }
1121
+ const atomicSpans = blocksByLane.flatMap(blocks => blocks
974
1122
  .filter(block => block.source)
975
1123
  .map(block => ({ start: block.start, end: block.end })))
976
1124
  .sort((left, right) => left.start.compare(right.start) || left.end.compare(right.end));
977
- const mergedTupletSpans = [];
978
- for (const span of tupletSpans) {
979
- const previous = mergedTupletSpans.at(-1);
1125
+ const mergedAtomicSpans = [];
1126
+ for (const span of atomicSpans) {
1127
+ const previous = mergedAtomicSpans.at(-1);
980
1128
  if (previous && span.start.compare(previous.end) < 0) {
981
1129
  if (span.end.compare(previous.end) > 0)
982
1130
  previous.end = span.end;
983
1131
  }
984
1132
  else
985
- mergedTupletSpans.push(span);
1133
+ mergedAtomicSpans.push(span);
986
1134
  }
987
1135
  const lineBreaks = new Map([...score.lineBreaks]
988
1136
  .map(value => [value, fractionFromKey(value)])
989
- .filter(([, at]) => !insideSpan(mergedTupletSpans, at)));
1137
+ .filter(([, at]) => !insideSpan(mergedAtomicSpans, at)));
990
1138
  // 每条 lane 独立沿同一组时间点输出;最后再按系统转置成完整 N: 组
991
1139
  const voices = score.lanes.map((lane, laneIndex) => {
992
1140
  const verses = new Set();
@@ -1007,7 +1155,7 @@ function renderScore(score, options, diagnostics) {
1007
1155
  }
1008
1156
  };
1009
1157
  const blocks = blocksByLane[laneIndex];
1010
- const tupletBlocks = blocks.filter(block => block.source);
1158
+ const atomicBlocks = blocks.filter(block => block.source);
1011
1159
  // 所有事件边界与控制点汇成一条时间线,每个相邻点只输出一个连续片段
1012
1160
  const points = new Map();
1013
1161
  points.set("0", new Fraction());
@@ -1017,15 +1165,21 @@ function renderScore(score, options, diagnostics) {
1017
1165
  points.set(keyOf(block.end), block.end);
1018
1166
  }
1019
1167
  for (const at of barTimes)
1020
- if (!insideSpan(tupletBlocks, at))
1168
+ if (!insideSpan(atomicBlocks, at))
1021
1169
  points.set(keyOf(at), at);
1022
1170
  for (const [value, at] of lineBreaks)
1023
1171
  points.set(value, at);
1024
1172
  const adjustments = adjustmentsByLane[laneIndex];
1025
1173
  for (const [value, point] of adjustments) {
1026
- if (!insideSpan(tupletBlocks, point.at))
1174
+ if (!insideSpan(atomicBlocks, point.at))
1027
1175
  points.set(value, point.at);
1028
1176
  }
1177
+ if (laneIndex === 0) {
1178
+ for (const [value, point] of barAdjustments) {
1179
+ if (!insideSpan(atomicBlocks, point.at))
1180
+ points.set(value, point.at);
1181
+ }
1182
+ }
1029
1183
  const timeline = [...points.values()].sort((left, right) => left.compare(right));
1030
1184
  let blockIndex = 0;
1031
1185
  for (let index = 0; index < timeline.length; index++) {
@@ -1034,8 +1188,21 @@ function renderScore(score, options, diagnostics) {
1034
1188
  blockIndex++;
1035
1189
  }
1036
1190
  const bar = score.bars.get(keyOf(at));
1037
- if (bar && (!at.isZero() || bar !== "|"))
1038
- outputs.at(-1).push(bar);
1191
+ const barChanges = laneIndex === 0 ? barAdjustments.get(keyOf(at)) : undefined;
1192
+ if (bar && (!at.isZero() || bar !== "|")) {
1193
+ if (barChanges) {
1194
+ const parts = bar.split(" ");
1195
+ parts[0] = attachAdjustment(parts[0], barChanges);
1196
+ outputs.at(-1).push(parts.join(" "));
1197
+ }
1198
+ else {
1199
+ outputs.at(-1).push(bar);
1200
+ }
1201
+ }
1202
+ else if (barChanges && at.compare(score.end) <= 0) {
1203
+ outputs.at(-1).push(...barChanges.sources, ...(barChanges.below ?? []));
1204
+ barChanges.pendingLocations.length = 0;
1205
+ }
1039
1206
  if (lineBreaks.has(keyOf(at))) {
1040
1207
  outputs.push([]);
1041
1208
  lyricTokens.push(new Map(orderedVerses.map(verse => [verse, []])));
@@ -1050,7 +1217,7 @@ function renderScore(score, options, diagnostics) {
1050
1217
  const block = blocks[blockIndex];
1051
1218
  if (block?.source) {
1052
1219
  if (!block.start.equals(at) || !block.end.equals(next)) {
1053
- throw new RangeError("MusicXML tuplet cannot cross a barline or state change");
1220
+ throw new RangeError("MusicXML atomic block cannot cross a barline or state change");
1054
1221
  }
1055
1222
  outputs.at(-1).push(block.source);
1056
1223
  for (const item of block.lyricEvents ?? []) {
@@ -1099,7 +1266,7 @@ function renderScore(score, options, diagnostics) {
1099
1266
  });
1100
1267
  });
1101
1268
  const omitted = new Set();
1102
- for (const adjustments of [scoreAdjustments, ...adjustmentsByLane]) {
1269
+ for (const adjustments of [scoreAdjustments, barAdjustments, ...adjustmentsByLane]) {
1103
1270
  for (const point of adjustments.values()) {
1104
1271
  for (const location of point.pendingLocations)
1105
1272
  omitted.add(location);
@@ -31,6 +31,11 @@ export interface MusicXmlPitch {
31
31
  octave: number;
32
32
  tieStart: boolean;
33
33
  tieStop: boolean;
34
+ glissandi?: {
35
+ kind: "slide" | "glissando";
36
+ number: string;
37
+ type: "start" | "stop";
38
+ }[];
34
39
  }
35
40
  /** 一个 lane 上的原子事件,同起止音高已合并为一个和弦事件 */
36
41
  export interface MusicXmlEvent {
@@ -52,6 +57,10 @@ export interface MusicXmlEvent {
52
57
  postGraces: MusicXmlPitch[][];
53
58
  lyrics: Map<string, string>;
54
59
  arpeggio?: MusicXmlArpeggio;
60
+ slides?: {
61
+ side: "pre" | "post";
62
+ direction: "up" | "down";
63
+ }[];
55
64
  program?: number;
56
65
  timeModification?: {
57
66
  actual: number;
@@ -84,6 +93,14 @@ export interface MusicXmlKeyPoint {
84
93
  fifths: number;
85
94
  mode: string;
86
95
  }
96
+ export type MusicXmlRepeatSymbol = "segno" | "coda" | "dc" | "ds" | "fine" | "tocoda";
97
+ /** 全谱时间流上的反复与跳转记号 */
98
+ export interface MusicXmlRepeatPoint {
99
+ at: Fraction;
100
+ symbol: MusicXmlRepeatSymbol;
101
+ placement: "above" | "below";
102
+ location: MusicXmlDiagnostic["location"];
103
+ }
87
104
  /** 尚未附着到事件的力度或文字方向 */
88
105
  export interface MusicXmlDirectionPoint {
89
106
  location: MusicXmlPartLocation & {
@@ -142,11 +159,18 @@ export interface ParsedMusicXmlScore {
142
159
  bpm: number;
143
160
  location?: MusicXmlDiagnostic["location"];
144
161
  }[];
162
+ repeats: MusicXmlRepeatPoint[];
145
163
  wedges: MusicXmlWedgeSpan[];
146
164
  endings: MusicXmlEndingSpan[];
147
165
  bars: Map<string, string>;
148
166
  measureBoundaries: Set<string>;
149
167
  lineBreaks: Set<string>;
168
+ multipleRests: {
169
+ location: MusicXmlPartLocation;
170
+ start: Fraction;
171
+ end?: Fraction;
172
+ count: number;
173
+ }[];
150
174
  end: Fraction;
151
175
  }
152
176
  export {};
package/dist/core.d.ts CHANGED
@@ -2,6 +2,7 @@ export * from "./pipeline.js";
2
2
  export * from "./functions/ASTtypes.js";
3
3
  export * from "./functions/temporal.js";
4
4
  export * from "./functions/default.js";
5
+ export { symbols, type OrnamentPattern, type SymbolDefinition, type SymbolShape, } from "./functions/symbol/index.js";
5
6
  export { transformNotes, type NoteTransform, type SourceEdit } from "./functions/note/index.js";
6
7
  export * from "./diagnostic.js";
7
8
  export * from "./fraction.js";
package/dist/core.js CHANGED
@@ -2,6 +2,7 @@ export * from "./pipeline.js";
2
2
  export * from "./functions/ASTtypes.js";
3
3
  export * from "./functions/temporal.js";
4
4
  export * from "./functions/default.js";
5
+ export { symbols, } from "./functions/symbol/index.js";
5
6
  export { transformNotes } from "./functions/note/index.js";
6
7
  export * from "./diagnostic.js";
7
8
  export * from "./fraction.js";
@@ -5,6 +5,7 @@ export interface LineColRange {
5
5
  endLine: number;
6
6
  endColumn: number;
7
7
  }
8
+ export type DiagnosticParams = Record<string, string>;
8
9
  export declare abstract class Diagnostic {
9
10
  /** 诊断代码 */
10
11
  code: string;
@@ -12,7 +13,12 @@ export declare abstract class Diagnostic {
12
13
  message: string;
13
14
  /** 诊断位置,指示问题在源代码中的位置 */
14
15
  span: SourceSpan;
15
- constructor(code: string, message: string, span: SourceSpan);
16
+ /** 诊断消息中的结构化参数(构造时复制并字符串化,不修改或持有原对象) */
17
+ params?: DiagnosticParams;
18
+ static format(code: string, message: string, params?: DiagnosticParams): string;
19
+ constructor(code: string, message: string, span: SourceSpan, params?: Record<string, string | number | {
20
+ toString(): string;
21
+ }>);
16
22
  toLineCol(lineStarts: ArrayLike<number>): LineColRange;
17
23
  static offsetToLineCol(offset: number, lineStarts: ArrayLike<number>): {
18
24
  line: number;