jpfun 0.5.0 → 0.7.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 (79) hide show
  1. package/dist/converter/midi/convert.d.ts +3 -1
  2. package/dist/converter/midi/convert.js +78 -66
  3. package/dist/converter/musicxml/features.d.ts +19 -5
  4. package/dist/converter/musicxml/features.js +46 -8
  5. package/dist/converter/musicxml/index.js +142 -23
  6. package/dist/converter/musicxml/model.d.ts +15 -0
  7. package/dist/diagnostic.js +1 -1
  8. package/dist/functions/ASTtypes.d.ts +4 -0
  9. package/dist/functions/ASTtypes.js +25 -14
  10. package/dist/functions/adjust/index.js +6 -2
  11. package/dist/functions/arpeggio/index.js +21 -17
  12. package/dist/functions/arpeggio/shape.d.ts +1 -1
  13. package/dist/functions/arpeggio/shape.js +27 -21
  14. package/dist/functions/bar/index.js +37 -36
  15. package/dist/functions/beam/auto.js +18 -24
  16. package/dist/functions/beam/layout.js +15 -23
  17. package/dist/functions/box/index.js +52 -1
  18. package/dist/functions/br/index.js +3 -4
  19. package/dist/functions/default.js +10 -5
  20. package/dist/functions/div/index.js +2 -3
  21. package/dist/functions/gliss/index.d.ts +2 -0
  22. package/dist/functions/gliss/index.js +180 -0
  23. package/dist/functions/grace/index.d.ts +4 -2
  24. package/dist/functions/grace/index.js +19 -11
  25. package/dist/functions/head/index.js +50 -62
  26. package/dist/functions/meter/index.js +45 -24
  27. package/dist/functions/meter/shape.d.ts +3 -0
  28. package/dist/functions/meter/shape.js +43 -0
  29. package/dist/functions/note/accidentals.js +10 -16
  30. package/dist/functions/note/index.js +38 -48
  31. package/dist/functions/ottava/index.d.ts +2 -0
  32. package/dist/functions/ottava/index.js +217 -0
  33. package/dist/functions/page/index.js +3 -3
  34. package/dist/functions/pagebreak/index.d.ts +2 -0
  35. package/dist/functions/pagebreak/index.js +36 -0
  36. package/dist/functions/rest/index.d.ts +2 -0
  37. package/dist/functions/rest/index.js +231 -0
  38. package/dist/functions/slide/index.d.ts +2 -0
  39. package/dist/functions/slide/index.js +132 -0
  40. package/dist/functions/stack/index.js +8 -15
  41. package/dist/functions/symbol/index.d.ts +9 -0
  42. package/dist/functions/symbol/index.js +41 -12
  43. package/dist/functions/symbol/ornament.js +15 -20
  44. package/dist/functions/symbol/shape.js +4 -1
  45. package/dist/functions/symbol/symbols/fine.js +1 -1
  46. package/dist/functions/symbol/symbols/tr.js +46 -1
  47. package/dist/functions/temporal.d.ts +36 -12
  48. package/dist/functions/temporal.js +29 -9
  49. package/dist/functions/tie/index.js +46 -32
  50. package/dist/functions/tuplet/index.js +1 -1
  51. package/dist/functions/up/index.js +51 -33
  52. package/dist/functions/voice/connections.d.ts +19 -0
  53. package/dist/functions/voice/connections.js +90 -0
  54. package/dist/functions/voice/index.js +245 -99
  55. package/dist/functions/volta/index.js +41 -21
  56. package/dist/jpfun.core.min.js +48 -55
  57. package/dist/jpfun.from-midi.min.js +5 -5
  58. package/dist/jpfun.from-musicxml.min.js +8 -8
  59. package/dist/jpfun.min.js +57 -64
  60. package/dist/layout/engine.d.ts +4 -1
  61. package/dist/layout/engine.js +232 -75
  62. package/dist/layout/model.js +22 -66
  63. package/dist/layout/page.d.ts +3 -2
  64. package/dist/layout/page.js +7 -6
  65. package/dist/layout/types.d.ts +34 -45
  66. package/dist/lowering/loweringContext.d.ts +1 -1
  67. package/dist/lowering/loweringContext.js +41 -171
  68. package/dist/parser/parserContext.d.ts +2 -0
  69. package/dist/parser/parserContext.js +31 -14
  70. package/dist/parser/preprocess.js +4 -6
  71. package/dist/playback/compile.js +12 -3
  72. package/dist/playback/types.d.ts +4 -2
  73. package/dist/render/paint.js +1 -1
  74. package/dist/render/svg.js +1 -0
  75. package/dist/render/text.d.ts +1 -1
  76. package/dist/render/text.js +3 -2
  77. package/dist/render/types.d.ts +1 -0
  78. package/grammar.md +221 -257
  79. package/package.json +1 -1
