jpfun 0.4.1 → 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 (89) hide show
  1. package/README.md +53 -113
  2. package/dist/converter/midi/convert.js +14 -7
  3. package/dist/converter/musicxml/features.d.ts +57 -16
  4. package/dist/converter/musicxml/features.js +204 -42
  5. package/dist/converter/musicxml/index.d.ts +7 -2
  6. package/dist/converter/musicxml/index.js +256 -268
  7. package/dist/converter/musicxml/model.d.ts +36 -7
  8. package/dist/converter/musicxml/resolve.d.ts +10 -0
  9. package/dist/converter/musicxml/resolve.js +152 -0
  10. package/dist/core.d.ts +1 -0
  11. package/dist/core.js +1 -0
  12. package/dist/fraction.js +7 -1
  13. package/dist/functions/ASTtypes.d.ts +6 -3
  14. package/dist/functions/ASTtypes.js +30 -23
  15. package/dist/functions/adjust/index.js +10 -50
  16. package/dist/functions/arpeggio/index.js +40 -25
  17. package/dist/functions/beam/auto.js +2 -11
  18. package/dist/functions/box/index.js +132 -82
  19. package/dist/functions/dash/index.js +20 -11
  20. package/dist/functions/default.js +2 -1
  21. package/dist/functions/div/index.d.ts +1 -1
  22. package/dist/functions/div/index.js +9 -10
  23. package/dist/functions/dot/index.js +4 -5
  24. package/dist/functions/dyn/index.js +28 -32
  25. package/dist/functions/grace/index.d.ts +23 -8
  26. package/dist/functions/grace/index.js +138 -119
  27. package/dist/functions/head/index.js +11 -4
  28. package/dist/functions/key/index.js +1 -1
  29. package/dist/functions/meter/index.js +40 -7
  30. package/dist/functions/meter/shape.d.ts +3 -0
  31. package/dist/functions/meter/shape.js +43 -0
  32. package/dist/functions/note/index.d.ts +6 -1
  33. package/dist/functions/note/index.js +60 -57
  34. package/dist/functions/note/source-transform.d.ts +21 -0
  35. package/dist/functions/note/source-transform.js +164 -0
  36. package/dist/functions/page/index.d.ts +5 -0
  37. package/dist/functions/page/index.js +8 -5
  38. package/dist/functions/rest/index.d.ts +2 -0
  39. package/dist/functions/rest/index.js +233 -0
  40. package/dist/functions/set/index.js +5 -1
  41. package/dist/functions/symbol/index.d.ts +2 -0
  42. package/dist/functions/symbol/index.js +1 -1
  43. package/dist/functions/symbol/ornament.d.ts +3 -3
  44. package/dist/functions/symbol/ornament.js +21 -35
  45. package/dist/functions/symbol/symbols/accent.js +5 -5
  46. package/dist/functions/symbol/symbols/fermata.js +5 -4
  47. package/dist/functions/temporal.d.ts +21 -7
  48. package/dist/functions/temporal.js +14 -4
  49. package/dist/functions/tie/index.js +36 -42
  50. package/dist/functions/tuplet/index.js +20 -24
  51. package/dist/functions/up/index.js +54 -34
  52. package/dist/functions/voice/connections.d.ts +19 -0
  53. package/dist/functions/voice/connections.js +88 -0
  54. package/dist/functions/voice/index.js +248 -102
  55. package/dist/functions/volta/index.js +7 -12
  56. package/dist/jpfun.core.min.js +61 -41
  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 +70 -50
  60. package/dist/layout/engine.d.ts +13 -1
  61. package/dist/layout/engine.js +458 -129
  62. package/dist/layout/model.js +22 -66
  63. package/dist/layout/page.js +3 -1
  64. package/dist/layout/range.d.ts +26 -0
  65. package/dist/layout/range.js +75 -0
  66. package/dist/layout/types.d.ts +63 -49
  67. package/dist/lowering/loweringContext.d.ts +1 -1
  68. package/dist/lowering/loweringContext.js +34 -4
  69. package/dist/lowering/types.d.ts +5 -0
  70. package/dist/parser/parse-utils/length-utils.js +2 -0
  71. package/dist/parser/parse-utils/note-utils.d.ts +2 -0
  72. package/dist/parser/parse-utils/note-utils.js +6 -2
  73. package/dist/parser/parserContext.js +5 -9
  74. package/dist/parser/preprocess.js +4 -6
  75. package/dist/playback/compile.d.ts +2 -9
  76. package/dist/playback/compile.js +297 -186
  77. package/dist/playback/event.d.ts +8 -16
  78. package/dist/playback/event.js +13 -3
  79. package/dist/playback/types.d.ts +76 -18
  80. package/dist/playback/types.js +1 -0
  81. package/dist/render/index.d.ts +1 -1
  82. package/dist/render/index.js +1 -1
  83. package/dist/render/paint.js +1 -1
  84. package/dist/render/recording.d.ts +1 -0
  85. package/dist/render/recording.js +21 -0
  86. package/dist/render/translate.d.ts +14 -0
  87. package/dist/render/translate.js +48 -0
  88. package/grammar.md +200 -250
  89. package/package.json +4 -4
