jpfun 0.8.0 → 1.0.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 (140) hide show
  1. package/README.md +10 -15
  2. package/dist/diagnostic.d.ts +29 -2
  3. package/dist/diagnostic.js +5 -4
  4. package/dist/functions/ASTtypes.d.ts +1 -14
  5. package/dist/functions/ASTtypes.js +5 -36
  6. package/dist/functions/adjust/index.js +45 -33
  7. package/dist/functions/arpeggio/index.js +44 -48
  8. package/dist/functions/arpeggio/shape.d.ts +2 -3
  9. package/dist/functions/arpeggio/shape.js +20 -50
  10. package/dist/functions/bar/index.d.ts +3 -0
  11. package/dist/functions/bar/index.js +21 -11
  12. package/dist/functions/beam/auto.js +54 -123
  13. package/dist/functions/beam/index.js +4 -9
  14. package/dist/functions/beam/layout.js +3 -2
  15. package/dist/functions/box/index.js +1 -6
  16. package/dist/functions/dash/index.js +6 -4
  17. package/dist/functions/div/index.d.ts +3 -5
  18. package/dist/functions/div/index.js +14 -12
  19. package/dist/functions/dot/index.js +3 -9
  20. package/dist/functions/dyn/index.js +7 -26
  21. package/dist/functions/gliss/index.js +99 -91
  22. package/dist/functions/grace/index.d.ts +2 -5
  23. package/dist/functions/grace/index.js +47 -94
  24. package/dist/functions/head/index.js +32 -36
  25. package/dist/functions/key/index.js +9 -12
  26. package/dist/functions/meter/index.d.ts +1 -0
  27. package/dist/functions/meter/index.js +6 -3
  28. package/dist/functions/meter/shape.d.ts +1 -1
  29. package/dist/functions/note/accidentals.d.ts +3 -3
  30. package/dist/functions/note/accidentals.js +29 -16
  31. package/dist/functions/note/index.js +12 -14
  32. package/dist/functions/note/source-transform.d.ts +15 -0
  33. package/dist/functions/note/source-transform.js +75 -71
  34. package/dist/functions/ottava/index.js +12 -32
  35. package/dist/functions/page/index.js +15 -17
  36. package/dist/functions/rest/index.js +10 -10
  37. package/dist/functions/slide/index.js +1 -1
  38. package/dist/functions/stack/index.js +8 -57
  39. package/dist/functions/temporal.d.ts +11 -5
  40. package/dist/functions/temporal.js +22 -2
  41. package/dist/functions/text/index.js +24 -30
  42. package/dist/functions/tie/index.js +42 -41
  43. package/dist/functions/tremolo/index.js +1 -1
  44. package/dist/functions/tuplet/index.js +1 -6
  45. package/dist/functions/up/index.js +82 -88
  46. package/dist/functions/voice/connections.d.ts +3 -2
  47. package/dist/functions/voice/connections.js +48 -10
  48. package/dist/functions/voice/index.d.ts +2 -3
  49. package/dist/functions/voice/index.js +2 -970
  50. package/dist/functions/voice/lyrics.d.ts +34 -0
  51. package/dist/functions/voice/lyrics.js +393 -0
  52. package/dist/functions/voice/voice.d.ts +67 -0
  53. package/dist/functions/voice/voice.js +405 -0
  54. package/dist/functions/voice/voices.d.ts +106 -0
  55. package/dist/functions/voice/voices.js +424 -0
  56. package/dist/functions/volta/index.js +6 -23
  57. package/dist/index.d.ts +97 -3
  58. package/dist/index.js +97 -3
  59. package/dist/jpfun.min.js +63 -67
  60. package/dist/layout/engine.d.ts +4 -3
  61. package/dist/layout/engine.js +190 -24
  62. package/dist/layout/model.d.ts +12 -4
  63. package/dist/layout/model.js +16 -11
  64. package/dist/layout/page.d.ts +2 -1
  65. package/dist/layout/page.js +15 -15
  66. package/dist/layout/path.js +1 -1
  67. package/dist/layout/range.d.ts +7 -6
  68. package/dist/layout/range.js +23 -14
  69. package/dist/layout/types.d.ts +19 -30
  70. package/dist/lowering/loweringContext.d.ts +8 -11
  71. package/dist/lowering/loweringContext.js +7 -13
  72. package/dist/lowering/track.d.ts +8 -1
  73. package/dist/lowering/types.d.ts +12 -8
  74. package/dist/parser/grammarType.d.ts +3 -3
  75. package/dist/parser/parse-utils/brace-utils.js +7 -17
  76. package/dist/parser/parse-utils/call-utils.d.ts +4 -3
  77. package/dist/parser/parse-utils/call-utils.js +23 -66
  78. package/dist/parser/parse-utils/note-utils.d.ts +7 -3
  79. package/dist/parser/parse-utils/note-utils.js +25 -40
  80. package/dist/parser/parse-utils/string-utils.d.ts +1 -1
  81. package/dist/parser/parse-utils/string-utils.js +8 -6
  82. package/dist/parser/parserContext.d.ts +17 -11
  83. package/dist/parser/parserContext.js +111 -65
  84. package/dist/parser/preprocess.d.ts +7 -0
  85. package/dist/parser/preprocess.js +21 -19
  86. package/dist/pipeline.d.ts +1 -1
  87. package/dist/pipeline.js +2 -2
  88. package/dist/playback/compile.js +14 -15
  89. package/dist/playback/event.d.ts +6 -6
  90. package/dist/playback/event.js +13 -49
  91. package/dist/render/canvas.d.ts +0 -2
  92. package/dist/render/canvas.js +50 -56
  93. package/dist/render/index.d.ts +1 -1
  94. package/dist/render/index.js +1 -1
  95. package/dist/render/paint.d.ts +7 -0
  96. package/dist/render/paint.js +70 -20
  97. package/dist/render/recording.d.ts +8 -1
  98. package/dist/render/recording.js +12 -0
  99. package/dist/render/svg.d.ts +5 -2
  100. package/dist/render/svg.js +70 -48
  101. package/dist/render/text.d.ts +37 -2
  102. package/dist/render/text.js +136 -1
  103. package/dist/render/translate.d.ts +3 -1
  104. package/dist/render/translate.js +6 -0
  105. package/dist/render/types.d.ts +9 -2
  106. package/grammar.md +18 -14
  107. package/package.json +8 -18
  108. package/dist/converter/midi/convert.d.ts +0 -42
  109. package/dist/converter/midi/convert.js +0 -729
  110. package/dist/converter/midi/index.d.ts +0 -5
  111. package/dist/converter/midi/index.js +0 -11
  112. package/dist/converter/midi/json.d.ts +0 -38
  113. package/dist/converter/midi/json.js +0 -1
  114. package/dist/converter/midi/triplet.d.ts +0 -30
  115. package/dist/converter/midi/triplet.js +0 -75
  116. package/dist/converter/musicxml/dom.d.ts +0 -25
  117. package/dist/converter/musicxml/dom.js +0 -65
  118. package/dist/converter/musicxml/features.d.ts +0 -114
  119. package/dist/converter/musicxml/features.js +0 -501
  120. package/dist/converter/musicxml/index.d.ts +0 -14
  121. package/dist/converter/musicxml/index.js +0 -1295
  122. package/dist/converter/musicxml/model.d.ts +0 -176
  123. package/dist/converter/musicxml/model.js +0 -1
  124. package/dist/converter/musicxml/resolve.d.ts +0 -10
  125. package/dist/converter/musicxml/resolve.js +0 -152
  126. package/dist/converter/source.d.ts +0 -22
  127. package/dist/converter/source.js +0 -51
  128. package/dist/core.d.ts +0 -24
  129. package/dist/core.js +0 -24
  130. package/dist/iife/core.d.ts +0 -1
  131. package/dist/iife/core.js +0 -3
  132. package/dist/iife/from-midi.d.ts +0 -1
  133. package/dist/iife/from-midi.js +0 -15
  134. package/dist/iife/from-musicxml.d.ts +0 -1
  135. package/dist/iife/from-musicxml.js +0 -3
  136. package/dist/iife/full.d.ts +0 -1
  137. package/dist/iife/full.js +0 -3
  138. package/dist/jpfun.core.min.js +0 -123
  139. package/dist/jpfun.from-midi.min.js +0 -9
  140. package/dist/jpfun.from-musicxml.min.js +0 -12
