jpfun 0.1.0 → 0.3.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 (114) hide show
  1. package/LICENSE +200 -200
  2. package/README.md +191 -133
  3. package/dist/diagnostic.js +5 -2
  4. package/dist/fraction.d.ts +24 -0
  5. package/dist/fraction.js +132 -0
  6. package/dist/functions/ASTtypes.d.ts +24 -7
  7. package/dist/functions/ASTtypes.js +35 -16
  8. package/dist/functions/adjust/index.d.ts +2 -0
  9. package/dist/functions/adjust/index.js +193 -0
  10. package/dist/functions/bar/index.d.ts +8 -0
  11. package/dist/functions/bar/index.js +48 -19
  12. package/dist/functions/beam/auto.js +35 -18
  13. package/dist/functions/beam/index.js +10 -6
  14. package/dist/functions/beam/layout.d.ts +3 -2
  15. package/dist/functions/beam/layout.js +42 -64
  16. package/dist/functions/box/index.js +35 -34
  17. package/dist/functions/br/index.js +14 -12
  18. package/dist/functions/dash/index.js +37 -5
  19. package/dist/functions/default.js +14 -7
  20. package/dist/functions/div/index.d.ts +16 -0
  21. package/dist/functions/div/index.js +51 -23
  22. package/dist/functions/dot/index.js +16 -8
  23. package/dist/functions/grace/index.d.ts +8 -18
  24. package/dist/functions/grace/index.js +98 -99
  25. package/dist/functions/head/index.d.ts +2 -0
  26. package/dist/functions/head/index.js +492 -0
  27. package/dist/functions/key/index.js +98 -5
  28. package/dist/functions/meter/index.d.ts +2 -0
  29. package/dist/functions/meter/index.js +154 -0
  30. package/dist/functions/note/accidentals.d.ts +24 -3
  31. package/dist/functions/note/accidentals.js +31 -1
  32. package/dist/functions/note/index.js +60 -80
  33. package/dist/functions/page/index.d.ts +9 -2
  34. package/dist/functions/page/index.js +50 -4
  35. package/dist/functions/set/index.js +42 -34
  36. package/dist/functions/stack/index.js +39 -34
  37. package/dist/functions/symbol/index.d.ts +21 -0
  38. package/dist/functions/symbol/index.js +94 -0
  39. package/dist/functions/symbol/ornament.d.ts +15 -0
  40. package/dist/functions/symbol/ornament.js +73 -0
  41. package/dist/functions/symbol/shape.d.ts +22 -0
  42. package/dist/functions/symbol/shape.js +48 -0
  43. package/dist/functions/symbol/symbols/accent.d.ts +2 -0
  44. package/dist/functions/symbol/symbols/accent.js +24 -0
  45. package/dist/functions/symbol/symbols/f.d.ts +2 -0
  46. package/dist/functions/symbol/symbols/f.js +55 -0
  47. package/dist/functions/symbol/symbols/fermata.d.ts +2 -0
  48. package/dist/functions/symbol/symbols/fermata.js +24 -0
  49. package/dist/functions/symbol/symbols/mordent.d.ts +2 -0
  50. package/dist/functions/symbol/symbols/mordent.js +43 -0
  51. package/dist/functions/symbol/symbols/p.d.ts +2 -0
  52. package/dist/functions/symbol/symbols/p.js +61 -0
  53. package/dist/functions/symbol/symbols/tr.d.ts +2 -0
  54. package/dist/functions/symbol/symbols/tr.js +75 -0
  55. package/dist/functions/tempo/glyph.d.ts +12 -0
  56. package/dist/functions/tempo/glyph.js +30 -0
  57. package/dist/functions/tempo/index.js +53 -3
  58. package/dist/functions/text/index.js +78 -26
  59. package/dist/functions/tie/index.js +103 -128
  60. package/dist/functions/tuplet/index.d.ts +2 -0
  61. package/dist/functions/tuplet/index.js +211 -0
  62. package/dist/functions/{over → up}/index.d.ts +1 -0
  63. package/dist/functions/up/index.js +370 -0
  64. package/dist/functions/voice/index.js +125 -108
  65. package/dist/functions/volta/index.d.ts +2 -0
  66. package/dist/functions/volta/index.js +227 -0
  67. package/dist/index.d.ts +4 -0
  68. package/dist/index.js +4 -0
  69. package/dist/jpfun.min.js +143 -0
  70. package/dist/layout/engine.d.ts +4 -11
  71. package/dist/layout/engine.js +100 -66
  72. package/dist/layout/model.d.ts +8 -1
  73. package/dist/layout/model.js +16 -6
  74. package/dist/layout/path.d.ts +19 -0
  75. package/dist/layout/path.js +101 -0
  76. package/dist/layout/types.d.ts +51 -18
  77. package/dist/layout/types.js +3 -1
  78. package/dist/lowering/loweringContext.d.ts +19 -23
  79. package/dist/lowering/loweringContext.js +179 -187
  80. package/dist/lowering/track.d.ts +33 -10
  81. package/dist/lowering/track.js +6 -6
  82. package/dist/lowering/types.d.ts +57 -43
  83. package/dist/lowering/types.js +20 -4
  84. package/dist/parser/parse-utils/call-utils.d.ts +0 -2
  85. package/dist/parser/parse-utils/call-utils.js +0 -6
  86. package/dist/parser/parse-utils/note-utils.d.ts +8 -0
  87. package/dist/parser/parse-utils/note-utils.js +35 -13
  88. package/dist/parser/parse-utils/string-utils.d.ts +8 -0
  89. package/dist/parser/parse-utils/string-utils.js +20 -0
  90. package/dist/parser/parserContext.d.ts +8 -5
  91. package/dist/parser/parserContext.js +38 -33
  92. package/dist/parser/preprocess.js +17 -11
  93. package/dist/playback/compile.d.ts +18 -0
  94. package/dist/playback/compile.js +401 -0
  95. package/dist/playback/event.d.ts +91 -0
  96. package/dist/playback/event.js +87 -0
  97. package/dist/playback/time.d.ts +14 -0
  98. package/dist/playback/time.js +81 -0
  99. package/dist/playback/types.d.ts +128 -0
  100. package/dist/playback/types.js +3 -0
  101. package/dist/render/canvas.d.ts +4 -4
  102. package/dist/render/canvas.js +20 -5
  103. package/dist/render/index.d.ts +1 -0
  104. package/dist/render/index.js +1 -0
  105. package/dist/render/paint.d.ts +8 -0
  106. package/dist/render/paint.js +101 -0
  107. package/dist/render/svg.d.ts +3 -3
  108. package/dist/render/svg.js +10 -8
  109. package/dist/render/text.d.ts +17 -0
  110. package/dist/render/text.js +35 -0
  111. package/dist/render/types.d.ts +1 -1
  112. package/grammar.md +217 -122
  113. package/package.json +14 -9
  114. package/dist/functions/over/index.js +0 -307
