jpfun 0.7.0 → 0.9.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 (152) 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 +19 -56
  6. package/dist/converter/musicxml/features.d.ts +16 -8
  7. package/dist/converter/musicxml/features.js +88 -19
  8. package/dist/converter/musicxml/index.js +88 -50
  9. package/dist/converter/musicxml/model.d.ts +9 -0
  10. package/dist/converter/source.d.ts +4 -7
  11. package/dist/converter/source.js +11 -9
  12. package/dist/core.d.ts +1 -0
  13. package/dist/core.js +1 -0
  14. package/dist/diagnostic.d.ts +7 -1
  15. package/dist/diagnostic.js +40 -88
  16. package/dist/fraction.js +3 -2
  17. package/dist/functions/ASTtypes.d.ts +3 -32
  18. package/dist/functions/ASTtypes.js +5 -52
  19. package/dist/functions/adjust/index.js +45 -33
  20. package/dist/functions/arpeggio/index.js +50 -55
  21. package/dist/functions/arpeggio/shape.d.ts +2 -3
  22. package/dist/functions/arpeggio/shape.js +20 -50
  23. package/dist/functions/bar/index.d.ts +8 -0
  24. package/dist/functions/bar/index.js +105 -8
  25. package/dist/functions/beam/auto.d.ts +1 -2
  26. package/dist/functions/beam/auto.js +80 -135
  27. package/dist/functions/beam/index.js +6 -12
  28. package/dist/functions/beam/layout.d.ts +1 -1
  29. package/dist/functions/beam/layout.js +1 -1
  30. package/dist/functions/box/index.js +0 -6
  31. package/dist/functions/br/index.d.ts +34 -2
  32. package/dist/functions/br/index.js +5 -4
  33. package/dist/functions/dash/index.js +9 -10
  34. package/dist/functions/default.js +2 -1
  35. package/dist/functions/div/index.d.ts +3 -4
  36. package/dist/functions/div/index.js +18 -14
  37. package/dist/functions/dot/index.js +5 -11
  38. package/dist/functions/dyn/index.js +55 -57
  39. package/dist/functions/gliss/index.js +131 -103
  40. package/dist/functions/grace/index.d.ts +3 -12
  41. package/dist/functions/grace/index.js +52 -102
  42. package/dist/functions/head/index.js +10 -7
  43. package/dist/functions/key/index.js +13 -15
  44. package/dist/functions/meter/index.d.ts +56 -1
  45. package/dist/functions/meter/index.js +15 -10
  46. package/dist/functions/note/index.js +6 -6
  47. package/dist/functions/note/noteName.d.ts +16 -0
  48. package/dist/functions/note/noteName.js +88 -0
  49. package/dist/functions/note/source-transform.js +8 -10
  50. package/dist/functions/ottava/index.js +35 -40
  51. package/dist/functions/page/index.d.ts +1 -0
  52. package/dist/functions/page/index.js +27 -21
  53. package/dist/functions/pagebreak/index.js +2 -2
  54. package/dist/functions/rest/index.js +5 -5
  55. package/dist/functions/set/index.js +4 -4
  56. package/dist/functions/slide/index.js +0 -1
  57. package/dist/functions/stack/index.js +8 -57
  58. package/dist/functions/symbol/index.d.ts +21 -2
  59. package/dist/functions/symbol/index.js +69 -24
  60. package/dist/functions/symbol/ornament.d.ts +1 -2
  61. package/dist/functions/symbol/shape.d.ts +6 -0
  62. package/dist/functions/symbol/shape.js +16 -3
  63. package/dist/functions/symbol/symbols/coda.d.ts +4 -0
  64. package/dist/functions/symbol/symbols/coda.js +56 -0
  65. package/dist/functions/symbol/symbols/dynamics.d.ts +1 -1
  66. package/dist/functions/symbol/symbols/dynamics.js +18 -8
  67. package/dist/functions/symbol/symbols/harmonic.d.ts +2 -0
  68. package/dist/functions/symbol/symbols/harmonic.js +11 -0
  69. package/dist/functions/symbol/symbols/marcato.d.ts +2 -0
  70. package/dist/functions/symbol/symbols/marcato.js +22 -0
  71. package/dist/functions/symbol/symbols/staccato.d.ts +2 -0
  72. package/dist/functions/symbol/symbols/staccato.js +24 -0
  73. package/dist/functions/symbol/symbols/tenuto.d.ts +2 -0
  74. package/dist/functions/symbol/symbols/tenuto.js +11 -0
  75. package/dist/functions/symbol/symbols/tocoda.d.ts +2 -0
  76. package/dist/functions/symbol/symbols/tocoda.js +16 -0
  77. package/dist/functions/symbol/symbols/turn.d.ts +3 -0
  78. package/dist/functions/symbol/symbols/turn.js +50 -0
  79. package/dist/functions/symbol/symbols/wheel.d.ts +2 -0
  80. package/dist/functions/symbol/symbols/wheel.js +36 -0
  81. package/dist/functions/temporal.d.ts +3 -2
  82. package/dist/functions/temporal.js +8 -0
  83. package/dist/functions/text/index.js +38 -35
  84. package/dist/functions/tie/index.js +44 -43
  85. package/dist/functions/tremolo/index.d.ts +2 -0
  86. package/dist/functions/tremolo/index.js +318 -0
  87. package/dist/functions/tuplet/index.js +4 -14
  88. package/dist/functions/up/index.js +81 -85
  89. package/dist/functions/voice/connections.d.ts +2 -1
  90. package/dist/functions/voice/connections.js +48 -10
  91. package/dist/functions/voice/index.d.ts +2 -3
  92. package/dist/functions/voice/index.js +2 -963
  93. package/dist/functions/voice/lyrics.d.ts +30 -0
  94. package/dist/functions/voice/lyrics.js +289 -0
  95. package/dist/functions/voice/voice.d.ts +63 -0
  96. package/dist/functions/voice/voice.js +373 -0
  97. package/dist/functions/voice/voices.d.ts +106 -0
  98. package/dist/functions/voice/voices.js +423 -0
  99. package/dist/functions/volta/index.js +5 -23
  100. package/dist/jpfun.core.min.js +76 -59
  101. package/dist/jpfun.from-midi.min.js +5 -5
  102. package/dist/jpfun.from-musicxml.min.js +8 -8
  103. package/dist/jpfun.min.js +81 -64
  104. package/dist/layout/default.d.ts +0 -1
  105. package/dist/layout/default.js +0 -1
  106. package/dist/layout/engine.js +30 -18
  107. package/dist/layout/model.d.ts +0 -1
  108. package/dist/layout/model.js +1 -4
  109. package/dist/layout/page.d.ts +2 -1
  110. package/dist/layout/page.js +14 -14
  111. package/dist/layout/range.d.ts +7 -6
  112. package/dist/layout/range.js +23 -14
  113. package/dist/layout/types.d.ts +9 -28
  114. package/dist/lowering/loweringContext.d.ts +18 -23
  115. package/dist/lowering/loweringContext.js +33 -46
  116. package/dist/lowering/track.d.ts +8 -1
  117. package/dist/lowering/types.d.ts +13 -11
  118. package/dist/parser/parse-utils/call-utils.d.ts +1 -2
  119. package/dist/parser/parse-utils/call-utils.js +6 -34
  120. package/dist/parser/parse-utils/note-utils.d.ts +3 -3
  121. package/dist/parser/parse-utils/note-utils.js +21 -33
  122. package/dist/parser/parse-utils/string-utils.d.ts +3 -2
  123. package/dist/parser/parse-utils/string-utils.js +20 -5
  124. package/dist/parser/parserContext.d.ts +9 -9
  125. package/dist/parser/parserContext.js +62 -11
  126. package/dist/pipeline.js +2 -3
  127. package/dist/playback/compile.js +131 -82
  128. package/dist/playback/event.d.ts +6 -6
  129. package/dist/playback/event.js +13 -49
  130. package/dist/playback/time.js +42 -31
  131. package/dist/playback/types.d.ts +3 -1
  132. package/dist/render/canvas.js +4 -22
  133. package/dist/render/recording.js +1 -4
  134. package/dist/render/svg.d.ts +0 -1
  135. package/dist/render/svg.js +33 -31
  136. package/dist/render/text.d.ts +36 -1
  137. package/dist/render/text.js +134 -0
  138. package/dist/render/translate.d.ts +0 -1
  139. package/dist/render/translate.js +6 -23
  140. package/dist/render/types.d.ts +0 -2
  141. package/grammar.md +39 -30
  142. package/package.json +3 -3
  143. package/dist/functions/note/noteNameFSM.d.ts +0 -8
  144. package/dist/functions/note/noteNameFSM.js +0 -181
  145. package/dist/iife/core.d.ts +0 -1
  146. package/dist/iife/core.js +0 -3
  147. package/dist/iife/from-midi.d.ts +0 -1
  148. package/dist/iife/from-midi.js +0 -15
  149. package/dist/iife/from-musicxml.d.ts +0 -1
  150. package/dist/iife/from-musicxml.js +0 -3
  151. package/dist/iife/full.d.ts +0 -1
  152. package/dist/iife/full.js +0 -3
