jpfun 0.3.0 → 0.4.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 (125) hide show
  1. package/README.md +73 -1
  2. package/dist/converter/midi/convert.d.ts +50 -0
  3. package/dist/converter/midi/convert.js +700 -0
  4. package/dist/converter/midi/index.d.ts +5 -0
  5. package/dist/converter/midi/index.js +11 -0
  6. package/dist/converter/midi/json.d.ts +38 -0
  7. package/dist/converter/midi/json.js +1 -0
  8. package/dist/converter/midi/triplet.d.ts +30 -0
  9. package/dist/converter/midi/triplet.js +75 -0
  10. package/dist/converter/musicxml/dom.d.ts +25 -0
  11. package/dist/converter/musicxml/dom.js +65 -0
  12. package/dist/converter/musicxml/features.d.ts +51 -0
  13. package/dist/converter/musicxml/features.js +232 -0
  14. package/dist/converter/musicxml/index.d.ts +9 -0
  15. package/dist/converter/musicxml/index.js +1140 -0
  16. package/dist/converter/musicxml/model.d.ts +123 -0
  17. package/dist/converter/musicxml/model.js +1 -0
  18. package/dist/converter/source.d.ts +22 -0
  19. package/dist/converter/source.js +51 -0
  20. package/dist/core.d.ts +22 -0
  21. package/dist/core.js +22 -0
  22. package/dist/functions/ASTtypes.d.ts +28 -25
  23. package/dist/functions/ASTtypes.js +25 -23
  24. package/dist/functions/adjust/index.js +1 -1
  25. package/dist/functions/arpeggio/index.d.ts +2 -0
  26. package/dist/functions/arpeggio/index.js +180 -0
  27. package/dist/functions/arpeggio/shape.d.ts +7 -0
  28. package/dist/functions/arpeggio/shape.js +122 -0
  29. package/dist/functions/bar/index.js +23 -15
  30. package/dist/functions/beam/auto.d.ts +1 -1
  31. package/dist/functions/beam/auto.js +1 -1
  32. package/dist/functions/beam/layout.d.ts +2 -2
  33. package/dist/functions/beam/layout.js +1 -1
  34. package/dist/functions/box/index.js +2 -2
  35. package/dist/functions/br/index.js +1 -1
  36. package/dist/functions/dash/index.js +7 -6
  37. package/dist/functions/default.js +6 -2
  38. package/dist/functions/dot/index.js +12 -22
  39. package/dist/functions/dyn/index.d.ts +2 -0
  40. package/dist/functions/dyn/index.js +242 -0
  41. package/dist/functions/grace/index.d.ts +1 -1
  42. package/dist/functions/grace/index.js +2 -3
  43. package/dist/functions/head/index.js +149 -145
  44. package/dist/functions/key/index.js +5 -4
  45. package/dist/functions/meter/index.js +6 -5
  46. package/dist/functions/note/index.js +68 -21
  47. package/dist/functions/note/noteNameFSM.js +52 -63
  48. package/dist/functions/page/index.d.ts +2 -0
  49. package/dist/functions/page/index.js +22 -7
  50. package/dist/functions/program/index.d.ts +2 -0
  51. package/dist/functions/program/index.js +30 -0
  52. package/dist/functions/set/index.js +8 -5
  53. package/dist/functions/symbol/index.d.ts +13 -3
  54. package/dist/functions/symbol/index.js +61 -16
  55. package/dist/functions/symbol/shape.d.ts +2 -0
  56. package/dist/functions/symbol/shape.js +14 -10
  57. package/dist/functions/symbol/symbols/dc.d.ts +4 -0
  58. package/dist/functions/symbol/symbols/dc.js +82 -0
  59. package/dist/functions/symbol/symbols/{f.d.ts → ds.d.ts} +1 -1
  60. package/dist/functions/symbol/symbols/ds.js +93 -0
  61. package/dist/functions/symbol/symbols/dynamics.d.ts +3 -0
  62. package/dist/functions/symbol/symbols/dynamics.js +168 -0
  63. package/dist/functions/symbol/symbols/{p.d.ts → fine.d.ts} +1 -1
  64. package/dist/functions/symbol/symbols/fine.js +12 -0
  65. package/dist/functions/symbol/symbols/mordent.js +44 -31
  66. package/dist/functions/symbol/symbols/prall.d.ts +2 -0
  67. package/dist/functions/symbol/symbols/prall.js +42 -0
  68. package/dist/functions/symbol/symbols/segno.d.ts +4 -0
  69. package/dist/functions/symbol/symbols/segno.js +82 -0
  70. package/dist/functions/symbol/symbols/tr.js +0 -4
  71. package/dist/functions/tempo/index.js +5 -3
  72. package/dist/functions/temporal.d.ts +138 -0
  73. package/dist/functions/temporal.js +101 -0
  74. package/dist/functions/text/index.js +14 -7
  75. package/dist/functions/tie/index.js +37 -28
  76. package/dist/functions/tuplet/index.js +14 -7
  77. package/dist/functions/up/index.js +23 -21
  78. package/dist/functions/voice/index.js +121 -45
  79. package/dist/functions/volta/index.js +51 -48
  80. package/dist/iife/core.d.ts +1 -0
  81. package/dist/iife/core.js +3 -0
  82. package/dist/iife/from-midi.d.ts +1 -0
  83. package/dist/iife/from-midi.js +15 -0
  84. package/dist/iife/from-musicxml.d.ts +1 -0
  85. package/dist/iife/from-musicxml.js +3 -0
  86. package/dist/iife/full.d.ts +1 -0
  87. package/dist/iife/full.js +3 -0
  88. package/dist/index.d.ts +3 -21
  89. package/dist/index.js +3 -21
  90. package/dist/jpfun.core.min.js +153 -0
  91. package/dist/jpfun.from-midi.min.js +9 -0
  92. package/dist/jpfun.from-musicxml.min.js +12 -0
  93. package/dist/jpfun.min.js +71 -48
  94. package/dist/layout/default.js +2 -3
  95. package/dist/layout/engine.d.ts +2 -1
  96. package/dist/layout/engine.js +71 -26
  97. package/dist/layout/model.d.ts +4 -4
  98. package/dist/layout/model.js +15 -12
  99. package/dist/layout/page.js +5 -4
  100. package/dist/layout/path.js +3 -3
  101. package/dist/layout/types.d.ts +20 -2
  102. package/dist/lowering/loweringContext.d.ts +3 -1
  103. package/dist/lowering/loweringContext.js +28 -14
  104. package/dist/lowering/track.d.ts +4 -8
  105. package/dist/lowering/track.js +6 -1
  106. package/dist/lowering/types.d.ts +5 -128
  107. package/dist/lowering/types.js +1 -98
  108. package/dist/parser/parse-utils/string-utils.d.ts +2 -0
  109. package/dist/parser/parse-utils/string-utils.js +4 -0
  110. package/dist/parser/parserContext.d.ts +7 -8
  111. package/dist/parser/parserContext.js +41 -36
  112. package/dist/pipeline.d.ts +6 -5
  113. package/dist/pipeline.js +4 -5
  114. package/dist/playback/compile.d.ts +1 -1
  115. package/dist/playback/compile.js +15 -2
  116. package/dist/playback/event.d.ts +17 -3
  117. package/dist/playback/event.js +30 -12
  118. package/dist/playback/time.js +1 -1
  119. package/dist/playback/types.d.ts +5 -4
  120. package/dist/render/text.d.ts +6 -1
  121. package/dist/render/text.js +8 -1
  122. package/grammar.md +44 -8
  123. package/package.json +11 -2
  124. package/dist/functions/symbol/symbols/f.js +0 -55
  125. package/dist/functions/symbol/symbols/p.js +0 -61
