jpfun 0.8.0 → 1.0.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 (140) hide show
  1. package/README.md +10 -15
  2. package/dist/diagnostic.d.ts +29 -2
  3. package/dist/diagnostic.js +5 -4
  4. package/dist/functions/ASTtypes.d.ts +1 -14
  5. package/dist/functions/ASTtypes.js +5 -36
  6. package/dist/functions/adjust/index.js +45 -33
  7. package/dist/functions/arpeggio/index.js +44 -48
  8. package/dist/functions/arpeggio/shape.d.ts +2 -3
  9. package/dist/functions/arpeggio/shape.js +20 -50
  10. package/dist/functions/bar/index.d.ts +3 -0
  11. package/dist/functions/bar/index.js +21 -11
  12. package/dist/functions/beam/auto.js +54 -123
  13. package/dist/functions/beam/index.js +4 -9
  14. package/dist/functions/beam/layout.js +3 -2
  15. package/dist/functions/box/index.js +1 -6
  16. package/dist/functions/dash/index.js +6 -4
  17. package/dist/functions/div/index.d.ts +3 -5
  18. package/dist/functions/div/index.js +14 -12
  19. package/dist/functions/dot/index.js +3 -9
  20. package/dist/functions/dyn/index.js +7 -26
  21. package/dist/functions/gliss/index.js +99 -91
  22. package/dist/functions/grace/index.d.ts +2 -5
  23. package/dist/functions/grace/index.js +47 -94
  24. package/dist/functions/head/index.js +32 -36
  25. package/dist/functions/key/index.js +9 -12
  26. package/dist/functions/meter/index.d.ts +1 -0
  27. package/dist/functions/meter/index.js +6 -3
  28. package/dist/functions/meter/shape.d.ts +1 -1
  29. package/dist/functions/note/accidentals.d.ts +3 -3
  30. package/dist/functions/note/accidentals.js +29 -16
  31. package/dist/functions/note/index.js +12 -14
  32. package/dist/functions/note/source-transform.d.ts +15 -0
  33. package/dist/functions/note/source-transform.js +75 -71
  34. package/dist/functions/ottava/index.js +12 -32
  35. package/dist/functions/page/index.js +15 -17
  36. package/dist/functions/rest/index.js +10 -10
  37. package/dist/functions/slide/index.js +1 -1
  38. package/dist/functions/stack/index.js +8 -57
  39. package/dist/functions/temporal.d.ts +11 -5
  40. package/dist/functions/temporal.js +22 -2
  41. package/dist/functions/text/index.js +24 -30
  42. package/dist/functions/tie/index.js +42 -41
  43. package/dist/functions/tremolo/index.js +1 -1
  44. package/dist/functions/tuplet/index.js +1 -6
  45. package/dist/functions/up/index.js +82 -88
  46. package/dist/functions/voice/connections.d.ts +3 -2
  47. package/dist/functions/voice/connections.js +48 -10
  48. package/dist/functions/voice/index.d.ts +2 -3
  49. package/dist/functions/voice/index.js +2 -970
  50. package/dist/functions/voice/lyrics.d.ts +34 -0
  51. package/dist/functions/voice/lyrics.js +393 -0
  52. package/dist/functions/voice/voice.d.ts +67 -0
  53. package/dist/functions/voice/voice.js +405 -0
  54. package/dist/functions/voice/voices.d.ts +106 -0
  55. package/dist/functions/voice/voices.js +424 -0
  56. package/dist/functions/volta/index.js +6 -23
  57. package/dist/index.d.ts +97 -3
  58. package/dist/index.js +97 -3
  59. package/dist/jpfun.min.js +63 -67
  60. package/dist/layout/engine.d.ts +4 -3
  61. package/dist/layout/engine.js +190 -24
  62. package/dist/layout/model.d.ts +12 -4
  63. package/dist/layout/model.js +16 -11
  64. package/dist/layout/page.d.ts +2 -1
  65. package/dist/layout/page.js +15 -15
  66. package/dist/layout/path.js +1 -1
  67. package/dist/layout/range.d.ts +7 -6
  68. package/dist/layout/range.js +23 -14
  69. package/dist/layout/types.d.ts +19 -30
  70. package/dist/lowering/loweringContext.d.ts +8 -11
  71. package/dist/lowering/loweringContext.js +7 -13
  72. package/dist/lowering/track.d.ts +8 -1
  73. package/dist/lowering/types.d.ts +12 -8
  74. package/dist/parser/grammarType.d.ts +3 -3
  75. package/dist/parser/parse-utils/brace-utils.js +7 -17
  76. package/dist/parser/parse-utils/call-utils.d.ts +4 -3
  77. package/dist/parser/parse-utils/call-utils.js +23 -66
  78. package/dist/parser/parse-utils/note-utils.d.ts +7 -3
  79. package/dist/parser/parse-utils/note-utils.js +25 -40
  80. package/dist/parser/parse-utils/string-utils.d.ts +1 -1
  81. package/dist/parser/parse-utils/string-utils.js +8 -6
  82. package/dist/parser/parserContext.d.ts +17 -11
  83. package/dist/parser/parserContext.js +111 -65
  84. package/dist/parser/preprocess.d.ts +7 -0
  85. package/dist/parser/preprocess.js +21 -19
  86. package/dist/pipeline.d.ts +1 -1
  87. package/dist/pipeline.js +2 -2
  88. package/dist/playback/compile.js +14 -15
  89. package/dist/playback/event.d.ts +6 -6
  90. package/dist/playback/event.js +13 -49
  91. package/dist/render/canvas.d.ts +0 -2
  92. package/dist/render/canvas.js +50 -56
  93. package/dist/render/index.d.ts +1 -1
  94. package/dist/render/index.js +1 -1
  95. package/dist/render/paint.d.ts +7 -0
  96. package/dist/render/paint.js +70 -20
  97. package/dist/render/recording.d.ts +8 -1
  98. package/dist/render/recording.js +12 -0
  99. package/dist/render/svg.d.ts +5 -2
  100. package/dist/render/svg.js +70 -48
  101. package/dist/render/text.d.ts +37 -2
  102. package/dist/render/text.js +136 -1
  103. package/dist/render/translate.d.ts +3 -1
  104. package/dist/render/translate.js +6 -0
  105. package/dist/render/types.d.ts +9 -2
  106. package/grammar.md +18 -14
  107. package/package.json +8 -18
  108. package/dist/converter/midi/convert.d.ts +0 -42
  109. package/dist/converter/midi/convert.js +0 -729
  110. package/dist/converter/midi/index.d.ts +0 -5
  111. package/dist/converter/midi/index.js +0 -11
  112. package/dist/converter/midi/json.d.ts +0 -38
  113. package/dist/converter/midi/json.js +0 -1
  114. package/dist/converter/midi/triplet.d.ts +0 -30
  115. package/dist/converter/midi/triplet.js +0 -75
  116. package/dist/converter/musicxml/dom.d.ts +0 -25
  117. package/dist/converter/musicxml/dom.js +0 -65
  118. package/dist/converter/musicxml/features.d.ts +0 -114
  119. package/dist/converter/musicxml/features.js +0 -501
  120. package/dist/converter/musicxml/index.d.ts +0 -14
  121. package/dist/converter/musicxml/index.js +0 -1295
  122. package/dist/converter/musicxml/model.d.ts +0 -176
  123. package/dist/converter/musicxml/model.js +0 -1
  124. package/dist/converter/musicxml/resolve.d.ts +0 -10
  125. package/dist/converter/musicxml/resolve.js +0 -152
  126. package/dist/converter/source.d.ts +0 -22
  127. package/dist/converter/source.js +0 -51
  128. package/dist/core.d.ts +0 -24
  129. package/dist/core.js +0 -24
  130. package/dist/iife/core.d.ts +0 -1
  131. package/dist/iife/core.js +0 -3
  132. package/dist/iife/from-midi.d.ts +0 -1
  133. package/dist/iife/from-midi.js +0 -15
  134. package/dist/iife/from-musicxml.d.ts +0 -1
  135. package/dist/iife/from-musicxml.js +0 -3
  136. package/dist/iife/full.d.ts +0 -1
  137. package/dist/iife/full.js +0 -3
  138. package/dist/jpfun.core.min.js +0 -123
  139. package/dist/jpfun.from-midi.min.js +0 -9
  140. package/dist/jpfun.from-musicxml.min.js +0 -12