@@ -0,0 +1,88 @@
1
+ import { ErrorDiagnostic } from "../../diagnostic.js";
2
+ function isLetterNote(ch) {
3
+ return (ch >= "A" && ch <= "G") || ch === "X" || ch === "Z";
4
+ }
5
+ function isDigit(ch) {
6
+ return ch >= "0" && ch <= "9";
7
+ }
8
+ function isAccidentalChar(ch) {
9
+ return ch === "#" || ch === "b" || ch === "n";
10
+ }
11
+ function readAccidental(str, pos, end) {
12
+ while (pos < end && isAccidentalChar(str[pos]))
13
+ pos++;
14
+ return pos;
15
+ }
16
+ /** 后置升降号不能紧接数字音名(例如 `C4#1` 或 `1#2` 中的 `#1`/`#2` 属于下一个音符) */
17
+ function readTrailingAccidental(str, pos, end) {
18
+ const accEnd = readAccidental(str, pos, end);
19
+ return accEnd > pos && !isDigit(str[accEnd] ?? "") ? str.slice(pos, accEnd) : null;
20
+ }
21
+ function readAbsOctave(str, pos, end) {
22
+ if (pos < end && (str[pos] === "+" || str[pos] === "-"))
23
+ pos++;
24
+ const digitStart = pos;
25
+ while (pos < end && isDigit(str[pos]))
26
+ pos++;
27
+ return pos > digitStart ? pos : -1;
28
+ }
29
+ function finishRelative(str, pos, end, name, acc) {
30
+ let octave = 0;
31
+ let next = pos;
32
+ while (next < end && (str[next] === "," || str[next] === "'")) {
33
+ octave += str[next++] === "'" ? 1 : -1;
34
+ }
35
+ return { name, next, acc, octave: next > pos ? octave : null, absOctave: false };
36
+ }
37
+ export function parseNoteName(str, start = 0, end = str.length, diagnose = true) {
38
+ if (end - start === 0) {
39
+ return diagnose ? new ErrorDiagnostic("E_WRONG_NOTE_NAME", '函数 @note 的参数 [0]:"name" 不能为空', { start, end }) : null;
40
+ }
41
+ const ch = str[start];
42
+ // 分支 1:字母音名(使用绝对八度)
43
+ if (isLetterNote(ch)) {
44
+ let pos = start + 1;
45
+ let acc = null;
46
+ let octave = null;
47
+ const octEnd = readAbsOctave(str, pos, end);
48
+ if (octEnd > 0) {
49
+ octave = parseInt(str.slice(pos, octEnd), 10);
50
+ pos = octEnd;
51
+ acc = readTrailingAccidental(str, pos, end);
52
+ if (acc)
53
+ pos += acc.length;
54
+ }
55
+ else {
56
+ const accEnd = readAccidental(str, pos, end);
57
+ if (accEnd > pos) {
58
+ acc = str.slice(pos, accEnd);
59
+ const oct2 = readAbsOctave(str, accEnd, end);
60
+ if (oct2 > 0) {
61
+ octave = parseInt(str.slice(accEnd, oct2), 10);
62
+ pos = oct2;
63
+ }
64
+ else
65
+ pos = accEnd;
66
+ }
67
+ }
68
+ return { name: ch, next: pos, acc, octave, absOctave: true };
69
+ }
70
+ // 分支 2:数字音名(使用相对八度)
71
+ if (isDigit(ch)) {
72
+ const acc = readTrailingAccidental(str, start + 1, end);
73
+ return finishRelative(str, start + 1 + (acc ? acc.length : 0), end, ch, acc);
74
+ }
75
+ // 分支 3:前置升降号 + 数字音名
76
+ if (isAccidentalChar(ch)) {
77
+ const accEnd = readAccidental(str, start, end);
78
+ if (accEnd >= end) {
79
+ return diagnose ? new ErrorDiagnostic("E_WRONG_NOTE_NAME", '函数 @note 的参数 [0]:"name" 格式错误: 在升降号开头时,应该接数字音名,但输入已结束', { start, end }) : null;
80
+ }
81
+ const noteCh = str[accEnd];
82
+ if (!isDigit(noteCh)) {
83
+ return diagnose ? new ErrorDiagnostic("E_WRONG_NOTE_NAME", '函数 @note 的参数 [0]:"name" 格式错误: 在升降号开头时,应该接数字音名,但发现字符 "{ch}"', { start: accEnd, end: accEnd + 1 }, { ch: noteCh }) : null;
84
+ }
85
+ return finishRelative(str, accEnd + 1, end, noteCh, str.slice(start, accEnd));
86
+ }
87
+ return diagnose ? new ErrorDiagnostic("E_WRONG_NOTE_NAME", '函数 @note 的参数 [0]:"name" 格式错误: 首字符 "{ch}" 不合法,期望 A-G (a-g)、0-9、X 或 Z 开头,或在开头直接使用升降号(#/b/n)', { start, end: start + 1 }, { ch }) : null;
88
+ }
@@ -1,9 +1,9 @@
1
- import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
1
+ import { ErrorDiagnostic } from "../../diagnostic.js";
2
2
  import { preprocessSource } from "../../parser/preprocess.js";
