jpfun 0.4.0 → 0.5.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 (83) hide show
  1. package/README.md +53 -113
  2. package/dist/converter/midi/convert.js +14 -7
  3. package/dist/converter/musicxml/features.d.ts +57 -16
  4. package/dist/converter/musicxml/features.js +204 -42
  5. package/dist/converter/musicxml/index.d.ts +7 -2
  6. package/dist/converter/musicxml/index.js +256 -268
  7. package/dist/converter/musicxml/model.d.ts +36 -7
  8. package/dist/converter/musicxml/resolve.d.ts +10 -0
  9. package/dist/converter/musicxml/resolve.js +152 -0
  10. package/dist/core.d.ts +1 -0
  11. package/dist/core.js +1 -0
  12. package/dist/fraction.js +7 -1
  13. package/dist/functions/ASTtypes.d.ts +4 -4
  14. package/dist/functions/ASTtypes.js +5 -9
  15. package/dist/functions/adjust/index.js +16 -53
  16. package/dist/functions/arpeggio/index.js +27 -15
  17. package/dist/functions/bar/index.js +7 -8
  18. package/dist/functions/beam/index.js +6 -1
  19. package/dist/functions/beam/layout.d.ts +1 -1
  20. package/dist/functions/beam/layout.js +5 -3
  21. package/dist/functions/box/index.js +88 -82
  22. package/dist/functions/br/index.js +9 -5
  23. package/dist/functions/dash/index.js +24 -13
  24. package/dist/functions/div/index.d.ts +5 -2
  25. package/dist/functions/div/index.js +15 -14
  26. package/dist/functions/dot/index.js +13 -11
  27. package/dist/functions/dyn/index.js +35 -39
  28. package/dist/functions/grace/index.d.ts +19 -6
  29. package/dist/functions/grace/index.js +136 -121
  30. package/dist/functions/head/index.js +19 -14
  31. package/dist/functions/key/index.js +8 -4
  32. package/dist/functions/meter/index.js +22 -2
  33. package/dist/functions/note/index.d.ts +6 -1
  34. package/dist/functions/note/index.js +48 -30
  35. package/dist/functions/note/source-transform.d.ts +21 -0
  36. package/dist/functions/note/source-transform.js +164 -0
  37. package/dist/functions/page/index.d.ts +8 -1
  38. package/dist/functions/page/index.js +23 -13
  39. package/dist/functions/program/index.js +11 -2
  40. package/dist/functions/set/index.js +14 -8
  41. package/dist/functions/stack/index.js +7 -5
  42. package/dist/functions/symbol/index.d.ts +2 -0
  43. package/dist/functions/symbol/index.js +11 -7
  44. package/dist/functions/symbol/ornament.d.ts +3 -3
  45. package/dist/functions/symbol/ornament.js +21 -35
  46. package/dist/functions/symbol/symbols/accent.js +5 -5
  47. package/dist/functions/symbol/symbols/fermata.js +5 -4
  48. package/dist/functions/tempo/index.js +7 -1
  49. package/dist/functions/text/index.js +11 -3
  50. package/dist/functions/tie/index.js +28 -32
  51. package/dist/functions/tuplet/index.js +26 -24
  52. package/dist/functions/up/index.js +24 -21
  53. package/dist/functions/voice/index.js +36 -26
  54. package/dist/functions/volta/index.js +16 -17
  55. package/dist/jpfun.core.min.js +98 -129
  56. package/dist/jpfun.from-midi.min.js +5 -5
  57. package/dist/jpfun.from-musicxml.min.js +8 -8
  58. package/dist/jpfun.min.js +107 -138
  59. package/dist/layout/engine.d.ts +11 -1
  60. package/dist/layout/engine.js +299 -96
  61. package/dist/layout/page.js +2 -0
  62. package/dist/layout/range.d.ts +26 -0
  63. package/dist/layout/range.js +75 -0
  64. package/dist/layout/types.d.ts +33 -4
  65. package/dist/lowering/types.d.ts +5 -0
  66. package/dist/parser/parse-utils/length-utils.js +2 -0
  67. package/dist/parser/parse-utils/note-utils.d.ts +2 -0
  68. package/dist/parser/parse-utils/note-utils.js +6 -2
  69. package/dist/parser/parserContext.js +1 -1
  70. package/dist/playback/compile.d.ts +2 -9
  71. package/dist/playback/compile.js +297 -186
  72. package/dist/playback/event.d.ts +8 -16
  73. package/dist/playback/event.js +13 -3
  74. package/dist/playback/types.d.ts +76 -18
  75. package/dist/playback/types.js +1 -0
  76. package/dist/render/index.d.ts +1 -1
  77. package/dist/render/index.js +1 -1
  78. package/dist/render/recording.d.ts +1 -0
  79. package/dist/render/recording.js +21 -0
  80. package/dist/render/translate.d.ts +14 -0
  81. package/dist/render/translate.js +48 -0
  82. package/grammar.md +103 -78
  83. package/package.json +4 -4
@@ -10,9 +10,10 @@
10
10
  */
11
11
  import { Fraction } from "../../fraction.js";
12
12
  import { NoteNameMap } from "../../parser/parse-utils/note-utils.js";
13
- import { child, children, descendant, nameOf, number, text, } from "./dom.js";
14
- import { directionDynamic, directionTexts, endingPasses, metronomeBpm, mergeArpeggio, noteArpeggio, noteLyrics, noteModifiers, parsePitch, parseTimeSignature, partMeasures, timeModification, } from "./features.js";
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";
15
15
  import { attachAbove, quote, renderHead, renderPitch, renderSystems } from "../source.js";
16
+ import { matchingLanes, resolveRelations, resolveVoices } from "./resolve.js";
16
17
  const MAJOR_KEYS = ["Cb", "Gb", "Db", "Ab", "Eb", "Bb", "F", "C", "G", "D", "A", "E", "B", "F#", "C#"];
17
18
  const MINOR_KEYS = ["Ab", "Eb", "Bb", "F", "C", "G", "D", "A", "E", "B", "F#", "C#", "G#", "D#", "A#"];
18
19
  // name = token[0] acc = token.slice(1)
