jpfun 0.7.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 (110) 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 +11 -1
  6. package/dist/converter/musicxml/features.d.ts +15 -7
  7. package/dist/converter/musicxml/features.js +87 -18
  8. package/dist/converter/musicxml/index.js +80 -32
  9. package/dist/converter/musicxml/model.d.ts +9 -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 +15 -17
  18. package/dist/functions/bar/index.d.ts +8 -0
  19. package/dist/functions/bar/index.js +102 -0
  20. package/dist/functions/beam/auto.d.ts +1 -2
  21. package/dist/functions/beam/auto.js +30 -16
  22. package/dist/functions/beam/index.js +2 -3
  23. package/dist/functions/beam/layout.d.ts +1 -1
  24. package/dist/functions/beam/layout.js +1 -1
  25. package/dist/functions/br/index.d.ts +34 -2
  26. package/dist/functions/br/index.js +5 -4
  27. package/dist/functions/dash/index.js +6 -6
  28. package/dist/functions/default.js +2 -1
  29. package/dist/functions/div/index.d.ts +1 -0
  30. package/dist/functions/div/index.js +8 -4
  31. package/dist/functions/dot/index.js +2 -2
  32. package/dist/functions/dyn/index.js +49 -31
  33. package/dist/functions/gliss/index.js +75 -53
  34. package/dist/functions/grace/index.d.ts +1 -7
  35. package/dist/functions/grace/index.js +8 -13
  36. package/dist/functions/head/index.js +1 -1
  37. package/dist/functions/key/index.js +8 -10
  38. package/dist/functions/meter/index.d.ts +56 -1
  39. package/dist/functions/meter/index.js +12 -7
  40. package/dist/functions/note/index.js +5 -5
  41. package/dist/functions/note/noteName.d.ts +16 -0
  42. package/dist/functions/note/noteName.js +88 -0
  43. package/dist/functions/note/source-transform.js +6 -5
  44. package/dist/functions/ottava/index.js +24 -8
  45. package/dist/functions/page/index.d.ts +1 -0
  46. package/dist/functions/page/index.js +20 -11
  47. package/dist/functions/pagebreak/index.js +2 -2
  48. package/dist/functions/rest/index.js +3 -1
  49. package/dist/functions/set/index.js +4 -4
  50. package/dist/functions/symbol/index.d.ts +21 -2
  51. package/dist/functions/symbol/index.js +69 -24
  52. package/dist/functions/symbol/ornament.d.ts +1 -2
  53. package/dist/functions/symbol/shape.d.ts +6 -0
  54. package/dist/functions/symbol/shape.js +16 -3
  55. package/dist/functions/symbol/symbols/coda.d.ts +4 -0
  56. package/dist/functions/symbol/symbols/coda.js +56 -0
  57. package/dist/functions/symbol/symbols/dynamics.d.ts +1 -1
  58. package/dist/functions/symbol/symbols/dynamics.js +18 -8
  59. package/dist/functions/symbol/symbols/harmonic.d.ts +2 -0
  60. package/dist/functions/symbol/symbols/harmonic.js +11 -0
  61. package/dist/functions/symbol/symbols/marcato.d.ts +2 -0
  62. package/dist/functions/symbol/symbols/marcato.js +22 -0
  63. package/dist/functions/symbol/symbols/staccato.d.ts +2 -0
  64. package/dist/functions/symbol/symbols/staccato.js +24 -0
  65. package/dist/functions/symbol/symbols/tenuto.d.ts +2 -0
  66. package/dist/functions/symbol/symbols/tenuto.js +11 -0
  67. package/dist/functions/symbol/symbols/tocoda.d.ts +2 -0
  68. package/dist/functions/symbol/symbols/tocoda.js +16 -0
  69. package/dist/functions/symbol/symbols/turn.d.ts +3 -0
  70. package/dist/functions/symbol/symbols/turn.js +50 -0
  71. package/dist/functions/symbol/symbols/wheel.d.ts +2 -0
  72. package/dist/functions/symbol/symbols/wheel.js +36 -0
  73. package/dist/functions/temporal.d.ts +1 -0
  74. package/dist/functions/temporal.js +1 -0
  75. package/dist/functions/text/index.js +15 -6
  76. package/dist/functions/tie/index.js +30 -6
  77. package/dist/functions/tremolo/index.d.ts +2 -0
  78. package/dist/functions/tremolo/index.js +319 -0
  79. package/dist/functions/tuplet/index.js +4 -8
  80. package/dist/functions/up/index.js +2 -2
  81. package/dist/functions/voice/index.js +17 -10
  82. package/dist/jpfun.core.min.js +57 -49
  83. package/dist/jpfun.from-midi.min.js +5 -5
  84. package/dist/jpfun.from-musicxml.min.js +8 -8
  85. package/dist/jpfun.min.js +62 -54
  86. package/dist/layout/default.d.ts +0 -1
  87. package/dist/layout/default.js +0 -1
  88. package/dist/lowering/loweringContext.d.ts +11 -13
  89. package/dist/lowering/loweringContext.js +26 -33
  90. package/dist/lowering/types.d.ts +1 -3
  91. package/dist/parser/parse-utils/note-utils.d.ts +1 -1
  92. package/dist/parser/parse-utils/note-utils.js +8 -9
  93. package/dist/parser/parse-utils/string-utils.d.ts +3 -2
  94. package/dist/parser/parse-utils/string-utils.js +16 -3
  95. package/dist/parser/parserContext.js +9 -2
  96. package/dist/pipeline.js +0 -1
  97. package/dist/playback/compile.js +120 -70
  98. package/dist/playback/event.d.ts +1 -1
  99. package/dist/playback/event.js +9 -9
  100. package/dist/playback/time.js +42 -31
  101. package/dist/playback/types.d.ts +3 -1
  102. package/dist/render/canvas.d.ts +2 -0
  103. package/dist/render/canvas.js +25 -22
  104. package/dist/render/recording.js +1 -4
  105. package/dist/render/translate.d.ts +0 -1
  106. package/dist/render/translate.js +6 -23
  107. package/grammar.md +26 -20
  108. package/package.json +3 -3
  109. package/dist/functions/note/noteNameFSM.d.ts +0 -8
  110. package/dist/functions/note/noteNameFSM.js +0 -181