@@ -1,6 +1,7 @@
1
1
  import { ASTNodeBase, ASTBraceNode, ASTFunctionNode, ASTTextNode } from "../ASTtypes.js";
2
2
  import { Diagnostic, ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
3
- import { findRightParen, removeQuote } from "../../parser/parse-utils/call-utils.js";
3
+ import { findRightParen } from "../../parser/parse-utils/call-utils.js";
4
+ import { findClosingQuote, removeQuote } from "../../parser/parse-utils/string-utils.js";
4
5
  import { ParserContext, skipSpaces } from "../../parser/parserContext.js";
5
6
  import { isVisualTemporalNode, TemporalNodeBase, } from "../../lowering/types.js";
6
7
  const WHITEPACE_RE = /\s/;
@@ -14,9 +15,9 @@ const WHITEPACE_RE = /\s/;
14
15
  * 本行没有实质高度的成员(空声部,或内容都在上一行)仍然占一个默认高度的槽位,
15
16
  * 声部数量因而保持稳定,居中结果也不会因为某一声部没写东西而跳变。
16
17
  */
17
- function makeVoicesArrange(emptySlotHeight) {
18
+ function makeVoicesMeasure(emptySlotHeight) {
18
19
  const half = emptySlotHeight / 2;
19
- return (_host, members, gap) => {
20
+ return (members, gap) => {
20
21
  const extents = members.map(member => member && member.bottom - member.top > 1e-6 ? member : { top: -half, bottom: half });
21
22
  const offsets = [];
22
23
  let y = 0;
@@ -33,20 +34,20 @@ class VoiceFunction extends ASTFunctionNode {
33
34
  static def = {
34
35
  name: ["voice", "v"],
35
36
  description: "声部",
36
- example: `@voice({}, name, 歌词1名=歌词1, 歌词2名=歌词2, ...)
37
- 第一个参数为音符内容,第二个参数为写在最左侧的声部名称(可不填);
38
- 命名参数为歌词左侧的名称和内容,可以任意多个。也可以是位置参数,表示不需要名称。
39
- 例:
40
- @voice({C1 D1 E1}, 钢琴, 男=ha ha ha, 女=la la la)
41
- @voice({C1 D1 E1}, , ha ha ha, 女="la la la") 表示音符和第一个歌词都没有名称
42
- 歌词可以被引号包裹,如果包含逗号等歧义字符一定需要引号
43
- 语法糖:
44
- N(name): C1 D1 E1
45
- L(name): ha ha ha...
46
- L: ...
47
- 前面可以有任意空白,但最后换行表示结束。歌词此时允许有逗号而不加引号
48
- 如果一定要换行,最后加上'\\'
49
- 英文歌词用空格和连字符'-'分词,用'@'占位
37
+ example: `@voice({}, name, 歌词1名=歌词1, 歌词2名=歌词2, ...)
38
+ 第一个参数为音符内容,第二个参数为写在最左侧的声部名称(可不填);
39
+ 命名参数为歌词左侧的名称和内容,可以任意多个。也可以是位置参数,表示不需要名称。
40
+ 例:
41
+ @voice({C1 D1 E1}, 钢琴, 男=ha ha ha, 女=la la la)
42
+ @voice({C1 D1 E1}, , ha ha ha, 女="la la la") 表示音符和第一个歌词都没有名称
43
+ 歌词可以被引号包裹,如果包含逗号等歧义字符一定需要引号
44
+ 语法糖:
45
+ N(name): C1 D1 E1
46
+ L(name): ha ha ha...
47
+ L: ...
48
+ 前面可以有任意空白,但最后换行表示结束。歌词此时允许有逗号而不加引号
49
+ 如果一定要换行,最后加上'\\'
50
+ 英文歌词用空格和连字符'-'分词,用'@'占位
50
51
  `,
51
52
  allowExtraArgs: true,
52
53
  extraArgType: "string",
@@ -94,44 +95,31 @@ L: ...
94
95
  }
95
96
  else {
96
97
  // 字符串收集
97
- let lystart = pos = skipSpaces(source, pos, end);
98
+ pos = skipSpaces(source, pos, end);
98
99
  if (pos >= end)
99
100
  return null; // 没有内容了 不去糖
100
- let lyend = end;
101
- const quote = source[pos];
101
+ let lyric;
102
102
  // 双引号才是字符串,单引号不是
103
- if (quote === '"') {
104
- // 有引号的 直接以引号为界切分
105
- lystart = ++pos;
106
- let escaped = false;
107
- for (; pos < end; pos++) {
108
- const ch = source[pos];
109
- if (escaped)
110
- escaped = false;
111
- else if (ch === "\\")
112
- escaped = true;
113
- else if (ch === quote)
114
- break;
115
- }
116
- if (pos >= end)
117
- throw Diagnostic.error.UnterminatedString({
118
- start: lystart - 1, end
119
- });
120
- lyend = pos++; // 跳过结尾引号
103
+ if (source[pos] === '"') {
104
+ // 未闭合就不去糖,词法层每次击键都跑,不能抛
105
+ const close = findClosingQuote(source, pos, end);
106
+ if (close < 0)
107
+ return null;
108
+ lyric = removeQuote(source.slice(pos, close + 1));
109
+ pos = close + 1;
121
110
  }
122
111
  else {
123
112
  // 没有引号的 以换行符为界切分 预处理已经跳过了转义的换行符了
124
- for (; pos < end; pos++) {
125
- if (source[pos] === '\n')
126
- break;
127
- }
128
- lyend = pos;
113
+ const from = pos;
114
+ while (pos < end && source[pos] !== '\n')
115
+ pos++;
116
+ lyric = source.slice(from, pos).trim();
129
117
  }
130
118
  const node = {
131
119
  kind: "sugar",
132
120
  data: {
133
121
  class: VoiceFunction,
134
- lyric: source.slice(lystart, lyend).trim(),
122
+ lyric,
135
123
  name,
136
124
  },
137
125
  span: { start, end: pos },
@@ -194,16 +182,15 @@ L: ...
194
182
  if (newCtx.nodes.length === 0) {
195
183
  throw Diagnostic.error.EmptyContent("voice", "content", n.span);
196
184
  }
185
+ const span = { start: n.span.start, end: newCtx.nodes.at(-1).sourceSpan.end };
197
186
  const argMap = new Map();
198
187
  if (newCtx.nodes.length === 1 && newCtx.nodes[0] instanceof ASTBraceNode)
199
188
  argMap.set(0, newCtx.nodes[0]);
189
+ // 复制一份:voice 的 span 之后会被歌词撑大,内容 brace 不该跟着长
200
190
  else
201
- argMap.set(0, new ASTBraceNode(n.span, newCtx.nodes));
191
+ argMap.set(0, new ASTBraceNode({ ...span }, newCtx.nodes));
202
192
  argMap.set("name", n.data.name);
203
- const newVoice = new VoiceFunction({
204
- start: n.span.start,
205
- end: breakAt < nodes.length ? nodes[breakAt] : ctx.source.length
206
- }, argMap, ctx, null);
193
+ const newVoice = new VoiceFunction(span, argMap, ctx, null);
207
194
  // 如果前面紧挨着 VoicesFunction | VoiceFunction 则直接加入
208
195
  let voicesNode = null;
209
196
  let voicesNodeAt = ctx.nodes.length - 1;
@@ -301,9 +288,10 @@ L: ...
301
288
  this.addLyric(key, value);
302
289
  continue;
303
290
  }
304
- const v = ctx.parseArgWithType(value.start, value.end, "string", span.start);
291
+ const arg = value;
292
+ const v = ctx.parseArgWithType(arg.valueSpan, "string", span.start);
305
293
  if (v === null) {
306
- ctx.diagnostics.push(new WarningDiagnostic("W_VOICE_INVALID_LYRIC", `@voice 的歌词参数值解析失败, 参数[${key}]将被忽略`, value));
294
+ ctx.diagnostics.push(new WarningDiagnostic("W_VOICE_INVALID_LYRIC", `@voice 的歌词参数值解析失败, 参数[${key}]将被忽略`, arg.valueSpan));
307
295
  }
308
296
  else
309
297
  this.addLyric(key, v);
@@ -318,8 +306,11 @@ L: ...
318
306
  }
319
307
  this.lyrics.push({ name, tokens });
320
308
  if (span) {
321
- this.sourceSpan.start = Math.min(span.start, this.sourceSpan.start);
322
- this.sourceSpan.end = Math.max(span.end, this.sourceSpan.end);
309
+ // 歌词是成节点之后才补上来的,祖先的 span 得一起长,否则按源码位置查节点会漏掉歌词那几行
310
+ for (let node = this; node; node = node.parent) {
311
+ node.sourceSpan.start = Math.min(span.start, node.sourceSpan.start);
312
+ node.sourceSpan.end = Math.max(span.end, node.sourceSpan.end);
313
+ }
323
314
  }
324
315
  }
325
316
  static parseLyric(value) {
@@ -374,16 +365,16 @@ class VoicesFunction extends ASTFunctionNode {
374
365
  static def = {
375
366
  name: ["voices", "vs"],
376
367
  description: "多个声部",
377
- example: `@voices(
378
- @voice({C1 D1 E1}, 钢琴, 男=ha ha ha),
379
- @voice({C2 D2 E2}, , "la la la")
380
- )
381
- 语法糖:当多个 voice 用 voice 的语法糖写在一起时,会自动创建一个 voices 组件包裹它们。
382
- 例:
383
- N(钢琴): C1 D1 E1
384
- L(男): ha ha ha
385
- N: C2 D2 E2
386
- L: la la la
368
+ example: `@voices(
369
+ @voice({C1 D1 E1}, 钢琴, 男=ha ha ha),
370
+ @voice({C2 D2 E2}, , "la la la")
371
+ )
372
+ 语法糖:当多个 voice 用 voice 的语法糖写在一起时,会自动创建一个 voices 组件包裹它们。
373
+ 例:
374
+ N(钢琴): C1 D1 E1
375
+ L(男): ha ha ha
376
+ N: C2 D2 E2
377
+ L: la la la
387
378
  `,
388
379
  allowExtraArgs: true,
389
380
  extraArgType: "content",
@@ -395,7 +386,7 @@ L: la la la
395
386
  /** 声部名右侧为大括号预留的横向空间 */
396
387
  braceSpace;
397
388
  /** 闭包捕获 parse 期冻结的字号,用来决定空声部槽位的默认高度(1em) */
398
- arrange;
389
+ measure;
399
390
  get children() { return this.voices; }
400
391
  timeFlowModel() {
401
392
  return {
@@ -404,7 +395,7 @@ L: la la la
404
395
  tracks: {
405
396
  laneKey: `voices/${this.voices.length}`,
406
397
  hostIndex: null, // 宿主不是成员:第一个 voice 也必须拥有独立轨道
407
- arrange: this.arrange,
398
+ measure: this.measure,
408
399
  },
409
400
  };
410
401
  }
@@ -429,7 +420,7 @@ L: la la la
429
420
  this.voices = [];
430
421
  this.size = ctx.fontSize;
431
422
  this.braceSpace = ctx.fontSize;
432
- this.arrange = makeVoicesArrange(ctx.fontSize);
423
+ this.measure = makeVoicesMeasure(ctx.fontSize);
433
424
  for (const [, value] of args) {
434
425
  if (value instanceof ASTNodeBase) {
435
426
  if (value instanceof VoiceFunction)
@@ -439,12 +430,12 @@ L: la la la
439
430
  }
440
431
  continue;
441
432
  }
442
- // 是用 SourceSpan 体现的原始参数
443
- const v = ctx.parseArgWithType(value.start, value.end, "content", span.start);
433
+ const arg = value;
434
+ const v = ctx.parseArgWithType(arg.valueSpan, "content", span.start);
444
435
  if (v instanceof VoiceFunction)
445
436
  this.addVoice(v);
446
437
  else {
447
- throw new ErrorDiagnostic("E_VOICES_INVALID_CHILD", `@voices 的参数必须是 @voice 函数,但发现了其他类型 ${v?.constructor.name}`, value);
438
+ throw new ErrorDiagnostic("E_VOICES_INVALID_CHILD", `@voices 的参数必须是 @voice 函数,但发现了其他类型 ${v?.constructor.name}`, arg.valueSpan);
448
439
  }
449
440
  }
450
441
  if (this.voices.length === 0) {
@@ -488,11 +479,7 @@ class VoiceNameTemporal extends TemporalNodeBase {
488
479
  super();
489
480
  this.ast = ast;
490
481
  this.braceSpace = braceSpace;
491
- this.T = 0;
492
- // 同一个 voices 块里每个成员都会产生本事件,列结构对称,
493
- // 因此可以安全地归并成一列并右对齐;
494
- // 独立的 @voice 与相邻分支不对称,必须单独成列,否则会把同时刻的音符挤到下一列
495
- this.type = ast.parent instanceof VoicesFunction ? 2 /* ColType.DEFAULT */ : 1 /* ColType.SINGLE */;
482
+ this.mergeKey = -2;
496
483
  // 既没有名称、也不需要括号空间和标签列时只保留不可见的占位事件:
497
484
  // 它不进入可见对象,也不让空声部失去默认槽位高度
498
485
  if (ast.name || braceSpace > 0 || ast.lyrics.some(lyric => lyric.name))
@@ -567,34 +554,30 @@ const BRACE_HOOK_COMMANDS = [
567
554
  * 因此不需要反查任何轨道信息。
568
555
  */
569
556
  class VoicesBraceAttachment {
570
- box = { x: 0, y: 0, w: 0, h: 0 };
571
557
  layer = "background";
572
558
  names;
573
559
  ast;
574
- bars = [];
575
- hooks = [];
560
+ get sourceSpan() { return this.ast.sourceSpan; }
576
561
  constructor(names, ast) {
577
562
  this.names = names;
578
563
  this.ast = ast;
579
564
  }
580
- layout() {
581
- this.bars = [];
582
- this.hooks = [];
565
+ createGeometry() {
583
566
  if (this.names.length < 2)
584
- return [];
567
+ return { regions: [], paint() { } };
585
568
  const first = this.names[0].box;
586
569
  const last = this.names[this.names.length - 1].box;
587
570
  const em = this.ast.size;
588
571
  const top = first.y + first.visualAxis - em * 0.5;
589
572
  const bottom = last.y + last.visualAxis + em * 0.5;
590
573
  if (bottom - top < 1e-6)
591
- return [];
574
+ return { regions: [], paint() { } };
592
575
  // 各部分尺寸都以粗竖线宽度为单位,比例取自常见简谱软件的括线
593
576
  const stem = Math.max(2.5, em * 0.19);
594
577
  const reach = stem * BRACE_HOOK_REACH;
595
578
  const drop = stem * BRACE_HOOK_DROP;
596
579
  const x = first.x + first.anchor + this.ast.braceSpace * 0.3 + stem / 2;
597
- this.bars = [
580
+ const bars = [
598
581
  { x: x - stem / 2, y: top, w: stem, h: bottom - top },
599
582
  {
600
583
  x: x + stem * 1.33 - stem * 0.165,
@@ -603,57 +586,90 @@ class VoicesBraceAttachment {
603
586
  h: bottom - top - stem * 1.34,
604
587
  },
605
588
  ];
606
- this.hooks = [
589
+ const hooks = [
607
590
  { x, y: top, scale: stem, dir: -1 },
608
591
  { x, y: bottom, scale: stem, dir: 1 },
609
592
  ];
610
593
  // 括线画在声部名左侧的空白里,只参与画布边界,不抢任何轨道的纵向空间
611
- return [{
594
+ const regions = [{
612
595
  x: x - stem / 2,
613
596
  y: top - drop,
614
597
  w: reach + stem / 2,
615
598
  h: bottom - top + drop * 2,
616
599
  }];
617
- }
618
- paint(painter) {
619
- for (const bar of this.bars) {
620
- painter.drawRect(bar.x, bar.y, bar.w, bar.h, { fill: "#000" });
621
- }
622
- for (const hook of this.hooks) {
623
- painter.drawPath(BRACE_HOOK_COMMANDS, { fill: "#000" }, { x: hook.x, y: hook.y, scaleX: hook.scale, scaleY: hook.scale * hook.dir });
624
- }
600
+ return {
601
+ regions,
602
+ paint(painter) {
603
+ for (const bar of bars) {
604
+ painter.drawRect(bar.x, bar.y, bar.w, bar.h, { fill: "#000" });
605
+ }
606
+ for (const hook of hooks) {
607
+ painter.drawPath(BRACE_HOOK_COMMANDS, { fill: "#000" }, { x: hook.x, y: hook.y, scaleX: hook.scale, scaleY: hook.scale * hook.dir });
608
+ }
609
+ },
610
+ };
625
611
  }
626
612
  }
627
613
  class VoiceLyricsAttachment {
628
- box = { x: 0, y: 0, w: 0, h: 0 };
629
614
  layer = "foreground";
630
615
  /** lowering 会持续向这个数组加入 voice 内容产生的 temporal */
631
616
  temporalMembers;
632
617
  /** 同一个 voice 的声部名事件,歌词行名称向它的对齐点右对齐 */
633
618
  nameHost;
634
- preparedText = [];
619
+ get sourceSpan() { return this.nameHost.ast.sourceSpan; }
635
620
  constructor(temporalMembers, nameHost) {
636
621
  this.temporalMembers = temporalMembers;
637
622
  this.nameHost = nameHost;
638
623
  }
639
- layout(context) {
640
- this.updateGeometry(context);
641
- // 同一行同一轨的多行歌词由引擎合并成一段占用
642
- return this.preparedText;
643
- }
644
- paint(painter) {
645
- for (const item of this.preparedText) {
646
- painter.drawText(item.text, item.x, item.y + item.textBaselineY, item.style);
624
+ prepareHorizontal(lines, context) {
625
+ const targets = this.temporalMembers
626
+ .filter(isVisualTemporalNode)
627
+ .filter(node => node.ports?.["lyric"]);
628
+ const { lyrics, size } = this.nameHost.ast;
629
+ if (targets.length === 0 || lyrics.length === 0)
630
+ return;
631
+ const style = { fontSize: size * LYRIC_SIZE_RATIO, fill: "#000" };
632
+ for (let i = 0; i < targets.length; i++) {
633
+ const target = targets[i];
634
+ let halfWidth = 0;
635
+ for (const lyric of lyrics) {
636
+ const text = lyric.tokens[i];
637
+ if (text)
638
+ halfWidth = Math.max(halfWidth, context.textMeasurer.measureText(text, style).w / 2);
639
+ }
640
+ if (halfWidth === 0)
641
+ continue;
642
+ // 只扩大求解占用;视觉盒和端口不动,音符内部几何因此保持原位。
643
+ lines[target.layoutLine]?.registerHorizontalLayoutHook(target, target, ({ columns, start }) => {
644
+ const element = columns[start].find(item => item.time === target);
645
+ if (!element)
646
+ return;
647
+ const lyricOffset = target.ports["lyric"].x - target.box.anchor;
648
+ element.WL = Math.max(element.WL, halfWidth - lyricOffset);
649
+ element.WR = Math.max(element.WR, halfWidth + lyricOffset);
650
+ });
647
651
  }
648
652
  }
649
- updateGeometry(context) {
653
+ createGeometry(context) {
654
+ const preparedText = this.prepareGeometry(context);
655
+ // 同一行同一轨的多行歌词由引擎合并成一段占用
656
+ return {
657
+ regions: preparedText,
658
+ paint(painter) {
659
+ for (const item of preparedText) {
660
+ painter.drawText(item.text, item.x, item.y + item.textBaselineY, item.style);
661
+ }
662
+ },
663
+ };
664
+ }
665
+ prepareGeometry(context) {
650
666
  const { lyrics, size } = this.nameHost.ast;
651
- this.preparedText.length = 0;
667
+ const preparedText = [];
652
668
  const targets = this.temporalMembers
653
669
  .filter(isVisualTemporalNode)
654
670
  .filter(node => node.ports?.["lyric"]);
655
671
  if (targets.length === 0 || lyrics.length === 0)
656
- return;
672
+ return preparedText;
657
673
  // 每个 system+track 的歌词共用一条基线
658
674
  // 装饰高度先汇总为下边界,不进入单个 token 的 y 计算
659
675
  const contentBottom = new Map();
@@ -683,7 +699,7 @@ class VoiceLyricsAttachment {
683
699
  if (!text || bottom === undefined)
684
700
  continue;
685
701
  const metrics = context.textMeasurer.measureText(text, lyricStyle);
686
- this.preparedText.push({
702
+ preparedText.push({
687
703
  text,
688
704
  style: lyricStyle,
689
705
  textBaselineY: metrics.baseline,
@@ -698,7 +714,7 @@ class VoiceLyricsAttachment {
698
714
  if (!lyric.name || !labelBox || labelBottom === undefined)
699
715
  continue;
700
716
  const metrics = context.textMeasurer.measureText(lyric.name, nameStyle);
701
- this.preparedText.push({
717
+ preparedText.push({
702
718
  text: lyric.name,
703
719
  style: nameStyle,
704
720
  textBaselineY: metrics.baseline,
@@ -710,5 +726,6 @@ class VoiceLyricsAttachment {
710
726
  track: labelTrack,
711
727
  });
712
728
  }
729
+ return preparedText;
713
730
  }
714
731
  }
@@ -0,0 +1,2 @@
1
+ import { type ASTFunctionClass } from "../ASTtypes.js";
2
+ export declare const VoltaNode: ASTFunctionClass;
@@ -0,0 +1,227 @@
1
+ import { ANCHOR_KEY, isVisualTemporalNode, } from "../../lowering/types.js";
2
+ import { repeatPass } from "../bar/index.js";
3
+ import { ASTFunctionNode, } from "../ASTtypes.js";
4
+ import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
5
+ class VoltaFunction extends ASTFunctionNode {
6
+ static def = {
7
+ name: ["volta"],
8
+ description: "反复房子",
9
+ example: `@volta(from, to, pass, ...) 只在指定遍数演奏的一段区间
10
+ from 和 to 是区间首末音符的标签,因此房子可以横跨谱面行
11
+ pass 是遍数:整段谱面演奏到第几遍时才播这里,必填正整数
12
+ 再写几个遍数就是几遍共用一个房子,顺序随意,标签按升序写成 1.2.
13
+
14
+ |: 1 2 | 3@a 4@b :| 5@c 6@d | 7
15
+ @volta(a, b, 1) @volta(c, d, 2)`,
16
+ allowExtraArgs: true,
17
+ extraArgType: "number",
18
+ args: [
19
+ {
20
+ name: "from",
21
+ type: "label",
22
+ default: null,
23
+ },
24
+ {
25
+ name: "to",
26
+ type: "label",
27
+ default: null,
28
+ },
29
+ {
30
+ // 不给默认值:房子上的数字本来就是谱面的一部分,漏写会让整段被静默跳过
31
+ name: "pass",
32
+ type: "number",
33
+ default: null,
34
+ },
35
+ ],
36
+ };
37
+ from;
38
+ to;
39
+ /** 进入本房子的遍数,升序去重 */
40
+ passes;
41
+ /** 区间没有可见宿主时括线的尺寸基准 */
42
+ size;
43
+ /** volta 不推进时间,只把 AST 端点解析成稳定的 temporal 引用 */
44
+ loweringEnter(ctx) {
45
+ let from = ctx.getTemporalNodes(this.from).at(0);
46
+ let to = ctx.getTemporalNodes(this.to).at(-1);
47
+ while (from?.foldedInto)
48
+ from = from.foldedInto;
49
+ while (to?.foldedInto)
50
+ to = to.foldedInto;
51
+ if (!from || !to) {
52
+ ctx.diagnostics.push(Diagnostic.warning.UnresolvedEndpoint("volta", this.sourceSpan));
53
+ return [];
54
+ }
55
+ ctx.addAttachment(new VoltaAttachment(this, from, to));
56
+ return [];
57
+ }
58
+ constructor(span, args, ctx, parent = null) {
59
+ super(span, parent);
60
+ const [from, to, pass] = this.getArgValue(args, ctx);
61
+ // 第一个遍数走 def.args,其余的落在 extraArgType 里,按位置索引取
62
+ const passes = new Set([pass]);
63
+ for (let i = 3; args.has(i); i++)
64
+ passes.add(args.get(i));
65
+ this.from = from;
66
+ this.to = to;
67
+ this.passes = [...passes].sort((a, b) => a - b);
68
+ this.size = ctx.fontSize;
69
+ if (this.passes.some(value => !Number.isSafeInteger(value) || value <= 0)) {
70
+ throw new ErrorDiagnostic("E_VOLTA_INVALID_PASS", "@volta 的遍数必须是正整数", span);
71
+ }
72
+ }
73
+ toString(source) {
74
+ const name = (node) => node.label ?? node.toString(source);
75
+ return `@volta(${name(this.from)}, ${name(this.to)}, ${this.passes.join(", ")})`;
76
+ }
77
+ }
78
+ export const VoltaNode = VoltaFunction;
79
+ /** 取 ANCHOR 列的几何宿主 */
80
+ function barIn(column) {
81
+ if (column?.[0]?.mergeKey !== ANCHOR_KEY)
82
+ return undefined;
83
+ return column[0];
84
+ }
85
+ class VoltaAttachment {
86
+ ast;
87
+ from;
88
+ to;
89
+ layer = "foreground";
90
+ /** 首末端点列最上方的对象、区间最大字号与紧邻的小节线,横向准备时填入 */
91
+ head;
92
+ tail;
93
+ span = 0;
94
+ leftBar;
95
+ rightBar;
96
+ /** 逐行记下覆盖列内各轨的最高点,相对该轨视觉轴;轴要等纵向求解才知道 */
97
+ topsByLine = [];
98
+ constructor(ast, from, to) {
99
+ this.ast = ast;
100
+ this.from = from;
101
+ this.to = to;
102
+ }
103
+ get sourceSpan() { return this.ast.sourceSpan; }
104
+ /** 房子只决定跳不跳过本列;遍数怎么数、什么时候回跳都归小节线 */
105
+ playbackFlow(columnOf) {
106
+ const from = columnOf(this.from);
107
+ const to = columnOf(this.to);
108
+ if (from === undefined || to === undefined)
109
+ return;
110
+ const start = Math.min(from, to);
111
+ const end = Math.max(from, to);
112
+ return {
113
+ range: [start, end],
114
+ // 这里还是会和 bar 耦合。但只有bar有反复功能,不值得抽取为系统机制
115
+ run: cursor => this.ast.passes.includes(repeatPass(cursor, start))
116
+ ? undefined
117
+ : { kind: "jump", column: end + 1 },
118
+ };
119
+ }
120
+ prepareHorizontal(lines) {
121
+ if (!isVisualTemporalNode(this.from) || !isVisualTemporalNode(this.to))
122
+ return;
123
+ const locate = (node) => {
124
+ const view = lines[node.layoutLine];
125
+ return { line: node.layoutLine, view, column: view.columnOf(node) };
126
+ };
127
+ // 两个标签谁写在前面不一定,按谱面顺序摆正
128
+ let [from, to] = [locate(this.from), locate(this.to)];
129
+ if (from.line > to.line || (from.line === to.line && from.column > to.column)) {
130
+ [from, to] = [to, from];
131
+ }
132
+ if (from.column < 0 || to.column < 0)
133
+ return;
134
+ this.head = from.view.columns[from.column][0];
135
+ this.tail = to.view.columns[to.column][0];
136
+ this.leftBar = barIn(from.view.columns[from.column - 1]);
137
+ this.rightBar = barIn(to.view.columns[to.column + 1]);
138
+ this.span = 0;
139
+ this.topsByLine.length = 0;
140
+ // 括线盖住的是:首行从起点列向右、末行向左到终点列、中间行整行
141
+ for (let line = from.line; line <= to.line; line++) {
142
+ const view = lines[line];
143
+ const start = line === from.line ? from.column : 0;
144
+ const end = line === to.line ? to.column : view.columns.length - 1;
145
+ const tops = new Map();
146
+ for (let column = start; column <= end; column++) {
147
+ const hosts = view.columns[column];
148
+ this.span = Math.max(this.span, hosts[0].ast.size);
149
+ // 此刻 visualAxis 已冻结,纵向求解后 box.y 就是 该轨视觉轴 - visualAxis
150
+ for (const host of hosts) {
151
+ const top = -host.box.visualAxis;
152
+ const known = tops.get(host.track);
153
+ if (known === undefined || top < known)
154
+ tops.set(host.track, top);
155
+ }
156
+ }
157
+ this.topsByLine.push(tops);
158
+ }
159
+ }
160
+ createGeometry(context) {
161
+ const { head, tail, leftBar, rightBar } = this;
162
+ if (!head || !tail)
163
+ return { regions: [], paint() { } };
164
+ const firstLine = head.layoutLine;
165
+ const lastLine = tail.layoutLine;
166
+ const size = this.span || this.ast.size;
167
+ const style = {
168
+ fontSize: size * 0.6,
169
+ textAlign: "left",
170
+ fill: "#000",
171
+ };
172
+ const text = this.ast.passes.map(pass => `${pass}.`).join("");
173
+ const metrics = context.textMeasurer.measureText(text, style);
174
+ const strokeWidth = Math.max(1, size * 0.055);
175
+ const halfStroke = strokeWidth / 2;
176
+ const hook = metrics.h * 1.2;
177
+ // 标签在下折钩的高度里垂直居中
178
+ const textY = (hook - metrics.h) / 2 + metrics.baseline;
179
+ // 中间行可能没有本房子的可见对象,仍要补满,所以按行号连续遍历
180
+ const draws = Array.from({ length: lastLine - firstLine + 1 }, (_, offset) => {
181
+ const line = firstLine + offset;
182
+ // 跨行断开的那一侧一直画到页边,接上下一行
183
+ const left = line !== firstLine ? context.originX
184
+ : leftBar?.layoutLine === line ? leftBar.box.x + leftBar.box.anchor + 5 // 5是防止前后房子竖线重合
185
+ : head.box.x + (head.ports["body.left"]?.x ?? 0);
186
+ const right = line !== lastLine ? context.originX + context.width
187
+ : rightBar?.layoutLine === line ? rightBar.box.x + rightBar.box.anchor
188
+ : tail.box.x + (tail.ports["body.right"]?.x ?? tail.box.w);
189
+ let topTrack = head.track;
190
+ let hostTop = Infinity;
191
+ for (const [track, top] of this.topsByLine[offset]) {
192
+ const y = context.getVisualAxis(line, track) + top;
193
+ if (y < hostTop) {
194
+ topTrack = track;
195
+ hostTop = y;
196
+ }
197
+ }
198
+ // 整行空白时没有主体可以参照,退到轨道轴上
199
+ if (hostTop === Infinity)
200
+ hostTop = context.getVisualAxis(line, topTrack);
201
+ return { left, right, lineY: hostTop - size * 0.2 - hook, line, track: topTrack };
202
+ });
203
+ return {
204
+ regions: draws.map(({ left, right, lineY, line, track }) => ({
205
+ x: left - halfStroke,
206
+ y: lineY - halfStroke,
207
+ w: right - left + strokeWidth,
208
+ h: hook + strokeWidth,
209
+ line,
210
+ track,
211
+ })),
212
+ paint(painter) {
213
+ const lineStyle = { stroke: "#000", strokeWidth };
214
+ for (const { left, right, lineY, line } of draws) {
215
+ painter.drawLine(left, lineY, right, lineY, lineStyle);
216
+ // 只有房子真正开始和结束的那一端才下折
217
+ if (line === firstLine) {
218
+ painter.drawLine(left, lineY, left, lineY + hook, lineStyle);
219
+ painter.drawText(text, left + size * 0.15, lineY + textY + 2, style);
220
+ }
221
+ if (line === lastLine)
222
+ painter.drawLine(right, lineY, right, lineY + hook, lineStyle);
223
+ }
224
+ },
225
+ };
226
+ }
227
+ }
package/dist/index.d.ts CHANGED
@@ -2,6 +2,7 @@ export * from "./pipeline.js";
2
2
  export * from "./functions/ASTtypes.js";
3
3
  export * from "./functions/default.js";
4
4
  export * from "./diagnostic.js";
5
+ export * from "./fraction.js";
5
6
  export * from "./parser/types.js";
6
7
  export * from "./parser/grammarType.js";
7
8
  export * from "./parser/parserContext.js";
@@ -9,6 +10,9 @@ export * from "./parser/preprocess.js";
9
10
  export * from "./lowering/types.js";
10
11
  export * from "./lowering/loweringContext.js";
11
12
  export * from "./lowering/track.js";
13
+ export * from "./playback/types.js";
14
+ export * from "./playback/time.js";
15
+ export * from "./playback/compile.js";
12
16
  export * from "./layout/types.js";
13
17
  export * from "./layout/model.js";
14
18
  export * from "./layout/default.js";