@@ -0,0 +1,90 @@
1
+ import { ErrorDiagnostic } from "../../diagnostic.js";
2
+ import { pathBounds } from "../../layout/path.js";
3
+ export const CURVED_BRACE_COMMANDS = [
4
+ { op: "M", x: 2.98438, y: -165.5 },
5
+ { op: "C", cx1: 8.9375, cy1: -171.781, cx2: 20.5156, cy2: -184.688, x: 20.5156, y: -208.531 },
6
+ { op: "C", cx1: 20.5156, cy1: -238.641, cx2: 7.60938, cy2: -269.094, x: 7.60938, y: -287.969 },
7
+ { op: "C", cx1: 7.60938, cy1: -308.156, cx2: 19.2031, cy2: -327.016, x: 19.8594, y: -327.688 },
8
+ { op: "C", cx1: 19.8594, cy1: -328.016, cx2: 19.8594, cy2: -328.016, x: 19.8594, y: -328.344 },
9
+ { op: "C", cx1: 19.8594, cy1: -328.672, cx2: 19.8594, cy2: -329, x: 19.5313, y: -329.344 },
10
+ { op: "C", cx1: 19.2031, cy1: -329.344, cx2: 18.5313, cy2: -329.344, x: 18.2031, y: -328.672 },
11
+ { op: "C", cx1: 17.875, cy1: -328.344, cx2: 0, cy2: -310.469, x: 0, y: -283.328 },
12
+ { op: "C", cx1: 0, cy1: -254.203, cx2: 11.5781, cy2: -233.688, x: 11.5781, y: -195.625 },
13
+ { op: "C", cx1: 11.5781, cy1: -188.328, cx2: 8.60938, cy2: -176.75, x: 0.328125, y: -166.484 },
14
+ { op: "C", cx1: 0, cy1: -166.484, cx2: 0, cy2: -165.828, x: 0, y: -165.5 },
15
+ { op: "C", cx1: -0.328125, cy1: -165.172, cx2: 0, cy2: -164.828, x: 0.328125, y: -164.5 },
16
+ { op: "C", cx1: 8.60938, cy1: -154.25, cx2: 11.5781, cy2: -142.656, x: 11.5781, y: -135.375 },
17
+ { op: "C", cx1: 11.5781, cy1: -97.3125, cx2: 0, cy2: -76.7969, x: 0, y: -47.6563 },
18
+ { op: "C", cx1: 0, cy1: -20.8594, cx2: 17.875, cy2: -2.64063, x: 18.2031, y: -2.3125 },
19
+ { op: "C", cx1: 18.5313, cy1: -1.65625, cx2: 19.2031, cy2: -1.32813, x: 19.5313, y: -1.65625 },
20
+ { op: "C", cx1: 19.8594, cy1: -1.98438, cx2: 20.1875, cy2: -2.3125, x: 19.8594, y: -2.64063 },
21
+ { op: "C", cx1: 19.8594, cy1: -2.64063, cx2: 19.8594, cy2: -2.98438, x: 19.8594, y: -3.3125 },
22
+ { op: "C", cx1: 19.2031, cy1: -3.96875, cx2: 7.60938, cy2: -22.8438, x: 7.60938, y: -43.0313 },
23
+ { op: "C", cx1: 7.60938, cy1: -61.8906, cx2: 20.5156, cy2: -92.3438, x: 20.5156, y: -122.469 },
24
+ { op: "C", cx1: 20.5156, cy1: -146.625, cx2: 8.9375, cy2: -159.203, x: 2.98438, y: -165.5 },
25
+ { op: "Z" },
26
+ ];
27
+ export const CURVED_BRACE_BOUNDS = pathBounds(CURVED_BRACE_COMMANDS);
28
+ /** 方括线端钩,以粗竖线宽度为单位,绘制时上下镜像 */
29
+ export const BRACKET_HOOK_REACH = 2.33;
30
+ export const BRACKET_HOOK_DROP = 1.17;
31
+ const BRACKET_HOOK_BASE = 0.34;
32
+ export const BRACKET_HOOK_COMMANDS = [
33
+ { op: "M", x: 0, y: 0 },
34
+ { op: "L", x: 0, y: -BRACKET_HOOK_BASE },
35
+ {
36
+ op: "C",
37
+ cx1: BRACKET_HOOK_REACH * 0.421, cy1: -BRACKET_HOOK_BASE + BRACKET_HOOK_DROP * 0.077,
38
+ cx2: BRACKET_HOOK_REACH * 0.733, cy2: -BRACKET_HOOK_BASE + BRACKET_HOOK_DROP * 0.346,
39
+ x: BRACKET_HOOK_REACH, y: -BRACKET_HOOK_BASE + BRACKET_HOOK_DROP,
40
+ },
41
+ { op: "L", x: BRACKET_HOOK_REACH * 0.929, y: -BRACKET_HOOK_BASE + BRACKET_HOOK_DROP },
42
+ {
43
+ op: "C",
44
+ cx1: BRACKET_HOOK_REACH * 0.696, cy1: -BRACKET_HOOK_BASE + BRACKET_HOOK_DROP * 0.535,
45
+ cx2: BRACKET_HOOK_REACH * 0.328, cy2: -BRACKET_HOOK_BASE + BRACKET_HOOK_DROP * 0.352,
46
+ x: 0, y: 0,
47
+ },
48
+ { op: "Z" },
49
+ ];
50
+ function invalidConnection(span) {
51
+ return new ErrorDiagnostic("E_VOICES_CONNECT", '@voices 的 connect 必须是 [起点-终点]、{起点-终点}、[编号] 或 {编号} 的组合;范围端点可省略,否则须为有效声部编号。空字符串表示只有连谱线。', span);
52
+ }
53
+ export function parseConnections(value, span) {
54
+ const source = value.trim();
55
+ // 粘连匹配必须消费整串,不能跳过非法字符
56
+ // 非空数字与其后空白一起可选,避免省略端点时重复回溯
57
+ const pattern = /\s*([\[{])\s*(?:(?:(\d+)\s*)?-\s*(?:(\d+)\s*)?|(\d+)\s*)([\]}])\s*/y;
58
+ const result = [];
59
+ while (pattern.lastIndex < source.length) {
60
+ const match = pattern.exec(source);
61
+ if (!match || match[5] !== (match[1] === "[" ? "]" : "}"))
62
+ throw invalidConnection(span);
63
+ const fromText = match[4] ?? match[2];
64
+ const toText = match[4] ?? match[3];
65
+ const from = fromText ? Number(fromText) : undefined;
66
+ const to = toText ? Number(toText) : undefined;
67
+ for (const endpoint of [from, to]) {
68
+ if (endpoint !== undefined && (!Number.isSafeInteger(endpoint) || endpoint < 1)) {
69
+ throw invalidConnection(span);
70
+ }
71
+ }
72
+ if (from !== undefined && to !== undefined && from > to)
73
+ throw invalidConnection(span);
74
+ result.push({ kind: match[1] === "[" ? "bracket" : "brace", from, to });
75
+ }
76
+ return result;
77
+ }
78
+ export function resolveConnections(specs, count, span) {
79
+ return specs.map(({ kind, from = 1, to = count }) => {
80
+ if (from > to || to > count)
81
+ throw invalidConnection(span);
82
+ return { kind, from, to };
83
+ });
84
+ }
85
+ export function serializeConnections(specs) {
86
+ return specs.map(({ kind, from, to }) => {
87
+ const range = `${from ?? ""}-${to ?? ""}`;
88
+ return kind === "brace" ? `{${range}}` : `[${range}]`;
89
+ }).join("");
90
+ }
@@ -3,8 +3,13 @@ import { Diagnostic, ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic
3
3
  import { findRightParen } from "../../parser/parse-utils/call-utils.js";
4
4
  import { findClosingQuote, quote, removeQuote } from "../../parser/parse-utils/string-utils.js";
5
5
  import { ParserContext, skipSpaces } from "../../parser/parserContext.js";
6
+ import { isLayoutAttachment } from "../../layout/types.js";
7
+ import { getLayoutBounds } from "../../layout/engine.js";
6
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";
7
10
  const WHITEPACE_RE = /\s/;
11
+ const MIN_CONNECTOR_STEM = 2.5;
12
+ const CONNECTOR_LABEL_GAP_RATIO = 0.3;
8
13
  // 分词跟后面的标点
9
14
  const LYRIC_OPENING_PUNCTUATION = new Set("(([[{〈《「『【〔〖〘〚‘“");
10
15
  // 不发声的标点;位于歌词槽首尾时只渲染,不占位,也不参与对齐中心计算
@@ -146,7 +151,7 @@ L: la la la
146
151
  return { next: pos, node };
147
152
  }