@@ -75,7 +76,7 @@ function setBar(bars, at, token) {
75
76
  * 每个 part 独立推进游标,第一 part 的小节长度作为多 part 对齐基准
76
77
  * backup/forward 只移动当前小节游标,不直接产生可见音符
77
78
  */
78
- function parseScore(root) {
79
+ function parseScore(root, diagnostics) {
79
80
  const partNames = new Map();
80
81
  const instrumentsByPart = new Map();
81
82
  const partList = child(root, "part-list");
@@ -88,63 +89,14 @@ function parseScore(root) {
88
89
  let fallback;
89
90
  // 一个 part 可声明多个 instrument,首个定义同时作为无 id note 的回退
90
91
  for (const midi of children(scorePart, "midi-instrument")) {
91
- const channelSource = text(midi, "midi-channel");
92
- const programSource = text(midi, "midi-program");
93
- const channel = channelSource === "" ? undefined : Number(channelSource);
94
- const program = programSource === "" ? undefined : Number(programSource) - 1;
95
- if (channel !== undefined && (!Number.isSafeInteger(channel) || channel < 1 || channel > 16)) {
96
- throw new RangeError("MusicXML midi-channel must be an integer in 1..16");
97
- }
98
- if (program !== undefined && (!Number.isSafeInteger(program) || program < 0 || program > 127)) {
99
- throw new RangeError("MusicXML midi-program must be an integer in 1..128");
100
- }
101
- const instrument = { channel, program };
92
+ const instrument = readInstrument(midi);
102
93
  fallback ??= instrument;
103
94
  byId.set(midi.getAttribute("id") ?? "", instrument);
104
95
  }
105
96
  instrumentsByPart.set(partId, { fallback, byId });
106
97
  }
107
98
  }
108
- // 标题作者等文档级元数据不进入时间线
109
- const credits = children(root, "credit");
110
- const credit = (type) => {
111
- const item = credits.find(value => text(value, "credit-type") === type);
112
- return item ? text(item, "credit-words") : "";
113
- };
114
- const workTitle = text(child(root, "work"), "work-title");
115
- // 优先采用语义明确的标题字段,并过滤 MuseScore 的默认占位标题
116
- const title = text(root, "movement-title")
117
- || (workTitle !== "Untitled Score" && workTitle !== "未命名乐谱" ? workTitle : "")
118
- || credit("title");
119
- const subtitle = credit("subtitle");
120
- const creator = credit("composer") || (() => {
121
- const identification = child(root, "identification");
122
- const creators = identification ? children(identification, "creator") : [];
123
- return text(creators.find(item => item.getAttribute("type") === "composer") ?? creators[0]);
124
- })();
125
- // 页面配置只有在 scaling 和完整尺寸同时存在时才接管 jpFun 默认值
126
- let page;
127
- const defaults = child(root, "defaults");
128
- const scaling = defaults && child(defaults, "scaling");
129
- const pageLayout = defaults && child(defaults, "page-layout");
130
- if (scaling && pageLayout && child(pageLayout, "page-width") && child(pageLayout, "page-height")) {
131
- // MusicXML 的 tenths 经毫米标尺换算成 CSS 像素
132
- const millimeters = number(scaling, "millimeters");
133
- const tenths = number(scaling, "tenths");
134
- const pixelsPerTenth = millimeters / tenths * 96 / 25.4;
135
- const marginList = children(pageLayout, "page-margins");
136
- const margins = marginList.find(item => item.getAttribute("type") === "odd") ?? marginList[0];
137
- if (Number.isFinite(pixelsPerTenth) && pixelsPerTenth > 0) {
138
- page = {
139
- width: number(pageLayout, "page-width") * pixelsPerTenth,
140
- height: number(pageLayout, "page-height") * pixelsPerTenth,
141
- top: margins ? number(margins, "top-margin", 48 / pixelsPerTenth) * pixelsPerTenth : 48,
142
- bottom: margins ? number(margins, "bottom-margin", 48 / pixelsPerTenth) * pixelsPerTenth : 48,
143
- left: margins ? number(margins, "left-margin", 40 / pixelsPerTenth) * pixelsPerTenth : 40,
144
- right: margins ? number(margins, "right-margin", 40 / pixelsPerTenth) * pixelsPerTenth : 40,
145
- };
146
- }
147
- }
99
+ const metadata = scoreMetadata(root);
148
100
  // 先收集按时间定位的原始语义;关系端点在所有 part 解析完后统一配对
149
101
  const lanes = new Map();
150
102
  const meters = new Map();
@@ -172,11 +124,28 @@ function parseScore(root) {
172
124
  let activeMeter = { numerator: 4, denominator: 4 };
173
125
  const lastEvent = new Map();
174
126
  const pendingGraces = new Map();
127
+ const transpositions = [];
128
+ const pitches = [];
129
+ const instrumentChanges = [];
130
+ const eventInstruments = new Map();
131
+ const instrumentAt = (id, at) => {
132
+ const value = { ...(partInstruments?.byId.get(id) ?? partInstruments?.fallback) };
133
+ for (const change of instrumentChanges) {
134
+ if (change.id === id && change.at.compare(at) <= 0)
135
+ Object.assign(value, change.instrument);
136
+ }
137
+ return value;
138
+ };
175
139
  // 小节游标从零开始,partTime 保存当前小节在全谱中的绝对起点
176
140
  for (let measureIndex = 0; measureIndex < measures.length; measureIndex++) {
177
141
  const { body: measure, container: measureContainer } = measures[measureIndex];
142
+ const measureLocation = {
143
+ partId, measureIndex: measureIndex + 1,
144
+ measureNumber: measureContainer.getAttribute("number") ?? undefined,
145
+ };
178
146
  let cursor = new Fraction();
179
147
  let measureEnd = new Fraction();
148
+ let chordStart;
180
149
  if (measureContainer.getAttribute("implicit") !== "yes" && measureIndex > 0) {
181
150
  setBar(bars, partTime, "|");
182
151
  if (partId === controlPartId)
@@ -209,6 +178,7 @@ function parseScore(root) {
209
178
  const passes = endingPasses(ending.getAttribute("number") ?? "");
210
179
  if (passes.length > 0)
211
180
  endingPoints.set(`${keyOf(at)}\0${endingType}\0${passes.join(",")}`, {
181
+ location: { ...measureLocation, element: "ending" },
212
182
  at: at.clone(),
213
183
  type: endingType,
214
184
  passes,
@@ -221,6 +191,15 @@ function parseScore(root) {
221
191
  // attributes 从当前位置起更新 divisions 拍号和调号
222
192
  if (tag === "attributes") {
223
193
  const at = add(partTime, cursor);
194
+ for (const transpose of children(item, "transpose")) {
195
+ const chromatic = number(transpose, "chromatic");
196
+ const diatonic = child(transpose, "diatonic") ? number(transpose, "diatonic") : undefined;
197
+ const octaves = number(transpose, "octave-change", 0);
198
+ if (![chromatic, octaves, diatonic ?? 0].every(Number.isSafeInteger) || child(transpose, "double")) {
199
+ throw new RangeError("jpFun requires integer MusicXML transposition without octave doubling");
200
+ }
201
+ transpositions.push({ at: at.clone(), staff: transpose.getAttribute("number") ?? "", chromatic, diatonic, octaves });
202
+ }
224
203
  if (child(item, "divisions"))
225
204
  divisions = number(item, "divisions");
226
205
  if (!Number.isSafeInteger(divisions) || divisions <= 0)
@@ -246,6 +225,7 @@ function parseScore(root) {
246
225
  }
247
226
  // backup 和 forward 只重定位当前小节游标,用于交错 voice
248
227
  if (tag === "backup" || tag === "forward") {
228
+ chordStart = undefined;
249
229
  const duration = new Fraction(number(item, "duration"), divisions);
250
230
  if (tag === "backup")
251
231
  cursor.sub(duration);
@@ -256,77 +236,102 @@ function parseScore(root) {
256
236
  measureEnd = measureEnd.compare(cursor) < 0 ? cursor.clone() : measureEnd;
257
237
  continue;
258
238
  }
259
- // direction 收集精确时间上的速度、力度、文字和楔形线端点
260
- if (tag === "direction") {
261
- const offset = new Fraction(number(item, "offset", 0), divisions);
239
+ // sound 共用速度和乐器读取;direction 继续收集力度、文字和楔形线端点
240
+ if (tag === "direction" || tag === "sound") {
241
+ const offset = new Fraction(tag === "direction" ? number(item, "offset", 0) : 0, divisions);
262
242
  const at = add(add(partTime, cursor), offset);
263
- const sound = child(item, "sound");
243
+ const sound = tag === "sound" ? item : child(item, "sound");
244
+ if (sound) {
245
+ for (const midi of children(sound, "midi-instrument")) {
246
+ instrumentChanges.push({ at, id: midi.getAttribute("id") ?? "", instrument: readInstrument(midi) });
247
+ }
248
+ instrumentChanges.sort((left, right) => left.at.compare(right.at));
249
+ }
264
250
  const tempo = sound?.getAttribute("tempo");
265
- const bpm = tempo !== null && tempo !== undefined && tempo !== "" ? Number(tempo) : metronomeBpm(item);
251
+ const reader = tag === "direction" ? new MusicXmlReader([item]) : undefined;
252
+ const metronome = reader?.read("metronome", true);
253
+ const markedBpm = metronomeBpm(metronome);
254
+ const bpm = tempo ? Number(tempo) : markedBpm;
266
255
  if (bpm !== undefined) {
267
256
  if (!Number.isFinite(bpm) || bpm <= 0)
268
257
  throw new RangeError("MusicXML tempo must be positive and finite");
269
- tempos.set(keyOf(at), { at, bpm });
258
+ const timeKey = keyOf(at);
259
+ const previous = tempos.get(timeKey);
260
+ if (previous?.location && previous.bpm !== bpm) {
261
+ reportDiagnostic(diagnostics, "tempoReplaced", previous.location, previous.bpm);
262
+ }
263
+ tempos.set(timeKey, { at, bpm, location: {
264
+ ...measureLocation, element: metronome && markedBpm === bpm ? "metronome" : "sound",
265
+ } });
270
266
  }
271
- const dynamic = directionDynamic(item);
272
- const texts = directionTexts(item);
267
+ if (!reader)
268
+ continue;
269
+ if (bpm !== undefined && markedBpm === bpm)
270
+ reader.accept(metronome);
271
+ const staff = text(item, "staff") || "1";
272
+ const voice = text(item, "voice");
273
+ 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);
273
278
  if (dynamic || texts.length > 0)
274
279
  directions.push({
280
+ location,
275
281
  at,
276
- partId,
277
- staff: text(item, "staff") || "1",
278
- voice: text(item, "voice") || "",
279
282
  placement: item.getAttribute("placement") === "below" ? "below" : "above",
280
283
  dynamic,
281
284
  texts,
282
285
  });
283
- const wedge = descendant(item, "wedge");
286
+ const wedge = reader.read("wedge", true);
284
287
  const wedgeType = wedge?.getAttribute("type");
285
288
  if (wedgeType === "crescendo" || wedgeType === "diminuendo" || wedgeType === "stop") {
286
289
  wedgePoints.push({
290
+ location: { ...location, element: "wedge" },
287
291
  at,
288
- partId,
289
- staff: text(item, "staff") || "1",
290
- voice: text(item, "voice") || "",
291
292
  number: wedge?.getAttribute("number") || "1",
292
293
  type: wedgeType,
293
294
  });
295
+ reader.accept(wedge);
296
+ }
297
+ for (const directionType of children(item, "direction-type")) {
298
+ reader.report(diagnostics, location, directionType);
294
299
  }
295
- continue;
296
- }
297
- // measure 直属 sound 也可能携带速度,不要求包在 direction 中
298
- const tempo = tag === "sound" ? item.getAttribute("tempo") : null;
299
- if (tempo !== null && tempo !== "") {
300
- const bpm = Number(tempo);
301
- if (!Number.isFinite(bpm) || bpm <= 0)
302
- throw new RangeError("MusicXML tempo must be positive and finite");
303
- const at = add(partTime, cursor);
304
- tempos.set(keyOf(at), { at, bpm });
305
300
  continue;
306
301
  }
307
302
  if (tag === "barline" && item.getAttribute("location") === "middle") {
308
303
  recordBarline(item, add(partTime, cursor));
309
304
  continue;
310
305
  }
311
- if (tag !== "note")
306
+ if (tag !== "note") {
307
+ if (tag === "harmony")
308
+ reportDiagnostic(diagnostics, "unsupported", { ...measureLocation, element: tag }, tag);
312
309
  continue;
310
+ }
313
311
  // note 先确定 lane 与 instrument,再区分打击乐、倚音、和弦成员和普通起音
314
312
  const voice = text(item, "voice") || "1";
315
313
  const staff = text(item, "staff") || "1";
314
+ const location = { ...measureLocation, element: "note", staff, voice };
316
315
  const laneKey = `${partId}\0${staff}\0${voice}`;
317
- const instrumentId = child(item, "instrument")?.getAttribute("id") ?? "";
318
- const instrument = instrumentId
319
- ? partInstruments?.byId.get(instrumentId)
320
- : partInstruments?.fallback;
321
- const pitch = parsePitch(item);
316
+ const instrumentId = child(item, "instrument")?.getAttribute("id")
317
+ || partInstruments?.byId.keys().next().value || "";
318
+ const notationElements = children(item, "notations");
319
+ const notations = notationElements.length ? new MusicXmlReader(notationElements) : undefined;
320
+ const pitch = parsePitch(item, location, notations);
322
321
  const rest = child(item, "rest") !== undefined;
323
322
  if (!pitch && !rest) {
324
323
  throw new TypeError("MusicXML note must contain pitch, unpitched, or rest");
325
324
  }
326
325
  const chord = child(item, "chord") !== undefined;
327
326
  const grace = child(item, "grace");
327
+ const start = chord && chordStart ? chordStart.clone() : add(partTime, cursor);
328
+ if (!chord && !grace)
329
+ chordStart = start.clone();
330
+ if (pitch && child(item, "pitch"))
331
+ pitches.push({ pitch, at: start });
328
332
  // 打击乐尚未建模,但普通音符仍须推进游标以保持后续事件位置
329
- if (instrument?.channel === 10) {
333
+ if (instrumentAt(instrumentId, start).channel === 10) {
334
+ reportDiagnostic(diagnostics, "percussion", location);
330
335
  if (grace)
331
336
  continue;
332
337
  const duration = new Fraction(number(item, "duration"), divisions);
@@ -338,6 +343,8 @@ function parseScore(root) {
338
343
  measureEnd = cursor.clone();
339
344
  continue;
340
345
  }
346
+ if (pitch && !child(item, "pitch"))
347
+ reportDiagnostic(diagnostics, "displayPitch", { ...location, element: "unpitched" });
341
348
  // lane 在首次遇到可保留事件时创建,纯打击乐轨不会留下空 lane
342
349
  let lane = lanes.get(laneKey);
343
350
  if (!lane) {
@@ -352,8 +359,11 @@ function parseScore(root) {
352
359
  }
353
360
  const previousEvent = lastEvent.get(laneKey);
354
361
  if (grace) {
355
- if (!pitch)
362
+ if (!pitch) {
363
+ reportDiagnostic(diagnostics, "gracePitch", { ...location, element: "grace" });
356
364
  continue;
365
+ }
366
+ notations?.report(diagnostics, location);
357
367
  // 后倚音挂到前一事件,前倚音暂存到下一次真实起音
358
368
  const stealTimePrevious = grace.getAttribute("steal-time-previous");
359
369
  if (stealTimePrevious !== null && stealTimePrevious !== "" && previousEvent) {
@@ -364,6 +374,9 @@ function parseScore(root) {
364
374
  groups.push([pitch]);
365
375
  }
366
376
  else {
377
+ if (stealTimePrevious !== null && stealTimePrevious !== "") {
378
+ reportDiagnostic(diagnostics, "afterGrace", { ...location, element: "grace" });
379
+ }
367
380
  const groups = pendingGraces.get(laneKey) ?? [];
368
381
  if (chord && groups.length > 0)
369
382
  groups.at(-1).push(pitch);
@@ -376,11 +389,11 @@ function parseScore(root) {
376
389
  const duration = new Fraction(number(item, "duration"), divisions);
377
390
  if (duration.compare(0) <= 0)
378
391
  throw new RangeError("MusicXML non-grace notes require a positive duration");
379
- const start = chord ? previousEvent?.start.clone() ?? add(partTime, cursor) : add(partTime, cursor);
380
392
  let event = chord ? previousEvent : undefined;
381
393
  const lyrics = noteLyrics(item);
382
- const modifiers = noteModifiers(item);
383
- const arpeggio = noteArpeggio(item);
394
+ const modifiers = noteModifiers(notations, diagnostics, location);
395
+ const arpeggio = noteArpeggio(notations, location);
396
+ const tuplets = notations?.readAll("tuplet");
384
397
  // chord 成员只有起点和时值都一致时才合并到前一事件
385
398
  if (!event || !event.start.equals(start) || !event.duration.equals(duration) || event.rest) {
386
399
  event = {
@@ -395,15 +408,14 @@ function parseScore(root) {
395
408
  postGraces: [],
396
409
  lyrics,
397
410
  arpeggio,
398
- program: instrument?.program,
399
- timeModification: timeModification(item),
411
+ timeModification: timeModification(item, tuplets),
400
412
  };
401
413
  pendingGraces.delete(laneKey);
402
414
  lane.events.push(event);
415
+ eventInstruments.set(event, instrumentId);
403
416
  lastEvent.set(laneKey, event);
404
417
  }
405
418
  else {
406
- event.program ??= instrument?.program;
407
419
  event.arpeggio = mergeArpeggio(event.arpeggio, arpeggio);
408
420
  for (const modifier of modifiers) {
409
421
  if (!event.modifiers.some(item => item.name === modifier.name && item.placement === modifier.placement)) {
@@ -411,6 +423,8 @@ function parseScore(root) {
411
423
  }
412
424
  }
413
425
  }
426
+ acceptTuplets(notations, tuplets, event.timeModification);
427
+ notations?.report(diagnostics, location);
414
428
  if (pitch)
415
429
  event.pitches.push(pitch);
416
430
  for (const [verse, words] of lyrics) {
@@ -449,35 +463,23 @@ function parseScore(root) {
449
463
  if (scoreEnd.compare(partTime) < 0)
450
464
  scoreEnd = partTime.clone();
451
465
  }
466
+ for (const groups of pendingGraces.values())
467
+ for (const group of groups)
468
+ for (const pitch of group) {
469
+ reportDiagnostic(diagnostics, "graceHost", { ...pitch.location, element: "grace" });
470
+ }
471
+ transpositions.sort((left, right) => left.at.compare(right.at)).reverse();
472
+ for (const { pitch, at } of pitches) {
473
+ const change = transpositions.find(item => (!item.staff || item.staff === pitch.location.staff) && item.at.compare(at) <= 0);
474
+ if (change)
475
+ transposePitch(pitch, change.chromatic, change.diatonic, change.octaves);
476
+ }
477
+ for (const [event, id] of eventInstruments)
478
+ event.program = instrumentAt(id, event.start).program;
452
479
  setBar(bars, partTime, "||");
453
480
  }
454
481
  const laneList = [...lanes.values()];
455
- // 将 start/stop 形式的范围标记配对,渲染阶段只消费完整区间
456
- const wedges = [];
457
- const activeWedges = new Map();
458
- // wedge 按 part staff voice 和 number 配对,允许多个楔形线并行存在
459
- for (const point of wedgePoints.sort((left, right) => left.at.compare(right.at))) {
460
- const key = `${point.partId}\0${point.staff}\0${point.voice}\0${point.number}`;
461
- if (point.type === "stop") {
462
- const from = activeWedges.get(key);
463
- if (from)
464
- wedges.push({ from, end: point.at });
465
- activeWedges.delete(key);
466
- }
467
- else
468
- activeWedges.set(key, point);
469
- }
470
- const endings = [];
471
- let activeEnding;
472
- // ending 沿全谱时间顺序配对,起点持有适用遍数
473
- for (const point of [...endingPoints.values()].sort((left, right) => left.at.compare(right.at))) {
474
- if (point.type === "start")
475
- activeEnding = point;
476
- else if (activeEnding) {
477
- endings.push({ from: activeEnding, end: point.at });
478
- activeEnding = undefined;
479
- }
480
- }
482
+ const { wedges, endings } = resolveRelations(wedgePoints, [...endingPoints.values()], diagnostics);
481
483
  // 只有房子没有音符时也要保留一条 lane 承载生成的端点
482
484
  if (endings.length > 0 && laneList.length === 0 && controlPartId !== undefined) {
483
485
  laneList.push({
@@ -488,84 +490,10 @@ function parseScore(root) {
488
490
  events: [],
489
491
  });
490
492
  }
491
- const topLane = laneList[0];
492
- // 为没有真实起音的房子补休止端点,保证 volta 始终能绑定可见事件
493
- if (topLane)
494
- for (const ending of endings) {
495
- if (ending.from.at.compare(ending.end) >= 0)
496
- continue;
497
- const direction = directions.find(item => item.at.compare(ending.from.at) >= 0
498
- && item.at.compare(ending.end) < 0);
499
- const hostPartId = direction?.partId ?? topLane.partId;
500
- const hostStaff = direction?.staff ?? topLane.staff;
501
- const hostLanes = laneList.filter(lane => lane.partId === hostPartId && lane.staff === hostStaff);
502
- const hasEndpoint = hostLanes.some(lane => lane.events.some(event => event.start.compare(ending.from.at) >= 0 && event.start.compare(ending.end) < 0));
503
- if (!hasEndpoint) {
504
- // 空房子需要一个不可冲突的休止事件作为 volta 标签端点
505
- let hostLane = hostLanes.find(lane => !lane.events.some(event => event.start.compare(ending.end) < 0
506
- && add(event.start, event.duration).compare(ending.from.at) > 0));
507
- if (!hostLane) {
508
- const voices = hostLanes.map(lane => Number(lane.voice)).filter(Number.isFinite);
509
- hostLane = {
510
- partId: hostPartId,
511
- partName: partNames.get(hostPartId) ?? hostPartId,
512
- staff: hostStaff,
513
- voice: String(Math.max(0, ...voices) + 1),
514
- events: [],
515
- };
516
- laneList.push(hostLane);
517
- }
518
- hostLane.events.push({
519
- start: ending.from.at.clone(),
520
- duration: ending.end.clone().sub(ending.from.at),
521
- pitches: [],
522
- rest: true,
523
- order: order++,
524
- modifiers: [],
525
- annotations: [],
526
- preGraces: [],
527
- postGraces: [],
528
- lyrics: new Map(),
529
- });
530
- hostLane.events.sort((left, right) => left.start.compare(right.start) || left.order - right.order);
531
- }
532
- }
533
- // direction 没有明确 voice 时作用于同 staff 的所有 lane;文字只显示一次
534
- for (const direction of directions) {
535
- const candidates = laneList.filter(lane => lane.partId === direction.partId && lane.staff === direction.staff
536
- && (!direction.voice || lane.voice === direction.voice));
537
- const targets = candidates.length > 0
538
- ? candidates
539
- : laneList.filter(item => item.partId === direction.partId).slice(0, 1);
540
- for (const lane of targets) {
541
- const contained = lane.events.find(item => item.start.compare(direction.at) <= 0
542
- && add(item.start, item.duration).compare(direction.at) > 0);
543
- let event = contained ?? lane.events.find(item => item.start.compare(direction.at) >= 0);
544
- if (!event)
545
- event = lane.events.at(-1);
546
- if (event && direction.dynamic)
547
- event.modifiers.push({ name: direction.dynamic, placement: direction.placement });
548
- }
549
- if (direction.texts.length > 0) {
550
- const events = targets.flatMap(lane => lane.events);
551
- const textTarget = events.find(event => event.start.compare(direction.at) < 0
552
- && add(event.start, event.duration).compare(direction.at) > 0)
553
- ?? events.filter(event => event.start.compare(direction.at) >= 0)
554
- .sort((left, right) => left.start.compare(right.start) || left.order - right.order)[0]
555
- ?? events.at(-1);
556
- textTarget?.annotations.push(...direction.texts.map(text => ({
557
- ...text,
558
- placement: direction.placement,
559
- })));
560
- }
561
- }
562
493
  // 输出顺序保持原 part 次序,再按 staff 和 voice 排列
563
494
  return {
564
- title,
565
- subtitle,
566
- creator,
567
- page,
568
- lanes: laneList.sort((left, right) => partOrder.get(left.partId) - partOrder.get(right.partId)
495
+ ...metadata,
496
+ lanes: resolveVoices(laneList, endings, directions, order, partNames, diagnostics).sort((left, right) => partOrder.get(left.partId) - partOrder.get(right.partId)
569
497
  || Number(left.staff) - Number(right.staff)
570
498
  || Number(left.voice) - Number(right.voice)),
571
499
  meters: [...meters.values()].sort((left, right) => left.at.compare(right.at)),
@@ -635,7 +563,7 @@ function pitchSource(pitch, mode, key, metadata, suffix = "") {
635
563
  return renderPitch({ name, accidental, octave }, mode, suffix) + (label ? `@${label}` : "");
636
564
  }
637
565
  /** 把和弦、倚音、力度和文字组合成一个 jpFun 原子表达式 */
638
- function eventSource(event, mode, key, metadata, suffix = "") {
566
+ function eventSource(event, mode, key, metadata, diagnostics, suffix = "") {
639
567
  let source;
640
568
  if (event.rest || event.pitches.length === 0)
641
569
  source = `0${suffix}`;
@@ -643,10 +571,14 @@ function eventSource(event, mode, key, metadata, suffix = "") {
643
571
  source = pitchSource(event.pitches[0], mode, key, metadata, suffix);
644
572
  else
645
573
  source = `{${event.pitches.map((pitch, index) => pitchSource(pitch, mode, key, metadata, index === 0 ? suffix : "")).join(" ^ ")}}`;
646
- if (event.arpeggio && event.pitches.length >= 2) {
647
- source = event.arpeggio === "none"
648
- ? `@arp(${source})`
649
- : `@arp(${source}, direction=${event.arpeggio})`;
574
+ if (event.arpeggio) {
575
+ if (event.pitches.length >= 2) {
576
+ source = event.arpeggio.direction === "none"
577
+ ? `@arp(${source})`
578
+ : `@arp(${source}, direction=${event.arpeggio.direction})`;
579
+ }
580
+ else
581
+ reportDiagnostic(diagnostics, "arpeggioOutput", event.arpeggio.location);
650
582
  }
651
583
  const graceSource = (groups) => groups.map(group => group.length === 1
652
584
  ? pitchSource(group[0], mode, key, metadata)
@@ -670,6 +602,14 @@ function eventSource(event, mode, key, metadata, suffix = "") {
670
602
  function powerOfTwo(value) {
671
603
  return value > 0 && Number.isInteger(Math.log2(value));
672
604
  }
605
+ function attachAdjustment(source, adjustment) {
606
+ source = attachAbove(source, adjustment?.sources ?? []);
607
+ for (const below of adjustment?.below ?? [])
608
+ source = `{${source} _ ${below}}`;
609
+ if (adjustment)
610
+ adjustment.pendingLocations.length = 0;
611
+ return source;
612
+ }
673
613
  function addDivisions(source, power) {
674
614
  const divisions = "/".repeat(power);
675
615
  // 标签必须留在减时线之后,否则词法层会把斜线吞进标签名
@@ -706,7 +646,8 @@ function durationSource(head, continuation, duration) {
706
646
  throw new RangeError(`MusicXML duration ${duration} requires a tuplet that jpFun cannot infer`);
707
647
  }
708
648
  const result = [];
709
- for (const [index, { fractionPower, dots }] of durationParts(duration).entries()) {
649
+ const parts = durationParts(duration);
650
+ for (const [index, { fractionPower, dots }] of parts.entries()) {
710
651
  const first = index === 0;
711
652
  const suffix = `${"/".repeat(Math.max(0, fractionPower))}${".".repeat(dots)}`;
712
653
  const renderedWithSuffix = first && typeof head === "function";
@@ -726,21 +667,19 @@ function durationSource(head, continuation, duration) {
726
667
  }
727
668
  result.push(source);
728
669
  }
729
- return result.join(" ");
730
- }
731
- function restSlotCount(duration) {
732
- if (!powerOfTwo(duration.denominator))
733
- return 0;
734
- return durationParts(duration).reduce((count, part) => count + (part.fractionPower < 0 ? 2 ** -part.fractionPower : 1), 0);
670
+ const tail = parts.at(-1);
671
+ const tailDuration = tail.fractionPower < 0 ? new Fraction(1)
672
+ : new Fraction(2 ** (tail.dots + 1) - 1, 2 ** (tail.fractionPower + tail.dots));
673
+ return { source: result.join(" "), tailDuration, slotCount: result.length };
735
674
  }
736
675
  /**
737
676
  * 将 lane 事件变成不可再切分的 RenderBlock。
738
677
  * 普通事件一对一成块;连续 time-modification 事件先恢复书面时值,
739
678
  * 再整体输出 @tuplet,保留跨小节组内的小节线。
740
679
  */
741
- function renderBlocks(lane, pitchMode, score, keys, adjustments, programs, metadata) {
680
+ function renderBlocks(lane, pitchMode, score, keys, adjustments, programs, metadata, diagnostics) {
742
681
  const blocks = [];
743
- const adjustmentPoints = [...adjustments?.values() ?? []]
682
+ const adjustmentPoints = [...adjustments.values()]
744
683
  .sort((left, right) => left.at.compare(right.at));
745
684
  for (let index = 0; index < lane.events.length;) {
746
685
  const event = lane.events[index];
@@ -782,6 +721,7 @@ function renderBlocks(lane, pitchMode, score, keys, adjustments, programs, metad
782
721
  ];
783
722
  return points.slice(0, -1).map((at, index) => ({
784
723
  at,
724
+ end: points[index + 1],
785
725
  duration: points[index + 1].clone().sub(at)
786
726
  .mul(modification.actual, modification.normal),
787
727
  }));
@@ -809,14 +749,16 @@ function renderBlocks(lane, pitchMode, score, keys, adjustments, programs, metad
809
749
  }
810
750
  const continuation = item.rest ? "0" : "-";
811
751
  let slotCount = item.rest ? 0 : 1;
812
- for (const [pointIndex, { at, duration }] of slices[groupIndex].entries()) {
813
- const changes = adjustments?.get(keyOf(at))?.sources ?? [];
814
- const head = pointIndex === 0 || changes.length > 0
815
- ? (suffix) => attachAbove(pointIndex === 0 ? eventSource(item, pitchMode, key, metadata, suffix) : `${continuation}${suffix}`, changes)
752
+ for (const [pointIndex, { at, end, duration }] of slices[groupIndex].entries()) {
753
+ const changes = adjustments.get(keyOf(at));
754
+ const head = pointIndex === 0 || changes
755
+ ? (suffix) => attachAdjustment(pointIndex === 0 ? eventSource(item, pitchMode, key, metadata, diagnostics, suffix) : `${continuation}${suffix}`, changes)
816
756
  : continuation;
817
- prefix.push(durationSource(head, continuation, duration));
757
+ const fragment = durationSource(head, continuation, duration);
758
+ fragment.tailDuration.mul(modification.normal, modification.actual);
759
+ prefix.push(metadata.labelEnding(fragment, end));
818
760
  if (item.rest)
819
- slotCount += restSlotCount(duration);
761
+ slotCount += fragment.slotCount;
820
762
  }
821
763
  lyricEvents.push({ event: item, slotCount });
822
764
  prefix.push(...metadata.afterSources.get(item) ?? []);
@@ -836,19 +778,32 @@ function renderBlocks(lane, pitchMode, score, keys, adjustments, programs, metad
836
778
  * 为 tie、wedge 和 ending 找到实际音符端点,并生成稳定标签。
837
779
  * tie 紧跟它的 stop 事件;dyn/volta 是完整区间关系,放在文档末尾。
838
780
  */
839
- function labelRelations(score) {
781
+ function labelRelations(score, diagnostics) {
840
782
  let labelIndex = 0;
841
783
  const relations = [];
784
+ const endingLabels = new Map();
842
785
  const metadata = {
843
786
  labels: new Map(),
844
787
  afterSources: new Map(),
788
+ labelEnding({ source, tailDuration }, end) {
789
+ const endpoint = endingLabels.get(keyOf(end));
790
+ if (!endpoint)
791
+ return source;
792
+ const at = end.clone().sub(tailDuration);
793
+ if (at.compare(endpoint.at) <= 0)
794
+ return source;
795
+ endpoint.at = at;
796
+ endpoint.label = `mx${labelIndex++}`;
797
+ return `${source}@${endpoint.label}`;
798
+ },
845
799
  };
846
- const pitchLabel = (pitch) => {
847
- const label = metadata.labels.get(pitch) ?? `mx${labelIndex++}`;
848
- metadata.labels.set(pitch, label);
800
+ const labelOf = (target) => {
801
+ const label = metadata.labels.get(target) ?? `mx${labelIndex++}`;
802
+ metadata.labels.set(target, label);
849
803
  return label;
850
804
  };
851
805
  const active = new Map();
806
+ const unmatchedTies = new Set();
852
807
  const endingActive = new Map();
853
808
  const endings = [...score.endings].sort((left, right) => left.from.at.compare(right.from.at));
854
809
  // 房子内维护独立 tie 状态,避免某一遍的端点污染房子外的主时间流
@@ -874,30 +829,33 @@ function labelRelations(score) {
874
829
  const key = `${lane.partId}\0${lane.staff}\0${lane.voice}\0${pitch.step}\0${pitch.alter}\0${pitch.octave}`;
875
830
  const previous = localActive.get(key) ?? (ending ? active.get(key) : undefined);
876
831
  if (pitch.tieStop && previous) {
832
+ unmatchedTies.delete(previous);
877
833
  const after = metadata.afterSources.get(event) ?? [];
878
- after.push(`@tie(${pitchLabel(previous)}, ${pitchLabel(pitch)})`);
834
+ after.push(`@tie(${labelOf(previous)}, ${labelOf(pitch)})`);
879
835
  metadata.afterSources.set(event, after);
880
836
  }
881
- if (pitch.tieStart)
837
+ else if (pitch.tieStop) {
838
+ reportDiagnostic(diagnostics, "tieStart", pitch.location);
839
+ }
840
+ if (pitch.tieStart) {
882
841
  localActive.set(key, pitch);
842
+ unmatchedTies.add(pitch);
843
+ }
883
844
  else if (pitch.tieStop)
884
845
  localActive.delete(key);
885
846
  }
886
847
  }
887
848
  }
888
- const eventLabel = (event) => {
889
- if (event.pitches.length === 1)
890
- return pitchLabel(event.pitches[0]);
891
- const label = metadata.labels.get(event) ?? `mx${labelIndex++}`;
892
- metadata.labels.set(event, label);
893
- return label;
894
- };
849
+ for (const pitch of unmatchedTies)
850
+ reportDiagnostic(diagnostics, "tieStop", pitch.location);
851
+ const eventLabel = (event) => labelOf(event.pitches.length === 1 ? event.pitches[0] : event);
895
852
  for (const wedge of score.wedges) {
896
853
  // 连续楔形区间落到实际起音端点后再输出离散的 dyn 关系
897
- const lanes = score.lanes.filter(item => item.partId === wedge.from.partId && item.staff === wedge.from.staff
898
- && (!wedge.from.voice || item.voice === wedge.from.voice));
899
- const targets = lanes.length > 0 ? lanes : score.lanes.filter(item => item.partId === wedge.from.partId).slice(0, 1);
854
+ const targets = matchingLanes(score.lanes, wedge.from.location);
855
+ if (targets.length === 0)
856
+ reportDiagnostic(diagnostics, "wedgeVoice", wedge.from.location);
900
857
  for (const lane of targets) {
858
+ const location = { ...wedge.from.location, staff: lane.staff, voice: lane.voice };
901
859
  const sounding = lane.events.filter(event => !event.rest && event.pitches.length > 0);
902
860
  const from = sounding.find(event => event.start.compare(wedge.from.at) <= 0
903
861
  && add(event.start, event.duration).compare(wedge.from.at) > 0)
@@ -908,10 +866,14 @@ function labelRelations(score) {
908
866
  break;
909
867
  to = event;
910
868
  }
911
- if (!from || !to || from.start.compare(to.start) >= 0)
869
+ if (!from || !to || from.start.compare(to.start) >= 0) {
870
+ reportDiagnostic(diagnostics, "wedgeEndpoints", location);
912
871
  continue;
872
+ }
913
873
  const delta = wedge.from.type === "crescendo" ? 24 : -24;
914
- relations.push(`@dyn(${eventLabel(from)}, ${eventLabel(to)}, ${delta})`);
874
+ reportDiagnostic(diagnostics, "wedge", location, delta);
875
+ const source = `@dyn(${eventLabel(from)}, ${eventLabel(to)}, ${delta})`;
876
+ relations.push(() => source);
915
877
  }
916
878
  }
917
879
  const events = score.lanes.flatMap(lane => lane.events)
@@ -919,16 +881,21 @@ function labelRelations(score) {
919
881
  for (const ending of endings) {
920
882
  const fromIndex = lowerBoundAt(events, ending.from.at, event => event.start);
921
883
  const toIndex = lowerBoundAt(events, ending.end, event => event.start);
922
- if (fromIndex >= toIndex)
884
+ if (fromIndex >= toIndex) {
885
+ reportDiagnostic(diagnostics, "endingEndpoints", ending.from.location);
923
886
  continue;
887
+ }
924
888
  const from = events[fromIndex];
925
889
  const to = events[toIndex - 1];
926
- relations.push(`@volta(${eventLabel(from)}, ${eventLabel(to)}, ${ending.from.passes.join(", ")})`);
890
+ const fromLabel = eventLabel(from);
891
+ const endpoint = endingLabels.get(keyOf(ending.end)) ?? { at: to.start, label: eventLabel(to) };
892
+ endingLabels.set(keyOf(ending.end), endpoint);
893
+ relations.push(() => `@volta(${fromLabel}, ${endpoint.label}, ${ending.from.passes.join(", ")})`);
927
894
  }
928
895
  return { relations, metadata };
929
896
  }
930
897
  /** 将完整 ParsedScore 序列化为 jpFun 源码 */
931
- function renderScore(score, options) {
898
+ function renderScore(score, options, diagnostics) {
932
899
  const pitchMode = options.pitchMode ?? "absolute";
933
900
  if (pitchMode !== "relative" && pitchMode !== "absolute")
934
901
  throw new TypeError("pitchMode must be relative or absolute");
@@ -947,18 +914,30 @@ function renderScore(score, options) {
947
914
  : score.tempos;
948
915
  // 初始状态进入 head;中途状态作为精确时间点只写在最上方 lane
949
916
  const scoreAdjustments = new Map();
950
- const addAdjustment = (at, source) => {
917
+ const addAdjustment = (adjustments, at, source, location, placement = "above") => {
951
918
  const key = keyOf(at);
952
- const point = scoreAdjustments.get(key) ?? { at, sources: [] };
953
- point.sources.push(source);
954
- scoreAdjustments.set(key, point);
919
+ const point = adjustments.get(key) ?? { at, sources: [], pendingLocations: [] };
920
+ if (placement === "below")
921
+ (point.below ??= []).push(source);
922
+ else
923
+ point.sources.push(source);
924
+ if (location)
925
+ point.pendingLocations.push(location);
926
+ adjustments.set(key, point);
955
927
  };
956
928
  for (const item of keys.slice(1))
957
- addAdjustment(item.at, `@1(${tonicName(item)}4)`);
929
+ addAdjustment(scoreAdjustments, item.at, `@1(${tonicName(item)}4)`);
958
930
  for (const item of meters.slice(1))
959
- addAdjustment(item.at, `@meter(${item.numerator}, ${item.denominator})`);
931
+ addAdjustment(scoreAdjustments, item.at, `@meter(${item.numerator}, ${item.denominator})`);
960
932
  for (const item of tempos.slice(1))
961
- addAdjustment(item.at, `@tempo(${item.bpm})`);
933
+ addAdjustment(scoreAdjustments, item.at, `@tempo(${item.bpm})`, item.location);
934
+ const adjustmentsByLane = score.lanes.map((lane, index) => {
935
+ const adjustments = index === 0 ? scoreAdjustments : new Map();
936
+ for (const dynamic of lane.dynamics ?? []) {
937
+ addAdjustment(adjustments, dynamic.at, `$${dynamic.name}`, dynamic.location, dynamic.placement);
938
+ }
939
+ return adjustments;
940
+ });
962
941
  // 每条 lane 只记录 program 真正变化的起点
963
942
  const programsByLane = score.lanes.map(lane => {
964
943
  const programs = new Map();
@@ -972,7 +951,7 @@ function renderScore(score, options) {
972
951
  return programs;
973
952
  });
974
953
  // 关系先分配标签,随后 eventSource 才能把标签写进正确音符
975
- const { relations, metadata } = labelRelations(score);
954
+ const { relations, metadata } = labelRelations(score, diagnostics);
976
955
  const barTimes = [...score.bars.keys()].map(fractionFromKey)
977
956
  .sort((left, right) => left.compare(right));
978
957
  const measureBars = [...score.measureBoundaries].map(fractionFromKey)
@@ -986,14 +965,11 @@ function renderScore(score, options) {
986
965
  }
987
966
  }
988
967
  }
989
- const initialKey = keys[0];
990
- const initialMeter = meters[0];
991
- const initialTempo = tempos[0];
992
968
  const page = score.page
993
969
  ? `@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`
994
970
  : "";
995
971
  // 明确的 MusicXML 换行优先;若会切开 tuplet,则丢弃该断点以保持时值组完整
996
- const blocksByLane = score.lanes.map((lane, index) => renderBlocks(lane, pitchMode, score, keys, index === 0 ? scoreAdjustments : undefined, programsByLane[index], metadata));
972
+ const blocksByLane = score.lanes.map((lane, index) => renderBlocks(lane, pitchMode, score, keys, adjustmentsByLane[index], programsByLane[index], metadata, diagnostics));
997
973
  const tupletSpans = blocksByLane.flatMap(blocks => blocks
998
974
  .filter(block => block.source)
999
975
  .map(block => ({ start: block.start, end: block.end })))
@@ -1045,11 +1021,10 @@ function renderScore(score, options) {
1045
1021
  points.set(keyOf(at), at);
1046
1022
  for (const [value, at] of lineBreaks)
1047
1023
  points.set(value, at);
1048
- if (laneIndex === 0) {
1049
- for (const [value, point] of scoreAdjustments) {
1050
- if (!insideSpan(tupletBlocks, point.at))
1051
- points.set(value, point.at);
1052
- }
1024
+ const adjustments = adjustmentsByLane[laneIndex];
1025
+ for (const [value, point] of adjustments) {
1026
+ if (!insideSpan(tupletBlocks, point.at))
1027
+ points.set(value, point.at);
1053
1028
  }
1054
1029
  const timeline = [...points.values()].sort((left, right) => left.compare(right));
1055
1030
  let blockIndex = 0;
@@ -1071,7 +1046,7 @@ function renderScore(score, options) {
1071
1046
  const duration = next.clone().sub(at);
1072
1047
  if (duration.isZero())
1073
1048
  continue;
1074
- const changes = laneIndex === 0 ? scoreAdjustments.get(keyOf(at))?.sources ?? [] : [];
1049
+ const changes = adjustments.get(keyOf(at));
1075
1050
  const block = blocks[blockIndex];
1076
1051
  if (block?.source) {
1077
1052
  if (!block.start.equals(at) || !block.end.equals(next)) {
@@ -1092,23 +1067,25 @@ function renderScore(score, options) {
1092
1067
  const key = pointAt(keys, event.start);
1093
1068
  const continuation = event.rest ? "0" : "-";
1094
1069
  // 中途状态挂到 continuation,起音片段则重新生成完整事件源码
1095
- const head = start || changes.length > 0
1096
- ? (suffix) => attachAbove(start ? eventSource(event, pitchMode, key, metadata, suffix) : `${continuation}${suffix}`, changes)
1070
+ const head = start || changes
1071
+ ? (suffix) => attachAdjustment(start ? eventSource(event, pitchMode, key, metadata, diagnostics, suffix) : `${continuation}${suffix}`, changes)
1097
1072
  : continuation;
1098
- outputs.at(-1).push(durationSource(head, continuation, duration));
1073
+ const fragment = durationSource(head, continuation, duration);
1074
+ outputs.at(-1).push(metadata.labelEnding(fragment, next));
1099
1075
  if (start)
1100
1076
  outputs.at(-1).push(...metadata.afterSources.get(event) ?? []);
1101
1077
  if (event.rest)
1102
- addLyricSlots(start ? event : undefined, restSlotCount(duration));
1078
+ addLyricSlots(start ? event : undefined, fragment.slotCount);
1103
1079
  else if (start)
1104
1080
  addLyricSlots(event, 1);
1105
1081
  }
1106
1082
  else {
1107
- const head = changes.length > 0
1108
- ? (suffix) => attachAbove(`0${suffix}`, changes)
1083
+ const head = changes
1084
+ ? (suffix) => attachAdjustment(`0${suffix}`, changes)
1109
1085
  : "0";
1110
- outputs.at(-1).push(durationSource(head, "0", duration));
1111
- addLyricSlots(undefined, restSlotCount(duration));
1086
+ const fragment = durationSource(head, "0", duration);
1087
+ outputs.at(-1).push(metadata.labelEnding(fragment, next));
1088
+ addLyricSlots(undefined, fragment.slotCount);
1112
1089
  }
1113
1090
  }
1114
1091
  const partName = lane.partName && (!score.lanes[laneIndex - 1] || score.lanes[laneIndex - 1].partId !== lane.partId)
@@ -1121,20 +1098,31 @@ function renderScore(score, options) {
1121
1098
  return `N${name}: { ${output.join(" ")} }${lyricLines ? `\n${lyricLines}` : ""}`;
1122
1099
  });
1123
1100
  });
1101
+ const omitted = new Set();
1102
+ for (const adjustments of [scoreAdjustments, ...adjustmentsByLane]) {
1103
+ for (const point of adjustments.values()) {
1104
+ for (const location of point.pendingLocations)
1105
+ omitted.add(location);
1106
+ }
1107
+ }
1108
+ for (const location of omitted)
1109
+ reportDiagnostic(diagnostics, "directionOutput", location);
1124
1110
  const head = renderHead({
1125
1111
  title: score.title,
1126
1112
  subtitle: score.subtitle,
1127
1113
  author: score.creator,
1128
- key: `${tonicName(initialKey)}4`,
1129
- meter: [initialMeter.numerator, initialMeter.denominator],
1130
- tempo: initialTempo.bpm,
1114
+ key: `${tonicName(keys[0])}4`,
1115
+ meter: [meters[0].numerator, meters[0].denominator],
1116
+ tempo: tempos[0].bpm,
1131
1117
  });
1132
1118
  const body = renderSystems(voices);
1133
- return `${page}${head}\n\n${body}${relations.length > 0 ? `\n${relations.join(" ")}` : ""}`;
1119
+ return `${page}${head}\n\n${body}${relations.length > 0 ? `\n${relations.map(source => source()).join(" ")}` : ""}`;
1134
1120
  }
1135
- /** 将解析好的 MusicXML 根元素同步转换为可重新解析的 jpFun 源码 */
1121
+ /** 将解析好的 MusicXML 根元素同步转换为 jpFun 源码,并报告未保留或近似转换的语义 */
1136
1122
  export function musicXmlToJpFun(root, options = {}) {
1137
1123
  if (!root || root.nodeType !== 1)
1138
1124
  throw new TypeError("MusicXML root must be an element");
1139
- return renderScore(parseScore(root), options);
1125
+ const diagnostics = [];
1126
+ const script = renderScore(parseScore(root, diagnostics), options, diagnostics);
1127
+ return { script, diagnostics };
1140
1128
  }