jpfun 0.5.0 → 0.6.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 (41) hide show
  1. package/dist/functions/ASTtypes.d.ts +4 -0
  2. package/dist/functions/ASTtypes.js +25 -14
  3. package/dist/functions/adjust/index.js +6 -2
  4. package/dist/functions/arpeggio/index.js +19 -12
  5. package/dist/functions/beam/auto.js +2 -11
  6. package/dist/functions/box/index.js +52 -1
  7. package/dist/functions/default.js +2 -1
  8. package/dist/functions/div/index.js +2 -3
  9. package/dist/functions/grace/index.d.ts +4 -2
  10. package/dist/functions/grace/index.js +16 -5
  11. package/dist/functions/head/index.js +11 -4
  12. package/dist/functions/meter/index.js +26 -6
  13. package/dist/functions/meter/shape.d.ts +3 -0
  14. package/dist/functions/meter/shape.js +43 -0
  15. package/dist/functions/note/index.js +25 -45
  16. package/dist/functions/rest/index.d.ts +2 -0
  17. package/dist/functions/rest/index.js +233 -0
  18. package/dist/functions/symbol/ornament.js +1 -1
  19. package/dist/functions/temporal.d.ts +21 -7
  20. package/dist/functions/temporal.js +14 -4
  21. package/dist/functions/tie/index.js +14 -10
  22. package/dist/functions/tuplet/index.js +1 -1
  23. package/dist/functions/up/index.js +47 -27
  24. package/dist/functions/voice/connections.d.ts +19 -0
  25. package/dist/functions/voice/connections.js +88 -0
  26. package/dist/functions/voice/index.js +244 -99
  27. package/dist/jpfun.core.min.js +56 -39
  28. package/dist/jpfun.min.js +65 -48
  29. package/dist/layout/engine.d.ts +3 -1
  30. package/dist/layout/engine.js +190 -64
  31. package/dist/layout/model.js +22 -66
  32. package/dist/layout/page.js +1 -1
  33. package/dist/layout/types.d.ts +30 -45
  34. package/dist/lowering/loweringContext.d.ts +1 -1
  35. package/dist/lowering/loweringContext.js +34 -4
  36. package/dist/parser/parserContext.js +4 -8
  37. package/dist/parser/preprocess.js +4 -6
  38. package/dist/playback/compile.js +1 -1
  39. package/dist/render/paint.js +1 -1
  40. package/grammar.md +200 -257
  41. package/package.json +1 -1
@@ -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,11 @@ class VoicesFunction extends ASTFunctionNode {
446
461
 
447
462
  接受多个声部作为位置参数,将它们按时间对齐、分行排布;声部名称和歌词由各自的 \`@voice\` 提供
448
463
 
464
+ **视觉连接**:仅命名参数 \`connect\` 使用字符串,如 \`connect="[1-4]{5-7}"\`。
465
+ \`[]\` 是现有括线,\`{}\` 是弯曲大括号;编号从 1 开始,省略起点/终点表示首/末声部。
466
+ 默认 \`"[-]"\` 连接全部声部;\`""\` 只保留公共细连谱线。未指定的声部仍有细线,范围可以重叠,不改变声部或播放关系。
467
+ 用 \`@set(voices.connect="{1-2}[3-]")\` 设置后续多声部块的默认方案,显式参数写在所有声部之后。
468
+
449
469
  **简写**:连续声明多个 \`N:\` 声部及其 \`L:\` 歌词,会自动组成 \`voices\`
450
470
 
451
471
  ~~~jpfun
@@ -453,16 +473,114 @@ N(钢琴): 1 2 3
453
473
  L(男): ha ha ha
454
474
  N: 3 4 5
455
475
  L: la la la
476
+ ~~~
477
+
478
+ 连接声明 \`V{}:\`、\`V[]:\`、\`V|:\` 分别指定后续声部的弯曲大括号、现有括线和仅细线,后面的 \`N:\` 可以同行,也可以换行。
479
+ 到下一条 V 声明或当前块末尾结束,组间不空行;空行结束整个多声部块。
480
+ 出现 V 声明时,当前块完整替换默认连接方案,不影响后面的块。V 不创建音轨,L 仍属于前面的 N。
481
+
482
+ ~~~jpfun
483
+ V{}: N(右手): 1 2 3
484
+ N(左手): 5 6 7
485
+ V[]: N(女高): 6 6 5
486
+ L: 啊 啊 啊
487
+ N(女低): 1 2 3
456
488
  ~~~`,
457
489
  allowExtraArgs: true,
458
490
  extraArgType: "content",
459
- args: []
491
+ args: [{
492
+ name: "connect",
493
+ namedOnly: true,
494
+ type: "string",
495
+ default: "[-]",
496
+ description: '视觉连接:[1-4] 为现有括线,{5-7} 为弯曲大括号;省略端点表示首/末声部,空字符串只保留公共连谱线。',
497
+ }]
460
498
  };