@@ -3,7 +3,8 @@ import { getLayoutBounds, layoutLocalSequence } from "../../layout/engine.js";
3
3
  import { Fraction } from "../../fraction.js";
4
4
  import { Track } from "../../lowering/track.js";
5
5
  import { transferFunctionAddons, isVisualTemporalNode, TemporalNodeBase, } from "../temporal.js";
6
- import { ASTBraceNode, ASTFunctionNode, ASTLabelNode, ASTTextNode, } from "../ASTtypes.js";
6
+ import { paintVisual } from "../../render/paint.js";
7
+ import { ASTFunctionNode, } from "../ASTtypes.js";
7
8
  import { createBeamLayoutAttachment } from "../beam/layout.js";
8
9
  import { DIV_ADDON_KEY } from "../div/index.js";
9
10
  /** 倚音相对宿主的字号比例 */
@@ -22,9 +23,17 @@ const SHOULDER_PORT = "shoulder";
22
23
  * 所以只能在此刻回头改。这发生在 parse 进行中,不违反「AST parse 后只读」。
23
24
  */
24
25
  function scaleFontSize(node, factor) {
26
+ if (factor === 1)
27
+ return;
25
28
  const sized = node;
26
29
  if (typeof sized.size === "number")
27
30
  sized.size *= factor;
31
+ if (typeof sized.gap === "number")
32
+ sized.gap *= factor;
33
+ if (typeof sized.minGap === "number")
34
+ sized.minGap *= factor;
35
+ sized.aboveGaps?.forEach((_, i, a) => a[i] *= factor);
36
+ sized.belowGaps?.forEach((_, i, a) => a[i] *= factor);
28
37
  for (const child of node.children ?? [])
29
38
  scaleFontSize(child, factor);
30
39
  }