148
153
  }
149
- static deSugarRelation(ctx, nodes, at) {
154
+ static deSugarRelation(ctx, nodes, at, members) {
150
155
  const n = nodes[at++];
151
156
  if (n.data?.class !== VoiceFunction)
152
157
  return null;
@@ -178,7 +183,7 @@ L: la la la
178
183
  at++;
179
184
  return at;
180
185
  }
181
- // 音符 向后找到第一个 \n 或下一个 voice 组件
186
+ // 当前层的换行或 N/L/V 声明结束音符内容,不能把下一组吞进声部
182
187
  let breakAt = at;
183
188
  let endWithBr = 0;
184
189
  for (; breakAt < nodes.length; breakAt++) {
@@ -190,7 +195,8 @@ L: la la la
190
195
  break;
191
196
  }
192
197
  }
193
- else if (n.kind === "sugar" && n.data?.class === VoiceFunction)
198
+ else if (n.kind === "sugar"
199
+ && (n.data?.class === VoiceFunction || n.data?.class === VoicesFunction))
194
200
  break;
195
201
  }
196
202
  // 解析后面的内容 得到 VoiceFunction
@@ -210,6 +216,12 @@ L: la la la
210
216
  argMap.set(0, new ASTBraceNode({ ...span }, newCtx.nodes));