@@ -1,6 +1,6 @@
1
1
  import { ASTFunctionNode } from "../ASTtypes.js";
2
2
  import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
3
- import { isVisualTemporalNode, } from "../../lowering/types.js";
3
+ import { isVisualTemporalNode, } from "../temporal.js";
4
4
  import { pathBounds } from "../../layout/path.js";
5
5
  /** 三次贝塞尔控制点的抬高系数:两个控制点同高时,实际弧高恰好是抬高的 3/4 */
6
6
  const CUBIC_LIFT = 4 / 3;
@@ -20,7 +20,7 @@ class TieFunction extends ASTFunctionNode {
20
20
  height;
21
21
  constructor(sourceSpan, args, ctx, parent = null) {
22
22
  super(sourceSpan, parent);
23
- let height = ctx.fontSize * 0.5;
23
+ let height = ctx.variables.fontsize * 0.5;
24
24
  for (const [key, value] of args) {
25
25
  if (key === "height") {
26
26
  const length = ctx.parseArgWithType(value.valueSpan, "length", sourceSpan.start);
@@ -70,17 +70,6 @@ class TieFunction extends ASTFunctionNode {
70
70
  }
71
71
  }
72
72
  export const TieNode = TieFunction;
73
- /** 二次贝塞尔在某一维上的内部极值 */
74
- function quadExtremum(p0, p1, p2) {
75
- const d = p0 - 2 * p1 + p2;
76
- if (Math.abs(d) < 1e-9)
77
- return null;
78
- const t = (p0 - p1) / d;
79
- if (t <= 0 || t >= 1)
80
- return null;
81
- const u = 1 - t;
82
- return u * u * p0 + 2 * u * t * p1 + t * t * p2;
83
- }
84
73
  class TieLayoutAttachment {
85
74
  layer = "foreground";
86
75
  sourceSpan;
@@ -114,6 +103,7 @@ class TieLayoutAttachment {
114
103
  && note.origins.some(origin => origin.node === this.endPoints[i])
115
104
  && note.track === head.track
116
105
  && note.midi === head.midi
106
+ && note.percussion === head.percussion
117
107
  && end.at.equals(note.at));
118
108
  if (!next)
119
109
  break;
@@ -136,6 +126,7 @@ class TieLayoutAttachment {
136
126
  const regions = segments.map(({ commands, ...region }) => region);
137
127
  const occupancy = segments.map(segment => {
138
128
  // 只申报主体上方那一段,下半截由主体自己占;本行没有主体时就只有弧带本身
129
+ // 用 getHostExtent 而不是 getRangeExtents:连音线只避让主体,彼此之间允许重叠
139
130
  const hostExtent = context.getHostExtent(segment.line, segment.track);
140
131
  const bottom = hostExtent
141
132
  ? Math.max(segment.y, context.getVisualAxis(segment.line, segment.track) + hostExtent.top)
@@ -160,8 +151,8 @@ class TieLayoutAttachment {
160
151
  },
161
152
  };
162
153
  }
163
- absolutePort(node, name) {
164
- const port = node.ports[name];
154
+ tiePort(node) {
155
+ const port = node.ports["tie.top"];
165
156
  if (port) {
166
157
  return {
167
158
  x: node.box.x + port.x,
@@ -173,7 +164,7 @@ class TieLayoutAttachment {
173
164
  y: node.box.y,
174
165
  };
175
166
  }
176
- /** 根据端点固化后的行号选择同行弧线或跨行分段。 */
167
+ /** 根据端点固化后的行号选择同行弧线或跨行分段 */
177
168
  createSegments(context) {
178
169
  const segments = [];
179
170
  for (let i = 1; i < this.endPoints.length; i++) {
@@ -182,8 +173,8 @@ class TieLayoutAttachment {
182
173
  // 标签书写顺序不保证时间顺序,先按谱面行升序规范化
183
174
  if (startNode.layoutLine > endNode.layoutLine)
184
175
  [startNode, endNode] = [endNode, startNode];
185
- const start = this.absolutePort(startNode, "tie.top");
186
- const end = this.absolutePort(endNode, "tie.top");
176
+ const start = this.tiePort(startNode);
177
+ const end = this.tiePort(endNode);
187
178
  if (startNode.layoutLine === endNode.layoutLine) {
188
179
  const startTop = context.getVisualAxis(startNode.layoutLine, startNode.track)
189
180
  + (context.getHostExtent(startNode.layoutLine, startNode.track)?.top ?? 0);
@@ -193,21 +184,39 @@ class TieLayoutAttachment {
193
184
  continue;
194
185
  }
195
186
  // 首行先起弧,再沿水平段延伸到当前谱面行最右侧
196
- segments.push(this.openingSegment(start, context.originX + context.width, this.plateauY(context, startNode.layoutLine, startNode.track, start.y), startNode.layoutLine, startNode.track));
187
+ segments.push(this.openingSegment(start, this.lineRightX(context, startNode.layoutLine), this.plateauY(context, startNode.layoutLine, startNode.track, start.y), startNode.layoutLine, startNode.track));
197
188
  // 中间行可能没有任何可见对象,仍然需要逐行补一段水平线
198
189
  for (let line = startNode.layoutLine + 1; line < endNode.layoutLine; line++) {
199
- segments.push(this.horizontalSegment(context.originX, context.originX + context.width, this.plateauY(context, line, startNode.track), line, startNode.track));
190
+ segments.push(this.horizontalSegment(this.lineEntryX(context, line, startNode.track), this.lineRightX(context, line), this.plateauY(context, line, startNode.track), line, startNode.track));
200
191
  }
201
- // 末行从最左侧进入,经过水平段后落弧到终点
202
- segments.push(this.closingSegment(context.originX, end, this.plateauY(context, endNode.layoutLine, endNode.track, end.y), endNode.layoutLine, endNode.track));
192
+ // 跳过声部名、大括号等位于端点列之前的系统前缀,再落弧到终点
193
+ segments.push(this.closingSegment(this.lineEntryX(context, endNode.layoutLine, endNode.track), end, this.plateauY(context, endNode.layoutLine, endNode.track, end.y), endNode.layoutLine, endNode.track));
203
194
  }
204
195
  return segments;
205
196
  }
206
- /** 沿用普通端点的抬高量,但基准至少是当前 Track 的最高主体。 */
197
+ lineEntryX(context, lineIndex, track) {
198
+ const line = context.lines[lineIndex];
199
+ const host = line.trackRuns.get(track)?.find(host => !host.T.isZero());
200
+ return host?.box.x ?? context.originX;
201
+ }
202
+ lineRightX(context, lineIndex) {
203
+ const runs = context.lines[lineIndex].trackRuns;
204
+ if (runs.size === 0)
205
+ return context.originX + context.width;
206
+ let right = context.originX;
207
+ for (const run of runs.values()) {
208
+ for (const host of run)
209
+ right = Math.max(right, host.box.x + host.box.w);
210
+ }
211
+ return right;
212
+ }
213
+ /** 有端点时从端点固定抬高;中间段没有端点,才以当前 Track 的主体顶部为基准 */
207
214
  plateauY(context, line, track, endpointY = Infinity) {
215
+ if (Number.isFinite(endpointY))
216
+ return endpointY - this.height;
208
217
  const axis = context.getVisualAxis(line, track);
209
218
  const hostTop = context.getHostExtent(line, track)?.top ?? 0;
210
- return Math.min(endpointY, axis + hostTop) - this.height;
219
+ return axis + hostTop - this.height;
211
220
  }
212
221
  /** 一条三次贝塞尔的外缘配上反向内缘,得到两端收尖、中部最厚的乐谱弧线 */
213
222
  arcSegment(startInput, endInput, line, track) {
@@ -230,8 +239,8 @@ class TieLayoutAttachment {
230
239
  }
231
240
  /** 跨行首段:从端点起弧,随后水平延伸到右边界 */
232
241
  openingSegment(start, right, plateauY, line, track) {
233
- const span = Math.max(0, right - start.x);
234
- const run = Math.min(this.height * 1.2, span * 0.4);
242
+ const run = this.height * 1.2;
243
+ right = Math.max(right, start.x + run);
235
244
  const curveX = start.x + run;
236
245
  const controlX = start.x + run * 0.45;
237
246
  const bottom = plateauY + this.thickness;
@@ -247,8 +256,8 @@ class TieLayoutAttachment {
247
256
  }
248
257
  /** 跨行末段:从左边界水平进入,最后落弧到端点 */
249
258
  closingSegment(left, end, plateauY, line, track) {
250
- const span = Math.max(0, end.x - left);
251
- const run = Math.min(this.height * 1.2, span * 0.4);
259
+ const run = this.height * 1.2;
260
+ left = Math.min(left, end.x - run);
252
261
  const curveX = end.x - run;
253
262
  const controlX = end.x - run * 0.45;
254
263
  const bottom = plateauY + this.thickness;
@@ -1,8 +1,7 @@
1
1
  import { ErrorDiagnostic } from "../../diagnostic.js";
2
2
  import { Fraction } from "../../fraction.js";
3
- import { isVisualTemporalNode, } from "../../lowering/types.js";
3
+ import { isVisualTemporalNode, } from "../temporal.js";
4
4
  import { ASTFunctionNode, } from "../ASTtypes.js";
5
- import { JIANPU_NUMBER_FONT } from "../../render/text.js";
6
5
  /**
7
6
  * 多连音是范围时值变换,不产生自己的 Temporal:
8
7
  * actual = 内容原总时值 / 最短正时值
@@ -34,6 +33,7 @@ class TupletFunction extends ASTFunctionNode {
34
33
  };
35
34
  content;
36
35
  normal;
36
+ font;
37
37
  get children() { return [this.content]; }
38
38
  timeFlowModel() {
39
39
  return {
@@ -99,13 +99,14 @@ class TupletFunction extends ASTFunctionNode {
99
99
  // 括线只依附可见主体;时值缩放本身仍覆盖所有收集到的事件。
100
100
  const visible = positive.filter(isVisualTemporalNode);
101
101
  if (visible.length >= 2) {
102
- ctx.addAttachment(new TupletLayoutAttachment(visible, actual, this.sourceSpan));
102
+ ctx.addAttachment(new TupletLayoutAttachment(visible, actual, this.sourceSpan, this.font));
103
103
  }
104
104
  return [];
105
105
  }
106
106
  constructor(span, args, ctx, parent = null) {
107
107
  super(span, parent);
108
108
  const [content, normal] = this.getArgValue(args, ctx);
109
+ this.font = ctx.variables.numberfont;
109
110
  // normal 是目标包含的“最短时值单位数”,不是 QN 数,也不是显示的 actual。
110
111
  if (!Number.isSafeInteger(normal) || normal <= 0) {
111
112
  throw new ErrorDiagnostic("E_TUPLET_INVALID_NORMAL", "@tuplet 的 normal 必须是正的安全整数", span);
@@ -132,14 +133,14 @@ class TupletLayoutAttachment {
132
133
  /** 由端点最大字号冻结的绘制规格 */
133
134
  style;
134
135
  size;
135
- constructor(endPoints, actual, sourceSpan) {
136
+ constructor(endPoints, actual, sourceSpan, font) {
136
137
  this.endPoints = endPoints;
137
138
  this.actual = actual;
138
139
  this.sourceSpan = sourceSpan;
139
140
  this.size = endPoints.reduce((size, endpoint) => Math.max(size, endpoint.ast.size), 0);
140
141
  this.style = {
141
142
  fontSize: this.size * 0.72,
142
- fontFamily: JIANPU_NUMBER_FONT,
143
+ fontFamily: font,
143
144
  textAlign: "center",
144
145
  fill: "#000",
145
146
  };
@@ -167,9 +168,15 @@ class TupletLayoutAttachment {
167
168
  const textGap = this.size * 0.12;
168
169
  const hookHeight = this.size * 0.18;
169
170
  const hostGap = this.size * 0.14;
170
- // hostExtent 是相对轨道视觉轴的主体占用;转为绝对坐标后再向上放置括线。
171
+ // 只测首尾时间列,并合并先注册的 attachment,使后声明的括线排在外层。
172
+ const view = context.lines[first.layoutLine];
173
+ const from = view?.columnOf(first) ?? -1;
174
+ const to = view?.columnOf(last) ?? -1;
171
175
  const axis = context.getVisualAxis(first.layoutLine, first.track);
172
- const hostTop = axis + (context.getHostExtent(first.layoutLine, first.track)?.top ?? 0);
176
+ const extent = from < 0 || to < 0
177
+ ? undefined
178
+ : context.getRangeExtents(first.layoutLine, [Math.min(from, to), Math.max(from, to)]).get(first.track);
179
+ const hostTop = axis + (extent?.top ?? 0);
173
180
  const strokeWidth = Math.max(1, this.size * 0.055);
174
181
  const lineY = hostTop - hostGap - Math.max(hookHeight, metrics.h / 2);
175
182
  const hookBottom = lineY + hookHeight;
@@ -1,6 +1,6 @@
1
1
  import { ASTNodeBase, ASTFunctionNode, ASTTextNode, ASTLabelNode, ASTBraceNode } from "../ASTtypes.js";
2
2
  import { ErrorDiagnostic } from "../../diagnostic.js";
3
- import { ANCHOR_KEY, DEFAULT_KEY, isVisualTemporalNode, TemporalNodeBase, } from "../../lowering/types.js";
3
+ import { ANCHOR_KEY, DEFAULT_KEY, isVisualTemporalNode, TemporalNodeBase, } from "../temporal.js";
4
4
  import { Fraction } from "../../fraction.js";
5
5
  import { prepareLayoutHost } from "../../layout/engine.js";
6
6
  /**
@@ -12,7 +12,7 @@ import { prepareLayoutHost } from "../../layout/engine.js";
12
12
  class FoldFunction extends ASTFunctionNode {
13
13
  contents = [];
14
14
  belows = [];
15
- size;
15
+ size; // 用于计算 gap
16
16
  /** 静态而不是实例字段:子类的字段初始化器晚于基类构造器,构造期读不到 */
17
17
  get side() { return this.constructor.side; }
18
18
  get children() {
@@ -20,7 +20,7 @@ class FoldFunction extends ASTFunctionNode {
20
20
  }
21
21
  constructor(span, args, ctx, parent = null) {
22
22
  super(span, parent);
23
- this.size = ctx.fontSize;
23
+ this.size = ctx.variables.fontsize;
24
24
  for (const [, value] of args) {
25
25
  if (value instanceof ASTNodeBase) {
26
26
  this.addContent(value, this.side, ctx);
@@ -229,8 +229,8 @@ class FoldTemporal extends TemporalNodeBase {
229
229
  members;
230
230
  /** members[0] 是宿主,`[1, aboveCount)` 向上叠,`[aboveCount, end)` 向下叠 */
231
231
  aboveCount;
232
- /** 每个成员相对本盒左上角的局部偏移,onPlaced 时同步为绝对坐标 */
233
- offsets = [];
232
+ /** 每个成员相对本盒顶部的纵向偏移,onPlaced 时同步为绝对坐标 */
233
+ verticalOffsets = [];
234
234
  constructor(ast, members) {
235
235
  super();
236
236
  this.ast = ast;
@@ -285,6 +285,9 @@ class FoldTemporal extends TemporalNodeBase {
285
285
  for (let i = this.members.length - 1; i >= 0; i--)
286
286
  emitter.play(this.members[i]);
287
287
  }
288
+ prepareHorizontal(line) {
289
+ this.members[0]?.prepareHorizontal?.(line);
290
+ }
288
291
  /**
289
292
  * 宿主留在轨道基线上,其余成员按书写顺序向上或向下叠放
290
293
  *
@@ -292,7 +295,6 @@ class FoldTemporal extends TemporalNodeBase {
292
295
  * 准备直接复用引擎的 prepareLayoutHost,保证成员的装饰、端口与顶层对象完全一致。
293
296
  */
294
297
  prepareLayout(context) {
295
- this.offsets.length = 0;
296
298
  // lowering 期间修饰挂在折叠体上(augmenter 要看到整体节奏),渲染时交给宿主:
297
299
  // 减时线要落在它的数字与下八度点之间,而不是压在整个盒子下面
298
300
  if (this.addon && this.members[0]) {
@@ -307,56 +309,56 @@ class FoldTemporal extends TemporalNodeBase {
307
309
  this.box.anchor = this.box.visualAxis = 0;
308
310
  return;
309
311
  }
312
+ this.springConfig = { ...first.springConfig, ...this.springConfig };
310
313
  // 横向完全等于宿主:上下的标记(变速、注释、力度)常常比音符宽得多,
311
314
  // 让它们撑宽盒子会把右邻推开一大截;它们画在基线外侧,伸出盒外也不会碰撞
312
315
  const anchor = first.box.anchor;
313
316
  const gap = this.ast.size * 0.12;
314
- for (const member of this.members)
315
- this.offsets.push({ x: anchor - member.box.anchor, y: 0 });
317
+ this.verticalOffsets.length = this.members.length;
318
+ this.verticalOffsets.fill(0);
316
319
  // 以宿主盒顶为 0,向上得到负坐标、向下得到正坐标,最后整体下移
317
320
  let top = 0;
318
321
  for (let i = 1; i < this.aboveCount; i++) {
319
322
  top -= gap + this.members[i].box.h;
320
- this.offsets[i].y = top;
323
+ this.verticalOffsets[i] = top;
321
324
  }
322
325
  let bottom = first.box.h;
323
326
  for (let i = this.aboveCount; i < this.members.length; i++) {
324
327
  bottom += gap;
325
- this.offsets[i].y = bottom;
328
+ this.verticalOffsets[i] = bottom;
326
329
  bottom += this.members[i].box.h;
327
330
  }
328
- for (const offset of this.offsets)
329
- offset.y -= top;
331
+ for (let i = 0; i < this.verticalOffsets.length; i++)
332
+ this.verticalOffsets[i] -= top;
330
333
  this.box.w = first.box.w;
331
334
  this.box.h = bottom - top;
332
335
  this.box.anchor = anchor;
333
336
  // 宿主对齐轨道基线,两侧成员各自向外撑开行高
334
337
  this.box.visualAxis = first.box.visualAxis - top;
335
- // 端口:宿主代表整个折叠体,把它发布的端口原样平移(它的 offset.x 恒为 0),
338
+ // 端口:宿主代表整个折叠体,把它发布的端口原样上提,
336
339
  // 减时线、歌词等端口于是与普通音符完全一致,关系函数不需要认识 up
337
- const firstOffset = this.offsets[0];
340
+ const firstOffset = this.verticalOffsets[0];
338
341
  for (const name in first.ports) {
339
342
  const port = first.ports[name];
340
- this.ports[name] = { x: port.x, y: firstOffset.y + port.y };
343
+ this.ports[name] = { x: port.x, y: firstOffset + port.y };
341
344
  }
342
345
  // 代表成员没声明核心范围时退回它的整个盒子
343
346
  this.ports["body.left"] ??= { x: 0, y: this.box.visualAxis };
344
347
  this.ports["body.right"] ??= { x: first.box.w, y: this.box.visualAxis };
345
348
  // 唯一的例外:连音线要接到最上面那个成员的顶部
346
349
  const topIndex = this.aboveCount - 1;
347
- const topOffset = this.offsets[topIndex];
350
+ const topOffset = this.verticalOffsets[topIndex];
348
351
  this.ports["tie.top"] = {
349
352
  x: anchor,
350
- y: topOffset.y + (this.members[topIndex].ports["tie.top"]?.y ?? 0),
353
+ y: topOffset + (this.members[topIndex].ports["tie.top"]?.y ?? 0),
351
354
  };
352
355
  }
353
- /** 引擎每次改变本节点坐标后,按准备阶段保存的局部偏移重算成员绝对坐标 */
356
+ /** 引擎每次改变本节点坐标后,按当前 anchor 与准备阶段的纵向偏移重算成员绝对坐标 */
354
357
  onPlaced() {
355
358
  for (let i = 0; i < this.members.length; i++) {
356
- const offset = this.offsets[i];
357
359
  const member = this.members[i];
358
- member.box.x = this.box.x + offset.x;
359
- member.box.y = this.box.y + offset.y;
360
+ member.box.x = this.box.x + this.box.anchor - member.box.anchor;
361
+ member.box.y = this.box.y + this.verticalOffsets[i];
360
362
  member.onPlaced?.();
361
363
  }
362
364
  }
@@ -1,10 +1,27 @@
1
1
  import { ASTNodeBase, ASTBraceNode, ASTFunctionNode, ASTTextNode } from "../ASTtypes.js";
2
2
  import { Diagnostic, ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
3
3
  import { findRightParen } from "../../parser/parse-utils/call-utils.js";
4
- import { findClosingQuote, removeQuote } from "../../parser/parse-utils/string-utils.js";
4
+ import { findClosingQuote, quote, removeQuote } from "../../parser/parse-utils/string-utils.js";
5
5
  import { ParserContext, skipSpaces } from "../../parser/parserContext.js";
6
- import { isVisualTemporalNode, TemporalNodeBase, } from "../../lowering/types.js";
6
+ import { isVisualTemporalNode, TemporalNodeBase, } from "../temporal.js";
7
7
  const WHITEPACE_RE = /\s/;
8
+ // 分词跟后面的标点
9
+ const LYRIC_OPENING_PUNCTUATION = new Set("(([[{〈《「『【〔〖〘〚‘“");
10
+ // 不发声的标点;位于歌词槽首尾时只渲染,不占位,也不参与对齐中心计算
11
+ const LYRIC_SILENT_PUNCTUATION = new Set([
12
+ ...LYRIC_OPENING_PUNCTUATION,
13
+ ...",。!?;:、,.!?;:))]]}〉》」』】〕〗〙〛’”\"'…—–",
14
+ ]);
15
+ // 分词
16
+ function splitLyricText(text) {
17
+ let start = 0;
18
+ let end = text.length;
19
+ while (start < end && LYRIC_SILENT_PUNCTUATION.has(text[start]))
20
+ start++;
21
+ while (end > start && LYRIC_SILENT_PUNCTUATION.has(text[end - 1]))
22
+ end--;
23
+ return { prefix: text.slice(0, start), body: text.slice(start, end) };
24
+ }
8
25
  /**
9
26
  * voices 块在宿主基线上局部居中:首末两条 voice 基线的中点对齐宿主轴
10
27
  *
@@ -138,7 +155,7 @@ L: ...
138
155
  for (; voiceNodeAt >= 0; voiceNodeAt--) {
139
156
  const n = ctx.nodes[voiceNodeAt];
140
157
  if (n instanceof ASTTextNode) {
141
- if (!ctx.strict)
158
+ if (!ctx.variables.strict)
142
159
  continue; // 非严格模式下允许文本节点夹在N和L之间
143
160
  // ParserContext.parseGrammar 处理后不会有空白字符
144
161
  throw new ErrorDiagnostic("E_LYRICS_WITHOUT_VOICE_NOTES", `strict 模式下,语法糖 'L:' 或 'L(name)' 必须跟在 @voice 的音符之后,但在其前面发现了未知文本`, n.sourceSpan);
@@ -198,7 +215,7 @@ L: ...
198
215
  ifCombine: for (; voicesNodeAt >= 0; voicesNodeAt--) {
199
216
  const n = ctx.nodes[voicesNodeAt];
200
217
  if (n instanceof ASTTextNode) {
201
- if (ctx.strict)
218
+ if (ctx.variables.strict)
202
219
  break;
203
220
  // 如果中间有换行符,直接说明是两个独立的 voice 组件,不能合并
204
221
  for (let i = n.sourceSpan.start; i < n.sourceSpan.end; i++) {
@@ -239,6 +256,7 @@ L: ...
239
256
  content; // 声部内容
240
257
  name; // 声部名称
241
258
  size; // 声部的字体大小
259
+ font;
242
260
  lyrics;
243
261
  get children() { return [this.content]; }
244
262
  timeFlowModel() {
@@ -276,9 +294,10 @@ L: ...
276
294
  }
277
295
  constructor(span, args, ctx, parent = null) {
278
296
  super(span, parent);
279
- this.size = ctx.fontSize;
297
+ this.size = ctx.variables.fontsize;
280
298
  [this.content, this.name] = this.getArgValue(args, ctx);
281
299
  this.content.parent = this;
300
+ this.font = ctx.variables.font;
282
301
  args.delete(0);
283
302
  args.delete("name");
284
303
  args.delete(1);
@@ -313,52 +332,101 @@ L: ...
313
332
  }
314
333
  }
315
334
  }
335
+ /**
336
+ * 把歌词拆成与音符一一对应的槽位。
337
+ * 例如 `hello world` 拆成 `hello`、`world`,`hel-lo` 拆成 `hel-`、`lo`;
338
+ * `你好吗` 默认逐字拆分,`你 @ 好` 中的 `@` 留出一个空槽,`{你好} 啊` 则把 `你好` 放在同一个槽位。
339
+ * 转义符:hel\-lo \@ {你\}好} 会得到 ["hel-lo", "@", "你}好"],而不是把 -、@、} 当控制符
340
+ */
316
341
  static parseLyric(value) {
317
342
  const result = [];
318
- let lastPos = 0;
343
+ let token = "";
344
+ let prefix = "";
345
+ const pushSlot = (text) => {
346
+ result.push(prefix + text);
347
+ prefix = "";
348
+ };
349
+ const pushToken = () => {
350
+ if (token)
351
+ pushSlot(token);
352
+ token = "";
353
+ };
319
354
  for (let i = 0; i < value.length; i++) {
320
355
  const ch = value[i];
321
- if (WHITEPACE_RE.test(ch)) {
322
- if (i > lastPos)
323
- result.push(value.slice(lastPos, i));
324
- lastPos = i + 1;
356
+ if (ch === "\\" && i + 1 < value.length && /[\\{}@-]/.test(value[i + 1])) {
357
+ token += value[++i];
325
358
  }
326
- else if (ch === "-") {
327
- // 如果前面有内容 则把-放到前一个词里
328
- if (i > lastPos) {
329
- result.push(value.slice(lastPos, i + 1));
330
- lastPos = i + 1;
359
+ else if (ch === "{") {
360
+ let close = i + 1;
361
+ let grouped = "";
362
+ for (; close < value.length && value[close] !== "}"; close++) {
363
+ if (value[close] === "\\" && close + 1 < value.length && /[\\{}@-]/.test(value[close + 1])) {
364
+ grouped += value[++close];
365
+ }
366
+ else
367
+ grouped += value[close];
368
+ }
369
+ if (close < value.length) {
370
+ pushToken();
371
+ pushSlot(grouped);
372
+ i = close;
331
373
  }
332
374
  else
333
- lastPos = i; // 把-放到下一个词里
375
+ token += ch;
376
+ }
377
+ else if (WHITEPACE_RE.test(ch)) {
378
+ pushToken();
379
+ }
380
+ else if (ch === "-") {
381
+ // 如果前面有内容 则把-放到前一个词里
382
+ token += ch;
383
+ if (token.length > 1)
384
+ pushToken();
334
385
  }
335
386
  else if (ch === "@") {
336
- if (i > lastPos)
337
- result.push(value.slice(lastPos, i + 1));
387
+ if (token) {
388
+ token += ch;
389
+ pushToken();
390
+ }
338
391
  result.push('');
339
- lastPos = i + 1;
392
+ }
393
+ else if (LYRIC_OPENING_PUNCTUATION.has(ch)) {
394
+ pushToken();
395
+ prefix += ch;
396
+ }
397
+ else if (LYRIC_SILENT_PUNCTUATION.has(ch)) {
398
+ if (token)
399
+ token += ch;
400
+ else if (prefix || !result.at(-1))
401
+ prefix += ch;
402
+ else
403
+ result[result.length - 1] += ch;
340
404
  }
341
405
  else if (ch.charCodeAt(0) > 0x7F) {
342
406
  // 遇到中文等非ASCII字符 直接切分成单个字符
343
- if (i > lastPos)
344
- result.push(value.slice(lastPos, i));
345
- result.push(ch);
346
- lastPos = i + 1;
407
+ pushToken();
408
+ pushSlot(ch);
347
409
  }
410
+ else
411
+ token += ch;
412
+ }
413
+ pushToken();
414
+ if (prefix) {
415
+ if (result.at(-1))
416
+ result[result.length - 1] += prefix;
417
+ else
418
+ result.push(prefix);
348
419
  }
349
- if (lastPos < value.length)
350
- result.push(value.slice(lastPos));
351
420
  return result;
352
421
  }
353
422
  toString(source) {
354
- const notes = this.content.toString(source);
355
- const lyricStrs = this.lyrics.map(lyric => {
356
- let lyricstr = lyric.tokens.map(token => token.length === 0 ? "@" : token).join(" ");
357
- if (lyricstr.includes(",") || lyricstr.includes("\n"))
358
- lyricstr = `"${lyricstr.replace(/"/g, '\\"')}"`;
359
- return `${lyric.name ? `${lyric.name}=${lyricstr}` : lyricstr}`;
360
- });
361
- return `@voice(\n\t${notes},${this.name},\n\t${lyricStrs.join(",\n\t")}\n)`;
423
+ const parameters = [`${this.content.toString(source)},${quote(this.name)}`];
424
+ for (const lyric of this.lyrics) {
425
+ const text = quote(lyric.tokens.map(token => token.length === 0
426
+ ? "@" : `{${token.replace(/[\\{}@-]/g, "\\$&")}}`).join(" "));
427
+ parameters.push(lyric.name ? `${lyric.name}=${text}` : text);
428
+ }
429
+ return `@voice(\n\t${parameters.join(",\n\t")}\n)`;
362
430
  }
363
431
  }
364
432
  class VoicesFunction extends ASTFunctionNode {
@@ -418,9 +486,9 @@ L: la la la
418
486
  constructor(span, args, ctx, parent = null) {
419
487
  super(span, parent);
420
488
  this.voices = [];
421
- this.size = ctx.fontSize;
422
- this.braceSpace = ctx.fontSize;
423
- this.measure = makeVoicesMeasure(ctx.fontSize);
489
+ this.size = ctx.variables.fontsize;
490
+ this.braceSpace = ctx.variables.fontsize;
491
+ this.measure = makeVoicesMeasure(ctx.variables.fontsize);
424
492
  for (const [, value] of args) {
425
493
  if (value instanceof ASTNodeBase) {
426
494
  if (value instanceof VoiceFunction)
@@ -451,7 +519,7 @@ L: la la la
451
519
  toString(source) {
452
520
  const voicelines = Array(this.voices.length);
453
521
  for (let i = 0; i < this.voices.length; i++) {
454
- const part = this.voices[i].toString(source).replace(/^/gm, "\t");
522
+ const part = `\t${this.voices[i].toString(source)}`;
455
523
  voicelines[i] = part;
456
524
  }
457
525
  return `@voices(\n${voicelines.join(",\n")}\n)`;
@@ -464,8 +532,9 @@ const LYRIC_SIZE_RATIO = 0.82;
464
532
  /** 无大括号时标签右侧的空隙,相对声部字号 */
465
533
  const NAME_GAP_RATIO = 0.6;
466
534
  /** 歌词行名称的宽度决定标签列宽度,因此声部名事件和歌词附件必须用同一个样式测量 */
467
- function lyricNameStyle(size) {
535
+ function lyricNameStyle(size, fontFamily) {
468
536
  return {
537
+ fontFamily,
469
538
  fontSize: size * LYRIC_SIZE_RATIO,
470
539
  fill: "#000",
471
540
  fontWeight: 600,
@@ -494,7 +563,7 @@ class VoiceNameTemporal extends TemporalNodeBase {
494
563
  for (const lyric of this.ast.lyrics) {
495
564
  if (!lyric.name)
496
565
  continue;
497
- const lyricMetrics = context.textMeasurer.measureText(lyric.name, lyricNameStyle(this.ast.size));
566
+ const lyricMetrics = context.textMeasurer.measureText(lyric.name, lyricNameStyle(this.ast.size, this.ast.font));
498
567
  labelWidth = Math.max(labelWidth, lyricMetrics.w);
499
568
  }
500
569
  // 没有大括号时也要在标签右侧留出与内容分离的空隙
@@ -513,6 +582,7 @@ class VoiceNameTemporal extends TemporalNodeBase {
513
582
  get style() {
514
583
  return {
515
584
  fontSize: this.ast.size * 0.85,
585
+ fontFamily: this.ast.font,
516
586
  fill: "#000",
517
587
  fontWeight: 600,
518
588
  textAlign: "right",
@@ -628,14 +698,17 @@ class VoiceLyricsAttachment {
628
698
  const { lyrics, size } = this.nameHost.ast;
629
699
  if (targets.length === 0 || lyrics.length === 0)
630
700
  return;
631
- const style = { fontSize: size * LYRIC_SIZE_RATIO, fill: "#000" };
701
+ const style = { fontSize: size * LYRIC_SIZE_RATIO, fontFamily: this.nameHost.ast.font, fill: "#000" };
632
702
  for (let i = 0; i < targets.length; i++) {
633
703
  const target = targets[i];
634
704
  let halfWidth = 0;
635
705
  for (const lyric of lyrics) {
636
706
  const text = lyric.tokens[i];
637
- if (text)
638
- halfWidth = Math.max(halfWidth, context.textMeasurer.measureText(text, style).w / 2);
707
+ if (text) {
708
+ const { body } = splitLyricText(text);
709
+ if (body)
710
+ halfWidth = Math.max(halfWidth, context.textMeasurer.measureText(body, style).w / 2);
711
+ }
639
712
  }
640
713
  if (halfWidth === 0)
641
714
  continue;
@@ -683,8 +756,8 @@ class VoiceLyricsAttachment {
683
756
  const fontSize = size * LYRIC_SIZE_RATIO;
684
757
  const rowGap = size * 0.24;
685
758
  const firstRowGap = size * 0.32;
686
- const lyricStyle = { fontSize, fill: "#000" };
687
- const nameStyle = lyricNameStyle(size);
759
+ const lyricStyle = { fontSize, fontFamily: this.nameHost.ast.font, fill: "#000" };
760
+ const nameStyle = lyricNameStyle(size, this.nameHost.ast.font);
688
761
  const baselineOffset = context.textMeasurer.measureText("M", lyricStyle).baseline + firstRowGap;
689
762
  const baselineOf = (bottom, row) => bottom + baselineOffset + row * (fontSize + rowGap);
690
763
  // 歌词行名称与声部名共用左侧那一列,因此只出现在声部名所在的那一行
@@ -699,11 +772,14 @@ class VoiceLyricsAttachment {
699
772
  if (!text || bottom === undefined)
700
773
  continue;
701
774
  const metrics = context.textMeasurer.measureText(text, lyricStyle);
775
+ const { prefix, body } = splitLyricText(text);
776
+ const bodyWidth = body ? context.textMeasurer.measureText(body, lyricStyle).w : 0;
777
+ const prefixWidth = prefix ? context.textMeasurer.measureText(prefix, lyricStyle).w : 0;
702
778
  preparedText.push({
703
779
  text,
704
780
  style: lyricStyle,
705
781
  textBaselineY: metrics.baseline,
706
- x: target.box.x + target.ports["lyric"].x - metrics.w / 2,
782
+ x: target.box.x + target.ports["lyric"].x - bodyWidth / 2 - prefixWidth,
707
783
  y: baselineOf(bottom, row) - metrics.baseline,
708
784
  w: metrics.w,
709
785
  h: metrics.h,