@@ -97,51 +106,17 @@ class GraceFunction extends ASTFunctionNode {
97
106
  if (n.kind !== "sugar" || n.data?.class !== GraceFunction)
98
107
  return null;
99
108
  const side = n.data.side;
100
- // 找上一个非文本节点 实现忽略中间内容的作用
101
- let left = ctx.nodes.length - 1;
102
- while (left >= 0 && ctx.nodes[left] instanceof ASTTextNode)
103
- left--;
104
- if (left < 0) {
109
+ const leftNode = ctx.takeLeftOperand();
110
+ if (!leftNode) {
105
111
  throw new ErrorDiagnostic("E_GRACE_NO_TARGET", "@grace语法糖错误: 左边没有找到目标", n.span);
106
112
  }
107
- let leftNode = ctx.nodes[left];
108
- /** 左操作数在 ctx.nodes 中的起点;只有这一段会被 grace 吞并 */
109
- let replaceFrom = left;
110
- // 对 label 的特判: 目标变为label到被标记的节点范围内的所有节点
111
- if (leftNode instanceof ASTLabelNode) {
112
- let tgt = leftNode.target;
113
- while (tgt && !ctx.nodes.includes(tgt))
114
- tgt = tgt.parent;
115
- for (let j = left - 1; j >= 0; j--) {
116
- if (ctx.nodes[j] === tgt) {
117
- leftNode = new ASTBraceNode({
118
- start: tgt.sourceSpan.start,
119
- end: leftNode.sourceSpan.end,
120
- }, ctx.nodes.slice(j, left + 1), null);
121
- replaceFrom = j;
122
- break;
123
- }
124
- }
125
- }
126
- // 找到下一个非文本节点 通过全量后续解析的方式进行
127
- const storage = ctx.nodes;
128
- ctx.nodes = [];
129
- ctx.makeNodes(nodes, at);
130
- for (let i = 0; i < ctx.nodes.length; i++) {
131
- const right = ctx.nodes[i];
132
- if (right instanceof ASTTextNode)
133
- continue;
134
- // '<' 的倚音在右侧,右结合的解析结果本来就是嵌套语义,不必像 '>' 那样重排
135
- const node = side === "pre"
136
- ? GraceFunction.attachPre(leftNode, right, n.span, ctx)
137
- : GraceFunction.create(ctx, n.span, "post", leftNode, right);
138
- storage.length = replaceFrom;
139
- storage.push(node);
140
- while (++i < ctx.nodes.length)
141
- storage.push(ctx.nodes[i]);
142
- ctx.nodes = storage;
143
- return nodes.length;
144
- }
113
+ const next = ctx.consumeRightOperand(nodes, at, right =>
114
+ // '<' 的倚音在右侧,右结合的解析结果本来就是嵌套语义,不必像 '>' 那样重排
115
+ side === "pre"
116
+ ? GraceFunction.attachPre(leftNode, right, n.span, ctx)
117
+ : GraceFunction.create(ctx, n.span, "post", leftNode, right));
118
+ if (next !== null)
119
+ return next;
145
120
  throw new ErrorDiagnostic("E_GRACE_NO_TARGET", "@grace语法糖错误: 右边没有找到目标", n.span);
146
121
  }
147
122
  host;
@@ -161,33 +136,25 @@ class GraceFunction extends ASTFunctionNode {
161
136
  deepest = deepest.grace;
162
137
  depth++;
163
138
  }
164
- const argMap = new Map();
165
- argMap.set(0, deepest.grace);
166
- argMap.set(1, left);
167
139
  const scale = GRACE_SCALE ** depth;
168
- const inner = new GraceFunction(span, argMap, ctx, null, GRACE_SCALE * scale);
140
+ const inner = GraceFunction.create(ctx, span, "pre", deepest.grace, left, GRACE_SCALE * scale);
169
141
  inner.size *= scale;
170
142
  deepest.setGrace(inner, 1); // inner 内部已按深度缩放,不能再缩
171
143
  return right;
172
144
  }
173
145
  return GraceFunction.create(ctx, span, "pre", right, left);
174
146
  }