211
217
  argMap.set("name", n.data.name);
212
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
+ }
213
225
  // 如果前面紧挨着 VoicesFunction | VoiceFunction 则直接加入
214
226
  let voicesNode = null;
215
227
  let voicesNodeAt = ctx.nodes.length - 1;
@@ -282,11 +294,14 @@ L: la la la
282
294
  const nameHost = new VoiceNameTemporal(this, braceSpace);
283
295
  // 收集范围内的
284
296
  const temporalMembers = [];
297
+ const frames = [];
285
298
  ctx.beginLoweringGroup(this, {
286
- attachment: new VoiceLyricsAttachment(temporalMembers, nameHost),
287
- onTemporal(node) {
288
- temporalMembers.push(node);
299
+ attachment: new VoiceLyricsAttachment(temporalMembers, nameHost, frames),
300
+ onAttachment(attachment) {
301
+ if (isLayoutAttachment(attachment) && attachment.layer === "background")
302
+ frames.push(attachment);
289
303
  },
304
+ onTemporal(node) { temporalMembers.push(node); },
290
305
  });
291
306
  return [nameHost];
292
307
  }
@@ -446,6 +461,12 @@ class VoicesFunction extends ASTFunctionNode {
446
461
 
447
462
  接受多个声部作为位置参数,将它们按时间对齐、分行排布;声部名称和歌词由各自的 \`@voice\` 提供
448
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
+
449
470
  **简写**:连续声明多个 \`N:\` 声部及其 \`L:\` 歌词,会自动组成 \`voices\`
450
471
 
451
472
  ~~~jpfun
@@ -453,16 +474,114 @@ N(钢琴): 1 2 3
453
474
  L(男): ha ha ha
454
475
  N: 3 4 5
455
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
456
489
  ~~~`,
457
490
  allowExtraArgs: true,
458
491
  extraArgType: "content",
459
- args: []
492
+ args: [{
493
+ name: "connect",
494
+ namedOnly: true,
495
+ type: "string",
496
+ default: "[-]",
497
+ description: '视觉连接:[1-4] 为现有括线,{5-7} 为弯曲大括号;[3]、{3} 表示单个声部,省略范围端点表示首/末声部,空字符串只保留公共连谱线。',
498
+ }]
460
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
+ }
461
575
  voices;
462
576
  createdBySugar = false; // 不同创建方式的不能合并
463
577
  size; // parse 期冻结的字号,px
464
578
  /** 声部名右侧为大括号预留的横向空间 */
465
579
  braceSpace;