@@ -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
  }
@@ -354,7 +369,8 @@ L: la la la
354
369
  token = "";
355
370
  };
356
371
  for (let i = 0; i < value.length; i++) {
357
- const ch = value[i];
372
+ const ch = String.fromCodePoint(value.codePointAt(i));
373
+ i += ch.length - 1;
358
374
  if (ch === "\\" && i + 1 < value.length && /[\\{}@-]/.test(value[i + 1])) {
359
375
  token += value[++i];
360
376
  }
@@ -445,6 +461,11 @@ class VoicesFunction extends ASTFunctionNode {
445
461
 
446
462
  接受多个声部作为位置参数,将它们按时间对齐、分行排布;声部名称和歌词由各自的 \`@voice\` 提供
447
463
 
464
+ **视觉连接**:仅命名参数 \`connect\` 使用字符串,如 \`connect="[1-4]{5-7}"\`。
465
+ \`[]\` 是现有括线,\`{}\` 是弯曲大括号;编号从 1 开始,省略起点/终点表示首/末声部。
466
+ 默认 \`"[-]"\` 连接全部声部;\`""\` 只保留公共细连谱线。未指定的声部仍有细线,范围可以重叠,不改变声部或播放关系。
467
+ 用 \`@set(voices.connect="{1-2}[3-]")\` 设置后续多声部块的默认方案,显式参数写在所有声部之后。
468
+
448
469
  **简写**:连续声明多个 \`N:\` 声部及其 \`L:\` 歌词,会自动组成 \`voices\`
449
470
 
450
471
  ~~~jpfun
@@ -452,16 +473,114 @@ N(钢琴): 1 2 3
452
473
  L(男): ha ha ha
453
474
  N: 3 4 5
454
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
455
488
  ~~~`,
456
489
  allowExtraArgs: true,
457
490
  extraArgType: "content",
458
- args: []
491
+ args: [{
492
+ name: "connect",
493
+ namedOnly: true,
494
+ type: "string",
495
+ default: "[-]",
496
+ description: '视觉连接:[1-4] 为现有括线,{5-7} 为弯曲大括号;省略端点表示首/末声部,空字符串只保留公共连谱线。',
497
+ }]
459
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
+ }
460
574
  voices;
461
575
  createdBySugar = false; // 不同创建方式的不能合并
462
576
  size; // parse 期冻结的字号,px
463
577
  /** 声部名右侧为大括号预留的横向空间 */
464
578
  braceSpace;
579
+ connect;
580
+ // 收集阶段只冻结配置,避免提前校验随后会被 V 声明覆盖的默认值。
581
+ get connectionSpecs() {
582
+ return parseConnections(this.connect, this.sourceSpan);
583
+ }
465
584
  /** 闭包捕获 parse 期冻结的字号,用来决定空声部槽位的默认高度(1em) */
466
585
  measure;
467
586
  get children() { return this.voices; }
@@ -480,9 +599,9 @@ L: la la la
480
599
  loweringEnter(ctx) {
481
600
  const names = [];
482
601
  ctx.beginLoweringGroup(this, {
483
- attachment: new VoicesBraceAttachment(names, this),
484
- onTemporal(node) {
485
- if (node instanceof VoiceNameTemporal)
602
+ attachment: new VoicesBraceAttachment(names, this, resolveConnections(this.connectionSpecs, this.voices.length, this.sourceSpan)),
603
+ onTemporal: node => {
604
+ if (node instanceof VoiceNameTemporal && node.ast.parent === this)
486
605
  names.push(node);
487
606
  },
488
607
  });
@@ -496,24 +615,19 @@ L: la la la
496
615
  super(span, parent);
497
616
  this.voices = [];
498
617
  this.size = ctx.variables.fontsize;
499
- 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));
500
620
  this.measure = makeVoicesMeasure(ctx.variables.fontsize);
501
- for (const [, value] of args) {
502
- if (value instanceof ASTNodeBase) {
503
- if (value instanceof VoiceFunction)
504
- this.addVoice(value);
505
- else {
506
- throw new ErrorDiagnostic("E_VOICES_INVALID_CHILD", `@voices 的参数必须是 @voice 函数,但发现了其他类型 ${value.constructor.name}`, value instanceof ASTNodeBase ? value.sourceSpan : span);
507
- }
621
+ [this.connect] = this.getArgValue(args, ctx);
622
+ for (const [key, value] of args) {
623
+ if (key === "connect")
508
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);
509
629
  }
510
- const arg = value;
511
- const v = ctx.parseArgWithType(arg.valueSpan, "content", span.start);
512
- if (v instanceof VoiceFunction)
513
- this.addVoice(v);
514
- else {
515
- throw new ErrorDiagnostic("E_VOICES_INVALID_CHILD", `@voices 的参数必须是 @voice 函数,但发现了其他类型 ${v?.constructor.name}`, arg.valueSpan);
516
- }
630
+ this.addVoice(voice);
517
631
  }
518
632
  if (this.voices.length === 0) {
519
633
  throw new ErrorDiagnostic("E_VOICES_EMPTY", `@voices 必须至少包含一个 @voice 函数`, span);
@@ -526,12 +640,9 @@ L: la la la
526
640
  this.sourceSpan.end = Math.max(v.sourceSpan.end, this.sourceSpan.end);
527
641
  }
528
642
  toString(source) {
529
- const voicelines = Array(this.voices.length);
530
- for (let i = 0; i < this.voices.length; i++) {
531
- const part = `\t${this.voices[i].toString(source)}`;
532
- voicelines[i] = part;
533
- }
534
- 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)`;
535
646
  }
536
647
  }
537
648
  export const VoiceNode = VoiceFunction;
@@ -603,41 +714,21 @@ class VoiceNameTemporal extends TemporalNodeBase {
603
714
  painter.drawText(this.ast.name, this.box.x + this.box.anchor, this.box.y + this.textBaselineY, this.style);
604
715
  }
605
716
  }
606
- /** 括线端头的小钩;单位尺寸,绘制时按粗竖线宽度缩放并上下镜像 */
607
- const BRACE_HOOK_REACH = 2.33;
608
- const BRACE_HOOK_DROP = 1.17;
609
- const BRACE_HOOK_BASE = 0.34;
610
- const BRACE_HOOK_COMMANDS = [
611
- { op: "M", x: 0, y: 0 },
612
- { op: "L", x: 0, y: -BRACE_HOOK_BASE },
613
- {
614
- op: "C",
615
- cx1: BRACE_HOOK_REACH * 0.421, cy1: -BRACE_HOOK_BASE + BRACE_HOOK_DROP * 0.077,
616
- cx2: BRACE_HOOK_REACH * 0.733, cy2: -BRACE_HOOK_BASE + BRACE_HOOK_DROP * 0.346,
617
- x: BRACE_HOOK_REACH, y: -BRACE_HOOK_BASE + BRACE_HOOK_DROP,
618
- },
619
- { op: "L", x: BRACE_HOOK_REACH * 0.929, y: -BRACE_HOOK_BASE + BRACE_HOOK_DROP },
620
- {
621
- op: "C",
622
- cx1: BRACE_HOOK_REACH * 0.696, cy1: -BRACE_HOOK_BASE + BRACE_HOOK_DROP * 0.535,
623
- cx2: BRACE_HOOK_REACH * 0.328, cy2: -BRACE_HOOK_BASE + BRACE_HOOK_DROP * 0.352,
624
- x: 0, y: 0,
625
- },
626
- { op: "Z" },
627
- ];
628
717
  /**
629
718
  * 画在声部名与音符之间的多声部括线
630
719
  *
631
- * 由一条粗竖线、一条略向内收的细竖线和两端的小钩组成。
720
+ * 共享一条细竖线,按连接范围添加粗括线或弯曲大括号
632
721
  * 纵向跨度直接取首末声部名事件的视觉轴(无名声部的占位盒高度为 0,其 y 就是轨道视觉轴),
633
- * 因此不需要反查任何轨道信息。
722
+ * 因此不需要反查任何轨道信息
634
723
  */
635
724
  class VoicesBraceAttachment {
725
+ connections;
636
726
  layer = "background";
637
727
  names;
638
728
  ast;
639
729
  get sourceSpan() { return this.ast.sourceSpan; }
640
- constructor(names, ast) {
730
+ constructor(names, ast, connections) {
731
+ this.connections = connections;
641
732
  this.names = names;
642
733
  this.ast = ast;
643
734
  }
@@ -652,53 +743,74 @@ class VoicesBraceAttachment {
652
743
  if (bottom - top < 1e-6)
653
744
  return { regions: [], paint() { } };
654
745
  // 各部分尺寸都以粗竖线宽度为单位,比例取自常见简谱软件的括线
655
- const stem = Math.max(2.5, em * 0.19);
656
- const reach = stem * BRACE_HOOK_REACH;
657
- const drop = stem * BRACE_HOOK_DROP;
658
- const x = first.x + first.anchor + this.ast.braceSpace * 0.3 + stem / 2;
659
- const bars = [
660
- { x: x - stem / 2, y: top, w: stem, h: bottom - top },
661
- {
662
- x: x + stem * 1.33 - stem * 0.165,
663
- y: top + stem * 0.67,
664
- w: stem * 0.33,
665
- h: bottom - top - stem * 1.34,
666
- },
667
- ];
668
- const hooks = [
669
- { x, y: top, scale: stem, dir: -1 },
670
- { x, y: bottom, scale: stem, dir: 1 },
671
- ];
672
- // 括线画在声部名左侧的空白里,只参与画布边界,不抢任何轨道的纵向空间
673
- const regions = [{
674
- x: x - stem / 2,
675
- y: top - drop,
676
- w: reach + stem / 2,
677
- h: bottom - top + drop * 2,
678
- }];
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);
679
790
  return {
680
791
  regions,
681
792
  paint(painter) {
682
793
  for (const bar of bars) {
683
794
  painter.drawRect(bar.x, bar.y, bar.w, bar.h, { fill: "#000" });
684
795
  }
685
- for (const hook of hooks) {
686
- 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);
687
798
  }
688
799
  },
689
800
  };
690
801
  }
691
802
  }
692
803
  class VoiceLyricsAttachment {
693
- layer = "foreground";
694
- /** lowering 会持续向这个数组加入 voice 内容产生的 temporal */
695
804
  temporalMembers;
696
- /** 同一个 voice 的声部名事件,歌词行名称向它的对齐点右对齐 */
697
805
  nameHost;
806
+ frames;
807
+ layer = "foreground";
698
808
  get sourceSpan() { return this.nameHost.ast.sourceSpan; }
699
- constructor(temporalMembers, nameHost) {
809
+ /** lowering 持续填入成员与内层框,布局阶段再读取 */
810
+ constructor(temporalMembers, nameHost, frames) {
700
811
  this.temporalMembers = temporalMembers;
701
812
  this.nameHost = nameHost;
813
+ this.frames = frames;
702
814
  }
703
815
  prepareHorizontal(lines, context) {
704
816
  const targets = this.temporalMembers
@@ -752,15 +864,37 @@ class VoiceLyricsAttachment {
752
864
  .filter(node => node.ports?.["lyric"]);
753
865
  if (targets.length === 0 || lyrics.length === 0)
754
866
  return preparedText;
755
- // 每个 system+track 的歌词共用一条基线
756
- // 装饰高度先汇总为下边界,不进入单个 token 的 y 计算
757
- const contentBottom = new Map();
867
+ // 同一行、原始轨共用下沿,跨轨框外的占用可归属另一条轨
868
+ const baselines = new Map();
758
869
  for (const target of targets) {
759
- let byTrack = contentBottom.get(target.layoutLine);
870
+ let byTrack = baselines.get(target.layoutLine);
760
871
  if (!byTrack)
761
- contentBottom.set(target.layoutLine, byTrack = new Map());
762
- const bottom = target.box.y + target.box.h;
763
- 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);
764
898
  }
765
899
  const fontSize = size * LYRIC_SIZE_RATIO;
766
900
  const rowGap = size * 0.24;
@@ -769,16 +903,28 @@ class VoiceLyricsAttachment {
769
903
  const nameStyle = lyricNameStyle(size, this.nameHost.ast.font);
770
904
  const baselineOffset = context.textMeasurer.measureText("M", lyricStyle).baseline + firstRowGap;
771
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
+ }
772
918
  // 歌词行名称与声部名共用左侧那一列,因此只出现在声部名所在的那一行
773
919
  const { box: labelBox, layoutLine: labelLine, track: labelTrack } = this.nameHost;
774
- const labelBottom = contentBottom.get(labelLine)?.get(labelTrack);
920
+ const labelBaseline = baselines.get(labelLine)?.get(labelTrack);
775
921
  for (let row = 0; row < lyrics.length; row++) {
776
922
  const lyric = lyrics[row];
777
923
  for (let i = 0; i < lyric.tokens.length && i < targets.length; i++) {
778
924
  const text = lyric.tokens[i];
779
925
  const target = targets[i];
780
- const bottom = contentBottom.get(target.layoutLine)?.get(target.track);
781
- if (!text || bottom === undefined)
926
+ const baseline = baselines.get(target.layoutLine)?.get(target.track);
927
+ if (!text || !baseline)
782
928
  continue;
783
929
  const metrics = context.textMeasurer.measureText(text, lyricStyle);
784
930
  const { prefix, body } = splitLyricText(text);
@@ -789,14 +935,14 @@ class VoiceLyricsAttachment {
789
935
  style: lyricStyle,
790
936
  textBaselineY: metrics.baseline,
791
937
  x: target.box.x + target.ports["lyric"].x - bodyWidth / 2 - prefixWidth,
792
- y: baselineOf(bottom, row) - metrics.baseline,
938
+ y: baselineOf(baseline.bottom, row) - metrics.baseline,
793
939
  w: metrics.w,
794
940
  h: metrics.h,
795
941
  line: target.layoutLine,
796
- track: target.track,
942
+ track: baseline.owner,
797
943
  });
798
944
  }
799
- if (!lyric.name || !labelBox || labelBottom === undefined)
945
+ if (!lyric.name || !labelBox || !labelBaseline)
800
946
  continue;
801
947
  const metrics = context.textMeasurer.measureText(lyric.name, nameStyle);
802
948
  preparedText.push({
@@ -804,11 +950,11 @@ class VoiceLyricsAttachment {
804
950
  style: nameStyle,
805
951
  textBaselineY: metrics.baseline,
806
952
  x: labelBox.x + labelBox.anchor - metrics.w,
807
- y: baselineOf(labelBottom, row) - metrics.baseline,
953
+ y: baselineOf(labelBaseline.bottom, row) - metrics.baseline,
808
954
  w: metrics.w,
809
955
  h: metrics.h,
810
956
  line: labelLine,
811
- track: labelTrack,
957
+ track: labelBaseline.owner,
812
958
  });
813
959
  }
814
960
  return preparedText;
@@ -19,13 +19,13 @@ class VoltaFunction extends ASTFunctionNode {
19
19
  args: [
20
20
  {
21
21
  name: "from",
22
- description: "区间首音的标签,区间允许跨谱面行",
22
+ description: "区间起点的标签,区间允许跨谱面行",
23
23
  type: "label",
24
24
  default: null,
25
25
  },
26
26
  {
27
27
  name: "to",
28
- description: "区间末音的标签",
28
+ description: "区间终点的标签",
29
29
  type: "label",
30
30
  default: null,
31
31
  },
@@ -99,6 +99,7 @@ class VoltaAttachment {
99
99
  this.to = to;
100
100
  }
101
101
  get sourceSpan() { return this.ast.sourceSpan; }
102
+ get endPoints() { return [this.from, this.to]; }
102
103
  /** 房子只决定跳不跳过本列;遍数怎么数、什么时候回跳都归小节线 */
103
104
  playbackFlow(columnOf) {
104
105
  const from = columnOf(this.from);
@@ -135,16 +136,11 @@ class VoltaAttachment {
135
136
  const leftBar = barIn(from.view.columns[from.column - 1]);
136
137
  const rightBar = barIn(to.view.columns[to.column + 1]);
137
138
  let span = 0;
138
- const coverage = [];
139
139
  // 括线盖住的是:首行从起点列向右、末行向左到终点列、中间行整行
140
140
  for (let line = from.line; line <= to.line; line++) {
141
- const view = context.lines[line];
142
- const start = line === from.line ? from.column : 0;
143
- const end = line === to.line ? to.column : view.columns.length - 1;
144
- for (let column = start; column <= end; column++) {
145
- span = Math.max(span, view.columns[column][0].ast.size);
141
+ for (const column of context.getRangeColumns(line, [head, tail])) {
142
+ span = Math.max(span, column[0].ast.size);
146
143
  }
147
- coverage.push({ from: start, to: end, wholeLine: line !== from.line && line !== to.line });
148
144
  }
149
145
  const firstLine = head.layoutLine;
150
146
  const lastLine = tail.layoutLine;
@@ -167,10 +163,9 @@ class VoltaAttachment {
167
163
  const line = firstLine + offset;
168
164
  let topTrack = head.track;
169
165
  let hostTop = Infinity;
170
- const range = coverage[offset];
171
- const extents = range.wholeLine
166
+ const extents = line !== firstLine && line !== lastLine
172
167
  ? context.getRangeExtents(line)
173
- : context.getRangeExtents(line, [range.from, range.to]);
168
+ : context.getRangeExtents(line, [head, tail]);
174
169
  for (const [track, extent] of extents) {
175
170
  const y = context.getVisualAxis(line, track) + extent.top;
176
171
  if (y < hostTop) {