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
@@ -1,963 +1,2 @@
1
- import { ASTNodeBase, ASTBraceNode, ASTFunctionNode, ASTTextNode } from "../ASTtypes.js";
2
- import { Diagnostic, ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
3
- import { findRightParen } from "../../parser/parse-utils/call-utils.js";
4
- import { findClosingQuote, quote, removeQuote } from "../../parser/parse-utils/string-utils.js";
5
- import { ParserContext, skipSpaces } from "../../parser/parserContext.js";
6
- import { isLayoutAttachment } from "../../layout/types.js";
7
- import { getLayoutBounds } from "../../layout/engine.js";
8
- import { isVisualTemporalNode, TemporalNodeBase, } from "../temporal.js";
9
- import { BRACKET_HOOK_COMMANDS, BRACKET_HOOK_DROP, BRACKET_HOOK_REACH, CURVED_BRACE_BOUNDS, CURVED_BRACE_COMMANDS, parseConnections, resolveConnections, serializeConnections, } from "./connections.js";
10
- const WHITEPACE_RE = /\s/;
11
- const MIN_CONNECTOR_STEM = 2.5;
12
- const CONNECTOR_LABEL_GAP_RATIO = 0.3;
13
- // 分词跟后面的标点
14
- const LYRIC_OPENING_PUNCTUATION = new Set("(([[{〈《「『【〔〖〘〚‘“");
15
- // 不发声的标点;位于歌词槽首尾时只渲染,不占位,也不参与对齐中心计算
16
- const LYRIC_SILENT_PUNCTUATION = new Set([
17
- ...LYRIC_OPENING_PUNCTUATION,
18
- ...",。!?;:、,.!?;:))]]}〉》」』】〕〗〙〛’”\"'…—–",
19
- ]);
20
- // 分词
21
- function splitLyricText(text) {
22
- let start = 0;
23
- let end = text.length;
24
- while (start < end && LYRIC_SILENT_PUNCTUATION.has(text[start]))
25
- start++;
26
- while (end > start && LYRIC_SILENT_PUNCTUATION.has(text[end - 1]))
27
- end--;
28
- return { prefix: text.slice(0, start), body: text.slice(start, end) };
29
- }
30
- /**
31
- * voices 块在宿主基线上局部居中:首末两条 voice 基线的中点对齐宿主轴
32
- *
33
- * 居中只看**基线**,不看成员的整体视觉边界,也不取所有基线的算术平均值。
34
- * 因此嵌套的 stack、歌词、装饰只会撑开相邻基线的间距和行高,
35
- * 不会把整个块相对于主旋律的语义中心挪走。
36
- *
37
- * 本行没有实质高度的成员(空声部,或内容都在上一行)仍然占一个默认高度的槽位,
38
- * 声部数量因而保持稳定,居中结果也不会因为某一声部没写东西而跳变。
39
- */
40
- function makeVoicesMeasure(emptySlotHeight) {
41
- const half = emptySlotHeight / 2;
42
- return (members, gap) => {
43
- const extents = members.map(member => member && member.bottom - member.top > 1e-6 ? member : { top: -half, bottom: half });
44
- const offsets = [];
45
- let y = 0;
46
- for (let i = 0; i < extents.length; i++) {
47
- if (i > 0)
48
- y += extents[i - 1].bottom + gap - extents[i].top;
49
- offsets.push(y);
50
- }
51
- const center = (offsets[0] + offsets[offsets.length - 1]) / 2;
52
- return offsets.map((offset, i) => ({ offset: offset - center, extent: extents[i] }));
53
- };
54
- }
55
- class VoiceFunction extends ASTFunctionNode {
56
- static def = {
57
- name: ["voice", "v"],
58
- description: "声部",
59
- details: `\
60
- ~~~jpfun
61
- @voice({1 2 3}, 钢琴, 男=ha ha ha, 女=la la la)
62
- ~~~
63
- - **额外参数**:每项为一行歌词;命名参数同时给出歌词行名,位置参数表示无行名。省略声部名但仍需歌词时,保留空位,如 \`@voice({1 2 3}, , ha ha ha)\`。
64
-
65
- 歌词可用引号包裹;显式调用中含逗号等歧义字符时必须加引号。英文用空格或连字符 \`-\` 分词,用 \`@\` 占位。
66
-
67
- **简写**:\`N\` 声明音符行,\`L\` 声明歌词行,括号内的名称可省略:
68
- ~~~jpfun
69
- N(钢琴): 1 2 3
70
- L(男): ha ha ha
71
- L: la la la
72
- ~~~
73
- 行首允许空白,换行结束当前声明;在行末加 \`\\\` 可续行。这种写法中的歌词允许直接使用逗号。`,
74
- allowExtraArgs: true,
75
- extraArgType: "string",
76
- args: [
77
- {
78
- type: "content",
79
- description: "声部的音符内容",
80
- default: null,
81
- },
82
- {
83
- name: "name",
84
- description: "显示在左侧的声部名称,空值隐藏名称",
85
- type: "string",
86
- default: "",
87
- },
88
- // 之后的参数都当作歌词参数
89
- ],
90
- };
91
- // 去糖第一阶段识别两个标签 这里先不消费换行符,因为 br 可能需要
92
- static deSugarAtom(source, start, end) {
93
- if (source[start] !== 'N' && source[start] !== 'L')
94
- return null;
95
- let pos = start + 1;
96
- let name = '';
97
- if (source[pos] === '(') {
98
- // `X(name)` 提取括号
99
- const at = findRightParen(source, pos + 1, end);
100
- if (at < 0)
101
- return null; // 没有找到匹配的右括号 不去糖
102
- name = removeQuote(source.slice(pos + 1, at).trim());
103
- pos = at + 1;
104
- }
105
- if (source[pos++] !== ':')
106
- return null; // `:` 之前不允许有空格
107
- // 识别具体内容
108
- if (source[start] === 'N') {
109
- // 等到第二轮寻找该层级的终止符 \n 来确定内容范围
110
- const node = {
111
- kind: "sugar",
112
- data: {
113
- class: VoiceFunction,
114
- name,
115
- },
116
- span: { start, end: pos },
117
- };
118
- return { next: pos, node };
119
- }
120
- else {
121
- // 字符串收集
122
- pos = skipSpaces(source, pos, end);
123
- if (pos >= end)
124
- return null; // 没有内容了 不去糖
125
- let lyric;
126
- // 双引号才是字符串,单引号不是
127
- if (source[pos] === '"') {
128
- // 未闭合就不去糖,词法层每次击键都跑,不能抛
129
- const close = findClosingQuote(source, pos, end);
130
- if (close < 0)
131
- return null;
132
- lyric = removeQuote(source.slice(pos, close + 1));
133
- pos = close + 1;
134
- }
135
- else {
136
- // 没有引号的 以换行符为界切分 预处理已经跳过了转义的换行符了
137
- const from = pos;
138
- while (pos < end && source[pos] !== '\n')
139
- pos++;
140
- lyric = source.slice(from, pos).trim();
141
- }
142
- const node = {
143
- kind: "sugar",
144
- data: {
145
- class: VoiceFunction,
146
- lyric,
147
- name,
148
- },
149
- span: { start, end: pos },
150
- };
151
- return { next: pos, node };
152
- }
153
- }
154
- static deSugarRelation(ctx, nodes, at, members) {
155
- const n = nodes[at++];
156
- if (n.data?.class !== VoiceFunction)
157
- return null;
158
- if (n.data?.lyric !== void 0) {
159
- // 歌词 需要找到最近的voice节点并添加歌词
160
- let voiceNode = null;
161
- let voiceNodeAt = ctx.nodes.length - 1;
162
- for (; voiceNodeAt >= 0; voiceNodeAt--) {
163
- const n = ctx.nodes[voiceNodeAt];
164
- if (n instanceof ASTTextNode) {
165
- if (!ctx.variables.strict)
166
- continue; // 非严格模式下允许文本节点夹在N和L之间
167
- // ParserContext.parseGrammar 处理后不会有空白字符
168
- throw new ErrorDiagnostic("E_LYRICS_WITHOUT_VOICE_NOTES", `strict 模式下,语法糖 'L:' 或 'L(name)' 必须跟在 @voice 的音符之后,但在其前面发现了未知文本`, n.sourceSpan);
169
- }
170
- if (n instanceof VoiceFunction)
171
- voiceNode = n;
172
- else if (n instanceof VoicesFunction)
173
- voiceNode = n.voices.at(-1) ?? null;
174
- break;
175
- }
176
- if (voiceNode === null) {
177
- throw new ErrorDiagnostic("E_LYRICS_WITHOUT_VOICE_NOTES", `语法糖 'L:' 或 'L(name):' 必须跟在 @voice(或 N:)之后,但没有找到符合要求的 voice;请检查语法或直接使用 @voice 函数`, n.span);
178
- }
179
- voiceNode.addLyric(n.data.name, n.data.lyric, n.span, ctx);
180
- ctx.nodes.length = voiceNodeAt + 1; // 清除voiceNodeAt之后的TextNode 因为被夹在N和L之间
181
- // 消费后面可能的换行符 只消费一个
182
- if (at < nodes.length && typeof nodes[at] === "number" && ctx.source[nodes[at]] === '\n')
183
- at++;
184
- return at;
185
- }
186
- // 当前层的换行或 N/L/V 声明结束音符内容,不能把下一组吞进声部
187
- let breakAt = at;
188
- let endWithBr = 0;
189
- for (; breakAt < nodes.length; breakAt++) {
190
- const n = nodes[breakAt];
191
- if (typeof n === "number") {
192
- if (ctx.source[n] === '\n') {
193
- // 换行符应该被 N: 消费
194
- endWithBr = 1;
195
- break;
196
- }
197
- }
198
- else if (n.kind === "sugar"
199
- && (n.data?.class === VoiceFunction || n.data?.class === VoicesFunction))
200
- break;
201
- }
202
- // 解析后面的内容 得到 VoiceFunction
203
- const newCtx = new ParserContext(ctx);
204
- const slicedNodes = nodes.slice(at, breakAt); // 防止子解析越界
205
- breakAt += endWithBr; // 不让子内容有换行符
206
- newCtx.makeNodes(slicedNodes);
207
- if (newCtx.nodes.length === 0) {
208
- throw Diagnostic.error.EmptyContent("voice", "content", n.span);
209
- }
210
- const span = { start: n.span.start, end: newCtx.nodes.at(-1).sourceSpan.end };
211
- const argMap = new Map();
212
- if (newCtx.nodes.length === 1 && newCtx.nodes[0] instanceof ASTBraceNode)
213
- argMap.set(0, newCtx.nodes[0]);
214
- // 复制一份:voice 的 span 之后会被歌词撑大,内容 brace 不该跟着长
215
- else
216
- argMap.set(0, new ASTBraceNode({ ...span }, newCtx.nodes));
217
- argMap.set("name", n.data.name);
218
- const newVoice = new VoiceFunction(span, argMap, ctx, null);
219
- // V 声明直接收集成员,最后统一组装,避免创建临时 voices
220
- if (members) {
221
- ctx.pushNode(newVoice);
222
- members.push(newVoice);
223
- return breakAt;
224
- }
225
- // 如果前面紧挨着 VoicesFunction | VoiceFunction 则直接加入
226
- let voicesNode = null;
227
- let voicesNodeAt = ctx.nodes.length - 1;
228
- let textBetween = null;
229
- ifCombine: for (; voicesNodeAt >= 0; voicesNodeAt--) {
230
- const n = ctx.nodes[voicesNodeAt];
231
- if (n instanceof ASTTextNode) {
232
- if (ctx.variables.strict)
233
- break;
234
- // 如果中间有换行符,直接说明是两个独立的 voice 组件,不能合并
235
- for (let i = n.sourceSpan.start; i < n.sourceSpan.end; i++) {
236
- if (ctx.source[i] === '\n')
237
- break ifCombine;
238
- }
239
- textBetween = n;
240
- continue;
241
- }
242
- if (n instanceof VoicesFunction) {
243
- if (!n.createdBySugar)
244
- break; // 不会合并到函数创建的 voices 中
245
- voicesNode = n;
246
- }
247
- else if (n instanceof VoiceFunction) {
248
- const args = new Map();
249
- args.set(0, n);
250
- voicesNode = new VoicesFunction({
251
- start: n.sourceSpan.start,
252
- end: n.sourceSpan.end
253
- }, args, ctx, null);
254
- voicesNode.createdBySugar = true;
255
- }
256
- break;
257
- }
258
- if (voicesNode) {
259
- ctx.nodes[voicesNodeAt] = voicesNode;
260
- voicesNode.addVoice(newVoice);
261
- if (textBetween) {
262
- ctx.nodes.length = voicesNodeAt + 1;
263
- ctx.diagnostics.push(new WarningDiagnostic("W_VOICES_TEXT_BETWEEN", `两个 @voice 之间有未知文本。当前处于非 strict 模式,会忽略该内容、合并为一个 @voices`, textBetween.sourceSpan));
264
- }
265
- }
266
- else
267
- ctx.pushNode(newVoice);
268
- return breakAt;
269
- }
270
- content; // 声部内容
271
- name; // 声部名称
272
- size; // 声部的字体大小
273
- font;
274
- lyrics;
275
- get children() { return [this.content]; }
276
- timeFlowModel() {
277
- return {
278
- children: this.children,
279
- mode: "sequence",
280
- };
281
- }
282
- /**
283
- * voice 的音符内容仍按普通 sequence 进入全局时间列
284
- * 此处只建立歌词作用域,并按需在内容前创建声部名对象
285
- */
286
- loweringEnter(ctx) {
287
- // 无名声部也要产出一个(不可见的)名称事件,才能保证同一个 voices 块内
288
- // 每个成员的列结构完全一致,从而把所有声部名归并到同一列
289
- const parent = this.parent;
290
- // 多声部时同时在名称右侧预留大括号的横向空间
291
- const braceSpace = parent instanceof VoicesFunction && parent.voices.length > 1
292
- ? parent.braceSpace
293
- : 0;
294
- const nameHost = new VoiceNameTemporal(this, braceSpace);
295
- // 收集范围内的
296
- const temporalMembers = [];
297
- const frames = [];
298
- ctx.beginLoweringGroup(this, {
299
- attachment: new VoiceLyricsAttachment(temporalMembers, nameHost, frames),
300
- onAttachment(attachment) {
301
- if (isLayoutAttachment(attachment) && attachment.layer === "background")
302
- frames.push(attachment);
303
- },
304
- onTemporal(node) { temporalMembers.push(node); },
305
- });
306
- return [nameHost];
307
- }
308
- loweringExit(ctx) {
309
- ctx.endLoweringGroup(this);
310
- return [];
311
- }
312
- constructor(span, args, ctx, parent = null) {
313
- super(span, parent);
314
- this.size = ctx.variables.fontsize;
315
- [this.content, this.name] = this.getArgValue(args, ctx);
316
- this.content.parent = this;
317
- this.font = ctx.variables.font;
318
- args.delete(0);
319
- args.delete("name");
320
- args.delete(1);
321
- this.lyrics = [];
322
- for (const [key, value] of args) {
323
- if (typeof value === "string") {
324
- this.addLyric(key, value);
325
- continue;
326
- }
327
- const arg = value;
328
- const v = ctx.parseArgWithType(arg.valueSpan, "string", span.start);
329
- if (v === null) {
330
- ctx.diagnostics.push(new WarningDiagnostic("W_VOICE_INVALID_LYRIC", `@voice 的歌词参数值解析失败, 参数[${key}]将被忽略`, arg.valueSpan));
331
- }
332
- else
333
- this.addLyric(key, v);
334
- }
335
- }
336
- addLyric(name, lyric, span = null, ctx = null) {
337
- if (typeof name === "number")
338
- name = "";
339
- const tokens = VoiceFunction.parseLyric(lyric);
340
- if (tokens.length === 0 && ctx && span) {
341
- ctx.diagnostics.push(new WarningDiagnostic("W_EMPTY_LYRIC", `@voice的歌词${name}是空的`, span));
342
- }
343
- this.lyrics.push({ name, tokens });
344
- if (span) {
345
- // 歌词是成节点之后才补上来的,祖先的 span 得一起长,否则按源码位置查节点会漏掉歌词那几行
346
- for (let node = this; node; node = node.parent) {
347
- node.sourceSpan.start = Math.min(span.start, node.sourceSpan.start);
348
- node.sourceSpan.end = Math.max(span.end, node.sourceSpan.end);
349
- }
350
- }
351
- }
352
- /**
353
- * 把歌词拆成与音符一一对应的槽位。
354
- * 例如 `hello world` 拆成 `hello`、`world`,`hel-lo` 拆成 `hel-`、`lo`;
355
- * `你好吗` 默认逐字拆分,`你 @ 好` 中的 `@` 留出一个空槽,`{你好} 啊` 则把 `你好` 放在同一个槽位。
356
- * 转义符:hel\-lo \@ {你\}好} 会得到 ["hel-lo", "@", "你}好"],而不是把 -、@、} 当控制符
357
- */
358
- static parseLyric(value) {
359
- const result = [];
360
- let token = "";
361
- let prefix = "";
362
- const pushSlot = (text) => {
363
- result.push(prefix + text);
364
- prefix = "";
365
- };
366
- const pushToken = () => {
367
- if (token)
368
- pushSlot(token);
369
- token = "";
370
- };
371
- for (let i = 0; i < value.length; i++) {
372
- const ch = String.fromCodePoint(value.codePointAt(i));
373
- i += ch.length - 1;
374
- if (ch === "\\" && i + 1 < value.length && /[\\{}@-]/.test(value[i + 1])) {
375
- token += value[++i];
376
- }
377
- else if (ch === "{") {
378
- let close = i + 1;
379
- let grouped = "";
380
- for (; close < value.length && value[close] !== "}"; close++) {
381
- if (value[close] === "\\" && close + 1 < value.length && /[\\{}@-]/.test(value[close + 1])) {
382
- grouped += value[++close];
383
- }
384
- else
385
- grouped += value[close];
386
- }
387
- if (close < value.length) {
388
- pushToken();
389
- pushSlot(grouped);
390
- i = close;
391
- }
392
- else
393
- token += ch;
394
- }
395
- else if (WHITEPACE_RE.test(ch)) {
396
- pushToken();
397
- }
398
- else if (ch === "-") {
399
- // 如果前面有内容 则把-放到前一个词里
400
- token += ch;
401
- if (token.length > 1)
402
- pushToken();
403
- }
404
- else if (ch === "@") {
405
- if (token) {
406
- token += ch;
407
- pushToken();
408
- }
409
- result.push('');
410
- }
411
- else if (LYRIC_OPENING_PUNCTUATION.has(ch)) {
412
- pushToken();
413
- prefix += ch;
414
- }
415
- else if (LYRIC_SILENT_PUNCTUATION.has(ch)) {
416
- if (token)
417
- token += ch;
418
- else if (prefix || !result.at(-1))
419
- prefix += ch;
420
- else
421
- result[result.length - 1] += ch;
422
- }
423
- else if (ch.charCodeAt(0) > 0x7F) {
424
- // 遇到中文等非ASCII字符 直接切分成单个字符
425
- pushToken();
426
- pushSlot(ch);
427
- }
428
- else
429
- token += ch;
430
- }
431
- pushToken();
432
- if (prefix) {
433
- if (result.at(-1))
434
- result[result.length - 1] += prefix;
435
- else
436
- result.push(prefix);
437
- }
438
- return result;
439
- }
440
- toString(source) {
441
- const parameters = [`${this.content.toString(source)},${quote(this.name)}`];
442
- for (const lyric of this.lyrics) {
443
- const text = quote(lyric.tokens.map(token => token.length === 0
444
- ? "@" : `{${token.replace(/[\\{}@-]/g, "\\$&")}}`).join(" "));
445
- parameters.push(lyric.name ? `${lyric.name}=${text}` : text);
446
- }
447
- return `@voice(\n\t${parameters.join(",\n\t")}\n)`;
448
- }
449
- }
450
- class VoicesFunction extends ASTFunctionNode {
451
- static def = {
452
- name: ["voices", "vs"],
453
- description: "多个声部",
454
- details: `\
455
- ~~~jpfun
456
- @voices(
457
- @voice({1 2 3}, 钢琴, 男=ha ha ha),
458
- @voice({3 4 5}, , "la la la")
459
- )
460
- ~~~
461
-
462
- 接受多个声部作为位置参数,将它们按时间对齐、分行排布;声部名称和歌词由各自的 \`@voice\` 提供
463
-
464
- **视觉连接**:仅命名参数 \`connect\` 使用字符串,如 \`connect="[1-4]{5-7}"\`。
465
- \`[]\` 是现有括线,\`{}\` 是弯曲大括号;编号从 1 开始,省略起点/终点表示首/末声部。
466
- \`[3]\` 等价于 \`[3-3]\`,\`{3}\` 等价于 \`{3-3}\`,用于单个声部。
467
- 默认 \`"[-]"\` 连接全部声部;\`""\` 只保留公共细连谱线。未指定的声部仍有细线,范围可以重叠,不改变声部或播放关系。
468
- 用 \`@set(voices.connect="{1-2}[3-]")\` 设置后续多声部块的默认方案,显式参数写在所有声部之后。
469
-
470
- **简写**:连续声明多个 \`N:\` 声部及其 \`L:\` 歌词,会自动组成 \`voices\`
471
-
472
- ~~~jpfun
473
- N(钢琴): 1 2 3
474
- L(男): ha ha ha
475
- N: 3 4 5
476
- L: la la la
477
- ~~~
478
-
479
- 连接声明 \`V{}:\`、\`V[]:\`、\`V|:\` 分别指定后续声部的弯曲大括号、现有括线和仅细线,后面的 \`N:\` 可以同行,也可以换行。
480
- 到下一条 V 声明或当前块末尾结束,组间不空行;空行结束整个多声部块。
481
- 出现 V 声明时,当前块完整替换默认连接方案,不影响后面的块。V 不创建音轨,L 仍属于前面的 N。
482
-
483
- ~~~jpfun
484
- V{}: N(右手): 1 2 3
485
- N(左手): 5 6 7
486
- V[]: N(女高): 6 6 5
487
- L: 啊 啊 啊
488
- N(女低): 1 2 3
489
- ~~~`,
490
- allowExtraArgs: true,
491
- extraArgType: "content",
492
- args: [{
493
- name: "connect",
494
- namedOnly: true,
495
- type: "string",
496
- default: "[-]",
497
- description: '视觉连接:[1-4] 为现有括线,{5-7} 为弯曲大括号;[3]、{3} 表示单个声部,省略范围端点表示首/末声部,空字符串只保留公共连谱线。',
498
- }]
499
- };
500
- static deSugarAtom(source, start, end) {
501
- if (source[start] !== "V")
502
- return null;
503
- const match = /^V(\{\}|\[\]|\|):/.exec(source.slice(start, end));
504
- if (!match)
505
- return null;
506
- const next = start + match[0].length;
507
- const node = {
508
- kind: "sugar",
509
- data: {
510
- class: VoicesFunction,
511
- kind: match[1] === "{}" ? "brace" : match[1] === "[]" ? "bracket" : "line",
512
- },
513
- span: { start, end: next },
514
- };
515
- return { next, node };
516
- }
517
- static deSugarRelation(ctx, nodes, at) {
518
- const first = nodes[at];
519
- if (typeof first === "number" || first.kind !== "sugar" || first.data?.class !== VoicesFunction)
520
- return null;
521
- let previousIndex = ctx.nodes.length - 1;
522
- while (previousIndex >= 0 && ctx.nodes[previousIndex] instanceof ASTTextNode) {
523
- const { sourceSpan } = ctx.nodes[previousIndex];
524
- const text = ctx.source.slice(sourceSpan.start, sourceSpan.end);
525
- if (text.includes("\n") || text.trim())
526
- break;
527
- previousIndex--;
528
- }
529
- const previous = ctx.nodes[previousIndex];
530
- const members = previous instanceof VoiceFunction ? [previous]
531
- : previous instanceof VoicesFunction && previous.createdBySugar ? [...previous.voices] : [];
532
- const mergePrevious = members.length > 0;
533
- const connections = [];
534
- let cursor = at;
535
- while (cursor < nodes.length) {
536
- const marker = nodes[cursor];
537
- if (typeof marker === "number" || marker.kind !== "sugar" || marker.data?.class !== VoicesFunction)
538
- break;
539
- cursor++;
540
- const carriageReturn = nodes[cursor];
541
- if (typeof carriageReturn === "number" && ctx.source[carriageReturn] === "\r")
542
- cursor++;
543
- const newline = nodes[cursor];
544
- if (typeof newline === "number" && ctx.source[newline] === "\n")
545
- cursor++;
546
- // 每段单独解析 N/L,防止歌词越过 V 声明附着到上一段
547
- const section = new ParserContext(ctx);
548
- const from = members.length + 1;
549
- while (cursor < nodes.length) {
550
- const node = nodes[cursor];
551
- if (typeof node === "number" || node.kind !== "sugar" || node.data?.class !== VoiceFunction)
552
- break;
553
- cursor = VoiceFunction.deSugarRelation(section, nodes, cursor, members);
554
- }
555
- if (members.length < from) {
556
- throw new ErrorDiagnostic("E_VOICES_GROUP_EMPTY", "V 声部分组必须至少包含一条 N: 声部声明", marker.span);
557
- }
558
- if (marker.data.kind === "brace" || marker.data.kind === "bracket") {
559
- connections.push({ kind: marker.data.kind, from, to: members.length });
560
- }
561
- }
562
- const args = new Map();
563
- members.forEach((member, index) => args.set(index, member));
564
- args.set("connect", serializeConnections(connections));
565
- const voices = new VoicesFunction({
566
- start: mergePrevious ? previous.sourceSpan.start : first.span.start,
567
- end: members.at(-1).sourceSpan.end,
568
- }, args, ctx);
569
- voices.createdBySugar = true;
570
- if (mergePrevious)
571
- ctx.nodes.length = previousIndex;
572
- ctx.pushNode(voices);
573
- return cursor;
574
- }
575
- voices;
576
- createdBySugar = false; // 不同创建方式的不能合并
577
- size; // parse 期冻结的字号,px
578
- /** 声部名右侧为大括号预留的横向空间 */
579
- braceSpace;
580
- connect;
581
- // 收集阶段只冻结配置,避免提前校验随后会被 V 声明覆盖的默认值。
582
- get connectionSpecs() {
583
- return parseConnections(this.connect, this.sourceSpan);
584
- }
585
- /** 闭包捕获 parse 期冻结的字号,用来决定空声部槽位的默认高度(1em) */
586
- measure;
587
- get children() { return this.voices; }
588
- timeFlowModel() {
589
- return {
590
- children: this.children,
591
- mode: "parallel",
592
- tracks: {
593
- laneKey: `voices/${this.voices.length}`,
594
- hostIndex: null, // 宿主不是成员:第一个 voice 也必须拥有独立轨道
595
- measure: this.measure,
596
- },
597
- };
598
- }
599
- /** 收集本块产生的声部名事件,退出时注册左侧大括号 */
600
- loweringEnter(ctx) {
601
- const names = [];
602
- ctx.beginLoweringGroup(this, {
603
- attachment: new VoicesBraceAttachment(names, this, resolveConnections(this.connectionSpecs, this.voices.length, this.sourceSpan)),
604
- onTemporal: node => {
605
- if (node instanceof VoiceNameTemporal && node.ast.parent === this)
606
- names.push(node);
607
- },
608
- });
609
- return [];
610
- }
611
- loweringExit(ctx) {
612
- ctx.endLoweringGroup(this);
613
- return [];
614
- }
615
- constructor(span, args, ctx, parent = null) {
616
- super(span, parent);
617
- this.voices = [];
618
- this.size = ctx.variables.fontsize;
619
- // 端钩有最小线宽,极小字号也要给它保留足够的横向空间
620
- this.braceSpace = Math.max(ctx.variables.fontsize, (MIN_CONNECTOR_STEM * (BRACKET_HOOK_REACH + 0.5) + 0.5) / (1 - CONNECTOR_LABEL_GAP_RATIO));
621
- this.measure = makeVoicesMeasure(ctx.variables.fontsize);
622
- [this.connect] = this.getArgValue(args, ctx);
623
- for (const [key, value] of args) {
624
- if (key === "connect")
625
- continue;
626
- const valueSpan = value instanceof ASTNodeBase ? value.sourceSpan : value.valueSpan;
627
- const voice = value instanceof ASTNodeBase ? value : ctx.parseArgWithType(valueSpan, "content", span.start);
628
- if (!(voice instanceof VoiceFunction)) {
629
- throw new ErrorDiagnostic("E_VOICES_INVALID_CHILD", `@voices 的参数必须是 @voice 函数,但发现了其他类型 ${voice?.constructor.name}`, valueSpan);
630
- }
631
- this.addVoice(voice);
632
- }
633
- if (this.voices.length === 0) {
634
- throw new ErrorDiagnostic("E_VOICES_EMPTY", `@voices 必须至少包含一个 @voice 函数`, span);
635
- }
636
- }
637
- addVoice(v) {
638
- this.voices.push(v);
639
- v.parent = this;
640
- this.sourceSpan.start = Math.min(v.sourceSpan.start, this.sourceSpan.start);
641
- this.sourceSpan.end = Math.max(v.sourceSpan.end, this.sourceSpan.end);
642
- }
643
- toString(source) {
644
- const parameters = this.voices.map(voice => `\t${voice.toString(source)}`);
645
- parameters.push(`\tconnect=${quote(serializeConnections(this.connectionSpecs))}`);
646
- return `@voices(\n${parameters.join(",\n")}\n)`;
647
- }
648
- }
649
- export const VoiceNode = VoiceFunction;
650
- export const VoicesNode = VoicesFunction;
651
- /** 歌词与歌词行名称相对声部字号的字号 */
652
- const LYRIC_SIZE_RATIO = 0.82;
653
- /** 无大括号时标签右侧的空隙,相对声部字号 */
654
- const NAME_GAP_RATIO = 0.6;
655
- /** 歌词行名称的宽度决定标签列宽度,因此声部名事件和歌词附件必须用同一个样式测量 */
656
- function lyricNameStyle(size, fontFamily) {
657
- return {
658
- fontFamily,
659
- fontSize: size * LYRIC_SIZE_RATIO,
660
- fill: "#000",
661
- fontWeight: 600,
662
- };
663
- }
664
- class VoiceNameTemporal extends TemporalNodeBase {
665
- /** 名称右侧为大括号预留的横向空间,0 表示不需要 */
666
- braceSpace;
667
- textBaselineY = 0;
668
- constructor(ast, braceSpace) {
669
- super();
670
- this.ast = ast;
671
- this.braceSpace = braceSpace;
672
- this.mergeKey = -2;
673
- // 既没有名称、也不需要括号空间和标签列时只保留不可见的占位事件:
674
- // 它不进入可见对象,也不让空声部失去默认槽位高度
675
- if (ast.name || braceSpace > 0 || ast.lyrics.some(lyric => lyric.name))
676
- this.initLayoutBox();
677
- }
678
- prepareLayout(context) {
679
- const metrics = this.ast.name
680
- ? context.textMeasurer.measureText(this.ast.name, this.style)
681
- : { w: 0, h: 0, baseline: 0 };
682
- // 声部名和歌词行名称共用这一列,列宽取其中最宽的一个
683
- let labelWidth = metrics.w;
684
- for (const lyric of this.ast.lyrics) {
685
- if (!lyric.name)
686
- continue;
687
- const lyricMetrics = context.textMeasurer.measureText(lyric.name, lyricNameStyle(this.ast.size, this.ast.font));
688
- labelWidth = Math.max(labelWidth, lyricMetrics.w);
689
- }
690
- // 没有大括号时也要在标签右侧留出与内容分离的空隙
691
- const rightSpace = this.braceSpace > 0 ? this.braceSpace
692
- : labelWidth > 0 ? this.ast.size * NAME_GAP_RATIO : 0;
693
- // 对齐点放在标签右边界:同一列共享 `x + anchor`,因此长短不一的声部名会右对齐,
694
- // 括号空间统一落在对齐点右侧
695
- this.box.w = labelWidth + rightSpace;
696
- this.box.h = metrics.h;
697
- this.box.anchor = labelWidth;
698
- this.box.visualAxis = metrics.h / 2;
699
- this.textBaselineY = metrics.baseline;
700
- // 声部名与第一个音符之间需要稳定但可压缩的横向间距
701
- this.springConfig.alpha_R = 0.45;
702
- }
703
- get style() {
704
- return {
705
- fontSize: this.ast.size * 0.85,
706
- fontFamily: this.ast.font,
707
- fill: "#000",
708
- fontWeight: 600,
709
- textAlign: "right",
710
- };
711
- }
712
- paint(painter) {
713
- if (!this.ast.name)
714
- return;
715
- painter.drawText(this.ast.name, this.box.x + this.box.anchor, this.box.y + this.textBaselineY, this.style);
716
- }
717
- }
718
- /**
719
- * 画在声部名与音符之间的多声部括线
720
- *
721
- * 共享一条细竖线,按连接范围添加粗括线或弯曲大括号
722
- * 纵向跨度直接取首末声部名事件的视觉轴(无名声部的占位盒高度为 0,其 y 就是轨道视觉轴),
723
- * 因此不需要反查任何轨道信息
724
- */
725
- class VoicesBraceAttachment {
726
- connections;
727
- layer = "background";
728
- names;
729
- ast;
730
- get sourceSpan() { return this.ast.sourceSpan; }
731
- constructor(names, ast, connections) {
732
- this.connections = connections;
733
- this.names = names;
734
- this.ast = ast;
735
- }
736
- createGeometry() {
737
- if (this.names.length < 2)
738
- return { regions: [], paint() { } };
739
- const first = this.names[0].box;
740
- const last = this.names[this.names.length - 1].box;
741
- const em = this.ast.size;
742
- const top = first.y + first.visualAxis - em * 0.5;
743
- const bottom = last.y + last.visualAxis + em * 0.5;
744
- if (bottom - top < 1e-6)
745
- return { regions: [], paint() { } };
746
- // 各部分尺寸都以粗竖线宽度为单位,比例取自常见简谱软件的括线
747
- const stem = Math.max(MIN_CONNECTOR_STEM, em * 0.19);
748
- const reach = stem * BRACKET_HOOK_REACH;
749
- const drop = stem * BRACKET_HOOK_DROP;
750
- const x = first.x + first.anchor + this.ast.braceSpace * CONNECTOR_LABEL_GAP_RATIO + stem / 2;
751
- const inset = Math.min(stem * 0.67, em * 0.25);
752
- const line = {
753
- x: x + stem * 1.33 - stem * 0.165,
754
- y: top + inset,
755
- w: stem * 0.33,
756
- h: bottom - top - inset * 2,
757
- };
758
- const bars = [];
759
- const paths = [];
760
- const regions = [line];
761
- for (const connection of this.connections) {
762
- const first = this.names[connection.from - 1].box;
763
- const last = this.names[connection.to - 1].box;
764
- const groupTop = first.y + first.visualAxis - em * 0.5;
765
- const groupBottom = last.y + last.visualAxis + em * 0.5;
766
- if (connection.kind === "bracket") {
767
- bars.push({ x: x - stem / 2, y: groupTop, w: stem, h: groupBottom - groupTop });
768
- paths.push({ commands: BRACKET_HOOK_COMMANDS, transform: { x, y: groupTop, scaleX: stem, scaleY: -stem } }, { commands: BRACKET_HOOK_COMMANDS, transform: { x, y: groupBottom, scaleX: stem, scaleY: stem } });
769
- regions.push({
770
- x: x - stem / 2, y: groupTop - drop,
771
- w: reach + stem / 2, h: groupBottom - groupTop + drop * 2,
772
- });
773
- }
774
- else {
775
- const width = em * 0.35;
776
- const left = line.x - em * 0.12 - width;
777
- const scaleX = width / CURVED_BRACE_BOUNDS.w;
778
- const scaleY = (groupBottom - groupTop) / CURVED_BRACE_BOUNDS.h;
779
- paths.push({
780
- commands: CURVED_BRACE_COMMANDS,
781
- transform: {
782
- x: left - CURVED_BRACE_BOUNDS.x * scaleX,
783
- y: groupTop - CURVED_BRACE_BOUNDS.y * scaleY,
784
- scaleX, scaleY,
785
- },
786
- });
787
- regions.push({ x: left, y: groupTop, w: width, h: groupBottom - groupTop });
788
- }
789
- }
790
- bars.push(line);
791
- return {
792
- regions,
793
- paint(painter) {
794
- for (const bar of bars) {
795
- painter.drawRect(bar.x, bar.y, bar.w, bar.h, { fill: "#000" });
796
- }
797
- for (const path of paths) {
798
- painter.drawPath(path.commands, { fill: "#000" }, path.transform);
799
- }
800
- },
801
- };
802
- }
803
- }
804
- class VoiceLyricsAttachment {
805
- temporalMembers;
806
- nameHost;
807
- frames;
808
- layer = "foreground";
809
- get sourceSpan() { return this.nameHost.ast.sourceSpan; }
810
- /** lowering 持续填入成员与内层框,布局阶段再读取 */
811
- constructor(temporalMembers, nameHost, frames) {
812
- this.temporalMembers = temporalMembers;
813
- this.nameHost = nameHost;
814
- this.frames = frames;
815
- }
816
- prepareHorizontal(lines, context) {
817
- const targets = this.temporalMembers
818
- .filter(isVisualTemporalNode)
819
- .filter(node => node.ports?.["lyric"]);
820
- const { lyrics, size } = this.nameHost.ast;
821
- if (targets.length === 0 || lyrics.length === 0)
822
- return;
823
- const style = { fontSize: size * LYRIC_SIZE_RATIO, fontFamily: this.nameHost.ast.font, fill: "#000" };
824
- for (let i = 0; i < targets.length; i++) {
825
- const target = targets[i];
826
- let halfWidth = 0;
827
- for (const lyric of lyrics) {
828
- const text = lyric.tokens[i];
829
- if (text) {
830
- const { body } = splitLyricText(text);
831
- if (body)
832
- halfWidth = Math.max(halfWidth, context.textMeasurer.measureText(body, style).w / 2);
833
- }
834
- }
835
- if (halfWidth === 0)
836
- continue;
837
- // 只扩大求解占用;视觉盒和端口不动,音符内部几何因此保持原位。
838
- lines[target.layoutLine]?.registerHorizontalLayoutHook(target, target, ({ columns, start }) => {
839
- const element = columns[start].find(item => item.time === target);
840
- if (!element)
841
- return;
842
- const lyricOffset = target.ports["lyric"].x - target.box.anchor;
843
- element.WL = Math.max(element.WL, halfWidth - lyricOffset);
844
- element.WR = Math.max(element.WR, halfWidth + lyricOffset);
845
- });
846
- }
847
- }
848
- createGeometry(context) {
849
- const preparedText = this.prepareGeometry(context);
850
- // 同一行同一轨的多行歌词由引擎合并成一段占用
851
- return {
852
- regions: preparedText,
853
- paint(painter) {
854
- for (const item of preparedText) {
855
- painter.drawText(item.text, item.x, item.y + item.textBaselineY, item.style);
856
- }
857
- },
858
- };
859
- }
860
- prepareGeometry(context) {
861
- const { lyrics, size } = this.nameHost.ast;
862
- const preparedText = [];
863
- const targets = this.temporalMembers
864
- .filter(isVisualTemporalNode)
865
- .filter(node => node.ports?.["lyric"]);
866
- if (targets.length === 0 || lyrics.length === 0)
867
- return preparedText;
868
- // 同一行、原始轨共用下沿,跨轨框外的占用可归属另一条轨
869
- const baselines = new Map();
870
- for (const target of targets) {
871
- let byTrack = baselines.get(target.layoutLine);
872
- if (!byTrack)
873
- baselines.set(target.layoutLine, byTrack = new Map());
874
- const baseline = byTrack.get(target.track) ?? { bottom: -Infinity, owner: target.track };
875
- const bounds = getLayoutBounds(target);
876
- let bottom = bounds.y + bounds.h;
877
- let owner = target.track;
878
- for (const frame of this.frames) {
879
- const box = context.getAttachmentBox(frame);
880
- if (box.x + box.w < bounds.x || box.x > bounds.x + bounds.w || box.y + box.h <= bottom)
881
- continue;
882
- const regions = context.getAttachmentOccupancy(frame);
883
- if (!regions)
884
- throw new Error("Layout attachment dependency has not been measured");
885
- const tracks = regions.filter(region => region.line === target.layoutLine);
886
- if (regions.some(region => region.line !== undefined) && tracks.length === 0)
887
- continue;
888
- bottom = box.y + box.h;
889
- for (const region of tracks) {
890
- if (region.line !== undefined && context.getVisualAxis(region.line, region.track)
891
- > context.getVisualAxis(target.layoutLine, owner))
892
- owner = region.track;
893
- }
894
- }
895
- if (bottom >= baseline.bottom)
896
- baseline.owner = owner;
897
- baseline.bottom = Math.max(baseline.bottom, bottom);
898
- byTrack.set(target.track, baseline);
899
- }
900
- const fontSize = size * LYRIC_SIZE_RATIO;
901
- const rowGap = size * 0.24;
902
- const firstRowGap = size * 0.32;
903
- const lyricStyle = { fontSize, fontFamily: this.nameHost.ast.font, fill: "#000" };
904
- const nameStyle = lyricNameStyle(size, this.nameHost.ast.font);
905
- const baselineOffset = context.textMeasurer.measureText("M", lyricStyle).baseline + firstRowGap;
906
- const baselineOf = (bottom, row) => bottom + baselineOffset + row * (fontSize + rowGap);
907
- // 跨轨框外的歌词由最下轨承担占用,各原始轨的歌词行依次排列
908
- if (this.frames.length)
909
- for (const [line, byTrack] of baselines) {
910
- if (byTrack.size < 2)
911
- continue;
912
- const rows = new Map();
913
- for (const [, baseline] of [...byTrack].sort(([left], [right]) => context.getVisualAxis(line, left) - context.getVisualAxis(line, right))) {
914
- const row = rows.get(baseline.owner) ?? 0;
915
- baseline.bottom += row * lyrics.length * (fontSize + rowGap);
916
- rows.set(baseline.owner, row + 1);
917
- }
918
- }
919
- // 歌词行名称与声部名共用左侧那一列,因此只出现在声部名所在的那一行
920
- const { box: labelBox, layoutLine: labelLine, track: labelTrack } = this.nameHost;
921
- const labelBaseline = baselines.get(labelLine)?.get(labelTrack);
922
- for (let row = 0; row < lyrics.length; row++) {
923
- const lyric = lyrics[row];
924
- for (let i = 0; i < lyric.tokens.length && i < targets.length; i++) {
925
- const text = lyric.tokens[i];
926
- const target = targets[i];
927
- const baseline = baselines.get(target.layoutLine)?.get(target.track);
928
- if (!text || !baseline)
929
- continue;
930
- const metrics = context.textMeasurer.measureText(text, lyricStyle);
931
- const { prefix, body } = splitLyricText(text);
932
- const bodyWidth = body ? context.textMeasurer.measureText(body, lyricStyle).w : 0;
933
- const prefixWidth = prefix ? context.textMeasurer.measureText(prefix, lyricStyle).w : 0;
934
- preparedText.push({
935
- text,
936
- style: lyricStyle,
937
- textBaselineY: metrics.baseline,
938
- x: target.box.x + target.ports["lyric"].x - bodyWidth / 2 - prefixWidth,
939
- y: baselineOf(baseline.bottom, row) - metrics.baseline,
940
- w: metrics.w,
941
- h: metrics.h,
942
- line: target.layoutLine,
943
- track: baseline.owner,
944
- });
945
- }
946
- if (!lyric.name || !labelBox || !labelBaseline)
947
- continue;
948
- const metrics = context.textMeasurer.measureText(lyric.name, nameStyle);
949
- preparedText.push({
950
- text: lyric.name,
951
- style: nameStyle,
952
- textBaselineY: metrics.baseline,
953
- x: labelBox.x + labelBox.anchor - metrics.w,
954
- y: baselineOf(labelBaseline.bottom, row) - metrics.baseline,
955
- w: metrics.w,
956
- h: metrics.h,
957
- line: labelLine,
958
- track: labelBaseline.owner,
959
- });
960
- }
961
- return preparedText;
962
- }
963
- }
1
+ export { VoiceNode } from "./voice.js";
2
+ export { VoicesNode } from "./voices.js";