jpfun 0.2.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 (112) hide show
  1. package/README.md +69 -11
  2. package/dist/diagnostic.js +5 -2
  3. package/dist/fraction.d.ts +24 -0
  4. package/dist/fraction.js +132 -0
  5. package/dist/functions/ASTtypes.d.ts +24 -7
  6. package/dist/functions/ASTtypes.js +35 -16
  7. package/dist/functions/adjust/index.d.ts +2 -0
  8. package/dist/functions/adjust/index.js +193 -0
  9. package/dist/functions/bar/index.d.ts +8 -0
  10. package/dist/functions/bar/index.js +39 -10
  11. package/dist/functions/beam/auto.js +32 -15
  12. package/dist/functions/beam/index.js +10 -6
  13. package/dist/functions/beam/layout.d.ts +3 -2
  14. package/dist/functions/beam/layout.js +42 -64
  15. package/dist/functions/box/index.js +35 -34
  16. package/dist/functions/br/index.js +9 -7
  17. package/dist/functions/dash/index.js +33 -1
  18. package/dist/functions/default.js +14 -7
  19. package/dist/functions/div/index.d.ts +16 -0
  20. package/dist/functions/div/index.js +45 -17
  21. package/dist/functions/dot/index.js +11 -3
  22. package/dist/functions/grace/index.d.ts +8 -11
  23. package/dist/functions/grace/index.js +82 -76
  24. package/dist/functions/head/index.d.ts +2 -0
  25. package/dist/functions/head/index.js +492 -0
  26. package/dist/functions/key/index.js +97 -3
  27. package/dist/functions/meter/index.d.ts +2 -0
  28. package/dist/functions/meter/index.js +154 -0
  29. package/dist/functions/note/accidentals.d.ts +24 -3
  30. package/dist/functions/note/accidentals.js +31 -1
  31. package/dist/functions/note/index.js +45 -65
  32. package/dist/functions/page/index.d.ts +9 -2
  33. package/dist/functions/page/index.js +50 -4
  34. package/dist/functions/set/index.js +37 -29
  35. package/dist/functions/stack/index.js +26 -22
  36. package/dist/functions/symbol/index.d.ts +21 -0
  37. package/dist/functions/symbol/index.js +94 -0
  38. package/dist/functions/symbol/ornament.d.ts +15 -0
  39. package/dist/functions/symbol/ornament.js +73 -0
  40. package/dist/functions/symbol/shape.d.ts +22 -0
  41. package/dist/functions/symbol/shape.js +48 -0
  42. package/dist/functions/symbol/symbols/accent.d.ts +2 -0
  43. package/dist/functions/symbol/symbols/accent.js +24 -0
  44. package/dist/functions/symbol/symbols/f.d.ts +2 -0
  45. package/dist/functions/symbol/symbols/f.js +55 -0
  46. package/dist/functions/symbol/symbols/fermata.d.ts +2 -0
  47. package/dist/functions/symbol/symbols/fermata.js +24 -0
  48. package/dist/functions/symbol/symbols/mordent.d.ts +2 -0
  49. package/dist/functions/symbol/symbols/mordent.js +43 -0
  50. package/dist/functions/symbol/symbols/p.d.ts +2 -0
  51. package/dist/functions/symbol/symbols/p.js +61 -0
  52. package/dist/functions/symbol/symbols/tr.d.ts +2 -0
  53. package/dist/functions/symbol/symbols/tr.js +75 -0
  54. package/dist/functions/tempo/glyph.d.ts +12 -0
  55. package/dist/functions/tempo/glyph.js +30 -0
  56. package/dist/functions/tempo/index.js +53 -2
  57. package/dist/functions/text/index.js +76 -24
  58. package/dist/functions/tie/index.js +102 -127
  59. package/dist/functions/tuplet/index.d.ts +2 -0
  60. package/dist/functions/tuplet/index.js +211 -0
  61. package/dist/functions/up/index.d.ts +1 -0
  62. package/dist/functions/up/index.js +245 -171
  63. package/dist/functions/voice/index.js +86 -68
  64. package/dist/functions/volta/index.d.ts +2 -0
  65. package/dist/functions/volta/index.js +227 -0
  66. package/dist/index.d.ts +4 -0
  67. package/dist/index.js +4 -0
  68. package/dist/jpfun.min.js +143 -0
  69. package/dist/layout/engine.d.ts +4 -11
  70. package/dist/layout/engine.js +65 -59
  71. package/dist/layout/model.d.ts +8 -1
  72. package/dist/layout/model.js +16 -6
  73. package/dist/layout/path.d.ts +19 -0
  74. package/dist/layout/path.js +101 -0
  75. package/dist/layout/types.d.ts +51 -18
  76. package/dist/layout/types.js +3 -1
  77. package/dist/lowering/loweringContext.d.ts +18 -20
  78. package/dist/lowering/loweringContext.js +132 -94
  79. package/dist/lowering/track.d.ts +1 -1
  80. package/dist/lowering/track.js +1 -1
  81. package/dist/lowering/types.d.ts +49 -12
  82. package/dist/lowering/types.js +9 -3
  83. package/dist/parser/parse-utils/call-utils.d.ts +0 -2
  84. package/dist/parser/parse-utils/call-utils.js +0 -6
  85. package/dist/parser/parse-utils/note-utils.d.ts +8 -0
  86. package/dist/parser/parse-utils/note-utils.js +35 -13
  87. package/dist/parser/parse-utils/string-utils.d.ts +8 -0
  88. package/dist/parser/parse-utils/string-utils.js +20 -0
  89. package/dist/parser/parserContext.d.ts +8 -5
  90. package/dist/parser/parserContext.js +38 -33
  91. package/dist/parser/preprocess.js +17 -11
  92. package/dist/playback/compile.d.ts +18 -0
  93. package/dist/playback/compile.js +401 -0
  94. package/dist/playback/event.d.ts +91 -0
  95. package/dist/playback/event.js +87 -0
  96. package/dist/playback/time.d.ts +14 -0
  97. package/dist/playback/time.js +81 -0
  98. package/dist/playback/types.d.ts +128 -0
  99. package/dist/playback/types.js +3 -0
  100. package/dist/render/canvas.d.ts +4 -4
  101. package/dist/render/canvas.js +20 -5
  102. package/dist/render/index.d.ts +1 -0
  103. package/dist/render/index.js +1 -0
  104. package/dist/render/paint.d.ts +8 -0
  105. package/dist/render/paint.js +101 -0
  106. package/dist/render/svg.d.ts +3 -3
  107. package/dist/render/svg.js +10 -8
  108. package/dist/render/text.d.ts +17 -0
  109. package/dist/render/text.js +35 -0
  110. package/dist/render/types.d.ts +1 -1
  111. package/grammar.md +93 -10
  112. package/package.json +10 -6