3
3
  import { readCall } from "../../parser/parse-utils/call-utils.js";
4
4
  import { findClosingQuote, quote } from "../../parser/parse-utils/string-utils.js";
5
5
  import { NoteNameMap, SHARP_NOTE_NAMES, FLAT_NOTE_NAMES, resolveLetterNameToJianpu, tonality2Midi } from "../../parser/parse-utils/note-utils.js";
6
- import { parseNoteName } from "./noteNameFSM.js";
6
+ import { parseNoteName } from "./noteName.js";
7
7
  const LETTERS = "CDEFGAB";
8
8
  const mod = (value, base) => ((value % base) + base) % base;
9
9
  const accidental = (offset) => offset < 0 ? "b".repeat(-offset) : "#".repeat(offset);
@@ -15,14 +15,13 @@ function targetPitch(note, operation) {
15
15
  const absolute = operation === "to-absolute"
16
16
  || operation !== "to-relative" && LETTERS.includes(note.ast.name);
17
17
  const midi = note.resolvedMidi + (operation === "semitone-up" ? 1 : operation === "semitone-down" ? -1 : 0);
18
- const tonic = tonality2Midi(note.keySignature, 4);
18
+ const tonic = tonality2Midi(note.keySignature);
19
19
  if (![midi, tonic, note.ast.octave, note.ast.jeOctaveOffset].every(Number.isSafeInteger))
20
20
  fail(note.ast.sourceSpan);
21
21
  const spelling = operation === "semitone-down" ? FLAT_NOTE_NAMES : SHARP_NOTE_NAMES;
22
22
  let name, acc, octave;
23
23
  if (operation === "to-absolute") {
24
- const tonicLetter = LETTERS.indexOf(note.keySignature[0]);
25
- const base = tonicLetter < 0 ? LETTERS.indexOf(SHARP_NOTE_NAMES[mod(tonic, 12)][0]) : tonicLetter;
24
+ const base = LETTERS.indexOf(note.keySignature[0]);
26
25
  const degree = Number(note.ast.name) - 1;
27
26
  name = LETTERS[(base + degree) % 7];
28
27
  const tonicAcc = mod(tonic - NoteNameMap[LETTERS[base]] + 6, 12) - 6;
@@ -32,9 +31,7 @@ function targetPitch(note, operation) {
32
31
  }
33
32
  else if (operation === "to-relative") {
34
33
  const ast = note.ast;
35
- const key = LETTERS.includes(note.keySignature[0]) ? note.keySignature
36
- : SHARP_NOTE_NAMES[mod(tonic, 12)] + (Math.floor(tonic / 12) - 1);
37
- const relative = resolveLetterNameToJianpu(ast.name, ast.acc, ast.octave + ast.jeOctaveOffset, key);
34
+ const relative = resolveLetterNameToJianpu(ast.name, ast.acc, ast.octave + ast.jeOctaveOffset, note.keySignature);
38
35
  if (!relative)
39
36
  fail(ast.sourceSpan);
40
37
  ({ renderName: name, renderAcc: acc, renderOctave: octave } = relative);
@@ -145,8 +142,9 @@ export function rewriteNotes(source, notes, operation, ranges) {
145
142
  const left = tokens[index], right = tokens[index + 1];
146
143
  if (left.span.end !== right.span.start || left.text.endsWith("}"))
147
144
  continue;
148
- const parsed = parseNoteName(left.text + right.text);
149
- if (parsed instanceof Diagnostic || parsed.next !== left.text.length) {
145
+ const merged = left.text + right.text;
146
+ const parsed = parseNoteName(merged, 0, merged.length, false);
147
+ if (!parsed || parsed.next !== left.text.length) {
150
148
  if (left.text !== source.slice(left.span.start, left.span.end))
151
149
  left.text += " ";
152
150
  else
@@ -1,12 +1,8 @@
1
1
  import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
2
2
  import { unionLayoutBoxes } from "../../layout/engine.js";
3
+ import { lineEntryX, lineRightX } from "../../layout/range.js";
3
4
  import { ASTFunctionNode, } from "../ASTtypes.js";
4
5
  import { isVisualTemporalNode } from "../temporal.js";
5
- function outerHost(node) {
6
- while (node.foldedInto)
7
- node = node.foldedInto;
8
- return node;
9
- }
10
6
  class OttavaFunction extends ASTFunctionNode {
11
7
  static def = {
12
8
  name: ["ottava"],
@@ -37,22 +33,37 @@ class OttavaFunction extends ASTFunctionNode {
37
33
  },
38
34
  ],
39
35
  };
40
- static loweringFinalize = (result) => {
41
- const ottavas = result.attachments.filter((attachment) => attachment instanceof OttavaAttachment).map(attachment => {
36
+ static loweringFinalize(result) {
37
+ const ottavasByTrack = new Map();
38
+ for (const attachment of result.attachments) {
39
+ if (!(attachment instanceof OttavaAttachment))
40
+ continue;
42
41
  const [from, to] = attachment.endPoints;
43
- return { from, end: to.t.clone().add(to.T), shift: attachment.ast.shift * 12 };
44
- });
45
- if (ottavas.length === 0)
42
+ const entry = { start: from.t, end: to.t.clone().add(to.T), shift: attachment.ast.shift * 12 };
43
+ const list = ottavasByTrack.get(from.track);
44
+ if (list)
45
+ list.push(entry);
46
+ else
47
+ ottavasByTrack.set(from.track, [entry]);
48
+ }
49
+ if (ottavasByTrack.size === 0)
46
50
  return;
51
+ for (const list of ottavasByTrack.values()) {
52
+ list.sort((left, right) => left.start.compare(right.start));
53
+ }
47
54
  for (const nodes of result.astToTemporal.values()) {
48
55
  for (const node of nodes) {
49
56
  if (!node.playbackState)
50
57
  continue;
51
- const host = outerHost(node);
58
+ const host = node.rootHost;
59
+ const ottavas = ottavasByTrack.get(host.track);
60
+ if (!ottavas)
61
+ continue;
52
62
  let shift = 0;
53
63
  for (const ottava of ottavas) {
54
- if (host.track === ottava.from.track && host.t.compare(ottava.from.t) >= 0
55
- && host.t.compare(ottava.end) < 0) {
64
+ if (host.t.compare(ottava.start) < 0)
65
+ break;
66
+ if (host.t.compare(ottava.end) < 0) {
56
67
  shift += ottava.shift;
57
68
  }
58
69
  }
@@ -64,7 +75,7 @@ class OttavaFunction extends ASTFunctionNode {
64
75
  }
65
76
  }
66
77
  }
67
- };
78
+ }
68
79
  from;
69
80
  to;
70
81
  shift;
@@ -83,10 +94,8 @@ class OttavaFunction extends ASTFunctionNode {
83
94
  this.font = ctx.variables.numberfont;
84
95
  }
85
96
  loweringEnter(ctx) {
86
- const from = ctx.getTemporalNodes(this.from).at(0);
87
- const to = ctx.getTemporalNodes(this.to).at(-1);
88
- const head = from && outerHost(from);
89
- const tail = to && outerHost(to);
97
+ const head = ctx.getTemporalNodes(this.from).at(0)?.rootHost;
98
+ const tail = ctx.getTemporalNodes(this.to).at(-1)?.rootHost;
90
99
  if (!head || !tail || !isVisualTemporalNode(head) || !isVisualTemporalNode(tail)) {
91
100
  ctx.diagnostics.push(Diagnostic.warning.UnresolvedEndpoint("ottava", this.sourceSpan));
92
101
  return [];
@@ -95,6 +104,7 @@ class OttavaFunction extends ASTFunctionNode {
95
104
  throw new ErrorDiagnostic("E_OTTAVA_CROSS_TRACK", "@ottava 的两个端点必须位于同一音轨", this.sourceSpan);
96
105
  }
97
106
  ctx.addAttachment(new OttavaAttachment(this, head, tail));
107
+ ctx.deferFinalize(OttavaFunction.loweringFinalize);
98
108
  return [];
99
109
  }
100
110
  toString(source) {
@@ -105,22 +115,16 @@ class OttavaFunction extends ASTFunctionNode {
105
115
  export const OttavaNode = OttavaFunction;
106
116
  class OttavaAttachment {
107
117
  ast;
108
- from;
109
- to;
110
118
  layer = "foreground";
119
+ endPoints;
111
120
  constructor(ast, from, to) {
112
121
  this.ast = ast;
113
- this.from = from;
114
- this.to = to;
122
+ this.endPoints = (from.t.compare(to.t) || from.order - to.order) > 0
123
+ ? [to, from] : [from, to];
115
124
  }
116
125
  get sourceSpan() { return this.ast.sourceSpan; }
117
- get endPoints() {
118
- return (this.from.t.compare(this.to.t) || this.from.order - this.to.order) > 0
119
- ? [this.to, this.from] : [this.from, this.to];
120
- }
121
126
  createGeometry(context) {
122
- const endpoints = this.endPoints;
123
- const [from, to] = endpoints;
127
+ const [from, to] = this.endPoints;
124
128
  const firstLine = from.layoutLine;
125
129
  const lastLine = to.layoutLine;
126
130
  if (context.lines[firstLine].columnOf(from) < 0 || context.lines[lastLine].columnOf(to) < 0) {
@@ -152,17 +156,8 @@ class OttavaAttachment {
152
156
  const line = firstLine + offset;
153
157
  const first = line === firstLine;
154
158
  const last = line === lastLine;
155
- const runs = context.lines[line].trackRuns;
156
- let left = first ? from.box.x + (from.ports["body.left"]?.x ?? 0)
157
- : runs.get(track)?.find(host => !host.T.isZero())?.box.x ?? context.originX;
158
- let right = to.box.x + (to.ports["body.right"]?.x ?? to.box.w);
159
- if (!last) {
160
- right = context.originX + (runs.size === 0 ? context.width : 0);
161
- for (const run of runs.values()) {
162
- for (const host of run)
163
- right = Math.max(right, host.box.x + host.box.w);
164
- }
165
- }
159
+ let left = first ? from.box.x + (from.ports["body.left"]?.x ?? 0) : lineEntryX(context, line, track);
160
+ let right = last ? to.box.x + (to.ports["body.right"]?.x ?? to.box.w) : lineRightX(context, line);
166
161
  if (left > right)
167
162
  [left, right] = [right, left];
168
163
  const lineStart = first ? left + metrics.w + labelGap : left;
@@ -185,7 +180,7 @@ class OttavaAttachment {
185
180
  }
186
181
  }
187
182
  if (!Number.isFinite(lineY)) {
188
- const extent = context.getRangeExtents(line, first || last ? endpoints : undefined, track);
183
+ const extent = context.getRangeExtents(line, first || last ? this.endPoints : undefined, track);
189
184
  const axis = context.getVisualAxis(line, track);
190
185
  lineY = above
191
186
  ? axis + (extent?.top ?? 0) - gap - (region.y + region.h)
@@ -28,6 +28,7 @@ export declare class PageFunction extends ASTFunctionNode {
28
28
  };
29
29
  readonly config: PageConfig | null;
30
30
  private readonly numbering;
31
+ private readonly barNumbering;
31
32
  readonly font: string;
32
33
  constructor(sourceSpan: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent?: ASTNodeBase | null);
33
34
  loweringEnter(ctx: LoweringContext): never[];
@@ -1,6 +1,7 @@
1
1
  import { DEFAULT_PAGE_CONFIG, normalizePageConfig, } from "../../layout/page.js";
2
- import { Diagnostic, WarningDiagnostic } from "../../diagnostic.js";
2
+ import { ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
3
3
  import { quote } from "../../parser/parse-utils/string-utils.js";
4
+ import { registerBarNumbering } from "../bar/index.js";
4
5
  import { ASTFunctionNode, } from "../ASTtypes.js";
5
6
  const px = (value) => ({ value, unit: "px" });
6
7
  /** 页码字号,同时也是放得下页码所需的最小下边距 */
@@ -50,10 +51,11 @@ export class PageFunction extends ASTFunctionNode {
50
51
  ~~~jpfun
51
52
  @page(
52
53
  width=794px, height=1123px, top=48px, bottom=48px,
53
- left=40px, right=40px, gap=1em, numbering="1/1", fillRatio=0.5
54
+ left=40px, right=40px, gap=1em, minGap=0.5em, fillRatio=0.5,
55
+ numbering="1/1", barNumbering="(1)"
54
56
  )
55
57
  ~~~
56
- 尺寸接受 \`px\` 或 \`em\`。页边距和行距须非负;左右边距之和须小于页宽,固定页高时上下边距之和须小于页高。`,
58
+ 页边距和行距须非负;左右边距之和须小于页宽,固定页高时上下边距之和须小于页高。`,
57
59
  allowExtraArgs: false,
58
60
  args: [
59
61
  { name: "width", description: "页面宽度,须大于左右页边距之和", type: "length", default: px(DEFAULT_PAGE_CONFIG.width) },
@@ -62,15 +64,17 @@ export class PageFunction extends ASTFunctionNode {
62
64
  { name: "bottom", description: "页面下边距,启用页码时至少为 `16px`", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginBottom) },
63
65
  { name: "left", description: "页面左边距", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginLeft) },
64
66
  { name: "right", description: "页面右边距", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginRight) },
65
- { name: "gap", description: "谱面行之间的最小间距", type: "length", default: { value: 1, unit: "em" } },
66
- // 单个 1 取当前页;多个 1 中最后一个取总页数
67
- { name: "numbering", description: "页码格式,空值隐藏;`1` 显示当前页,`1/1` 显示当前页/总页数", type: "string", default: "" },
68
- { name: "font", description: "页码字体,空值沿用当前字体设置", type: "string", default: "" },
67
+ { name: "gap", description: "谱面行主旋律之间的标准间距", type: "length", default: { value: 1, unit: "em" } },
68
+ { name: "minGap", description: "行间保留的最小间距", type: "length", default: { value: 0.5, unit: "em" } },
69
+ { name: "numbering", description: "页码格式,空值隐藏;`1`:当前页,`1/1`:显示当前页/总页数", type: "string", default: "" },
70
+ { name: "barNumbering", description: "行首小节号格式,默认空值隐藏;`1` 显示当前小节号,`(1)` 显示带括号的小节号", type: "string", default: "" },
71
+ { name: "font", description: "页码/小节号字体,空值沿用当前字体设置", type: "string", default: "" },
69
72
  { name: "fillRatio", description: "自然宽度达到该比例后撑满", type: "number", default: DEFAULT_PAGE_CONFIG.fillRatio },
70
73
  ],
71
74
  };
72
75
  config;
73
76
  numbering = "";
77
+ barNumbering = "";
74
78
  font;
75
79
  constructor(sourceSpan, args, ctx, parent = null) {
76
80
  super(sourceSpan, parent);
@@ -86,23 +90,21 @@ export class PageFunction extends ASTFunctionNode {
86
90
  return;
87
91
  }
88
92
  ctx.documentDeclarations["page"] = true;
89
- const values = this.getArgValue(args, ctx);
90
- const fillRatio = values.pop();
91
- this.font = values.pop() || ctx.variables.font;
92
- const numbering = values.pop();
93
- const [width, height, top, bottom, left, right, gap] = values.map(value => ctx.length2px(value));
93
+ const [w, h, t, b, l, r, g, mg, numbering, barNumbering, font, fillRatio,] = this.getArgValue(args, ctx);
94
+ this.font = font || ctx.variables.font;
95
+ const [width, height, top, bottom, left, right, gap, minGap] = [w, h, t, b, l, r, g, mg].map(value => ctx.length2px(value));
94
96
  if (!Number.isFinite(width) || width <= 0)
95
- throw Diagnostic.error.InvalidPageConfig("@page 的 width 必须是正有限长度", sourceSpan);
97
+ throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的 width 必须是正有限长度", sourceSpan);
96
98
  if (!Number.isFinite(height))
97
- throw Diagnostic.error.InvalidPageConfig("@page 的 height 必须是有限长度;小于等于 0 表示不自动分页", sourceSpan);
98
- if ([top, bottom, left, right, gap].some(value => !Number.isFinite(value) || value < 0))
99
- throw Diagnostic.error.InvalidPageConfig("@page 的边距和 gap 必须是非负有限长度", sourceSpan);
99
+ throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的 height 必须是有限长度;小于等于 0 表示不自动分页", sourceSpan);
100
+ if ([top, bottom, left, right, gap, minGap].some(value => !Number.isFinite(value) || value < 0))
101
+ throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的边距、gap 和 minGap 必须是非负有限长度", sourceSpan);
100
102
  if (left + right >= width)
101
- throw Diagnostic.error.InvalidPageConfig("@page 的左右边距没有留下可用内容宽度", sourceSpan);
103
+ throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的左右边距没有留下可用内容宽度", sourceSpan);
102
104
  if (height > 0 && top + bottom >= height)
103
- throw Diagnostic.error.InvalidPageConfig("@page 的上下边距没有留下可用内容高度", sourceSpan);
105
+ throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的上下边距没有留下可用内容高度", sourceSpan);
104
106
  if (numbering && bottom < PAGE_NUMBER_FONT_SIZE)
105
- throw Diagnostic.error.InvalidPageConfig(`@page 的 bottom 至少需要 ${PAGE_NUMBER_FONT_SIZE}px 才能放下页码`, sourceSpan);
107
+ throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的 bottom 至少需要 {minBottom}px 才能放下页码", sourceSpan, { minBottom: PAGE_NUMBER_FONT_SIZE });
106
108
  this.config = normalizePageConfig({
107
109
  width,
108
110
  height,
@@ -111,9 +113,11 @@ export class PageFunction extends ASTFunctionNode {
111
113
  marginLeft: left,
112
114
  marginRight: right,
113
115
  lineGap: gap,
116
+ minLineGap: minGap,
114
117
  fillRatio,
115
118
  });
116
119
  this.numbering = numbering;
120
+ this.barNumbering = barNumbering;
117
121
  }
118
122
  loweringEnter(ctx) {
119
123
  if (!ctx || !this.config)
@@ -122,13 +126,15 @@ export class PageFunction extends ASTFunctionNode {
122
126
  if (this.numbering) {
123
127
  ctx.addAttachment(new PageNumberAttachment(this.sourceSpan, this.numbering, this.config.marginBottom, { ...PAGE_NUMBER_STYLE, fontFamily: this.font }));
124
128
  }
129
+ if (this.barNumbering)
130
+ registerBarNumbering(ctx, this.barNumbering, this.font);
125
131
  return [];
126
132
  }
127
133
  toString() {
128
134
  if (!this.config)
129
135
  return "@page()";
130
- const { width, height, marginTop, marginBottom, marginLeft, marginRight, lineGap, fillRatio } = this.config;
131
- return `@page(width=${width}px, height=${Number.isFinite(height) ? height : 0}px, top=${marginTop}px, bottom=${marginBottom}px, left=${marginLeft}px, right=${marginRight}px, gap=${lineGap}px, numbering=${quote(this.numbering)}, font=${quote(this.font)}, fillRatio=${fillRatio})`;
136
+ const { width, height, marginTop, marginBottom, marginLeft, marginRight, lineGap, minLineGap, fillRatio } = this.config;
137
+ return `@page(width=${width}px, height=${Number.isFinite(height) ? height : 0}px, top=${marginTop}px, bottom=${marginBottom}px, left=${marginLeft}px, right=${marginRight}px, gap=${lineGap}px, minGap=${minLineGap}px, numbering=${quote(this.numbering)}, barNumbering=${quote(this.barNumbering)}, font=${quote(this.font)}, fillRatio=${fillRatio})`;
132
138
  }
133
139
  }
134
140
  export const PageNode = PageFunction;
@@ -18,13 +18,13 @@ class PageBreakFunction extends ASTFunctionNode {
18
18
  default: true,
19
19
  }],
20
20
  };
21
- static loweringFinalize = BrNode.loweringFinalize;
22
21
  justify;
23
22
  constructor(span, args, ctx, parent = null) {
24
23
  super(span, parent);
25
24
  [this.justify] = this.getArgValue(args, ctx);
26
25
  }
27
- loweringEnter() {
26
+ loweringEnter(ctx) {
27
+ ctx.deferFinalize(BrNode.loweringFinalize);
28
28
  const node = new TemporalNodeBase();
29
29
  node.ast = this;
30
30
  node.mergeKey = -1;
@@ -56,7 +56,9 @@ class RestFunction extends ASTFunctionNode {
56
56
  }
57
57
  // 可以被 volta 这样的标记
58
58
  labelable() { return this; }
59
- loweringEnter() {
59
+ loweringEnter(ctx) {
60
+ // 先于拍号校验(默认 order=0)补入多小节休止内部的虚拟小节边界
61
+ ctx.deferFinalize(RestFunction.loweringFinalize, -10);
60
62
  return [new RestTemporal(this)];
61
63
  }
62
64
  static loweringFinalize(result) {
@@ -73,10 +75,8 @@ class RestFunction extends ASTFunctionNode {
73
75
  if (!(node.ast instanceof ASTFunctionNode)
74
76
  || (node.ast.callName !== "note" && node.ast.callName !== "dash"))
75
77
  continue;
76
- let host = node;
77
78
  // 沿折叠链找到最外层宿主,将内部成员归到同一主体
78
- while (host.foldedInto)
79
- host = host.foldedInto;
79
+ const host = node.rootHost;
80
80
  // 私有倚音属于独立轨道,不代表外层宿主的休止或起音
81
81
  if (node.track !== host.track)
82
82
  continue;
@@ -151,7 +151,7 @@ class RestTemporal extends TemporalNodeBase {
151
151
  }
152
152
  this.measureDuration.copyFrom(measure);
153
153
  this.T.copyFrom(measure).mul(this.ast.count);
154
- const host = state.currentEvent ?? this;
154
+ const host = this.rootHost;
155
155
  // 只登记全局休止宿主的同轨成员,私有倚音不接管宿主。
156
156
  if (host.mergeKey === REST_KEY && this.track === host.track) {
157
157
  const rest = restsByHost.get(host);
@@ -28,11 +28,11 @@ class SetFunction extends ASTFunctionNode {
28
28
  const def = ctx.functions.get(key.slice(0, dot))?.prototype.def;
29
29
  const type = def && resolveArgType(def, argName, -1);
30
30
  if (!def || !type) {
31
- ctx.diagnostics.push(new WarningDiagnostic("W_SET_UNKNOWN_TARGET", `@set 的参数 [${key}] 没有对应的函数或其参数,将被忽略`, nameSpan));
31
+ ctx.diagnostics.push(new WarningDiagnostic("W_SET_UNKNOWN_TARGET", "@set 的参数 [{key}] 没有对应的函数或其参数,将被忽略", nameSpan, { key }));
32
32
  return null;
33
33
  }
34
34
  if (type === "content" || type === "label") {
35
- ctx.diagnostics.push(new WarningDiagnostic("W_SET_INVALID_VALUE_TYPE", `@set 的参数 [${key}] 内容和标签不能作为默认值,将被忽略`, nameSpan));
35
+ ctx.diagnostics.push(new WarningDiagnostic("W_SET_INVALID_VALUE_TYPE", "@set 的参数 [{key}] 内容和标签不能作为默认值,将被忽略", nameSpan, { key }));
36
36
  return null;
37
37
  }
38
38
  // 别名统一成主名,否则 getArgValue 按主名查不到
@@ -44,7 +44,7 @@ class SetFunction extends ASTFunctionNode {
44
44
  for (const [key, value] of args) {
45
45
  const arg = value;
46
46
  if (typeof key !== "string") {
47
- ctx.diagnostics.push(new WarningDiagnostic("W_SET_POSITIONAL_ARG", `函数 @set 不接收位置参数, 位置参数[${key}]将被忽略`, arg.span));
47
+ ctx.diagnostics.push(new WarningDiagnostic("W_SET_POSITIONAL_ARG", "函数 @set 不接收位置参数, 位置参数[{key}]将被忽略", arg.span, { key }));
48
48
  continue;
49
49
  }
50
50
  const target = SetFunction.resolveTarget(ctx, key.toLowerCase(), arg.nameSpan ?? arg.span);
@@ -54,7 +54,7 @@ class SetFunction extends ASTFunctionNode {
54
54
  // 按目标参数的声明类型固化,否则消费者只能拿到 raw text 各自再解析一遍
55
55
  const v = ctx.parseArgWithType(arg.valueSpan, type, sourceSpan.start);
56
56
  if (v === null) {
57
- ctx.diagnostics.push(new WarningDiagnostic("W_SET_INVALID_VALUE", `函数 @set 的参数值解析失败, 参数[${key}]将被忽略`, arg.valueSpan));
57
+ ctx.diagnostics.push(new WarningDiagnostic("W_SET_INVALID_VALUE", "函数 @set 的参数值解析失败, 参数[{key}]将被忽略", arg.valueSpan, { key }));
58
58
  continue;
59
59
  }
60
60
  ctx.setVariable(k, v);
@@ -22,7 +22,6 @@ class SlideFunction extends ASTFunctionNode {
22
22
  side;
23
23
  direction;
24
24
  get children() { return [this.content]; }
25
- timeFlowModel() { return { children: this.children, mode: "sequence" }; }
26
25
  labelable() { return ASTFunctionNode.findLabelable(this.content); }
27
26
  constructor(span, args, ctx, parent = null) {
28
27
  super(span, parent);
@@ -1,4 +1,4 @@
1
- import { ASTNodeBase, ASTFunctionNode, ASTTextNode, ASTBraceNode, ASTLabelNode } from "../ASTtypes.js";
1
+ import { ASTFunctionNode } from "../ASTtypes.js";
2
2
  import { ErrorDiagnostic } from "../../diagnostic.js";
3
3
  /**
4
4
  * 临时伴奏紧贴主旋律,用比系统级行距更小的间隙
@@ -65,59 +65,16 @@ class StackFunction extends ASTFunctionNode {
65
65
  const n = nodes[at++];
66
66
  if (!(n.kind === "sugar" && n.data === StackFunction))
67
67
  return null;
68
- // 找上一个非文本节点 实现忽略中间内容的作用
69
- // 另一个做法是如果上一个不是可用节点就报错
70
- let left = ctx.nodes.length - 1;
71
- for (; left >= 0; left--) {
72
- if (ctx.nodes[left] instanceof ASTTextNode)
73
- continue;
74
- break;
75
- }
76
- let leftNode = left >= 0 ? ctx.nodes[left] : null;
77
- if (leftNode === null) {
68
+ const leftNode = ctx.takeLeftOperand();
69
+ if (!leftNode) {
78
70
  throw new ErrorDiagnostic("E_STACK_NO_TARGET", "@stack语法糖错误: 左边没有找到可叠加的目标", n.span);
79
71
  }
80
- /** 左操作数在 ctx.nodes 中的起点;只有这一段会被 stack 吞并,更早的节点必须保留 */
81
- let replaceFrom = left;
82
- // 对 label 的特判: 目标变为label到被标记的节点范围内的所有节点
83
- if (leftNode instanceof ASTLabelNode) {
84
- const labelNode = leftNode;
85
- let tgt = labelNode.target;
86
- // 在本层这个节点位于哪里(标签节点可能被wrap)
87
- while (tgt && !ctx.nodes.includes(tgt))
88
- tgt = tgt.parent;
89
- for (let j = left - 1; j >= 0; j--) {
90
- if (ctx.nodes[j] === tgt) {
91
- leftNode = new ASTBraceNode({
92
- start: tgt.sourceSpan.start,
93
- end: labelNode.sourceSpan.end,
94
- }, ctx.nodes.slice(j, left + 1), null);
95
- replaceFrom = j;
96
- break;
97
- }
98
- }
99
- }
100
- // 左操作数收敛成一个 stack,后续合并都在它身上进行
101
72
  const host = leftNode instanceof StackFunction
102
73
  ? leftNode
103
74
  : new StackFunction(n.span, new Map(), ctx).addContent(leftNode);
104
- // 找到下一个非文本节点 通过全量后续解析的方式进行 还是有些trick
105
- const storage = ctx.nodes;
106
- ctx.nodes = [];
107
- ctx.makeNodes(nodes, at);
108
- for (let i = 0; i < ctx.nodes.length; i++) {
109
- // 后向跳过文本节点 和上面保持一致
110
- const right = ctx.nodes[i];
111
- if (right instanceof ASTTextNode)
112
- continue;
113
- host.addContent(right);
114
- storage.length = replaceFrom;
115
- storage.push(host);
116
- while (++i < ctx.nodes.length)
117
- storage.push(ctx.nodes[i]);
118
- ctx.nodes = storage;
119
- return nodes.length;
120
- }
75
+ const next = ctx.consumeRightOperand(nodes, at, right => host.addContent(right));
76
+ if (next !== null)
77
+ return next;
121
78
  throw new ErrorDiagnostic("E_STACK_NO_TARGET", "@stack语法糖错误: 右边没有找到可叠加的目标", n.span);
122
79
  }
123
80
  contents = [];
@@ -131,15 +88,9 @@ class StackFunction extends ASTFunctionNode {
131
88
  }
132
89
  constructor(span, args, ctx, parent = null) {
133
90
  super(span, parent);
134
- for (const [, value] of args) {
135
- if (value instanceof ASTNodeBase) {
91
+ for (const [key, value] of args) {
92
+ if (typeof key === "number")
136
93
  this.addContent(value);
137
- continue;
138
- }
139
- const c = ctx.parseArgWithType(value.valueSpan, "content", span.start);
140
- if (c !== null) {
141
- this.addContent(c);
142
- }
143
94
  }
144
95
  }
145
96
  /** 遇到另一个 stack 就展平;接收者存活,被吞并的成员列表最后清空 */
@@ -2,11 +2,14 @@ import { type TimeState } from "../temporal.js";
2
2
  import type { PlaybackCursor, PlaybackEmitter, PlaybackFlowAction } from "../../playback/types.js";
3
3
  import type { TextStyle } from "../../render/types.js";
4
4
  import { type ASTFunctionClass } from "../ASTtypes.js";
5
- import { type SymbolShape } from "./shape.js";
5
+ import { ornament } from "./ornament.js";
6
+ import { symbolBounds, type SymbolShape } from "./shape.js";
7
+ export type { OrnamentPattern } from "./ornament.js";
8
+ export type { SymbolShape };
6
9
  /**
7
10
  * 一个乐谱符号:固定图形加可选的播放语义
8
11
  *
9
- * 每个符号自成一个文件、彼此没有依赖,新增一个符号就是新增一个对象字面量
12
+ * 每个符号或符号族自成一个文件,新增符号就是新增对象字面量,可复用已有图形和播放能力
10
13
  */
11
14
  export interface SymbolDefinition {
12
15
  readonly name: string;
@@ -39,4 +42,20 @@ export interface SymbolDefinition {
39
42
  /** 播放到达本符号所在列时决定去留;符号恒占一列,所以生效范围不由符号自己声明 */
40
43
  readonly onVisit?: (cursor: PlaybackCursor, at: number) => PlaybackFlowAction | undefined;
41
44
  }
45
+ export declare const symbols: Readonly<{
46
+ /** 内置符号的只读备份列表 */
47
+ core: readonly SymbolDefinition[];
48
+ /** 当前注册表的只读视图 */
49
+ table: ReadonlyMap<string, SymbolDefinition>;
50
+ /** 注册或同名覆盖一个或多个符号定义 */
51
+ register: (...definitions: readonly SymbolDefinition[]) => void;
52
+ /** 清空所有已注册符号(含内置符号) */
53
+ clear: () => void;
54
+ /** 清空并恢复到最初的 symbols.core 状态 */
55
+ reset: () => void;
56
+ /** 装饰音播放展开工具 */
57
+ ornament: typeof ornament;
58
+ /** 计算符号图元在自身坐标系中的固有包围盒 */
59
+ bounds: typeof symbolBounds;
60
+ }>;
42
61
  export declare const SymbolNode: ASTFunctionClass;