580
+ connect;
581
+ // 收集阶段只冻结配置,避免提前校验随后会被 V 声明覆盖的默认值。
582
+ get connectionSpecs() {
583
+ return parseConnections(this.connect, this.sourceSpan);
584
+ }
466
585
  /** 闭包捕获 parse 期冻结的字号,用来决定空声部槽位的默认高度(1em) */
467
586
  measure;
468
587
  get children() { return this.voices; }
@@ -481,7 +600,7 @@ L: la la la
481
600
  loweringEnter(ctx) {
482
601
  const names = [];
483
602
  ctx.beginLoweringGroup(this, {
484
- attachment: new VoicesBraceAttachment(names, this),
603
+ attachment: new VoicesBraceAttachment(names, this, resolveConnections(this.connectionSpecs, this.voices.length, this.sourceSpan)),
485
604
  onTemporal: node => {
486
605
  if (node instanceof VoiceNameTemporal && node.ast.parent === this)
487
606
  names.push(node);
@@ -497,24 +616,19 @@ L: la la la
497
616
  super(span, parent);
498
617
  this.voices = [];
499
618
  this.size = ctx.variables.fontsize;
500
- this.braceSpace = 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));
501
621
  this.measure = makeVoicesMeasure(ctx.variables.fontsize);
502
- for (const [, value] of args) {
503
- if (value instanceof ASTNodeBase) {
504
- if (value instanceof VoiceFunction)
505
- this.addVoice(value);
506
- else {
507
- throw new ErrorDiagnostic("E_VOICES_INVALID_CHILD", `@voices 的参数必须是 @voice 函数,但发现了其他类型 ${value.constructor.name}`, value instanceof ASTNodeBase ? value.sourceSpan : span);
508
- }
622
+ [this.connect] = this.getArgValue(args, ctx);
623
+ for (const [key, value] of args) {
624
+ if (key === "connect")
509
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);
510
630
  }
511
- const arg = value;
512
- const v = ctx.parseArgWithType(arg.valueSpan, "content", span.start);
513
- if (v instanceof VoiceFunction)
514
- this.addVoice(v);
515
- else {
516
- throw new ErrorDiagnostic("E_VOICES_INVALID_CHILD", `@voices 的参数必须是 @voice 函数,但发现了其他类型 ${v?.constructor.name}`, arg.valueSpan);
517
- }
631
+ this.addVoice(voice);
518
632
  }
519
633
  if (this.voices.length === 0) {
520
634
  throw new ErrorDiagnostic("E_VOICES_EMPTY", `@voices 必须至少包含一个 @voice 函数`, span);
@@ -527,12 +641,9 @@ L: la la la
527
641
  this.sourceSpan.end = Math.max(v.sourceSpan.end, this.sourceSpan.end);
528
642
  }
529
643
  toString(source) {
530
- const voicelines = Array(this.voices.length);
531
- for (let i = 0; i < this.voices.length; i++) {
532
- const part = `\t${this.voices[i].toString(source)}`;
533
- voicelines[i] = part;
534
- }
535
- return `@voices(\n${voicelines.join(",\n")}\n)`;
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)`;
536
647
  }
537
648
  }
538
649
  export const VoiceNode = VoiceFunction;
@@ -604,41 +715,21 @@ class VoiceNameTemporal extends TemporalNodeBase {
604
715
  painter.drawText(this.ast.name, this.box.x + this.box.anchor, this.box.y + this.textBaselineY, this.style);
605
716
  }
606
717
  }
607
- /** 括线端头的小钩;单位尺寸,绘制时按粗竖线宽度缩放并上下镜像 */
608
- const BRACE_HOOK_REACH = 2.33;
609
- const BRACE_HOOK_DROP = 1.17;
610
- const BRACE_HOOK_BASE = 0.34;
611
- const BRACE_HOOK_COMMANDS = [
612
- { op: "M", x: 0, y: 0 },
613
- { op: "L", x: 0, y: -BRACE_HOOK_BASE },
614
- {
615
- op: "C",
616
- cx1: BRACE_HOOK_REACH * 0.421, cy1: -BRACE_HOOK_BASE + BRACE_HOOK_DROP * 0.077,
617
- cx2: BRACE_HOOK_REACH * 0.733, cy2: -BRACE_HOOK_BASE + BRACE_HOOK_DROP * 0.346,
618
- x: BRACE_HOOK_REACH, y: -BRACE_HOOK_BASE + BRACE_HOOK_DROP,
619
- },
620
- { op: "L", x: BRACE_HOOK_REACH * 0.929, y: -BRACE_HOOK_BASE + BRACE_HOOK_DROP },
621
- {
622
- op: "C",
623
- cx1: BRACE_HOOK_REACH * 0.696, cy1: -BRACE_HOOK_BASE + BRACE_HOOK_DROP * 0.535,
624
- cx2: BRACE_HOOK_REACH * 0.328, cy2: -BRACE_HOOK_BASE + BRACE_HOOK_DROP * 0.352,
625
- x: 0, y: 0,
626
- },
627
- { op: "Z" },
628
- ];
629
718
  /**
630
719
  * 画在声部名与音符之间的多声部括线
631
720
  *
632
- * 由一条粗竖线、一条略向内收的细竖线和两端的小钩组成。
721
+ * 共享一条细竖线,按连接范围添加粗括线或弯曲大括号
633
722
  * 纵向跨度直接取首末声部名事件的视觉轴(无名声部的占位盒高度为 0,其 y 就是轨道视觉轴),
634
- * 因此不需要反查任何轨道信息。
723
+ * 因此不需要反查任何轨道信息
635
724
  */
636
725
  class VoicesBraceAttachment {
726
+ connections;
637
727
  layer = "background";
638
728
  names;
639
729
  ast;
640
730
  get sourceSpan() { return this.ast.sourceSpan; }
641
- constructor(names, ast) {
731
+ constructor(names, ast, connections) {
732
+ this.connections = connections;
642
733
  this.names = names;
643
734
  this.ast = ast;
644
735
  }
@@ -653,53 +744,74 @@ class VoicesBraceAttachment {
653
744
  if (bottom - top < 1e-6)
654
745
  return { regions: [], paint() { } };
655
746
  // 各部分尺寸都以粗竖线宽度为单位,比例取自常见简谱软件的括线
656
- const stem = Math.max(2.5, em * 0.19);
657
- const reach = stem * BRACE_HOOK_REACH;
658
- const drop = stem * BRACE_HOOK_DROP;
659
- const x = first.x + first.anchor + this.ast.braceSpace * 0.3 + stem / 2;
660
- const bars = [
661
- { x: x - stem / 2, y: top, w: stem, h: bottom - top },
662
- {
663
- x: x + stem * 1.33 - stem * 0.165,
664
- y: top + stem * 0.67,
665
- w: stem * 0.33,
666
- h: bottom - top - stem * 1.34,
667
- },
668
- ];
669
- const hooks = [
670
- { x, y: top, scale: stem, dir: -1 },
671
- { x, y: bottom, scale: stem, dir: 1 },
672
- ];
673
- // 括线画在声部名左侧的空白里,只参与画布边界,不抢任何轨道的纵向空间
674
- const regions = [{
675
- x: x - stem / 2,
676
- y: top - drop,
677
- w: reach + stem / 2,
678
- h: bottom - top + drop * 2,
679
- }];
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);
680
791
  return {
681
792
  regions,
682
793
  paint(painter) {
683
794
  for (const bar of bars) {
684
795
  painter.drawRect(bar.x, bar.y, bar.w, bar.h, { fill: "#000" });
685
796
  }
686
- for (const hook of hooks) {
687
- painter.drawPath(BRACE_HOOK_COMMANDS, { fill: "#000" }, { x: hook.x, y: hook.y, scaleX: hook.scale, scaleY: hook.scale * hook.dir });
797
+ for (const path of paths) {
798
+ painter.drawPath(path.commands, { fill: "#000" }, path.transform);
688
799
  }
689
800
  },
690
801
  };
691
802
  }
692
803
  }
693
804
  class VoiceLyricsAttachment {
694
- layer = "foreground";
695
- /** lowering 会持续向这个数组加入 voice 内容产生的 temporal */
696
805
  temporalMembers;
697
- /** 同一个 voice 的声部名事件,歌词行名称向它的对齐点右对齐 */
698
806
  nameHost;
807
+ frames;
808
+ layer = "foreground";
699
809
  get sourceSpan() { return this.nameHost.ast.sourceSpan; }
700
- constructor(temporalMembers, nameHost) {
810
+ /** lowering 持续填入成员与内层框,布局阶段再读取 */
811
+ constructor(temporalMembers, nameHost, frames) {
701
812
  this.temporalMembers = temporalMembers;
702
813
  this.nameHost = nameHost;
814
+ this.frames = frames;
703
815
  }
704
816
  prepareHorizontal(lines, context) {
705
817
  const targets = this.temporalMembers
@@ -753,15 +865,37 @@ class VoiceLyricsAttachment {
753
865
  .filter(node => node.ports?.["lyric"]);
754
866
  if (targets.length === 0 || lyrics.length === 0)
755
867
  return preparedText;
756
- // 每个 system+track 的歌词共用一条基线
757
- // 装饰高度先汇总为下边界,不进入单个 token 的 y 计算
758
- const contentBottom = new Map();
868
+ // 同一行、原始轨共用下沿,跨轨框外的占用可归属另一条轨
869
+ const baselines = new Map();
759
870
  for (const target of targets) {
760
- let byTrack = contentBottom.get(target.layoutLine);
871
+ let byTrack = baselines.get(target.layoutLine);
761
872
  if (!byTrack)
762
- contentBottom.set(target.layoutLine, byTrack = new Map());
763
- const bottom = target.box.y + target.box.h;
764
- byTrack.set(target.track, Math.max(byTrack.get(target.track) ?? bottom, bottom));
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);
765
899
  }
766
900
  const fontSize = size * LYRIC_SIZE_RATIO;
767
901
  const rowGap = size * 0.24;
@@ -770,16 +904,28 @@ class VoiceLyricsAttachment {
770
904
  const nameStyle = lyricNameStyle(size, this.nameHost.ast.font);
771
905
  const baselineOffset = context.textMeasurer.measureText("M", lyricStyle).baseline + firstRowGap;
772
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
+ }
773
919
  // 歌词行名称与声部名共用左侧那一列,因此只出现在声部名所在的那一行
774
920
  const { box: labelBox, layoutLine: labelLine, track: labelTrack } = this.nameHost;
775
- const labelBottom = contentBottom.get(labelLine)?.get(labelTrack);
921
+ const labelBaseline = baselines.get(labelLine)?.get(labelTrack);
776
922
  for (let row = 0; row < lyrics.length; row++) {
777
923
  const lyric = lyrics[row];
778
924
  for (let i = 0; i < lyric.tokens.length && i < targets.length; i++) {
779
925
  const text = lyric.tokens[i];
780
926
  const target = targets[i];
781
- const bottom = contentBottom.get(target.layoutLine)?.get(target.track);
782
- if (!text || bottom === undefined)
927
+ const baseline = baselines.get(target.layoutLine)?.get(target.track);
928
+ if (!text || !baseline)
783
929
  continue;
784
930
  const metrics = context.textMeasurer.measureText(text, lyricStyle);
785
931
  const { prefix, body } = splitLyricText(text);
@@ -790,14 +936,14 @@ class VoiceLyricsAttachment {
790
936
  style: lyricStyle,
791
937
  textBaselineY: metrics.baseline,
792
938
  x: target.box.x + target.ports["lyric"].x - bodyWidth / 2 - prefixWidth,
793
- y: baselineOf(bottom, row) - metrics.baseline,
939
+ y: baselineOf(baseline.bottom, row) - metrics.baseline,
794
940
  w: metrics.w,
795
941
  h: metrics.h,
796
942
  line: target.layoutLine,
797
- track: target.track,
943
+ track: baseline.owner,
798
944
  });
799
945
  }
800
- if (!lyric.name || !labelBox || labelBottom === undefined)
946
+ if (!lyric.name || !labelBox || !labelBaseline)
801
947
  continue;
802
948
  const metrics = context.textMeasurer.measureText(lyric.name, nameStyle);
803
949
  preparedText.push({
@@ -805,11 +951,11 @@ class VoiceLyricsAttachment {
805
951
  style: nameStyle,
806
952
  textBaselineY: metrics.baseline,
807
953
  x: labelBox.x + labelBox.anchor - metrics.w,
808
- y: baselineOf(labelBottom, row) - metrics.baseline,
954
+ y: baselineOf(labelBaseline.bottom, row) - metrics.baseline,
809
955
  w: metrics.w,
810
956
  h: metrics.h,
811
957
  line: labelLine,
812
- track: labelTrack,
958
+ track: labelBaseline.owner,
813
959
  });
814
960
  }
815
961
  return preparedText;