@@ -1,6 +1,7 @@
1
1
  import { ASTFunctionNode } from "../ASTtypes.js";
2
- import { ErrorDiagnostic } from "../../diagnostic.js";
2
+ import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
3
3
  import { isVisualTemporalNode, } from "../../lowering/types.js";
4
+ import { pathBounds } from "../../layout/path.js";
4
5
  /** 三次贝塞尔控制点的抬高系数:两个控制点同高时,实际弧高恰好是抬高的 3/4 */
5
6
  const CUBIC_LIFT = 4 / 3;
6
7
  /** 弧带中部最大厚度与字号之比 */
@@ -22,25 +23,24 @@ class TieFunction extends ASTFunctionNode {
22
23
  let height = ctx.fontSize * 0.5;
23
24
  for (const [key, value] of args) {
24
25
  if (key === "height") {
25
- const length = ctx.parseArgWithType(value.start, value.end, "length", sourceSpan.start);
26
+ const length = ctx.parseArgWithType(value.valueSpan, "length", sourceSpan.start);
26
27
  if (length)
27
28
  height = Math.max(0, ctx.length2px(length));
28
29
  continue;
29
30
  }
30
31
  const v = value instanceof ASTFunctionNode
31
32
  ? value
32
- : ctx.parseArgWithType(value.start, value.end, "label", sourceSpan.start);
33
+ : ctx.parseArgWithType(value.valueSpan, "label", sourceSpan.start);
33
34
  if (v !== null)
34
35
  this.endPoints.push(v);
35
36
  }
36
- // 数目不足,则找最近的
37
+ // 数目不足,则找最近的;用 unshift 而不是按下标赋值,否则空洞会让 length 虚高、骗过下面的校验
37
38
  let k = ctx.labelableNodes.length - 1;
38
- for (let i = this.endPoints.length; i < 2; i++) {
39
- while (k >= 0 && this.endPoints.includes(ctx.labelableNodes[k]))
40
- k--;
41
- if (k < 0)
42
- break;
43
- this.endPoints[1 - i] = ctx.labelableNodes[k--]; // 保持顺序
39
+ while (this.endPoints.length < 2 && k >= 0) {
40
+ const candidate = ctx.labelableNodes[k--];
41
+ if (!candidate || this.endPoints.includes(candidate))
42
+ continue;
43
+ this.endPoints.unshift(candidate);
44
44
  }
45
45
  if (this.endPoints.length < 2)
46
46
  throw new ErrorDiagnostic("E_NOT_ENOUGH_ARGS", "@tie 连音线需要至少两个端点", sourceSpan);
@@ -58,9 +58,11 @@ class TieFunction extends ASTFunctionNode {
58
58
  continue;
59
59
  endPoints.push(temporal);
60
60
  }
61
- if (endPoints.length < 2)
61
+ if (endPoints.length < 2) {
62
+ ctx.diagnostics.push(Diagnostic.warning.UnresolvedEndpoint("tie", this.sourceSpan));
62
63
  return [];
63
- ctx.addLayoutAttachment(new TieLayoutAttachment(endPoints, this.height));
64
+ }
65
+ ctx.addAttachment(new TieLayoutAttachment(endPoints, this.height, this.sourceSpan));
64
66
  return [];
65
67
  }
66
68
  toString(source) {
@@ -79,110 +81,85 @@ function quadExtremum(p0, p1, p2) {
79
81
  const u = 1 - t;
80
82
  return u * u * p0 + 2 * u * t * p1 + t * t * p2;
81
83
  }
82
- /** 三次贝塞尔在某一维上的内部极值,最多两个 */
83
- function cubicExtrema(p0, p1, p2, p3, out) {
84
- // 导数为 3(qa*t^2 + qb*t + a),下面的 a 就是常数项
85
- const a = p1 - p0;
86
- const b = p2 - p1;
87
- const c = p3 - p2;
88
- const qa = a - 2 * b + c;
89
- const qb = 2 * (b - a);
90
- const push = (t) => {
91
- if (t <= 0 || t >= 1)
92
- return;
93
- const u = 1 - t;
94
- out.push(u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3);
95
- };
96
- if (Math.abs(qa) < 1e-9) {
97
- if (Math.abs(qb) > 1e-9)
98
- push(-a / qb);
99
- return;
100
- }
101
- const disc = qb * qb - 4 * qa * a;
102
- if (disc < 0)
103
- return;
104
- const root = Math.sqrt(disc);
105
- push((-qb + root) / (2 * qa));
106
- push((-qb - root) / (2 * qa));
107
- }
108
- /**
109
- * 精确求出路径的外接矩形
110
- *
111
- * 控制点不直接计入:贝塞尔曲线并不会到达控制点,
112
- * 直接用它会把弧顶高估约三分之一,从而让上方的轨道被无谓推开
113
- */
114
- function pathBounds(commands) {
115
- let left = Infinity;
116
- let top = Infinity;
117
- let right = -Infinity;
118
- let bottom = -Infinity;
119
- const includeX = (x) => { left = Math.min(left, x); right = Math.max(right, x); };
120
- const includeY = (y) => { top = Math.min(top, y); bottom = Math.max(bottom, y); };
121
- let cx = 0;
122
- let cy = 0;
123
- const extrema = [];
124
- for (const command of commands) {
125
- if (command.op === "Z")
126
- continue;
127
- if (command.op === "Q") {
128
- const ex = quadExtremum(cx, command.cx, command.x);
129
- if (ex !== null)
130
- includeX(ex);
131
- const ey = quadExtremum(cy, command.cy, command.y);
132
- if (ey !== null)
133
- includeY(ey);
134
- }
135
- else if (command.op === "C") {
136
- extrema.length = 0;
137
- cubicExtrema(cx, command.cx1, command.cx2, command.x, extrema);
138
- for (const value of extrema)
139
- includeX(value);
140
- extrema.length = 0;
141
- cubicExtrema(cy, command.cy1, command.cy2, command.y, extrema);
142
- for (const value of extrema)
143
- includeY(value);
144
- }
145
- includeX(cx = command.x);
146
- includeY(cy = command.y);
147
- }
148
- if (!Number.isFinite(left))
149
- return { left: 0, top: 0, right: 0, bottom: 0 };
150
- return { left, top, right, bottom };
151
- }
152
84
  class TieLayoutAttachment {
153
- box = {
154
- x: 0,
155
- y: 0,
156
- w: 0,
157
- h: 0,
158
- };
159
85
  layer = "foreground";
86
+ sourceSpan;
160
87
  endPoints;
161
88
  height;
162
- segments = [];
163
- /** 弧带中部厚度;两端收尖到 0 */
164
- thickness = 1;
165
- constructor(endPoints, height) {
89
+ /** 弧带中部厚度;两端收尖到 0。端点字号不随布局变化,可以一次算定 */
90
+ thickness;
91
+ constructor(endPoints, height, sourceSpan) {
166
92
  this.endPoints = endPoints;
167
93
  this.height = height;
94
+ this.sourceSpan = sourceSpan;
95
+ const size = endPoints.reduce((current, endpoint) => Math.max(current, endpoint.ast.size), 0);
96
+ this.thickness = Math.max(1.2, size * THICKNESS_RATIO);
168
97
  }
169
- layout(context) {
170
- this.updateGeometry(context);
171
- return this.segments.map(segment => ({
172
- x: segment.left,
173
- y: segment.top,
174
- w: segment.right - segment.left,
175
- h: segment.bottom - segment.top,
176
- line: segment.line,
177
- track: segment.track,
178
- }));
179
- }
180
- paint(painter) {
181
- for (const segment of this.segments) {
182
- // 弧带本身就是闭合轮廓,直接填充就能得到两端收尖、中部较粗的乐谱弧线
183
- painter.drawPath(segment.commands, { fill: "#000" });
98
+ /**
99
+ * 只有同轨、同音、演奏时间连续的事件对才合并,其余 tie 纯视觉
100
+ *
101
+ * 反复会让同一个端点产生多个事件对,所以按首端点的每一个 NoteOn 各串一条链。
102
+ */
103
+ applyPlayback(context) {
104
+ const noteOns = () => context.events
105
+ .filter((event) => event.kind === "note-on");
106
+ const noteOff = (noteId) => context.events
107
+ .find((event) => event.kind === "note-off" && event.noteId === noteId);
108
+ for (const head of noteOns().filter(note => note.origins.some(origin => origin.node === this.endPoints[0]))) {
109
+ for (let i = 1; i < this.endPoints.length; i++) {
110
+ const end = noteOff(head.noteId);
111
+ if (!end)
112
+ break;
113
+ const next = noteOns().find(note => note.noteId !== head.noteId
114
+ && note.origins.some(origin => origin.node === this.endPoints[i])
115
+ && note.track === head.track
116
+ && note.midi === head.midi
117
+ && end.at.equals(note.at));
118
+ if (!next)
119
+ break;
120
+ const nextOff = noteOff(next.noteId);
121
+ if (!nextOff)
122
+ break;
123
+ head.sourceSpans.push(...next.sourceSpans);
124
+ for (const origin of next.origins) {
125
+ if (!head.origins.includes(origin))
126
+ head.origins.push(origin);
127
+ }
128
+ nextOff.noteId = head.noteId;
129
+ nextOff.origins = [...head.origins];
130
+ context.events.splice(0, context.events.length, ...context.events.filter(event => event !== end && event !== next));
131
+ }
184
132
  }
185
133
  }
134
+ createGeometry(context) {
135
+ const segments = this.createSegments(context);
136
+ const regions = segments.map(({ commands, ...region }) => region);
137
+ const occupancy = segments.map(segment => {
138
+ // 只申报主体上方那一段,下半截由主体自己占;本行没有主体时就只有弧带本身
139
+ const hostExtent = context.getHostExtent(segment.line, segment.track);
140
+ const bottom = hostExtent
141
+ ? Math.max(segment.y, context.getVisualAxis(segment.line, segment.track) + hostExtent.top)
142
+ : segment.y + segment.h;
143
+ return {
144
+ x: segment.x,
145
+ y: segment.y,
146
+ w: segment.w,
147
+ h: bottom - segment.y,
148
+ line: segment.line,
149
+ track: segment.track,
150
+ };
151
+ });
152
+ return {
153
+ regions,
154
+ occupancy,
155
+ paint(painter) {
156
+ for (const segment of segments) {
157
+ // 弧带本身就是闭合轮廓,直接填充就能得到两端收尖、中部较粗的乐谱弧线
158
+ painter.drawPath(segment.commands, { fill: "#000" });
159
+ }
160
+ },
161
+ };
162
+ }
186
163
  absolutePort(node, name) {
187
164
  const port = node.ports[name];
188
165
  if (port) {
@@ -197,10 +174,8 @@ class TieLayoutAttachment {
197
174
  };
198
175
  }
199
176
  /** 根据端点固化后的行号选择同行弧线或跨行分段。 */
200
- updateGeometry(context) {
201
- const size = this.endPoints.reduce((current, endpoint) => Math.max(current, endpoint.ast.size), 0);
202
- this.segments.length = 0;
203
- this.thickness = Math.max(1.2, size * THICKNESS_RATIO);
177
+ createSegments(context) {
178
+ const segments = [];
204
179
  for (let i = 1; i < this.endPoints.length; i++) {
205
180
  let startNode = this.endPoints[i - 1];
206
181
  let endNode = this.endPoints[i];
@@ -214,18 +189,19 @@ class TieLayoutAttachment {
214
189
  + (context.getHostExtent(startNode.layoutLine, startNode.track)?.top ?? 0);
215
190
  const endTop = context.getVisualAxis(endNode.layoutLine, endNode.track)
216
191
  + (context.getHostExtent(endNode.layoutLine, endNode.track)?.top ?? 0);
217
- this.addArc(start, end, startNode.layoutLine, startTop <= endTop ? startNode.track : endNode.track);
192
+ segments.push(this.arcSegment(start, end, startNode.layoutLine, startTop <= endTop ? startNode.track : endNode.track));
218
193
  continue;
219
194
  }
220
195
  // 首行先起弧,再沿水平段延伸到当前谱面行最右侧
221
- this.addOpeningSegment(start, context.originX + context.width, this.plateauY(context, startNode.layoutLine, startNode.track, start.y), startNode.layoutLine, startNode.track);
196
+ segments.push(this.openingSegment(start, context.originX + context.width, this.plateauY(context, startNode.layoutLine, startNode.track, start.y), startNode.layoutLine, startNode.track));
222
197
  // 中间行可能没有任何可见对象,仍然需要逐行补一段水平线
223
198
  for (let line = startNode.layoutLine + 1; line < endNode.layoutLine; line++) {
224
- this.addHorizontalSegment(context.originX, context.originX + context.width, this.plateauY(context, line, startNode.track), line, startNode.track);
199
+ segments.push(this.horizontalSegment(context.originX, context.originX + context.width, this.plateauY(context, line, startNode.track), line, startNode.track));
225
200
  }
226
201
  // 末行从最左侧进入,经过水平段后落弧到终点
227
- this.addClosingSegment(context.originX, end, this.plateauY(context, endNode.layoutLine, endNode.track, end.y), endNode.layoutLine, endNode.track);
202
+ segments.push(this.closingSegment(context.originX, end, this.plateauY(context, endNode.layoutLine, endNode.track, end.y), endNode.layoutLine, endNode.track));
228
203
  }
204
+ return segments;
229
205
  }
230
206
  /** 沿用普通端点的抬高量,但基准至少是当前 Track 的最高主体。 */
231
207
  plateauY(context, line, track, endpointY = Infinity) {
@@ -234,7 +210,7 @@ class TieLayoutAttachment {
234
210
  return Math.min(endpointY, axis + hostTop) - this.height;
235
211
  }
236
212
  /** 一条三次贝塞尔的外缘配上反向内缘,得到两端收尖、中部最厚的乐谱弧线 */
237
- addArc(startInput, endInput, line, track) {
213
+ arcSegment(startInput, endInput, line, track) {
238
214
  let start = startInput;
239
215
  let end = endInput;
240
216
  if (start.x > end.x)
@@ -250,16 +226,16 @@ class TieLayoutAttachment {
250
226
  { op: "C", cx1: rightX, cy1: end.y - inner, cx2: leftX, cy2: start.y - inner, x: start.x, y: start.y },
251
227
  { op: "Z" },
252
228
  ];
253
- this.addSegment(commands, line, track);
229
+ return makeSegment(commands, line, track);
254
230
  }
255
231
  /** 跨行首段:从端点起弧,随后水平延伸到右边界 */
256
- addOpeningSegment(start, right, plateauY, line, track) {
232
+ openingSegment(start, right, plateauY, line, track) {
257
233
  const span = Math.max(0, right - start.x);
258
234
  const run = Math.min(this.height * 1.2, span * 0.4);
259
235
  const curveX = start.x + run;
260
236
  const controlX = start.x + run * 0.45;
261
237
  const bottom = plateauY + this.thickness;
262
- this.addSegment([
238
+ return makeSegment([
263
239
  { op: "M", x: start.x, y: start.y },
264
240
  { op: "Q", cx: controlX, cy: plateauY, x: curveX, y: plateauY },
265
241
  { op: "L", x: right, y: plateauY },
@@ -270,13 +246,13 @@ class TieLayoutAttachment {
270
246
  ], line, track);
271
247
  }
272
248
  /** 跨行末段:从左边界水平进入,最后落弧到端点 */
273
- addClosingSegment(left, end, plateauY, line, track) {
249
+ closingSegment(left, end, plateauY, line, track) {
274
250
  const span = Math.max(0, end.x - left);
275
251
  const run = Math.min(this.height * 1.2, span * 0.4);
276
252
  const curveX = end.x - run;
277
253
  const controlX = end.x - run * 0.45;
278
254
  const bottom = plateauY + this.thickness;
279
- this.addSegment([
255
+ return makeSegment([
280
256
  { op: "M", x: left, y: plateauY },
281
257
  { op: "L", x: curveX, y: plateauY },
282
258
  { op: "Q", cx: controlX, cy: plateauY, x: end.x, y: end.y },
@@ -285,8 +261,8 @@ class TieLayoutAttachment {
285
261
  { op: "Z" },
286
262
  ], line, track);
287
263
  }
288
- addHorizontalSegment(left, right, y, line, track) {
289
- this.addSegment([
264
+ horizontalSegment(left, right, y, line, track) {
265
+ return makeSegment([
290
266
  { op: "M", x: left, y },
291
267
  { op: "L", x: right, y },
292
268
  { op: "L", x: right, y: y + this.thickness },
@@ -294,8 +270,7 @@ class TieLayoutAttachment {
294
270
  { op: "Z" },
295
271
  ], line, track);
296
272
  }
297
- addSegment(commands, line, track) {
298
- const bounds = pathBounds(commands);
299
- this.segments.push({ commands, line, track, ...bounds });
300
- }
273
+ }
274
+ function makeSegment(commands, line, track) {
275
+ return { commands, line, track, ...pathBounds(commands) };
301
276
  }
@@ -0,0 +1,2 @@
1
+ import { type ASTFunctionClass } from "../ASTtypes.js";
2
+ export declare const TupletNode: ASTFunctionClass;
@@ -0,0 +1,211 @@
1
+ import { ErrorDiagnostic } from "../../diagnostic.js";
2
+ import { Fraction } from "../../fraction.js";
3
+ import { isVisualTemporalNode, } from "../../lowering/types.js";
4
+ import { ASTFunctionNode, } from "../ASTtypes.js";
5
+ import { JIANPU_NUMBER_FONT } from "../../render/text.js";
6
+ /**
7
+ * 多连音是范围时值变换,不产生自己的 Temporal:
8
+ * actual = 内容原总时值 / 最短正时值
9
+ * 目标总时值 = 最短正时值 * normal
10
+ */
11
+ class TupletFunction extends ASTFunctionNode {
12
+ static def = {
13
+ name: ["tuplet"],
14
+ description: "多连音",
15
+ example: `@tuplet({1/23}, 4): 内容含5个最短时值单位,压缩到4倍最短单位的总时长,所以是八分音符的五连音,总时长为二分音符`,
16
+ allowExtraArgs: false,
17
+ args: [
18
+ {
19
+ type: "content",
20
+ default: null,
21
+ },
22
+ {
23
+ name: "normal",
24
+ type: "number",
25
+ default: null,
26
+ },
27
+ ],
28
+ };
29
+ static loweringFinalize = (result) => {
30
+ for (const attachment of result.attachments) {
31
+ if (attachment instanceof TupletLayoutAttachment)
32
+ attachment.validate();
33
+ }
34
+ };
35
+ content;
36
+ normal;
37
+ get children() { return [this.content]; }
38
+ timeFlowModel() {
39
+ return {
40
+ mode: "sequence",
41
+ children: [this.content],
42
+ };
43
+ }
44
+ loweringEnter(ctx) {
45
+ const events = [];
46
+ const group = {
47
+ events,
48
+ onTemporal(node) {
49
+ // 此时不能改 T:actual 依赖整个作用域的最短值和总和。
50
+ events.push(node);
51
+ },
52
+ };
53
+ ctx.beginLoweringGroup(this, group);
54
+ return [];
55
+ }
56
+ loweringExit(ctx, _track, timeOffset) {
57
+ const group = ctx.endLoweringGroup(this);
58
+ // 零时长控制事件不构成连音单位,但稍后仍要随整组移动其开始位置。
59
+ const positive = group.events.filter(event => event.T.compare(0) > 0);
60
+ if (positive.length === 0) {
61
+ throw new ErrorDiagnostic("E_TUPLET_EMPTY", "@tuplet 的内容必须产生至少一个正时值事件", this.sourceSpan);
62
+ }
63
+ // 一个 tuplet 只拥有一个时间游标和一条括线;并行分支无法用这组语义表达。
64
+ const track = positive[0].track;
65
+ if (positive.some(event => event.track !== track)) {
66
+ throw new ErrorDiagnostic("E_TUPLET_PARALLEL_CONTENT", "@tuplet 的内容不能包含并行音轨", this.sourceSpan);
67
+ }
68
+ // writtenTotal / shortest 必须精确为整数,该整数就是谱面上显示的 actual
69
+ const shortest = positive[0].T.clone();
70
+ const writtenTotal = new Fraction();
71
+ for (const event of positive) {
72
+ if (event.T.compare(shortest) < 0)
73
+ shortest.copyFrom(event.T);
74
+ writtenTotal.add(event.T);
75
+ }
76
+ const units = writtenTotal.clone().div(shortest);
77
+ const actual = units.numerator;
78
+ if (units.denominator !== 1 || actual < 2 || !Number.isSafeInteger(actual)) {
79
+ throw new ErrorDiagnostic("E_TUPLET_NON_INTEGRAL_UNITS", "@tuplet 的总时值必须是最短正时值的整数倍,且至少包含2个单位", this.sourceSpan);
80
+ }
81
+ if (this.normal === actual) {
82
+ throw new ErrorDiagnostic("E_TUPLET_INVALID_RATIO", `@tuplet 的 normal 不能等于推导出的 actual (${actual})`, this.sourceSpan);
83
+ }
84
+ // 以作用域最早时间为仿射缩放原点,不能直接缩放绝对 t,否则嵌套位置会漂移。
85
+ let start = group.events[0].t;
86
+ for (let i = 1; i < group.events.length; i++) {
87
+ if (group.events[i].t.compare(start) < 0)
88
+ start = group.events[i].t;
89
+ }
90
+ start = start.clone();
91
+ // t、T 与 lowering 游标必须一起修改;后继节点才会从缩放后的组尾继续。
92
+ const offset = new Fraction();
93
+ for (const event of group.events) {
94
+ offset.copyFrom(event.t).sub(start).mul(this.normal, actual);
95
+ event.t.copyFrom(start).add(offset);
96
+ event.T.mul(this.normal, actual);
97
+ }
98
+ timeOffset.copyFrom(start).add(shortest.mul(this.normal));
99
+ // 括线只依附可见主体;时值缩放本身仍覆盖所有收集到的事件。
100
+ const visible = positive.filter(isVisualTemporalNode);
101
+ if (visible.length >= 2) {
102
+ ctx.addAttachment(new TupletLayoutAttachment(visible, actual, this.sourceSpan));
103
+ }
104
+ return [];
105
+ }
106
+ constructor(span, args, ctx, parent = null) {
107
+ super(span, parent);
108
+ const [content, normal] = this.getArgValue(args, ctx);
109
+ // normal 是目标包含的“最短时值单位数”,不是 QN 数,也不是显示的 actual。
110
+ if (!Number.isSafeInteger(normal) || normal <= 0) {
111
+ throw new ErrorDiagnostic("E_TUPLET_INVALID_NORMAL", "@tuplet 的 normal 必须是正的安全整数", span);
112
+ }
113
+ this.content = content;
114
+ this.normal = normal;
115
+ content.parent = this;
116
+ }
117
+ toString(source) {
118
+ return `@tuplet(${this.content.toString(source)}, ${this.normal})`;
119
+ }
120
+ }
121
+ export const TupletNode = TupletFunction;
122
+ /**
123
+ * 多连音括线是跨多个宿主的前景 attachment。lowering 冻结端点与 actual,
124
+ * layout 根据最终宿主坐标测量数字和括线,paint 只回放已冻结的绝对几何。
125
+ */
126
+ class TupletLayoutAttachment {
127
+ layer = "foreground";
128
+ /** lowering 固化的连音语义;重复 layout 时保持不变 */
129
+ endPoints;
130
+ actual;
131
+ sourceSpan;
132
+ /** 由端点最大字号冻结的绘制规格 */
133
+ style;
134
+ size;
135
+ constructor(endPoints, actual, sourceSpan) {
136
+ this.endPoints = endPoints;
137
+ this.actual = actual;
138
+ this.sourceSpan = sourceSpan;
139
+ this.size = endPoints.reduce((size, endpoint) => Math.max(size, endpoint.ast.size), 0);
140
+ this.style = {
141
+ fontSize: this.size * 0.72,
142
+ fontFamily: JIANPU_NUMBER_FONT,
143
+ textAlign: "center",
144
+ fill: "#000",
145
+ };
146
+ }
147
+ validate() {
148
+ const first = this.endPoints[0];
149
+ // 当前实现只有单段括线,没有跨谱面行的首段/末段几何。
150
+ if (this.endPoints.some(endpoint => endpoint.layoutLine !== first.layoutLine)) {
151
+ throw new ErrorDiagnostic("E_TUPLET_CROSS_LINE", "@tuplet 的内容不能跨越谱面行", this.sourceSpan);
152
+ }
153
+ }
154
+ createGeometry(context) {
155
+ const first = this.endPoints[0];
156
+ const last = this.endPoints[this.endPoints.length - 1];
157
+ // 括线覆盖首末主体的核心范围;没有 body 端口时回退到完整盒边界。
158
+ const firstLeft = first.ports["body.left"]?.x ?? 0;
159
+ const lastRight = last.ports["body.right"]?.x ?? last.box.w;
160
+ let left = first.box.x + firstLeft;
161
+ let right = last.box.x + lastRight;
162
+ if (left > right)
163
+ [left, right] = [right, left];
164
+ // 数字位于跨度中心,水平线在数字两侧断开,并预留一个字号相关的空隙。
165
+ const metrics = context.textMeasurer.measureText(String(this.actual), this.style);
166
+ const center = (left + right) / 2;
167
+ const textGap = this.size * 0.12;
168
+ const hookHeight = this.size * 0.18;
169
+ const hostGap = this.size * 0.14;
170
+ // hostExtent 是相对轨道视觉轴的主体占用;转为绝对坐标后再向上放置括线。
171
+ const axis = context.getVisualAxis(first.layoutLine, first.track);
172
+ const hostTop = axis + (context.getHostExtent(first.layoutLine, first.track)?.top ?? 0);
173
+ const strokeWidth = Math.max(1, this.size * 0.055);
174
+ const lineY = hostTop - hostGap - Math.max(hookHeight, metrics.h / 2);
175
+ const hookBottom = lineY + hookHeight;
176
+ const textBaseline = lineY - metrics.h / 2 + metrics.baseline;
177
+ const textLeft = center - metrics.w / 2 - textGap;
178
+ const textRight = center + metrics.w / 2 + textGap;
179
+ // 先记录左右横线,再记录两端向下的短钩;短跨度允许省略横线但保留端钩
180
+ const lines = [];
181
+ if (textLeft > left)
182
+ lines.push([left, lineY, textLeft, lineY]);
183
+ if (textRight < right)
184
+ lines.push([textRight, lineY, right, lineY]);
185
+ lines.push([left, lineY, left, hookBottom], [right, lineY, right, hookBottom]);
186
+ // region 同时包含文字与描边,并声明 line/track 让纵向求解为括线腾出空间
187
+ const halfStroke = strokeWidth / 2;
188
+ const top = Math.min(lineY - metrics.h / 2, lineY - halfStroke);
189
+ const bottom = Math.max(lineY + metrics.h / 2, hookBottom + halfStroke);
190
+ const regions = [{
191
+ x: left - halfStroke,
192
+ y: top,
193
+ w: right - left + strokeWidth,
194
+ h: bottom - top,
195
+ line: first.layoutLine,
196
+ track: first.track,
197
+ }];
198
+ const text = String(this.actual);
199
+ const style = this.style;
200
+ return {
201
+ regions,
202
+ paint(painter) {
203
+ const lineStyle = { stroke: "#000", strokeWidth };
204
+ for (const [x1, y1, x2, y2] of lines) {
205
+ painter.drawLine(x1, y1, x2, y2, lineStyle);
206
+ }
207
+ painter.drawText(text, center, textBaseline, style);
208
+ },
209
+ };
210
+ }
211
+ }
@@ -1,2 +1,3 @@
1
1
  import { ASTFunctionClass } from "../ASTtypes.js";
2
2
  export declare const UpNode: ASTFunctionClass;
3
+ export declare const DownNode: ASTFunctionClass;