@@ -1,501 +0,0 @@
1
- import { child, children, descendant, descendants, nameOf, number, text, } from "./dom.js";
2
- import { NoteNameMap, SHARP_NOTE_NAMES } from "../../parser/parse-utils/note-utils.js";
3
- const DYNAMIC_NAME = /^(?:p+|f+|mp|mf)$/;
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
- }
26
- const DIAGNOSTICS = {
27
- percussion: ["PERCUSSION_SKIPPED", "MIDI channel 10 percussion note was omitted."],
28
- displayPitch: ["APPROXIMATED", "Unpitched note was converted to a melodic note using its display pitch."],
29
- afterGrace: ["APPROXIMATED", "After-grace note has no preceding event and was treated as a before-grace note."],
30
- wedge: ["APPROXIMATED", "Wedge was mapped to note onsets with a fixed velocity change of {value}."],
31
- unsupported: ["UNSUPPORTED_ELEMENT", "MusicXML <{value}> was omitted."],
32
- gracePitch: ["UNATTACHED_CONTENT", "Grace note without a pitch was omitted."],
33
- graceHost: ["UNATTACHED_CONTENT", "Before-grace note has no following event and was omitted."],
34
- dynamicHost: ["UNATTACHED_CONTENT", "Dynamic {value} has no target voice and was omitted."],
35
- directionOutput: ["UNATTACHED_CONTENT", "Direction mark has no generated output position and was omitted."],
36
- tempoReplaced: ["UNATTACHED_CONTENT", "Tempo {value} was replaced by a different tempo at the same time and was omitted."],
37
- arpeggioOutput: ["UNSUPPORTED_ELEMENT", "Arpeggiate mark requires at least two pitches in one event and was omitted."],
38
- multipleRest: ["APPROXIMATED", "Multiple-rest grouping could not be preserved without discarding musical content; individual rests were retained."],
39
- textHost: ["UNATTACHED_CONTENT", "Text {value} has no target event and was omitted."],
40
- wedgeStart: ["UNRESOLVED_RELATION", "Wedge stop has no matching start and was omitted."],
41
- wedgeReplaced: ["UNRESOLVED_RELATION", "Wedge start was replaced before a matching stop and was omitted."],
42
- wedgeStop: ["UNRESOLVED_RELATION", "Wedge start has no matching stop and was omitted."],
43
- wedgeVoice: ["UNRESOLVED_RELATION", "Wedge has no target voice and was omitted."],
44
- wedgeEndpoints: ["UNRESOLVED_RELATION", "Wedge has no two distinct note onsets to use as endpoints and was omitted."],
45
- endingStart: ["UNRESOLVED_RELATION", "Ending stop has no matching start and was omitted."],
46
- endingReplaced: ["UNRESOLVED_RELATION", "Ending start was replaced before a matching stop and was omitted."],
47
- endingStop: ["UNRESOLVED_RELATION", "Ending start has no matching stop and was omitted."],
48
- endingEndpoints: ["UNRESOLVED_RELATION", "Ending has no event endpoints in its interval and was omitted."],
49
- tieStart: ["UNRESOLVED_RELATION", "Tie stop has no matching start and was omitted."],
50
- tieStop: ["UNRESOLVED_RELATION", "Tie start has no matching stop in any ending branch and was omitted."],
51
- glissStart: ["UNRESOLVED_RELATION", "Glissando stop has no matching start and was omitted."],
52
- glissStop: ["UNRESOLVED_RELATION", "Glissando start has no matching stop and was omitted."],
53
- glissReplaced: ["UNRESOLVED_RELATION", "Glissando start was replaced before a matching stop and was omitted."],
54
- glissEndpoints: ["UNRESOLVED_RELATION", "Glissando endpoints are simultaneous or cross a score line and were omitted."],
55
- glissStyle: ["APPROXIMATED", "MusicXML <{value}> was converted to a straight glissando arrow."],
56
- symbolStyle: ["APPROXIMATED", "MusicXML <{value}> was mapped to the default symbol shape."],
57
- };
58
- export function reportDiagnostic(diagnostics, issue, location, value = "") {
59
- const [kind, message] = DIAGNOSTICS[issue];
60
- diagnostics.push({ code: `W_MUSICXML_${kind}`, severity: "warning",
61
- message: message.replace("{value}", () => String(value)), location });
62
- }
63
- /** 查询不改变覆盖状态;解析结果写入语义模型后显式确认,未确认项按 XML 顺序报告 */
64
- export class MusicXmlReader {
65
- roots;
66
- accepted = [];
67
- constructor(roots) {
68
- this.roots = roots;
69
- }
70
- read(name, deep = false, parent) {
71
- for (const root of parent ? [parent] : this.roots) {
72
- const element = deep ? descendant(root, name) : child(root, name);
73
- if (element)
74
- return element;
75
- }
76
- return undefined;
77
- }
78
- readAll(name, deep = false) {
79
- return this.roots.flatMap(root => deep ? descendants(root, name) : children(root, name));
80
- }
81
- accept(element) {
82
- if (element)
83
- this.accepted.push(element);
84
- }
85
- report(diagnostics, location, parent) {
86
- for (const root of parent ? [parent] : this.roots)
87
- for (const element of children(root)) {
88
- if (this.accepted.includes(element))
89
- continue;
90
- const name = nameOf(element);
91
- reportDiagnostic(diagnostics, "unsupported", { ...location, element: name }, name);
92
- }
93
- }
94
- }
95
- /** 读取上下方位置,非法或缺失值回落到调用方默认值 */
96
- function placementOf(element, fallback) {
97
- const placement = element.getAttribute("placement");
98
- return placement === "above" || placement === "below" ? placement : fallback;
99
- }
100
- /** 将 score-partwise 和 score-timewise 统一为每个 part 的小节序列 */
101
- export function partMeasures(root) {
102
- const result = new Map();
103
- const rootName = nameOf(root);
104
- if (rootName === "score-partwise") {
105
- for (const part of children(root, "part"))
106
- result.set(part.getAttribute("id") ?? "", children(part, "measure").map(measure => ({ body: measure, container: measure })));
107
- return result;
108
- }
109
- if (rootName === "score-timewise") {
110
- for (const measure of children(root, "measure")) {
111
- for (const part of children(measure, "part")) {
112
- const id = part.getAttribute("id") ?? "";
113
- const list = result.get(id) ?? [];
114
- list.push({ body: part, container: measure });
115
- result.set(id, list);
116
- }
117
- }
118
- return result;
119
- }
120
- throw new TypeError(`Unsupported MusicXML root <${rootName}>`);
121
- }
122
- /** 校验 MIDI 乐器字段,并将一基 program 转为内部零基编号 */
123
- export function readInstrument(midi) {
124
- const instrument = {};
125
- if (child(midi, "midi-channel")) {
126
- instrument.channel = number(midi, "midi-channel");
127
- if (!Number.isSafeInteger(instrument.channel) || instrument.channel < 1 || instrument.channel > 16) {
128
- throw new RangeError("MusicXML midi-channel must be an integer in 1..16");
129
- }
130
- }
131
- if (child(midi, "midi-program")) {
132
- instrument.program = number(midi, "midi-program") - 1;
133
- if (!Number.isSafeInteger(instrument.program) || instrument.program < 0 || instrument.program > 127) {
134
- throw new RangeError("MusicXML midi-program must be an integer in 1..128");
135
- }
136
- }
137
- return instrument;
138
- }
139
- /** 文档元数据不参与时间推进;仅完整的页面声明覆盖默认页面 */
140
- export function scoreMetadata(root) {
141
- const credits = children(root, "credit");
142
- const credit = (type) => {
143
- const item = credits.find(value => text(value, "credit-type") === type);
144
- return item ? text(item, "credit-words") : "";
145
- };
146
- const workTitle = text(child(root, "work"), "work-title");
147
- const title = text(root, "movement-title")
148
- || (workTitle !== "Untitled Score" && workTitle !== "未命名乐谱" ? workTitle : "")
149
- || credit("title");
150
- const subtitle = credit("subtitle");
151
- const creator = credit("composer") || (() => {
152
- const identification = child(root, "identification");
153
- const creators = identification ? children(identification, "creator") : [];
154
- return text(creators.find(item => item.getAttribute("type") === "composer") ?? creators[0]);
155
- })();
156
- let page;
157
- const defaults = child(root, "defaults");
158
- const scaling = defaults && child(defaults, "scaling");
159
- const pageLayout = defaults && child(defaults, "page-layout");
160
- if (scaling && pageLayout && child(pageLayout, "page-width") && child(pageLayout, "page-height")) {
161
- const pixelsPerTenth = number(scaling, "millimeters") / number(scaling, "tenths") * 96 / 25.4;
162
- const marginList = children(pageLayout, "page-margins");
163
- const margins = marginList.find(item => item.getAttribute("type") === "odd") ?? marginList[0];
164
- if (Number.isFinite(pixelsPerTenth) && pixelsPerTenth > 0) {
165
- page = {
166
- width: number(pageLayout, "page-width") * pixelsPerTenth,
167
- height: number(pageLayout, "page-height") * pixelsPerTenth,
168
- top: margins ? number(margins, "top-margin", 48 / pixelsPerTenth) * pixelsPerTenth : 48,
169
- bottom: margins ? number(margins, "bottom-margin", 48 / pixelsPerTenth) * pixelsPerTenth : 48,
170
- left: margins ? number(margins, "left-margin", 40 / pixelsPerTenth) * pixelsPerTenth : 40,
171
- right: margins ? number(margins, "right-margin", 40 / pixelsPerTenth) * pixelsPerTenth : 40,
172
- };
173
- }
174
- }
175
- return { title, subtitle, creator, page };
176
- }
177
- /** 解析书面音高及该和弦成员自己的 tie 起止标记 */
178
- export function parsePitch(note, location, notations) {
179
- const tied = notations?.readAll("tied");
180
- const pitched = child(note, "pitch");
181
- const pitch = pitched ?? child(note, "unpitched");
182
- if (!pitch)
183
- return null;
184
- const step = text(pitch, pitched ? "step" : "display-step").toUpperCase();
185
- const alter = pitched ? number(pitch, "alter", 0) : 0;
186
- const octave = number(pitch, pitched ? "octave" : "display-octave");
187
- if (!/^[A-G]$/.test(step) || !Number.isInteger(alter) || !Number.isInteger(octave)) {
188
- throw new RangeError("jpFun requires MusicXML pitches with integer step alterations and octaves");
189
- }
190
- const tieTypes = new Set();
191
- const ties = children(note, "tie");
192
- for (const tie of ties)
193
- tieTypes.add(tie.getAttribute("type") ?? "");
194
- if (tied)
195
- for (const tie of tied) {
196
- const type = tie.getAttribute("type") ?? "";
197
- tieTypes.add(type);
198
- if (type === "start" || type === "stop" || type === "continue")
199
- notations?.accept(tie);
200
- }
201
- return {
202
- location: { ...location, element: ties.length ? "tie" : tied?.length ? "tied" : nameOf(note) },
203
- step,
204
- alter,
205
- octave,
206
- tieStart: tieTypes.has("start") || tieTypes.has("continue"),
207
- tieStop: tieTypes.has("stop") || tieTypes.has("continue"),
208
- };
209
- }
210
- export function transposePitch(pitch, chromatic, diatonic, octaves) {
211
- const midi = (pitch.octave + 1) * 12 + NoteNameMap[pitch.step] + pitch.alter + chromatic + octaves * 12;
212
- if (diatonic === undefined) {
213
- const spelling = SHARP_NOTE_NAMES[((midi % 12) + 12) % 12];
214
- pitch.step = spelling[0];
215
- pitch.alter = spelling.length - 1;
216
- pitch.octave = Math.floor(midi / 12) - 1;
217
- }
218
- else {
219
- const letters = "CDEFGAB";
220
- const degree = pitch.octave * 7 + letters.indexOf(pitch.step) + diatonic + octaves * 7;
221
- pitch.step = letters[((degree % 7) + 7) % 7];
222
- pitch.octave = Math.floor(degree / 7);
223
- pitch.alter = midi - (pitch.octave + 1) * 12 - NoteNameMap[pitch.step];
224
- }
225
- }
226
- /** 将支持的延长、奏法与装饰音记号转成 jpFun 修饰符 */
227
- export function noteModifiers(notations, diagnostics, location) {
228
- const modifiers = [];
229
- const slides = [];
230
- if (!notations)
231
- return { modifiers, slides };
232
- const fermata = notations.read("fermata");
233
- if (fermata) {
234
- modifiers.push({ name: "fermata", placement: placementOf(fermata, fermata.getAttribute("type") === "inverted" ? "below" : "above") });
235
- notations.accept(fermata);
236
- }
237
- const articulations = notations.read("articulations");
238
- if (articulations) {
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
- }
251
- }
252
- for (const [tag, side, direction] of [
253
- ["scoop", "pre", "up"], ["plop", "pre", "down"],
254
- ["doit", "post", "up"], ["falloff", "post", "down"],
255
- ]) {
256
- for (const articulation of children(articulations, tag)) {
257
- slides.push({ side, direction });
258
- notations.accept(articulation);
259
- if (articulation.getAttribute("line-shape") === "curved"
260
- || articulation.getAttribute("line-type") === "wavy") {
261
- reportDiagnostic(diagnostics, "glissStyle", { ...location, element: tag }, tag);
262
- }
263
- }
264
- }
265
- notations.report(diagnostics, location, articulations);
266
- notations.accept(articulations);
267
- }
268
- const ornaments = notations.read("ornaments");
269
- if (ornaments) {
270
- for (const [tag, name] of [
271
- ["trill-mark", "tr"],
272
- ["mordent", "mordent"],
273
- ["inverted-mordent", "prall"],
274
- ["turn", "turn"],
275
- ["inverted-turn", "iturn"],
276
- ]) {
277
- const ornament = notations.read(tag, false, ornaments);
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);
284
- }
285
- }
286
- notations.report(diagnostics, location, ornaments);
287
- notations.accept(ornaments);
288
- }
289
- return { modifiers, slides };
290
- }
291
- /** 双音 slide 与 glissando 均是标签关系;与 articulations 下的单音滑音区别处理 */
292
- export function noteGlissandi(notations, pitch, diagnostics) {
293
- if (!notations || !pitch)
294
- return;
295
- for (const kind of ["slide", "glissando"]) {
296
- for (const element of notations.readAll(kind)) {
297
- const type = element.getAttribute("type");
298
- if (type !== "start" && type !== "stop")
299
- continue;
300
- (pitch.glissandi ??= []).push({ kind, type, number: element.getAttribute("number") || "1" });
301
- notations.accept(element);
302
- if (type === "start" && (kind === "glissando" && element.getAttribute("line-type") !== "solid"
303
- || element.getAttribute("line-type") === "wavy" || text(element))) {
304
- reportDiagnostic(diagnostics, "glissStyle", { ...pitch.location, element: kind }, kind);
305
- }
306
- }
307
- }
308
- }
309
- /** 无箭头不覆盖显式方向,两个相反的显式方向不能属于同一和弦 */
310
- export function mergeArpeggio(current, next) {
311
- if (!next || next.direction === "none")
312
- return current ?? next;
313
- if (current && current.direction !== "none" && current.direction !== next.direction) {
314
- throw new RangeError("Conflicting MusicXML arpeggiate directions in one chord");
315
- }
316
- return next;
317
- }
318
- /** 读取和弦成员上的琶音方向;none 表示无箭头但仍按自下而上演奏 */
319
- export function noteArpeggio(notations, location) {
320
- if (!notations)
321
- return undefined;
322
- let result;
323
- for (const arpeggiate of notations.readAll("arpeggiate")) {
324
- const value = arpeggiate.getAttribute("direction") || "none";
325
- if (value !== "none" && value !== "up" && value !== "down") {
326
- throw new RangeError(`Unsupported MusicXML arpeggiate direction: ${value}`);
327
- }
328
- result = mergeArpeggio(result, { direction: value, location: { ...location, element: "arpeggiate" } });
329
- notations.accept(arpeggiate);
330
- }
331
- return result;
332
- }
333
- /** 解析 tuplet 的实际音数与正常音数,并保留显式组边界 */
334
- export function timeModification(note, tuplets) {
335
- const modification = child(note, "time-modification");
336
- if (!modification)
337
- return undefined;
338
- const actual = number(modification, "actual-notes");
339
- const normal = number(modification, "normal-notes");
340
- if (!Number.isSafeInteger(actual) || actual < 2 || !Number.isSafeInteger(normal) || normal <= 0) {
341
- throw new RangeError("MusicXML time-modification requires positive integer actual-notes and normal-notes");
342
- }
343
- return {
344
- actual,
345
- normal,
346
- start: tuplets?.some(item => item.getAttribute("type") === "start") ?? false,
347
- stop: tuplets?.some(item => item.getAttribute("type") === "stop") ?? false,
348
- };
349
- }
350
- /** 和弦成员可重复声明同一边界;仅确认最终事件确实持有的节奏标记 */
351
- export function acceptTuplets(notations, tuplets, rhythm) {
352
- if (!notations || !tuplets || !rhythm)
353
- return;
354
- for (const tuplet of tuplets) {
355
- const type = tuplet.getAttribute("type");
356
- if ((type === "start" || type === "stop") && rhythm[type])
357
- notations.accept(tuplet);
358
- }
359
- }
360
- /** 按 verse 收集歌词并用尾部连字符保留音节延续 */
361
- export function noteLyrics(note) {
362
- const result = new Map();
363
- for (const lyric of children(note, "lyric")) {
364
- const verse = lyric.getAttribute("number") || lyric.getAttribute("name") || "1";
365
- const words = children(lyric)
366
- .filter(item => ["text", "elision"].includes(nameOf(item)))
367
- .map(item => nameOf(item) === "elision" ? "~" : text(item))
368
- .join("");
369
- const syllabic = text(lyric, "syllabic");
370
- result.set(verse, words && (syllabic === "begin" || syllabic === "middle") ? `${words}-` : words);
371
- }
372
- return result;
373
- }
374
- /** 返回 dynamics 中首个受支持的力度记号 */
375
- export function directionDynamic(dynamics, diagnostics, location) {
376
- if (!dynamics)
377
- return undefined;
378
- let dynamic;
379
- for (const element of children(dynamics)) {
380
- const name = nameOf(element);
381
- if (!dynamic && DYNAMIC_NAME.test(name))
382
- dynamic = name;
383
- else
384
- reportDiagnostic(diagnostics, "unsupported", { ...location, element: name }, name);
385
- }
386
- return dynamic;
387
- }
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
- }
402
- for (const name of ["rehearsal", "words"]) {
403
- for (const node of direction.readAll(name, true)) {
404
- const value = node.textContent?.trim();
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
- }
418
- direction.accept(node);
419
- }
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
- }
434
- return result;
435
- }
436
- /** 将 metronome 的拍单位和附点折算成四分音符 BPM */
437
- export function metronomeBpm(metronome) {
438
- if (!metronome)
439
- return undefined;
440
- const perMinute = Number(text(metronome, "per-minute"));
441
- const unit = text(metronome, "beat-unit");
442
- const quarterLengths = {
443
- maxima: 32, long: 16, breve: 8, whole: 4, half: 2, quarter: 1,
444
- eighth: 0.5, "16th": 0.25, "32nd": 0.125, "64th": 0.0625,
445
- "128th": 0.03125, "256th": 0.015625, "512th": 0.0078125, "1024th": 0.00390625,
446
- };
447
- let length = quarterLengths[unit];
448
- if (!Number.isFinite(perMinute) || length === undefined)
449
- return undefined;
450
- let addition = length / 2;
451
- for (const _dot of children(metronome, "beat-unit-dot")) {
452
- length += addition;
453
- addition /= 2;
454
- }
455
- return perMinute * length;
456
- }
457
- /** 将单一或复合拍号归一成一个等值分数 */
458
- export function parseTimeSignature(time) {
459
- const pairs = [];
460
- let beats;
461
- // beats 与紧随其后的 beat-type 组成一组,多个组表示复合拍号
462
- for (const item of children(time)) {
463
- const tag = nameOf(item);
464
- if (tag === "beats") {
465
- beats = text(item).split("+").reduce((sum, value) => sum + Number(value), 0);
466
- }
467
- else if (tag === "beat-type" && beats !== undefined) {
468
- pairs.push({ beats, beatType: Number(text(item)) });
469
- beats = undefined;
470
- }
471
- }
472
- if (pairs.length === 0 || pairs.some(pair => !Number.isSafeInteger(pair.beats) || pair.beats <= 0
473
- || !Number.isSafeInteger(pair.beatType) || pair.beatType <= 0)) {
474
- throw new RangeError("MusicXML time signature must contain positive integer beats/beat-type pairs");
475
- }
476
- const gcd = (left, right) => right === 0 ? left : gcd(right, left % right);
477
- const denominator = pairs.reduce((result, pair) => result / gcd(result, pair.beatType) * pair.beatType, 1);
478
- const numerator = pairs.reduce((sum, pair) => sum + pair.beats * denominator / pair.beatType, 0);
479
- if (!Number.isSafeInteger(numerator) || !Number.isSafeInteger(denominator)) {
480
- throw new RangeError("MusicXML time signature exceeds the supported integer range");
481
- }
482
- return { numerator, denominator };
483
- }
484
- /** 展开逗号分隔的遍数与闭区间范围,并返回升序去重结果 */
485
- export function endingPasses(value) {
486
- const result = new Set();
487
- for (const part of value.split(/\s*,\s*/)) {
488
- const match = part.match(/^(\d+)(?:\s*-\s*(\d+))?$/);
489
- if (!match)
490
- throw new RangeError("MusicXML ending number must contain positive integers or ascending ranges");
491
- const from = Number(match[1]);
492
- const to = Number(match[2] ?? match[1]);
493
- if (!Number.isSafeInteger(from) || !Number.isSafeInteger(to)
494
- || from < 1 || to < from || to > MAX_ENDING_PASS) {
495
- throw new RangeError(`MusicXML ending passes must be ascending integers in 1..${MAX_ENDING_PASS}`);
496
- }
497
- for (let pass = from; pass <= to; pass++)
498
- result.add(pass);
499
- }
500
- return [...result].sort((left, right) => left - right);
501
- }
@@ -1,14 +0,0 @@
1
- import { type MusicXmlElement } from "./dom.js";
2
- import type { MusicXmlDiagnostic } from "./model.js";
3
- import { type PitchMode } from "../source.js";
4
- export type { MusicXmlElement, MusicXmlNode } from "./dom.js";
5
- export type { MusicXmlDiagnostic } from "./model.js";
6
- export interface MusicXmlToJpFunOptions {
7
- pitchMode?: PitchMode;
8
- barsPerLine?: number;
9
- }
10
- /** 将解析好的 MusicXML 根元素同步转换为 jpFun 源码,并报告未保留或近似转换的语义 */
11
- export declare function musicXmlToJpFun(root: MusicXmlElement, options?: MusicXmlToJpFunOptions): {
12
- script: string;
13
- diagnostics: MusicXmlDiagnostic[];
14
- };