175
- static create(ctx, span, side, host, grace) {
147
+ static create(ctx, span, side, host, grace, scale = GRACE_SCALE) {
176
148
  const argMap = new Map();
177
149
  argMap.set(0, host);
178
150
  argMap.set(1, grace);
179
151
  argMap.set("side", side);
180
- return new GraceFunction(span, argMap, ctx);
152
+ return new GraceFunction(span, argMap, ctx, null, scale);
181
153
  }
182
- /** 宿主在前:findActiveDivs 下潜子树时要先命中宿主的 @div,而不是倚音的 */
183
154
  get children() {
184
- const out = [];
185
- if (this.host)
186
- out.push(this.host);
187
- if (this.grace)
188
- out.push(this.grace);
189
- return out;
155
+ return [this.host, this.grace];
190
156
  }
157
+ timeFlowModel() { return null; }
191
158
  constructor(span, args, ctx, parent = null, scale = GRACE_SCALE) {
192
159
  super(span, parent);
193
160
  this.size = ctx.variables.fontsize;
@@ -210,11 +177,7 @@ class GraceFunction extends ASTFunctionNode {
210
177
  }
211
178
  /** 宿主收敛成一个可见 Temporal,倚音展开成局部时间列,然后整体折叠进一个复合节点 */
212
179
  loweringEnter(ctx, track) {
213
- const host = this.host;
214
- const grace = this.grace;
215
- if (!host || !grace) {
216
- throw new ErrorDiagnostic("E_GRACE_MISSING_ARGS", "@grace 需要同时给出宿主和倚音", this.sourceSpan);
217
- }
180
+ const { host, grace } = this;
218
181
  // 倚音内容是一个子域:在私有根轨上展开,根轨不挂进宿主轨的分组,其中的并行结构另开声部
219
182
  const root = new Track(track);
220
183
  let hostEvents = [];
@@ -240,20 +203,10 @@ class GraceFunction extends ASTFunctionNode {
240
203
  if (!events.some(isVisualTemporalNode) || events.some(event => (event.addon?.breakBefore ?? 0) > 0)) {
241
204
  throw new ErrorDiagnostic("E_GRACE_INVALID_CONTENT", "@grace 的倚音至少产生一个可见对象,且不能换行", grace.sourceSpan);
242
205
  }
243
- const composite = new GraceTemporal(this, hostNode, columns, root, attachments, this.side);
244
- // 倚音同段无条件全部相连,只被零时长标记切断,所以 grace 一定认识 beam,允许耦合
245
- // 折叠成员不进全局时间列,autobeam 看不到它们,要手动调用且强制连接
246
- for (const run of composite.graceRuns) {
247
- if (run.length < 2)
248
- continue;
249
- ctx.addAttachment(createBeamLayoutAttachment([...run], false, grace.sourceSpan));
250
- }
251
- return [composite];
206
+ return [new GraceTemporal(this, hostNode, columns, root, attachments, ctx)];
252
207
  }
253
208
  toString(source) {
254
- const host = this.host?.toString(source) ?? "";
255
- const grace = this.grace?.toString(source) ?? "";
256
- return `@grace(${host}, ${grace}, side=${this.side})`;
209
+ return `@grace(${this.host.toString(source)}, ${this.grace.toString(source)}, side=${this.side})`;
257
210
  }
258
211
  }
259
212
  export const GraceNode = GraceFunction;
@@ -274,9 +227,6 @@ export class GraceTemporal extends TemporalNodeBase {
274
227
  graceColumns;
275
228
  /** graceColumns 按列展开 */
276
229
  graces;
277
- /** 承担节奏的倚音成员,按声部与零时长标记切段;同段视觉上首尾相接,无条件连成一束减时线 */
278
- graceRuns;
279
- side;
280
230
  /** 倚音子域的根轨:由宿主轨分出,不挂进它的分组,子域之外不可见 */
281
231
  root;
282
232
  /** 倚音内容里声明的附件,随子域排版 */
@@ -290,13 +240,12 @@ export class GraceTemporal extends TemporalNodeBase {
290
240
  graceOffsets = [];
291
241
  /** 倚音线起点,同样是局部偏移 */
292
242
  hookOrigin = null;
293
- constructor(ast, host, columns, root, attachments, side) {
243
+ constructor(ast, host, columns, root, attachments, ctx) {
294
244
  super();
295
245
  this.ast = ast;
296
246
  this.host = host;
297
247
  this.root = root;
298
248
  this.attachments = attachments;
299
- this.side = side;
300
249
  this.T.copyFrom(host.T);
301
250
  this.mergeKey = host.mergeKey;
302
251
  this.initLayoutBox();
@@ -327,6 +276,8 @@ export class GraceTemporal extends TemporalNodeBase {
327
276
  this.graces = graceColumns.flat();
328
277
  this.events = events;
329
278
  this.starts = starts;
279
+ // 承担节奏的倚音成员按声部与零时长标记切段;同段视觉上首尾相接,无条件连成一束减时线
280
+ // 折叠成员不进全局时间列,autobeam 看不到它们,要手动调用且强制连接
330
281
  const runs = new Map();
331
282
  const graceRuns = [];
332
283
  for (const grace of this.graces) {
@@ -346,14 +297,17 @@ export class GraceTemporal extends TemporalNodeBase {
346
297
  addon[DIV_ADDON_KEY] = (Number(addon[DIV_ADDON_KEY]) || 0) + 1;
347
298
  grace.T.divPow2();
348
299
  }
349
- this.graceRuns = graceRuns;
300
+ for (const run of graceRuns) {
301
+ if (run.length >= 2)
302
+ ctx.addAttachment(createBeamLayoutAttachment(run, false, ast.grace.sourceSpan));
303
+ }
350
304
  }
351
305
  /** 成员共享全局时间状态,按发声顺序固化 */
352
306
  onTimeState(state) {
353
307
  // 同步时间的修改。比如tuplet修改的是GraceTemporal.T,这里要把它传给成员
354
308
  this.host.T.copyFrom(this.T);
355
309
  let offset = undefined;
356
- for (const member of this.side === "pre" ? [...this.events, this.host] : [this.host, ...this.events]) {
310
+ for (const member of this.ast.side === "pre" ? [...this.events, this.host] : [this.host, ...this.events]) {
357
311
  member.t.copyFrom(this.t);
358
312
  member.layoutLine = this.layoutLine;
359
313
  const result = member.onTimeState?.(state);
@@ -385,13 +339,14 @@ export class GraceTemporal extends TemporalNodeBase {
385
339
  steal.copyFrom(limit);
386
340
  }
387
341
  const hostDuration = total.sub(steal);
388
- const base = this.side === "pre" ? emitter.start.clone() : emitter.start.clone().add(hostDuration);
389
- if (this.side === "post")
342
+ const pre = this.ast.side === "pre";
343
+ const base = pre ? emitter.start.clone() : emitter.start.clone().add(hostDuration);
344
+ if (!pre)
390
345
  emitter.play(this.host, emitter.start.clone(), hostDuration);
391
346
  this.events.forEach((event, index) => {
392
347
  emitter.play(event, this.starts[index].clone().mul(scale).add(base), event.T.clone().mul(scale));
393
348
  });
394
- if (this.side === "pre")
349
+ if (pre)
395
350
  emitter.play(this.host, base.add(steal), hostDuration);
396
351
  }
397
352
  /**
@@ -406,19 +361,20 @@ export class GraceTemporal extends TemporalNodeBase {
406
361
  transferFunctionAddons(this, this.host);
407
362
  const block = context.layoutSubdomain(this, this.graceColumns, this.root, this.attachments);
408
363
  const hostWidth = layoutLocalSequence([this.host], context);
409
- this.springConfig = { ...this.host.springConfig, ...this.springConfig };
364
+ this.springConfig = { ...this.host.springConfig };
410
365
  const graceEm = this.ast.size * GRACE_SCALE;
411
366
  const sideGap = graceEm * 0.2;
412
367
  const rise = graceEm * GRACE_RISE;
368
+ const pre = this.ast.side === "pre";
413
369
  // 倚音贴着宿主的肩线而不是宿主盒顶:宿主本身也是复合体时,
414
370
  // 肩线由它转发上来,所以两侧倚音会落在同一高度而不是层层叠高
415
371
  const shoulder = this.host.ports[SHOULDER_PORT]?.y ?? 0;
416
372
  const graceTop = shoulder - rise - block.height;
417
373
  const hostBounds = getLayoutBounds(this.host);
418
374
  const lift = Math.max(0, -graceTop, -hostBounds.y);
419
- const graceX = this.side === "pre" ? 0 : hostWidth + sideGap;
375
+ const graceX = pre ? 0 : hostWidth + sideGap;
420
376
  this.hostOffset = {
421
- x: this.host.box.x + (this.side === "pre" ? block.width + sideGap : 0),
377
+ x: this.host.box.x + (pre ? block.width + sideGap : 0),
422
378
  y: lift,
423
379
  };
424
380
  this.graceOffsets = block.positions.map(position => ({
@@ -442,7 +398,7 @@ export class GraceTemporal extends TemporalNodeBase {
442
398
  this.ports[SHOULDER_PORT] ??= { x: this.box.anchor, y: this.hostOffset.y };
443
399
  // 钩形曲线挂在靠近宿主的那个倚音成员下方,零时长标记不承接它;高度取成员的最低下沿,不含块内附件
444
400
  const rhythmic = this.graces.filter(grace => !grace.T.isZero());
445
- const near = this.side === "pre" ? rhythmic.at(-1) : rhythmic[0];
401
+ const near = pre ? rhythmic.at(-1) : rhythmic[0];
446
402
  this.hookOrigin = near ? {
447
403
  x: this.graceOffsets[this.graces.indexOf(near)].x + near.box.anchor,
448
404
  y: Math.max(...this.graces.map((grace, index) => this.graceOffsets[index].y + grace.box.h)),
@@ -460,16 +416,13 @@ export class GraceTemporal extends TemporalNodeBase {
460
416
  });
461
417
  }
462
418
  paint(painter) {
463
- for (const member of [this.host, ...this.graces]) {
464
- member.paint(painter);
465
- for (const decoration of member.decorations)
466
- decoration.paint?.(painter);
467
- }
419
+ for (const member of [this.host, ...this.graces])
420
+ paintVisual(painter, member);
468
421
  if (!this.hookOrigin)
469
422
  return;
470
423
  const graceEm = this.ast.size * GRACE_SCALE;
471
424
  const hookOrigin = this.hookOrigin;
472
- const dir = this.side === "pre" ? 1 : -1;
425
+ const dir = this.ast.side === "pre" ? 1 : -1;
473
426
  painter.drawPath(HOOK_COMMANDS, { stroke: "#000", strokeWidth: Math.max(0.8, graceEm * HOOK_WIDTH) }, {
474
427
  x: this.box.x + hookOrigin.x,
475
428
  y: this.box.y + hookOrigin.y,
@@ -12,7 +12,7 @@ const FIELD_SLOT = {
12
12
  signature: "left", tempo: "left", left: "left", center: "center", right: "right",
13
13
  };
14
14
  const TEXT_PRESET = {
15
- title: [2, "center"], subtitle: [0.85, "center"], author: [0.8, "right"],
15
+ title: [2, "center"], subtitle: [1, "center"], author: [0.88, "right"],
16
16
  };
17
17
  const ITEM_GAP_EM = 0.25;
18
18
  const DEFAULT_GAP_PX = 5;
@@ -57,6 +57,7 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
57
57
  members = [];
58
58
  slots = [];
59
59
  titleBottom = 0;
60
+ aligned = false; // 侧栏横向重排在一轮布局中只执行一次,避免二次 onPlaced 把成员微调后的 box.x 当成未偏移基准
60
61
  sideExtents = { left: null, right: null };
61
62
  constructor(ast) {
62
63
  super();
@@ -70,15 +71,20 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
70
71
  }
71
72
  }
72
73
  }
73
- prepareLayout() { this.box.w = this.box.h = this.box.anchor = this.box.visualAxis = 0; }
74
+ prepareLayout() {
75
+ this.box.w = this.box.h = this.box.anchor = this.box.visualAxis = 0;
76
+ this.aligned = false;
77
+ }
74
78
  prepareHorizontal(line) {
75
79
  // 只由第一个边界协调一次整块 Head,避免六个边界重复改弹簧
76
80
  if (this.slots.length > 0)
77
81
  this.prepareHead(line);
78
82
  }
79
83
  onPlaced() {
80
- if (this.slots.length > 0)
84
+ if (this.slots.length > 0 && !this.aligned) {
85
+ this.aligned = true;
81
86
  this.alignHead();
87
+ }
82
88
  }
83
89
  onTemporal(node) { this.members.push(node); }
84
90
  createTracks(slot) {
@@ -152,7 +158,7 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
152
158
  cells.set(cell, [member]);
153
159
  }
154
160
  const [left, , right] = this.slots;
155
- this.packRows(left.ast, left.start.box.x, cells);
161
+ this.packRows(left.ast, left.start.box.x - (left.start.placementOffset?.x ?? 0), cells);
156
162
  this.packRows(right.ast, right.end.box.x, cells);
157
163
  }
158
164
  stretch(node, side) {
@@ -325,9 +331,6 @@ H.tempo: 94
325
331
  gap;
326
332
  createdBySugar = false;
327
333
  get children() { return this.slots; }
328
- timeFlowModel() {
329
- return { mode: "sequence", children: this.slots };
330
- }
331
334
  static deSugarAtom(source, start, end) {
332
335
  if (source[start] !== "H" || source[start + 1] !== ".")
333
336
  return null;
@@ -343,12 +346,17 @@ H.tempo: 94
343
346
  const explicitContent = source[contentStart] === "@" || source[contentStart] === "{";
344
347
  // 裸文本整行归 Head 所有,直接越过可避免其中的 F 等字符被识别成音符
345
348
  // 显式 DSL 仍从冒号后继续扫描,保留内部函数高亮
349
+ const last = skipSpacesBack(source, lineEnd - 1, contentStart);
350
+ const contentSpan = explicitContent ? undefined : { start: contentStart, end: Math.max(contentStart, last + 1) };
346
351
  return {
347
352
  next: explicitContent ? pos : lineEnd,
348
353
  node: {
349
354
  kind: "sugar",
350
- data: { class: HeadFunction, field },
355
+ data: { class: HeadFunction, field, contentSpan },
351
356
  span: { start, end: pos },
357
+ syntaxKind: contentSpan && field !== "signature" && field !== "tempo" && contentSpan.start < contentSpan.end
358
+ ? [{ kind: "operator", span: { start, end: pos } }, { kind: "string", span: contentSpan }]
359
+ : undefined,
352
360
  },
353
361
  };
354
362
  }
@@ -358,39 +366,26 @@ H.tempo: 94
358
366
  return null;
359
367
  const field = sugar.data.field;
360
368
  let breakAt = at;
361
- for (; breakAt < nodes.length; breakAt++) {
362
- const node = nodes[breakAt];
363
- if (typeof node === "number" && (ctx.source[node] === "\r" || ctx.source[node] === "\n"))
364
- break;
365
- if (typeof node !== "number" && node.kind === "sugar" && node.data?.class === HeadFunction)
366
- break;
367
- }
368
- const stop = nodes[breakAt];
369
- // 裸文本在第一轮被整体越过,EOF 时 nodes 中没有末尾标记,需从源码恢复边界
370
- let boundary;
371
- if (typeof stop === "number")
372
- boundary = stop;
373
- else if (stop)
374
- boundary = stop.span.start;
375
- else if (breakAt > at) {
376
- const last = nodes[breakAt - 1];
377
- boundary = typeof last === "number" ? last + 1 : last.span.end;
378
- }
379
- else
380
- boundary = findLineEnd(ctx.source, sugar.span.end);
381
- const start = skipSpaces(ctx.source, sugar.span.end, boundary);
382
- const last = skipSpacesBack(ctx.source, boundary - 1, start);
383
- const span = { start, end: Math.max(start, last + 1) };
384
- if (span.start >= span.end) {
385
- throw new ErrorDiagnostic("E_HEAD_EMPTY_DECLARATION", "H.{field}: 后必须有内容", sugar.span, { field });
386
- }
387
- const text = ctx.source.slice(span.start, span.end).trim();
369
+ let span = sugar.data.contentSpan;
388
370
  let parsed;
389
- if (text.startsWith("@") || text.startsWith("{")) {
371
+ if (!span) {
372
+ for (; breakAt < nodes.length; breakAt++) {
373
+ const node = nodes[breakAt];
374
+ if (typeof node === "number" && (ctx.source[node] === "\r" || ctx.source[node] === "\n"))
375
+ break;
376
+ if (typeof node !== "number" && node.kind === "sugar" && node.data?.class === HeadFunction)
377
+ break;
378
+ }
390
379
  const sub = new ParserContext(ctx);
391
380
  sub.makeNodes(nodes.slice(at, breakAt));
392
381
  parsed = sub.nodes;
382
+ const last = parsed.at(-1)?.sourceSpan.end ?? sugar.span.end;
383
+ span = { start: skipSpaces(ctx.source, sugar.span.end, last), end: last };
393
384
  }
385
+ if (span.start >= span.end) {
386
+ throw new ErrorDiagnostic("E_HEAD_EMPTY_DECLARATION", "H.{field}: 后必须有内容", sugar.span, { field });
387
+ }
388
+ const text = ctx.source.slice(span.start, span.end);
394
389
  const previous = ctx.nodes.at(-1);
395
390
  // 只有相邻的 H.* 声明合并;普通节点或空行都会切断组合
396
391
  const head = previous instanceof HeadFunction && previous.createdBySugar
@@ -402,6 +397,7 @@ H.tempo: 94
402
397
  head.sourceSpan.end = span.end;
403
398
  if (head !== previous)
404
399
  ctx.pushNode(head);
400
+ const stop = nodes[breakAt];
405
401
  if (typeof stop !== "number")
406
402
  return breakAt;
407
403
  let next = breakAt + 1;
@@ -2,17 +2,15 @@ import { DEFAULT_TONALITY, TemporalNodeBase } from "../temporal.js";
2
2
  import { ASTFunctionNode } from "../ASTtypes.js";
3
3
  import { ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
4
4
  import { parseNoteName } from "../note/noteName.js";
5
- import { acc2Offset, NoteNameMap, tonality2Midi } from "../../parser/parse-utils/note-utils.js";
5
+ import { acc2Offset, FLAT_NOTE_NAMES, NoteNameMap, SHARP_NOTE_NAMES, wrapPitchClass } from "../../parser/parse-utils/note-utils.js";
6
6
  import { paintAccidental, placeAccidentals } from "../note/accidentals.js";
7
7
  /**
8
8
  * 把宽松的调性写法收敛成 tonality2Midi 认得的 [音名][最多一个 #b][绝对八度]
9
9
  *
10
- * 本来就合法就原样返回,彻底读不懂返回 null
10
+ * 彻底读不懂返回 null
11
11
  * `C###` 这种超过一个变音记号的写法按实际音高换字母(→ D#4),落在黑键上则跟随原来的升降方向拼写
12
12
  */
13
13
  function normalizeTonality(tonality) {
14
- if (tonality2Midi(tonality) !== null)
15
- return tonality;
16
14
  const normalizedInput = tonality.replace(/^[a-g]/, letter => letter.toUpperCase());
17
15
  const parsed = parseNoteName(normalizedInput, 0, normalizedInput.length, false);
18
16
  if (!parsed || parsed.next !== normalizedInput.length)
@@ -23,9 +21,10 @@ function normalizeTonality(tonality) {
23
21
  const offset = acc2Offset(parsed.acc ?? "", false);
24
22
  const octave = parsed.absOctave ? parsed.octave ?? 4 : 4 + (parsed.octave ?? 0);
25
23
  const midi = (octave + 1) * 12 + pitchClass + offset;
26
- // NoteNameMap 里同一音高的升号拼写在前、降号在后,正好用来挑方向;数字音名不参与拼写
27
- const spellings = Object.keys(NoteNameMap).filter(name => NoteNameMap[name] === ((midi % 12) + 12) % 12 && /^[A-G]/.test(name));
28
- return (offset < 0 ? spellings.at(-1) : spellings[0]) + (Math.floor(midi / 12) - 1);
24
+ if (!Number.isSafeInteger(midi))
25
+ return null;
26
+ const spelling = (offset < 0 ? FLAT_NOTE_NAMES : SHARP_NOTE_NAMES)[wrapPitchClass(midi)];
27
+ return spelling + (Math.floor(midi / 12) - 1);
29
28
  }
30
29
  class KeyFunction extends ASTFunctionNode {
31
30
  static def = {
@@ -65,13 +64,12 @@ class KeyFunction extends ASTFunctionNode {
65
64
  super(sourceSpan, parent);
66
65
  const [tonality, size] = this.getArgValue(args, ctx);
67
66
  this.font = ctx.variables.numberfont;
68
- this.tonality = tonality;
69
67
  this.size = ctx.length2px(size);
70
68
  const normalized = normalizeTonality(tonality);
71
- if (normalized !== tonality) {
69
+ this.tonality = normalized ?? DEFAULT_TONALITY;
70
+ if (normalized !== tonality && normalized !== `${tonality}4`) {
72
71
  if (ctx.variables.strict)
73
72
  throw new ErrorDiagnostic("E_KEY_TONALITY", '@key 无法解析调性 "{tonality}"', sourceSpan, { tonality });
74
- this.tonality = normalized ?? DEFAULT_TONALITY;
75
73
  ctx.diagnostics.push(new WarningDiagnostic("W_KEY_TONALITY", '@key 的调性 "{input}" 不是规范写法,已自动切换到 {tonality}', sourceSpan, { input: tonality, tonality: this.tonality }));
76
74
  }
77
75
  // 归一化保证了格式是 [音名][最多一个 #b][八度]
@@ -111,8 +109,7 @@ class KeyTemporalNode extends TemporalNodeBase {
111
109
  const style = this.style;
112
110
  const prefix = context.textMeasurer.measureText(PREFIX, style);
113
111
  const name = context.textMeasurer.measureText(this.ast.displayName, style);
114
- const accidentalGap = size * 0.02;
115
- const { placed, right, top } = placeAccidentals(this.ast.displayAcc, size, prefix.w, prefix.baseline, accidentalGap);
112
+ const { placed, right, top } = placeAccidentals(this.ast.displayAcc, size, prefix.w, prefix.baseline);
116
113
  this.accidentals = placed;
117
114
  // 升降号抬高后可能高过文字,整块下移把它装回盒子里
118
115
  const shift = -top;
@@ -30,6 +30,7 @@ declare class MeterFunction extends ASTFunctionNode {
30
30
  readonly size: number;
31
31
  readonly strict: boolean;
32
32
  readonly font: string;
33
+ readonly weight: number;
33
34
  constructor(span: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent?: ASTNodeBase | null);
34
35
  loweringEnter(ctx: LoweringContext): MeterTemporal[];
35
36
  /**
@@ -9,8 +9,8 @@ const changesByPosition = new WeakMap();
9
9
  export function meterChangeAt(node) {
10
10
  return changesByPosition.get(node)?.meter;
11
11
  }
12
- function recordMeasureChange(state, node, meter) {
13
- const position = state.currentEvent ?? node;
12
+ function recordMeasureChange(node, meter) {
13
+ const position = node.rootHost;
14
14
  const span = node.ast.sourceSpan;
15
15
  let change = changesByPosition.get(position);
16
16
  if (!change)
@@ -56,10 +56,12 @@ class MeterFunction extends ASTFunctionNode {
56
56
  size;
57
57
  strict;
58
58
  font;
59
+ weight;
59
60
  constructor(span, args, ctx, parent = null) {
60
61
  super(span, parent);
61
62
  let [num, den, size] = this.getArgValue(args, ctx);
62
63
  this.font = ctx.variables.numberfont;
64
+ this.weight = ctx.variables.numberweight;
63
65
  if (!Number.isSafeInteger(num) || !Number.isSafeInteger(num * 4) || num < 0
64
66
  || !Number.isSafeInteger(den) || den < 0) {
65
67
  const message = `@meter 的分子和分母必须是非负整数`;
@@ -147,6 +149,7 @@ class MeterTemporal extends TemporalNodeBase {
147
149
  this.style = {
148
150
  fontSize: ast.size,
149
151
  fontFamily: ast.font,
152
+ fontWeight: ast.weight,
150
153
  textAlign: "center",
151
154
  fill: "#000",
152
155
  };
@@ -154,7 +157,7 @@ class MeterTemporal extends TemporalNodeBase {
154
157
  }
155
158
  onTimeState(state) {
156
159
  state.meter = this.ast.measureDuration;
157
- recordMeasureChange(state, this, this.ast);
160
+ recordMeasureChange(this, this.ast);
158
161
  }
159
162
  emitPlayback(emitter) {
160
163
  if (!this.ast.measureDuration)
@@ -1,3 +1,3 @@
1
1
  import { type SymbolShape } from "../symbol/shape.js";
2
2
  export declare const sanbanShapes: readonly SymbolShape[];
3
- export declare const sanbanBounds: import("../../core.js").Rect;
3
+ export declare const sanbanBounds: import("../../index.js").Rect;
@@ -3,6 +3,7 @@ export interface PreparedAccidental {
3
3
  w: number;
4
4
  h: number;
5
5
  baseline: number;
6
+ fill?: boolean;
6
7
  strokeWidth: number;
7
8
  commands: readonly PathCommand[];
8
9
  }
@@ -13,13 +14,12 @@ export interface PlacedAccidental {
13
14
  y: number;
14
15
  }
15
16
  /**
16
- * 把升降号串按同一基线依次排在 x 右侧
17
+ * 把升降号串按同一基线依次紧挨着排在 x 右侧
17
18
  * @param size 宿主数字的字号
18
19
  * @param baselineY 宿主文字基线在宿主盒局部坐标中的 y
19
- * @param gap 相邻升降号之间的间隔;末尾也留一份,宿主据此得到 right
20
20
  * @returns right 是下一个字形的起点,top 是最高处(可能为负,宿主自行决定是否下移)
21
21
  */
22
- export declare function placeAccidentals(symbols: string, size: number, x: number, baselineY: number, gap: number): {
22
+ export declare function placeAccidentals(symbols: string, size: number, x: number, baselineY: number): {
23
23
  placed: PlacedAccidental[];
24
24
  right: number;
25
25
  top: number;
@@ -5,18 +5,31 @@ const STROKE_RATIO = 0.06;
5
5
  const RAISE_RATIO = 0.42;
6
6
  const ACCIDENTALS = {
7
7
  "#": {
8
- w: 0.46,
9
- h: 0.78,
10
- baseline: 0.63,
8
+ w: 0.42,
9
+ h: 0.82,
10
+ baseline: 0.67,
11
+ fill: true,
11
12
  commands: [
12
- { op: "M", x: 0.34, y: 0.05 },
13
- { op: "L", x: 0.27, y: 0.95 },
14
- { op: "M", x: 0.72, y: 0.05 },
15
- { op: "L", x: 0.65, y: 0.95 },
16
- { op: "M", x: 0.08, y: 0.38 },
17
- { op: "L", x: 0.9, y: 0.28 },
18
- { op: "M", x: 0.05, y: 0.72 },
19
- { op: "L", x: 0.87, y: 0.62 },
13
+ { op: "M", x: 0.22, y: 0.07 },
14
+ { op: "L", x: 0.35, y: 0.07 },
15
+ { op: "L", x: 0.35, y: 1 },
16
+ { op: "L", x: 0.22, y: 1 },
17
+ { op: "Z" },
18
+ { op: "M", x: 0.65, y: 0 },
19
+ { op: "L", x: 0.78, y: 0 },
20
+ { op: "L", x: 0.78, y: 0.93 },
21
+ { op: "L", x: 0.65, y: 0.93 },
22
+ { op: "Z" },
23
+ { op: "M", x: 0, y: 0.33 },
24
+ { op: "L", x: 1, y: 0.18 },
25
+ { op: "L", x: 1, y: 0.32 },
26
+ { op: "L", x: 0, y: 0.47 },
27
+ { op: "Z" },
28
+ { op: "M", x: 0, y: 0.68 },
29
+ { op: "L", x: 1, y: 0.53 },
30
+ { op: "L", x: 1, y: 0.67 },
31
+ { op: "L", x: 0, y: 0.82 },
32
+ { op: "Z" },
20
33
  ],
21
34
  },
22
35
  b: {
@@ -47,13 +60,12 @@ const ACCIDENTALS = {
47
60
  },
48
61
  };
49
62
  /**
50
- * 把升降号串按同一基线依次排在 x 右侧
63
+ * 把升降号串按同一基线依次紧挨着排在 x 右侧
51
64
  * @param size 宿主数字的字号
52
65
  * @param baselineY 宿主文字基线在宿主盒局部坐标中的 y
53
- * @param gap 相邻升降号之间的间隔;末尾也留一份,宿主据此得到 right
54
66
  * @returns right 是下一个字形的起点,top 是最高处(可能为负,宿主自行决定是否下移)
55
67
  */
56
- export function placeAccidentals(symbols, size, x, baselineY, gap) {
68
+ export function placeAccidentals(symbols, size, x, baselineY) {
57
69
  const placed = [];
58
70
  const glyphSize = size * GLYPH_SCALE;
59
71
  const raise = size * RAISE_RATIO;
@@ -67,6 +79,7 @@ export function placeAccidentals(symbols, size, x, baselineY, gap) {
67
79
  w: definition.w * glyphSize,
68
80
  h: definition.h * glyphSize,
69
81
  baseline: definition.baseline * glyphSize,
82
+ fill: definition.fill,
70
83
  strokeWidth: size * STROKE_RATIO,
71
84
  commands: definition.commands,
72
85
  };
@@ -74,11 +87,11 @@ export function placeAccidentals(symbols, size, x, baselineY, gap) {
74
87
  placed.push({ shape, x: right, y });
75
88
  if (y < top)
76
89
  top = y;
77
- right += shape.w + gap;
90
+ right += shape.w;
78
91
  }
79
92
  return { placed, right, top };
80
93
  }
81
94
  /** commands 是 0..1 归一化坐标,必须配回字形自己的 w/h 才不会画歪 */
82
95
  export function paintAccidental(painter, { shape, x, y }, origin, color) {
83
- painter.drawPath(shape.commands, { stroke: color, strokeWidth: shape.strokeWidth }, { x: origin.x + x, y: origin.y + y, scaleX: shape.w, scaleY: shape.h });
96
+ painter.drawPath(shape.commands, shape.fill ? { fill: color } : { stroke: color, strokeWidth: shape.strokeWidth }, { x: origin.x + x, y: origin.y + y, scaleX: shape.w, scaleY: shape.h });
84
97
  }