@@ -1,7 +1,28 @@
1
1
  import { child, children, descendant, descendants, nameOf, number, text, } from "./dom.js";
2
2
  import { NoteNameMap, SHARP_NOTE_NAMES } from "../../parser/parse-utils/note-utils.js";
3
- const DYNAMIC_NAMES = new Set(["ppp", "pp", "p", "mp", "mf", "f", "ff", "fff"]);
3
+ const DYNAMIC_NAME = /^(?:p+|f+|mp|mf)$/;
4
4
  const MAX_ENDING_PASS = 256;
5
+ const SOUND_REPEATS = [
6
+ ["segno", "segno"],
7
+ ["coda", "coda"],
8
+ ["dacapo", "dc"],
9
+ ["dalsegno", "ds"],
10
+ ["fine", "fine"],
11
+ ["tocoda", "tocoda"],
12
+ ];
13
+ /** 识别 <words> 中的标准反复跳转与终止术语 */
14
+ export function repeatWordSymbol(value) {
15
+ const normalized = value.trim().replace(/\s+/g, " ");
16
+ if (/^(?:d\.\s*c\.?|da\s+capo)(?:\s+al\s+(?:fine|coda)\.?)?$/i.test(normalized))
17
+ return "dc";
18
+ if (/^(?:d\.\s*s\.?|dal\s+segno)(?:\s+al\s+(?:fine|coda)\.?)?$/i.test(normalized))
19
+ return "ds";
20
+ if (/^fine\.?$/i.test(normalized))
21
+ return "fine";
22
+ if (/^(?:to\s+coda|al\s+coda)\.?$/i.test(normalized))
23
+ return "tocoda";
24
+ return undefined;
25
+ }
5
26
  const DIAGNOSTICS = {
6
27
  percussion: ["PERCUSSION_SKIPPED", "MIDI channel 10 percussion note was omitted."],
7
28
  displayPitch: ["APPROXIMATED", "Unpitched note was converted to a melodic note using its display pitch."],
@@ -32,6 +53,7 @@ const DIAGNOSTICS = {
32
53
  glissReplaced: ["UNRESOLVED_RELATION", "Glissando start was replaced before a matching stop and was omitted."],
33
54
  glissEndpoints: ["UNRESOLVED_RELATION", "Glissando endpoints are simultaneous or cross a score line and were omitted."],
34
55
  glissStyle: ["APPROXIMATED", "MusicXML <{value}> was converted to a straight glissando arrow."],
56
+ symbolStyle: ["APPROXIMATED", "MusicXML <{value}> was mapped to the default symbol shape."],
35
57
  };
36
58
  export function reportDiagnostic(diagnostics, issue, location, value = "") {
37
59
  const [kind, message] = DIAGNOSTICS[issue];
@@ -201,7 +223,7 @@ export function transposePitch(pitch, chromatic, diatonic, octaves) {
201
223
  pitch.alter = midi - (pitch.octave + 1) * 12 - NoteNameMap[pitch.step];
202
224
  }
203
225
  }
204
- /** 将支持的 fermata articulation 和 ornament 转成 jpFun 修饰符 */
226
+ /** 将支持的延长、奏法与装饰音记号转成 jpFun 修饰符 */
205
227
  export function noteModifiers(notations, diagnostics, location) {
206
228
  const modifiers = [];
207
229
  const slides = [];
@@ -214,10 +236,18 @@ export function noteModifiers(notations, diagnostics, location) {
214
236
  }
215
237
  const articulations = notations.read("articulations");
216
238
  if (articulations) {
217
- const accent = notations.read("accent", false, articulations);
218
- if (accent) {
219
- modifiers.push({ name: "accent", placement: placementOf(accent, "above") });
220
- notations.accept(accent);
239
+ for (const [tag, name] of [
240
+ ["accent", "accent"], ["staccato", "staccato"], ["tenuto", "tenuto"],
241
+ ["strong-accent", "marcato"], ["staccatissimo", "staccato"],
242
+ ]) {
243
+ const articulation = notations.read(tag, false, articulations);
244
+ if (!articulation)
245
+ continue;
246
+ modifiers.push({ name, placement: placementOf(articulation, "above") });
247
+ notations.accept(articulation);
248
+ if (tag === "strong-accent" && articulation.getAttribute("type") === "down") {
249
+ reportDiagnostic(diagnostics, "symbolStyle", { ...location, element: tag }, tag);
250
+ }
221
251
  }
222
252
  for (const [tag, side, direction] of [
223
253
  ["scoop", "pre", "up"], ["plop", "pre", "down"],
@@ -237,16 +267,20 @@ export function noteModifiers(notations, diagnostics, location) {
237
267
  }
238
268
  const ornaments = notations.read("ornaments");
239
269
  if (ornaments) {
240
- const names = [
270
+ for (const [tag, name] of [
241
271
  ["trill-mark", "tr"],
242
272
  ["mordent", "mordent"],
243
273
  ["inverted-mordent", "prall"],
244
- ];
245
- for (const [tag, name] of names) {
274
+ ["turn", "turn"],
275
+ ["inverted-turn", "iturn"],
276
+ ]) {
246
277
  const ornament = notations.read(tag, false, ornaments);
247
- if (ornament) {
248
- modifiers.push({ name, placement: placementOf(ornament, "above") });
249
- notations.accept(ornament);
278
+ if (!ornament)
279
+ continue;
280
+ modifiers.push({ name, placement: placementOf(ornament, "above") });
281
+ notations.accept(ornament);
282
+ if ((tag === "turn" || tag === "inverted-turn") && ornament.getAttribute("slash") === "yes") {
283
+ reportDiagnostic(diagnostics, "symbolStyle", { ...location, element: tag }, tag);
250
284
  }
251
285
  }
252
286
  notations.report(diagnostics, location, ornaments);
@@ -344,24 +378,59 @@ export function directionDynamic(dynamics, diagnostics, location) {
344
378
  let dynamic;
345
379
  for (const element of children(dynamics)) {
346
380
  const name = nameOf(element);
347
- if (!dynamic && DYNAMIC_NAMES.has(name))
381
+ if (!dynamic && DYNAMIC_NAME.test(name))
348
382
  dynamic = name;
349
383
  else
350
384
  reportDiagnostic(diagnostics, "unsupported", { ...location, element: name }, name);
351
385
  }
352
386
  return dynamic;
353
387
  }
354
- /** 收集排练标记与普通文字,排练标记保留方框语义;空白文字视为空内容 */
355
- export function directionTexts(direction) {
356
- const result = [];
388
+ /** 收集排练标记、反复记号与普通文字,排练标记保留方框语义;空白文字视为空内容 */
389
+ export function directionTexts(direction, defaultPlacement = "above", location) {
390
+ const texts = [];
391
+ const repeats = [];
392
+ for (const tag of ["segno", "coda"]) {
393
+ for (const node of direction.readAll(tag, true)) {
394
+ repeats.push({
395
+ symbol: tag,
396
+ placement: placementOf(node, defaultPlacement),
397
+ location: { ...(location ?? { element: tag }), element: tag },
398
+ });
399
+ direction.accept(node);
400
+ }
401
+ }
357
402
  for (const name of ["rehearsal", "words"]) {
358
403
  for (const node of direction.readAll(name, true)) {
359
404
  const value = node.textContent?.trim();
360
- if (value)
361
- result.push({ text: value, boxed: name === "rehearsal" });
405
+ if (value) {
406
+ const symbol = name === "words" ? repeatWordSymbol(value) : undefined;
407
+ if (symbol) {
408
+ repeats.push({
409
+ symbol,
410
+ placement: placementOf(node, defaultPlacement),
411
+ location: { ...(location ?? { element: name }), element: name },
412
+ });
413
+ }
414
+ else {
415
+ texts.push({ text: value, boxed: name === "rehearsal" });
416
+ }
417
+ }
362
418
  direction.accept(node);
363
419
  }
364
420
  }
421
+ return { texts, repeats };
422
+ }
423
+ /** 读取 <sound> 上的反复与跳转属性 */
424
+ export function soundRepeats(sound, placement, location) {
425
+ if (!sound)
426
+ return [];
427
+ const result = [];
428
+ for (const [attr, symbol] of SOUND_REPEATS) {
429
+ const value = sound.getAttribute(attr)?.trim().toLowerCase();
430
+ if (value && value !== "no") {
431
+ result.push({ symbol, placement, location: { ...location, element: "sound" } });
432
+ }
433
+ }
365
434
  return result;
366
435
  }
367
436
  /** 将 metronome 的拍单位和附点折算成四分音符 BPM */
@@ -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, noteGlissandi, 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#"];
@@ -102,6 +102,7 @@ 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();
@@ -111,6 +112,11 @@ function parseScore(root, diagnostics) {
111
112
  const multipleRests = [];
112
113
  let scoreEnd = new Fraction();
113
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
+ };
114
120
  // 主时间解析:逐 part、逐小节扫描 attributes/direction/note/barline
115
121
  const measuresByPart = partMeasures(root);
116
122
  const partOrder = new Map([...measuresByPart.keys()].map((id, index) => [id, index]));
@@ -188,6 +194,16 @@ function parseScore(root, diagnostics) {
188
194
  passes,
189
195
  });
190
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
+ }
191
207
  };
192
208
  // 必须按 XML 原始顺序扫描,backup forward 和 chord 都依赖当前游标或前一事件
193
209
  for (const item of measureItems) {
@@ -282,38 +298,44 @@ function parseScore(root, diagnostics) {
282
298
  ...measureLocation, element: metronome && markedBpm === bpm ? "metronome" : "sound",
283
299
  } });
284
300
  }
285
- if (!reader)
286
- continue;
287
- if (bpm !== undefined && markedBpm === bpm)
288
- reader.accept(metronome);
301
+ const placement = item.getAttribute("placement") === "below" ? "below" : "above";
289
302
  const staff = text(item, "staff") || "1";
290
303
  const voice = text(item, "voice");
291
304
  const location = { ...measureLocation, element: tag, staff, voice: voice || undefined };
292
- const dynamics = reader.read("dynamics", true);
293
- const dynamic = directionDynamic(dynamics, diagnostics, location);
294
- reader.accept(dynamics);
295
- const texts = directionTexts(reader);
296
- if (dynamic || texts.length > 0)
297
- directions.push({
298
- location,
299
- at,
300
- placement: item.getAttribute("placement") === "below" ? "below" : "above",
301
- dynamic,
302
- texts,
303
- });
304
- const wedge = reader.read("wedge", true);
305
- const wedgeType = wedge?.getAttribute("type");
306
- if (wedgeType === "crescendo" || wedgeType === "diminuendo" || wedgeType === "stop") {
307
- wedgePoints.push({
308
- location: { ...location, element: "wedge" },
309
- at,
310
- number: wedge?.getAttribute("number") || "1",
311
- type: wedgeType,
312
- });
313
- 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
+ }
314
336
  }
315
- for (const directionType of children(item, "direction-type")) {
316
- reader.report(diagnostics, location, directionType);
337
+ for (const repeat of soundRepeats(sound, placement, { ...measureLocation, element: "sound" })) {
338
+ recordRepeat({ ...repeat, at: at.clone() });
317
339
  }
318
340
  continue;
319
341
  }
@@ -528,6 +550,7 @@ function parseScore(root, diagnostics) {
528
550
  meters: [...meters.values()].sort((left, right) => left.at.compare(right.at)),
529
551
  keys: [...keys.values()].sort((left, right) => left.at.compare(right.at)),
530
552
  tempos: [...tempos.values()].sort((left, right) => left.at.compare(right.at)),
553
+ repeats: [...repeats.values()].sort((left, right) => left.at.compare(right.at)),
531
554
  wedges,
532
555
  endings,
533
556
  bars,
@@ -993,6 +1016,7 @@ function renderScore(score, options, diagnostics) {
993
1016
  : score.tempos;
994
1017
  // 初始状态进入 head;中途状态作为精确时间点只写在最上方 lane
995
1018
  const scoreAdjustments = new Map();
1019
+ const barAdjustments = new Map();
996
1020
  const addAdjustment = (adjustments, at, source, location, placement = "above") => {
997
1021
  const key = keyOf(at);
998
1022
  const point = adjustments.get(key) ?? { at, sources: [], pendingLocations: [] };
@@ -1010,6 +1034,10 @@ function renderScore(score, options, diagnostics) {
1010
1034
  addAdjustment(scoreAdjustments, item.at, `@meter(${item.numerator}, ${item.denominator})`);
1011
1035
  for (const item of tempos.slice(1))
1012
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
+ }
1013
1041
  const adjustmentsByLane = score.lanes.map((lane, index) => {
1014
1042
  const adjustments = index === 0 ? scoreAdjustments : new Map();
1015
1043
  for (const dynamic of lane.dynamics ?? []) {
@@ -1064,6 +1092,7 @@ function renderScore(score, options, diagnostics) {
1064
1092
  && !meters.some(point => interior(point.at))
1065
1093
  && ![...score.bars].some(([at, bar]) => interior(fractionFromKey(at)) && bar !== "|")
1066
1094
  && !score.endings.some(span => interior(span.from.at) || interior(span.end))
1095
+ && ![...barAdjustments.values()].some(point => interior(point.at))
1067
1096
  && adjustmentsByLane.every(points => ![...points.values()].some(point => interior(point.at)))
1068
1097
  && programsByLane.every(points => ![...points.keys()].some(at => interior(fractionFromKey(at))))
1069
1098
  && covered.length > 0 && covered.every(blocks => blocks.length === count
@@ -1145,6 +1174,12 @@ function renderScore(score, options, diagnostics) {
1145
1174
  if (!insideSpan(atomicBlocks, point.at))
1146
1175
  points.set(value, point.at);
1147
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
+ }
1148
1183
  const timeline = [...points.values()].sort((left, right) => left.compare(right));
1149
1184
  let blockIndex = 0;
1150
1185
  for (let index = 0; index < timeline.length; index++) {
@@ -1153,8 +1188,21 @@ function renderScore(score, options, diagnostics) {
1153
1188
  blockIndex++;
1154
1189
  }
1155
1190
  const bar = score.bars.get(keyOf(at));
1156
- if (bar && (!at.isZero() || bar !== "|"))
1157
- 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
+ }
1158
1206
  if (lineBreaks.has(keyOf(at))) {
1159
1207
  outputs.push([]);
1160
1208
  lyricTokens.push(new Map(orderedVerses.map(verse => [verse, []])));
@@ -1218,7 +1266,7 @@ function renderScore(score, options, diagnostics) {
1218
1266
  });
1219
1267
  });
1220
1268
  const omitted = new Set();
1221
- for (const adjustments of [scoreAdjustments, ...adjustmentsByLane]) {
1269
+ for (const adjustments of [scoreAdjustments, barAdjustments, ...adjustmentsByLane]) {
1222
1270
  for (const point of adjustments.values()) {
1223
1271
  for (const location of point.pendingLocations)
1224
1272
  omitted.add(location);
@@ -93,6 +93,14 @@ export interface MusicXmlKeyPoint {
93
93
  fifths: number;
94
94
  mode: string;
95
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
+ }
96
104
  /** 尚未附着到事件的力度或文字方向 */
97
105
  export interface MusicXmlDirectionPoint {
98
106
  location: MusicXmlPartLocation & {
@@ -151,6 +159,7 @@ export interface ParsedMusicXmlScore {
151
159
  bpm: number;
152
160
  location?: MusicXmlDiagnostic["location"];
153
161
  }[];
162
+ repeats: MusicXmlRepeatPoint[];
154
163
  wedges: MusicXmlWedgeSpan[];
155
164
  endings: MusicXmlEndingSpan[];
156
165
  bars: Map<string, string>;
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;
@@ -1,3 +1,4 @@
1
+ const PLACEHOLDER_RE = /\{(\w+)\}/g;
1
2
  export class Diagnostic {
2
3
  /** 诊断代码 */
3
4
  code;
@@ -5,10 +6,24 @@ export class Diagnostic {
5
6
  message;
6
7
  /** 诊断位置,指示问题在源代码中的位置 */
7
8
  span;
8
- constructor(code, message, span) {
9
+ /** 诊断消息中的结构化参数(构造时复制并字符串化,不修改或持有原对象) */
10
+ params;
11
+ // 多语言支持:仅需要替换此函数
12
+ static format(code, message, params) {
13
+ return params
14
+ ? message.replace(PLACEHOLDER_RE, (match, k) => Object.hasOwn(params, k) ? params[k] : match)
15
+ : message;
16
+ }
17
+ constructor(code, message, span, params) {
9
18
  this.code = code;
10
- this.message = message;
11
19
  this.span = span;
20
+ if (params) {
21
+ const dict = {};
22
+ for (const key of Object.keys(params))
23
+ dict[key] = String(params[key]);
24
+ this.params = dict;
25
+ }
26
+ this.message = Diagnostic.format(code, message, this.params);
12
27
  }
13
28
  toLineCol(lineStarts) {
14
29
  const start = Diagnostic.offsetToLineCol(this.span.start, lineStarts);
@@ -47,98 +62,35 @@ export class Diagnostic {
47
62
  static error;
48
63
  static warning;
49
64
  }
65
+ const formatArg = (arg) => typeof arg === "number" ? `[${arg}]` : `"${arg}"`;
50
66
  // 两个基类区分 Warning 和 Error
51
67
  export class ErrorDiagnostic extends Diagnostic {
52
68
  }
53
- ;
54
69
  export class WarningDiagnostic extends Diagnostic {
55
70
  }
56
- ;
57
71
  Diagnostic.error = {
58
- Bug: (message, span) => {
59
- return new ErrorDiagnostic("E_BUG", `解析器错误: ${message},请联系开发者修复这个问题`, span);
60
- },
61
- MissingArg: (functionName, argumentName, span) => {
62
- const argname = typeof argumentName === "number" ? `[${argumentName}]` : `"${argumentName}"`;
63
- return new ErrorDiagnostic("E_MISSING_REQUIRED_ARG", `函数@${functionName} 缺少必需的参数 ${argname}`, span);
64
- },
65
- InvalidArgType: (functionName, argumentName, expectedType, actualType, span) => {
66
- const argname = typeof argumentName === "number" ? `[${argumentName}]` : `"${argumentName}"`;
67
- return new ErrorDiagnostic("E_WRONG_ARG_TYPE", `函数 @${functionName} 的参数 ${argname} 类型错误: 得到了 ${actualType},但期望 ${expectedType}`, span);
68
- },
69
- PosAfterNamedArg: (functionName, span) => {
70
- return new ErrorDiagnostic("E_POSARG_AFTER_KWARG", `函数 @${functionName} 的位置参数出现在命名参数之后,这是不允许的`, span);
71
- },
72
- EmptyContent: (functionName, argumentName, span) => {
73
- const argname = typeof argumentName === "number" ? `[${argumentName}]` : `"${argumentName}"`;
74
- return new ErrorDiagnostic("E_EMPTY_CONTENT", `函数 @${functionName} 的参数 ${argname} 内容为空(或无可用内容);请提供有效内容`, span);
75
- },
76
- UnterminatedCall: (functionName, span) => {
77
- return new ErrorDiagnostic("E_UNTERMINATED_CALL", `函数调用未闭合: @${functionName}(...)`, span);
78
- },
79
- UnterminatedString: (span) => {
80
- return new ErrorDiagnostic("E_UNTERMINATED_String", `引号未闭合`, span);
81
- },
82
- UnknownFunction: (functionName, span) => {
83
- return new ErrorDiagnostic("E_UNKNOWN_FUNCTION", `未知函数: @${functionName},请检查拼写`, span);
84
- },
85
- UnknownLabel: (labelName, span) => {
86
- return new ErrorDiagnostic("E_UNKNOWN_LABEL", `未知标签: "${labelName}"`, span);
87
- },
88
- InvalidTonality: (tonality, span) => {
89
- return new ErrorDiagnostic("E_INVALID_TONALITY", `无效的调性: "${tonality}",请提供有效的调性名称,必须 [一个大写字母][变音记号#bn只能一个][绝对八度数字],后二者可选`, span);
90
- },
91
- BreakInsideEvent: (span) => {
92
- return new ErrorDiagnostic("E_BREAK_INSIDE_EVENT", `换行或换页切断了一个仍在持续的事件;请把长音写成多个事件,或调整换行、换页的位置`, span);
93
- },
94
- InvalidPageConfig: (message, span) => {
95
- return new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", message, span);
96
- },
97
- PageOverflow: (required, available, span) => {
98
- return new ErrorDiagnostic("E_PAGE_OVERFLOW", `谱面行需要 ${required}px 高度,但页面内容区只有 ${available}px`, span);
99
- }
72
+ Bug: (message, span) => new ErrorDiagnostic("E_BUG", "解析器错误: {message},请联系开发者修复这个问题", span, { message }),
73
+ MissingArg: (functionName, argumentName, span) => new ErrorDiagnostic("E_MISSING_REQUIRED_ARG", "函数@{fn} 缺少必需的参数 {arg}", span, { fn: functionName, arg: formatArg(argumentName) }),
74
+ PosAfterNamedArg: (functionName, span) => new ErrorDiagnostic("E_POSARG_AFTER_KWARG", "函数 @{fn} 的位置参数出现在命名参数之后,这是不允许的", span, { fn: functionName }),
75
+ EmptyContent: (functionName, argumentName, span) => new ErrorDiagnostic("E_EMPTY_CONTENT", "函数 @{fn} 的参数 {arg} 内容为空(或无可用内容);请提供有效内容", span, { fn: functionName, arg: formatArg(argumentName) }),
76
+ UnterminatedCall: (functionName, span) => new ErrorDiagnostic("E_UNTERMINATED_CALL", "函数调用未闭合: @{fn}(...)", span, { fn: functionName }),
77
+ UnknownFunction: (functionName, span) => new ErrorDiagnostic("E_UNKNOWN_FUNCTION", "未知函数: @{fn},请检查拼写", span, { fn: functionName }),
78
+ UnknownLabel: (labelName, span) => new ErrorDiagnostic("E_UNKNOWN_LABEL", '未知标签: "{label}"', span, { label: labelName }),
79
+ BreakInsideEvent: (span) => new ErrorDiagnostic("E_BREAK_INSIDE_EVENT", "换行或换页切断了一个仍在持续的事件;请把长音写成多个事件,或调整换行、换页的位置", span),
80
+ PageOverflow: (required, available, span) => new ErrorDiagnostic("E_PAGE_OVERFLOW", "谱面行需要 {required}px 高度,但页面内容区只有 {available}px", span, { required, available }),
100
81
  };
101
82
  Diagnostic.warning = {
102
- UnknownFunction: (functionName, span) => {
103
- return new WarningDiagnostic("W_UNKNOWN_FUNCTION", `未知函数: @${functionName},将被当作普通文本处理`, span);
104
- },
105
- UnknownNamedArg: (functionName, argumentName, span) => {
106
- return new WarningDiagnostic("W_UNKNOWN_NAMED_ARG", `函数 @${functionName} 收到未知的命名参数 "${argumentName}"`, span);
107
- },
108
- TooManyPosArgs: (functionName, expected, actual, span) => {
109
- return new WarningDiagnostic("W_TOO_MANY_POS_ARGS", `函数 @${functionName} 接收了过多的位置参数,期望 ${expected} 个但得到了 ${actual} 个`, span);
110
- },
111
- InvalidNumber: (value, span) => {
112
- return new WarningDiagnostic("W_INVALID_NUMBER", `无效的数字: "${value}";将使用默认值(若存在)`, span);
113
- },
114
- InvalidBoolean: (value, span) => {
115
- return new WarningDiagnostic("W_INVALID_BOOL", `无效的布尔值: "${value}": 应为 'true' 或 'false';将使用默认值(若存在)`, span);
116
- },
117
- InvalidLength: (value, span) => {
118
- return new WarningDiagnostic("W_INVALID_LENGTH", `无效的长度值: "${value}";请提供有效的长度值,例如 "10px" 或 "2em";将使用默认值(若存在)`, span);
119
- },
120
- InvalidLengthUnit: (unit, span) => {
121
- return new WarningDiagnostic("W_INVALID_LENGTH_UNIT", `无效的长度单位: "${unit}";仅支持 "px" 和 "em";请检查函数参数或变量定义;将使用默认值(若存在)`, span);
122
- },
123
- InvalidContent: (span) => {
124
- return new WarningDiagnostic("W_INVALID_CONTENT", `内容解析失败,错误原因见上;将使用默认值(但往往不存在,极有可能导致错误)`, span);
125
- },
126
- EmptyContent: (functionName, argumentName, span) => {
127
- return new WarningDiagnostic("W_EMPTY_CONTENT", `函数 @${functionName} 的参数 "${argumentName}" 内容为空(或无可用内容)`, span);
128
- },
129
- UnmatchedBrace: (span) => {
130
- return new WarningDiagnostic("W_UNMATCHED_BRACE", `未匹配的大括号: 缺少右大括号'}';将尝试自动修复`, span);
131
- },
132
- LabelWithoutTarget: (labelName, span) => {
133
- return new WarningDiagnostic("W_LABEL_WITHOUT_TARGET", `标签 "${labelName}" 没有可绑定的目标;标签将被忽略`, span);
134
- },
135
- TargetAlreadyLabeled: (newLabel, oldLabel, span) => {
136
- return new WarningDiagnostic("W_TARGET_ALREADY_LABELED", `目标已标注为 "${oldLabel}","${newLabel}" 将被忽略`, span);
137
- },
138
- UnresolvedEndpoint: (functionName, span) => {
139
- return new WarningDiagnostic("W_UNRESOLVED_ENDPOINT", `@${functionName} 有端点找不到对应的谱面对象;该关系将被忽略`, span);
140
- },
141
- ZeroTimeTrack: (span, trackOrder) => {
142
- return new WarningDiagnostic("W_ZERO_TIME_TRACK", `第${trackOrder}个子轨道的时长为0`, span);
143
- },
83
+ InvalidUnicodeEscape: (span) => new WarningDiagnostic("W_STRING_INVALID_UNICODE_ESCAPE", "无效的 Unicode 转义:请使用 \\uXXXX(四位十六进制数字);将保留该字符串原文", span),
84
+ UnknownFunction: (functionName, span) => new WarningDiagnostic("W_UNKNOWN_FUNCTION", "未知函数: @{fn},将被当作普通文本处理", span, { fn: functionName }),
85
+ TooManyPosArgs: (functionName, expected, actual, span) => new WarningDiagnostic("W_TOO_MANY_POS_ARGS", "函数 @{fn} 接收了过多的位置参数,期望 {expected} 个但得到了 {actual} 个", span, { fn: functionName, expected, actual }),
86
+ InvalidNumber: (value, span) => new WarningDiagnostic("W_INVALID_NUMBER", '无效的数字: "{value}";将使用默认值(若存在)', span, { value }),
87
+ InvalidBoolean: (value, span) => new WarningDiagnostic("W_INVALID_BOOL", '无效的布尔值: "{value}": 应为 \'true\' 或 \'false\';将使用默认值(若存在)', span, { value }),
88
+ InvalidLength: (value, span) => new WarningDiagnostic("W_INVALID_LENGTH", '无效的长度值: "{value}";请提供有效的长度值,例如 "10px" 或 "2em";将使用默认值(若存在)', span, { value }),
89
+ InvalidLengthUnit: (unit, span) => new WarningDiagnostic("W_INVALID_LENGTH_UNIT", '无效的长度单位: "{unit}";仅支持 "px" 和 "em";请检查函数参数或变量定义;将使用默认值(若存在)', span, { unit }),
90
+ InvalidContent: (span) => new WarningDiagnostic("W_INVALID_CONTENT", "内容解析失败,错误原因见上;将使用默认值(但往往不存在,极有可能导致错误)", span),
91
+ UnmatchedBrace: (span) => new WarningDiagnostic("W_UNMATCHED_BRACE", "未匹配的大括号: 缺少右大括号'}';将尝试自动修复", span),
92
+ LabelWithoutTarget: (labelName, span) => new WarningDiagnostic("W_LABEL_WITHOUT_TARGET", '标签 "{label}" 没有可绑定的目标;标签将被忽略', span, { label: labelName }),
93
+ TargetAlreadyLabeled: (newLabel, oldLabel, span) => new WarningDiagnostic("W_TARGET_ALREADY_LABELED", '目标已标注为 "{oldLabel}","{newLabel}" 将被忽略', span, { oldLabel, newLabel }),
94
+ UnresolvedEndpoint: (functionName, span) => new WarningDiagnostic("W_UNRESOLVED_ENDPOINT", "@{fn} 有端点找不到对应的谱面对象;该关系将被忽略", span, { fn: functionName }),
95
+ ZeroTimeTrack: (span, trackOrder) => new WarningDiagnostic("W_ZERO_TIME_TRACK", "第{track}个子轨道的时长为0", span, { track: trackOrder }),
144
96
  };
package/dist/fraction.js CHANGED
@@ -15,7 +15,8 @@ export class Fraction {
15
15
  _numerator = 0;
16
16
  _denominator = 1;
17
17
  constructor(numerator = 0, denominator = 1) {
18
- this.set(numerator, denominator);
18
+ if (numerator !== 0 || denominator !== 1)
19
+ this.set(numerator, denominator);
19
20
  }
20
21
  get numerator() {
21
22
  return this._numerator;
@@ -44,7 +45,7 @@ export class Fraction {
44
45
  return this;
45
46
  }
46
47
  clone() {
47
- return new Fraction(this._numerator, this._denominator);
48
+ return new Fraction().copyFrom(this);
48
49
  }
49
50
  add(value, denominator = 1) {
50
51
  let numerator;
@@ -2,7 +2,7 @@ import type { SourceSpan, LengthValue, deSugarAtomFunction, deSugarRelationFunct
2
2
  import type { CallArgumentInfo } from "../parser/grammarType.js";
3
3
  import type { ParserContext } from "../parser/parserContext.js";
4
4
  import type { Fraction } from "../fraction.js";
5
- import type { LoweringAugmenter, LoweringFinalizer, TimeFlowModel } from "../lowering/types.js";
5
+ import type { TimeFlowModel } from "../lowering/types.js";
6
6
  import type { TemporalNodeBase } from "./temporal.js";
7
7
  import type { LoweringContext } from "../lowering/loweringContext.js";
8
8
  import type { Track } from "../lowering/track.js";
@@ -101,22 +101,6 @@ export declare class ASTFunctionNode extends ASTNodeBase {
101
101
  get deSugarRelation(): deSugarRelationFunction;
102
102
  getArgValue(args: FunctionArgs, ctx: ParserContext): paramValue[];
103
103
  toString(source: string): string;
104
- /**
105
- * lowering 固化后的 attachment 生成钩子
106
- *
107
- * 普通 loweringEnter/loweringExit 在递归遍历 AST 时执行,
108
- * 此时尚未完成锚点归并,事件的 t、track 和 layoutLine 不可用,因此需要观察完整事件流的功能不能在普通 hook 中可靠决定分组。
109
- * 该 hook 读取 LoweringResult 并返回新建的 LoweringAttachment,LoweringContext 将返回值追加到当前文档或 fragment 的 attachments,不会把它们放入时间列或推进时间。
110
- *
111
- * 例:autobeam 扫描最终列,按轨道、谱面行、拍点和显式 beam 端点决定分组,再生成 BeamLayoutAttachment
112
- */
113
- static loweringAugment?: LoweringAugmenter;
114
- /**
115
- * 所有 loweringAugment 结果追加完成后的最终处理;此时已经得到了完整的 lowering 语义
116
- * 所有派生 attachment 追加完成后,按函数注册顺序处理完整结果
117
- * 可以进行校验(如 beam 和 tie)或者修改某些值
118
- */
119
- static loweringFinalize?: LoweringFinalizer;
120
104
  /**
121
105
  * 装饰函数可选的排版声明
122
106
  * layout 引擎按 key 收集,不需要识别具体函数类
@@ -136,4 +120,4 @@ export declare class ASTFunctionNode extends ASTNodeBase {
136
120
  */
137
121
  static findLastFuncContentIndex(nodes: ASTNodeBase[], i: number): number;
138
122
  }
139
- export type ASTFunctionClass = (new (sourceSpan: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent: ASTNodeBase | null) => ASTFunctionNode) & Pick<typeof ASTFunctionNode, "prototype" | "def" | "deSugarAtom" | "deSugarRelation" | "loweringAugment" | "loweringFinalize" | "layoutDecorationHandler">;
123
+ export type ASTFunctionClass = (new (sourceSpan: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent: ASTNodeBase | null) => ASTFunctionNode) & Pick<typeof ASTFunctionNode, "prototype" | "def" | "deSugarAtom" | "deSugarRelation" | "layoutDecorationHandler">;