499
+ static deSugarAtom(source, start, end) {
500
+ if (source[start] !== "V")
501
+ return null;
502
+ const match = /^V(\{\}|\[\]|\|):/.exec(source.slice(start, end));
503
+ if (!match)
504
+ return null;
505
+ const next = start + match[0].length;
506
+ const node = {
507
+ kind: "sugar",
508
+ data: {
509
+ class: VoicesFunction,
510
+ kind: match[1] === "{}" ? "brace" : match[1] === "[]" ? "bracket" : "line",
511
+ },
512
+ span: { start, end: next },
513
+ };
514
+ return { next, node };
515
+ }
516
+ static deSugarRelation(ctx, nodes, at) {
517
+ const first = nodes[at];
518
+ if (typeof first === "number" || first.kind !== "sugar" || first.data?.class !== VoicesFunction)
519
+ return null;
520
+ let previousIndex = ctx.nodes.length - 1;
521
+ while (previousIndex >= 0 && ctx.nodes[previousIndex] instanceof ASTTextNode) {
522
+ const { sourceSpan } = ctx.nodes[previousIndex];
523
+ const text = ctx.source.slice(sourceSpan.start, sourceSpan.end);
524
+ if (text.includes("\n") || text.trim())
525
+ break;
526
+ previousIndex--;
527
+ }
528
+ const previous = ctx.nodes[previousIndex];
529
+ const members = previous instanceof VoiceFunction ? [previous]
530
+ : previous instanceof VoicesFunction && previous.createdBySugar ? [...previous.voices] : [];
531
+ const mergePrevious = members.length > 0;
532
+ const connections = [];
533
+ let cursor = at;
534
+ while (cursor < nodes.length) {
535
+ const marker = nodes[cursor];
536
+ if (typeof marker === "number" || marker.kind !== "sugar" || marker.data?.class !== VoicesFunction)
537
+ break;
538
+ cursor++;
539
+ const carriageReturn = nodes[cursor];
540
+ if (typeof carriageReturn === "number" && ctx.source[carriageReturn] === "\r")
541
+ cursor++;
542
+ const newline = nodes[cursor];
543
+ if (typeof newline === "number" && ctx.source[newline] === "\n")
544
+ cursor++;
545
+ // 每段单独解析 N/L,防止歌词越过 V 声明附着到上一段
546
+ const section = new ParserContext(ctx);
547
+ const from = members.length + 1;
548
+ while (cursor < nodes.length) {
549
+ const node = nodes[cursor];
550
+ if (typeof node === "number" || node.kind !== "sugar" || node.data?.class !== VoiceFunction)
551
+ break;
552
+ cursor = VoiceFunction.deSugarRelation(section, nodes, cursor, members);
553
+ }
554
+ if (members.length < from) {
555
+ throw new ErrorDiagnostic("E_VOICES_GROUP_EMPTY", "V 声部分组必须至少包含一条 N: 声部声明", marker.span);
556
+ }
557
+ if (marker.data.kind === "brace" || marker.data.kind === "bracket") {
558
+ connections.push({ kind: marker.data.kind, from, to: members.length });
559
+ }
560
+ }
561
+ const args = new Map();
562
+ members.forEach((member, index) => args.set(index, member));
563
+ args.set("connect", serializeConnections(connections));
564
+ const voices = new VoicesFunction({
565
+ start: mergePrevious ? previous.sourceSpan.start : first.span.start,
566
+ end: members.at(-1).sourceSpan.end,
567
+ }, args, ctx);
568
+ voices.createdBySugar = true;
569
+ if (mergePrevious)
570
+ ctx.nodes.length = previousIndex;
571
+ ctx.pushNode(voices);
572
+ return cursor;
573
+ }
461
574
  voices;
462
575
  createdBySugar = false; // 不同创建方式的不能合并
463
576
  size; // parse 期冻结的字号,px
464
577
  /** 声部名右侧为大括号预留的横向空间 */
465
578
  braceSpace;
579
+ connect;
580
+ // 收集阶段只冻结配置,避免提前校验随后会被 V 声明覆盖的默认值。
581
+ get connectionSpecs() {
582
+ return parseConnections(this.connect, this.sourceSpan);
583
+ }
466
584
  /** 闭包捕获 parse 期冻结的字号,用来决定空声部槽位的默认高度(1em) */
467
585
  measure;
468
586
  get children() { return this.voices; }
@@ -481,7 +599,7 @@ L: la la la
481
599
  loweringEnter(ctx) {
482
600
  const names = [];
483
601
  ctx.beginLoweringGroup(this, {
484
- attachment: new VoicesBraceAttachment(names, this),
602
+ attachment: new VoicesBraceAttachment(names, this, resolveConnections(this.connectionSpecs, this.voices.length, this.sourceSpan)),
485
603
  onTemporal: node => {
486
604
  if (node instanceof VoiceNameTemporal && node.ast.parent === this)
487
605
  names.push(node);
@@ -497,24 +615,19 @@ L: la la la
497
615
  super(span, parent);
498
616
  this.voices = [];
499
617
  this.size = ctx.variables.fontsize;
500
- this.braceSpace = ctx.variables.fontsize;
618
+ // 端钩有最小线宽,极小字号也要给它保留足够的横向空间
619
+ this.braceSpace = Math.max(ctx.variables.fontsize, (MIN_CONNECTOR_STEM * (BRACKET_HOOK_REACH + 0.5) + 0.5) / (1 - CONNECTOR_LABEL_GAP_RATIO));
501
620
  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
- }
621
+ [this.connect] = this.getArgValue(args, ctx);
622
+ for (const [key, value] of args) {
623
+ if (key === "connect")
509
624
  continue;
625
+ const valueSpan = value instanceof ASTNodeBase ? value.sourceSpan : value.valueSpan;
626
+ const voice = value instanceof ASTNodeBase ? value : ctx.parseArgWithType(valueSpan, "content", span.start);
627
+ if (!(voice instanceof VoiceFunction)) {
628
+ throw new ErrorDiagnostic("E_VOICES_INVALID_CHILD", `@voices 的参数必须是 @voice 函数,但发现了其他类型 ${voice?.constructor.name}`, valueSpan);
510
629
  }
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
- }
630
+ this.addVoice(voice);
518
631
  }
519
632
  if (this.voices.length === 0) {
520
633
  throw new ErrorDiagnostic("E_VOICES_EMPTY", `@voices 必须至少包含一个 @voice 函数`, span);
@@ -527,12 +640,9 @@ L: la la la
527
640
  this.sourceSpan.end = Math.max(v.sourceSpan.end, this.sourceSpan.end);
528
641
  }
529
642
  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)`;
643
+ const parameters = this.voices.map(voice => `\t${voice.toString(source)}`);
644
+ parameters.push(`\tconnect=${quote(serializeConnections(this.connectionSpecs))}`);
645
+ return `@voices(\n${parameters.join(",\n")}\n)`;
536
646
  }
537
647
  }
538
648
  export const VoiceNode = VoiceFunction;
@@ -604,41 +714,21 @@ class VoiceNameTemporal extends TemporalNodeBase {
604
714
  painter.drawText(this.ast.name, this.box.x + this.box.anchor, this.box.y + this.textBaselineY, this.style);
605
715
  }
606
716
  }
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
717
  /**
630
718
  * 画在声部名与音符之间的多声部括线
631
719
  *
632
- * 由一条粗竖线、一条略向内收的细竖线和两端的小钩组成。
720
+ * 共享一条细竖线,按连接范围添加粗括线或弯曲大括号
633
721
  * 纵向跨度直接取首末声部名事件的视觉轴(无名声部的占位盒高度为 0,其 y 就是轨道视觉轴),
634
- * 因此不需要反查任何轨道信息。
722
+ * 因此不需要反查任何轨道信息
635
723
  */
636
724
  class VoicesBraceAttachment {
725
+ connections;
637
726
  layer = "background";
638
727
  names;
639
728
  ast;
640
729
  get sourceSpan() { return this.ast.sourceSpan; }
641
- constructor(names, ast) {
730
+ constructor(names, ast, connections) {
731
+ this.connections = connections;
642
732
  this.names = names;
643
733
  this.ast = ast;
644
734
  }
@@ -653,53 +743,74 @@ class VoicesBraceAttachment {
653
743
  if (bottom - top < 1e-6)
654
744
  return { regions: [], paint() { } };
655
745
  // 各部分尺寸都以粗竖线宽度为单位,比例取自常见简谱软件的括线
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
- }];
746
+ const stem = Math.max(MIN_CONNECTOR_STEM, em * 0.19);
747
+ const reach = stem * BRACKET_HOOK_REACH;
748
+ const drop = stem * BRACKET_HOOK_DROP;
749
+ const x = first.x + first.anchor + this.ast.braceSpace * CONNECTOR_LABEL_GAP_RATIO + stem / 2;
750
+ const inset = Math.min(stem * 0.67, em * 0.25);
751
+ const line = {
752
+ x: x + stem * 1.33 - stem * 0.165,
753
+ y: top + inset,
754
+ w: stem * 0.33,
755
+ h: bottom - top - inset * 2,
756
+ };
757
+ const bars = [];
758
+ const paths = [];
759
+ const regions = [line];
760
+ for (const connection of this.connections) {
761
+ const first = this.names[connection.from - 1].box;
762
+ const last = this.names[connection.to - 1].box;
763
+ const groupTop = first.y + first.visualAxis - em * 0.5;
764
+ const groupBottom = last.y + last.visualAxis + em * 0.5;
765
+ if (connection.kind === "bracket") {
766
+ bars.push({ x: x - stem / 2, y: groupTop, w: stem, h: groupBottom - groupTop });
767
+ 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 } });
768
+ regions.push({
769
+ x: x - stem / 2, y: groupTop - drop,
770
+ w: reach + stem / 2, h: groupBottom - groupTop + drop * 2,
771
+ });
772
+ }
773
+ else {
774
+ const width = em * 0.35;
775
+ const left = line.x - em * 0.12 - width;
776
+ const scaleX = width / CURVED_BRACE_BOUNDS.w;
777
+ const scaleY = (groupBottom - groupTop) / CURVED_BRACE_BOUNDS.h;
778
+ paths.push({
779
+ commands: CURVED_BRACE_COMMANDS,
780
+ transform: {
781
+ x: left - CURVED_BRACE_BOUNDS.x * scaleX,
782
+ y: groupTop - CURVED_BRACE_BOUNDS.y * scaleY,
783
+ scaleX, scaleY,
784
+ },
785
+ });
786
+ regions.push({ x: left, y: groupTop, w: width, h: groupBottom - groupTop });
787
+ }
788
+ }
789
+ bars.push(line);
680
790
  return {
681
791
  regions,
682
792
  paint(painter) {
683
793
  for (const bar of bars) {
684
794
  painter.drawRect(bar.x, bar.y, bar.w, bar.h, { fill: "#000" });
685
795
  }
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 });
796
+ for (const path of paths) {
797
+ painter.drawPath(path.commands, { fill: "#000" }, path.transform);
688
798
  }
689
799
  },
690
800
  };
691
801
  }
692
802
  }
693
803
  class VoiceLyricsAttachment {
694
- layer = "foreground";
695
- /** lowering 会持续向这个数组加入 voice 内容产生的 temporal */
696
804
  temporalMembers;
697
- /** 同一个 voice 的声部名事件,歌词行名称向它的对齐点右对齐 */
698
805
  nameHost;
806
+ frames;
807
+ layer = "foreground";
699
808
  get sourceSpan() { return this.nameHost.ast.sourceSpan; }
700
- constructor(temporalMembers, nameHost) {
809
+ /** lowering 持续填入成员与内层框,布局阶段再读取 */
810
+ constructor(temporalMembers, nameHost, frames) {
701
811
  this.temporalMembers = temporalMembers;
702
812
  this.nameHost = nameHost;
813
+ this.frames = frames;
703
814
  }
704
815
  prepareHorizontal(lines, context) {
705
816
  const targets = this.temporalMembers
@@ -753,15 +864,37 @@ class VoiceLyricsAttachment {
753
864
  .filter(node => node.ports?.["lyric"]);
754
865
  if (targets.length === 0 || lyrics.length === 0)
755
866
  return preparedText;
756
- // 每个 system+track 的歌词共用一条基线
757
- // 装饰高度先汇总为下边界,不进入单个 token 的 y 计算
758
- const contentBottom = new Map();
867
+ // 同一行、原始轨共用下沿,跨轨框外的占用可归属另一条轨
868
+ const baselines = new Map();
759
869
  for (const target of targets) {
760
- let byTrack = contentBottom.get(target.layoutLine);
870
+ let byTrack = baselines.get(target.layoutLine);
761
871
  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));
872
+ baselines.set(target.layoutLine, byTrack = new Map());
873
+ const baseline = byTrack.get(target.track) ?? { bottom: -Infinity, owner: target.track };
874
+ const bounds = getLayoutBounds(target);
875
+ let bottom = bounds.y + bounds.h;
876
+ let owner = target.track;
877
+ for (const frame of this.frames) {
878
+ const box = context.getAttachmentBox(frame);
879
+ if (box.x + box.w < bounds.x || box.x > bounds.x + bounds.w || box.y + box.h <= bottom)
880
+ continue;
881
+ const regions = context.getAttachmentOccupancy(frame);
882
+ if (!regions)
883
+ throw new Error("Layout attachment dependency has not been measured");
884
+ const tracks = regions.filter(region => region.line === target.layoutLine);
885
+ if (regions.some(region => region.line !== undefined) && tracks.length === 0)
886
+ continue;
887
+ bottom = box.y + box.h;
888
+ for (const region of tracks) {
889
+ if (region.line !== undefined && context.getVisualAxis(region.line, region.track)
890
+ > context.getVisualAxis(target.layoutLine, owner))
891
+ owner = region.track;
892
+ }
893
+ }
894
+ if (bottom >= baseline.bottom)
895
+ baseline.owner = owner;
896
+ baseline.bottom = Math.max(baseline.bottom, bottom);
897
+ byTrack.set(target.track, baseline);
765
898
  }
766
899
  const fontSize = size * LYRIC_SIZE_RATIO;
767
900
  const rowGap = size * 0.24;
@@ -770,16 +903,28 @@ class VoiceLyricsAttachment {
770
903
  const nameStyle = lyricNameStyle(size, this.nameHost.ast.font);
771
904
  const baselineOffset = context.textMeasurer.measureText("M", lyricStyle).baseline + firstRowGap;
772
905
  const baselineOf = (bottom, row) => bottom + baselineOffset + row * (fontSize + rowGap);
906
+ // 跨轨框外的歌词由最下轨承担占用,各原始轨的歌词行依次排列
907
+ if (this.frames.length)
908
+ for (const [line, byTrack] of baselines) {
909
+ if (byTrack.size < 2)
910
+ continue;
911
+ const rows = new Map();
912
+ for (const [, baseline] of [...byTrack].sort(([left], [right]) => context.getVisualAxis(line, left) - context.getVisualAxis(line, right))) {
913
+ const row = rows.get(baseline.owner) ?? 0;
914
+ baseline.bottom += row * lyrics.length * (fontSize + rowGap);
915
+ rows.set(baseline.owner, row + 1);
916
+ }
917
+ }
773
918
  // 歌词行名称与声部名共用左侧那一列,因此只出现在声部名所在的那一行
774
919
  const { box: labelBox, layoutLine: labelLine, track: labelTrack } = this.nameHost;
775
- const labelBottom = contentBottom.get(labelLine)?.get(labelTrack);
920
+ const labelBaseline = baselines.get(labelLine)?.get(labelTrack);
776
921
  for (let row = 0; row < lyrics.length; row++) {
777
922
  const lyric = lyrics[row];
778
923
  for (let i = 0; i < lyric.tokens.length && i < targets.length; i++) {
779
924
  const text = lyric.tokens[i];
780
925
  const target = targets[i];
781
- const bottom = contentBottom.get(target.layoutLine)?.get(target.track);
782
- if (!text || bottom === undefined)
926
+ const baseline = baselines.get(target.layoutLine)?.get(target.track);
927
+ if (!text || !baseline)
783
928
  continue;
784
929
  const metrics = context.textMeasurer.measureText(text, lyricStyle);
785
930
  const { prefix, body } = splitLyricText(text);
@@ -790,14 +935,14 @@ class VoiceLyricsAttachment {
790
935
  style: lyricStyle,
791
936
  textBaselineY: metrics.baseline,
792
937
  x: target.box.x + target.ports["lyric"].x - bodyWidth / 2 - prefixWidth,
793
- y: baselineOf(bottom, row) - metrics.baseline,
938
+ y: baselineOf(baseline.bottom, row) - metrics.baseline,
794
939
  w: metrics.w,
795
940
  h: metrics.h,
796
941
  line: target.layoutLine,
797
- track: target.track,
942
+ track: baseline.owner,
798
943
  });
799
944
  }
800
- if (!lyric.name || !labelBox || labelBottom === undefined)
945
+ if (!lyric.name || !labelBox || !labelBaseline)
801
946
  continue;
802
947
  const metrics = context.textMeasurer.measureText(lyric.name, nameStyle);
803
948
  preparedText.push({
@@ -805,11 +950,11 @@ class VoiceLyricsAttachment {
805
950
  style: nameStyle,
806
951
  textBaselineY: metrics.baseline,
807
952
  x: labelBox.x + labelBox.anchor - metrics.w,
808
- y: baselineOf(labelBottom, row) - metrics.baseline,
953
+ y: baselineOf(labelBaseline.bottom, row) - metrics.baseline,
809
954
  w: metrics.w,
810
955
  h: metrics.h,
811
956
  line: labelLine,
812
- track: labelTrack,
957
+ track: labelBaseline.owner,
813
958
  });
814
959
  }
815
960
  return preparedText;