jpfun 0.4.1 → 0.5.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 (73) hide show
  1. package/README.md +53 -113
  2. package/dist/converter/midi/convert.js +14 -7
  3. package/dist/converter/musicxml/features.d.ts +57 -16
  4. package/dist/converter/musicxml/features.js +204 -42
  5. package/dist/converter/musicxml/index.d.ts +7 -2
  6. package/dist/converter/musicxml/index.js +256 -268
  7. package/dist/converter/musicxml/model.d.ts +36 -7
  8. package/dist/converter/musicxml/resolve.d.ts +10 -0
  9. package/dist/converter/musicxml/resolve.js +152 -0
  10. package/dist/core.d.ts +1 -0
  11. package/dist/core.js +1 -0
  12. package/dist/fraction.js +7 -1
  13. package/dist/functions/ASTtypes.d.ts +2 -3
  14. package/dist/functions/ASTtypes.js +5 -9
  15. package/dist/functions/adjust/index.js +4 -48
  16. package/dist/functions/arpeggio/index.js +21 -13
  17. package/dist/functions/box/index.js +81 -82
  18. package/dist/functions/dash/index.js +20 -11
  19. package/dist/functions/div/index.d.ts +1 -1
  20. package/dist/functions/div/index.js +7 -7
  21. package/dist/functions/dot/index.js +4 -5
  22. package/dist/functions/dyn/index.js +28 -32
  23. package/dist/functions/grace/index.d.ts +19 -6
  24. package/dist/functions/grace/index.js +123 -115
  25. package/dist/functions/key/index.js +1 -1
  26. package/dist/functions/meter/index.js +14 -1
  27. package/dist/functions/note/index.d.ts +6 -1
  28. package/dist/functions/note/index.js +37 -14
  29. package/dist/functions/note/source-transform.d.ts +21 -0
  30. package/dist/functions/note/source-transform.js +164 -0
  31. package/dist/functions/page/index.d.ts +5 -0
  32. package/dist/functions/page/index.js +8 -5
  33. package/dist/functions/set/index.js +5 -1
  34. package/dist/functions/symbol/index.d.ts +2 -0
  35. package/dist/functions/symbol/index.js +1 -1
  36. package/dist/functions/symbol/ornament.d.ts +3 -3
  37. package/dist/functions/symbol/ornament.js +21 -35
  38. package/dist/functions/symbol/symbols/accent.js +5 -5
  39. package/dist/functions/symbol/symbols/fermata.js +5 -4
  40. package/dist/functions/tie/index.js +22 -32
  41. package/dist/functions/tuplet/index.js +19 -23
  42. package/dist/functions/up/index.js +9 -9
  43. package/dist/functions/voice/index.js +4 -3
  44. package/dist/functions/volta/index.js +7 -12
  45. package/dist/jpfun.core.min.js +40 -37
  46. package/dist/jpfun.from-midi.min.js +5 -5
  47. package/dist/jpfun.from-musicxml.min.js +8 -8
  48. package/dist/jpfun.min.js +49 -46
  49. package/dist/layout/engine.d.ts +11 -1
  50. package/dist/layout/engine.js +299 -96
  51. package/dist/layout/page.js +2 -0
  52. package/dist/layout/range.d.ts +26 -0
  53. package/dist/layout/range.js +75 -0
  54. package/dist/layout/types.d.ts +33 -4
  55. package/dist/lowering/types.d.ts +5 -0
  56. package/dist/parser/parse-utils/length-utils.js +2 -0
  57. package/dist/parser/parse-utils/note-utils.d.ts +2 -0
  58. package/dist/parser/parse-utils/note-utils.js +6 -2
  59. package/dist/parser/parserContext.js +1 -1
  60. package/dist/playback/compile.d.ts +2 -9
  61. package/dist/playback/compile.js +297 -186
  62. package/dist/playback/event.d.ts +8 -16
  63. package/dist/playback/event.js +13 -3
  64. package/dist/playback/types.d.ts +76 -18
  65. package/dist/playback/types.js +1 -0
  66. package/dist/render/index.d.ts +1 -1
  67. package/dist/render/index.js +1 -1
  68. package/dist/render/recording.d.ts +1 -0
  69. package/dist/render/recording.js +21 -0
  70. package/dist/render/translate.d.ts +14 -0
  71. package/dist/render/translate.js +48 -0
  72. package/grammar.md +13 -6
  73. package/package.json +4 -4
@@ -1,6 +1,7 @@
1
1
  import { ErrorDiagnostic } from "../../diagnostic.js";
2
- import { prepareLayoutHost } from "../../layout/engine.js";
2
+ import { layoutLocalSequence } from "../../layout/engine.js";
3
3
  import { Fraction } from "../../fraction.js";
4
+ import { Track } from "../../lowering/track.js";
4
5
  import { isVisualTemporalNode, TemporalNodeBase, } from "../temporal.js";
5
6
  import { ASTBraceNode, ASTFunctionNode, ASTLabelNode, ASTTextNode, } from "../ASTtypes.js";
6
7
  import { createBeamLayoutAttachment } from "../beam/layout.js";
@@ -8,10 +9,10 @@ import { DIV_ADDON_KEY } from "../div/index.js";
8
9
  /** 倚音相对宿主的字号比例 */
9
10
  const GRACE_SCALE = 0.7;
10
11
  /**
11
- * 肩线端口:要在这个盒子上方叠东西的人,应该从哪条线开始
12
+ * 肩线端口:倚音相对宿主的纵向定位基准
12
13
  *
13
- * 普通音符不发布它,读取方退化成盒顶即可(倚音本来就该避开上八度点);
14
- * 复合节点发布它,指向自己内部那个真正承载节奏的音符的顶边。
14
+ * 普通音符指向数字顶边,不含上八度点;复合节点转发内部宿主的肩线,
15
+ * 缺少端口的其他对象回退到盒顶
15
16
  */
16
17
  const SHOULDER_PORT = "shoulder";
17
18
  /**
@@ -41,7 +42,9 @@ class GraceFunction extends ASTFunctionNode {
41
42
  - \`{3 2}>1\`:一组前倚音,等价于上例
42
43
  - \`1>2>3\`:允许嵌套,\`1\` 修饰 \`2\`,\`2\` 修饰 \`3\`
43
44
 
44
- 倚音默认带一条减时线,按八分音符书写;再加 \`/\` 变为十六分音符`,
45
+ 倚音默认带一条减时线,按八分音符书写;再加 \`/\` 变为十六分音符
46
+
47
+ 倚音内容可以是换行以外的任意结构,例如 \`{1 & 3}>2\` 的两个声部同时奏出`,
45
48
  allowExtraArgs: false,
46
49
  args: [
47
50
  {
@@ -52,7 +55,7 @@ class GraceFunction extends ASTFunctionNode {
52
55
  },
53
56
  {
54
57
  name: "grace",
55
- description: "倚音内容,多个音符可用大括号组合",
58
+ description: "倚音内容,多个音符可用大括号组合,也可以含多个声部",
56
59
  type: "content",
57
60
  default: null,
58
61
  },
@@ -205,45 +208,45 @@ class GraceFunction extends ASTFunctionNode {
205
208
  this.sourceSpan.start = Math.min(this.sourceSpan.start, node.sourceSpan.start);
206
209
  this.sourceSpan.end = Math.max(this.sourceSpan.end, node.sourceSpan.end);
207
210
  }
208
- /** 倚音与宿主各自收敛成可见 Temporal,然后整体折叠进一个复合节点 */
211
+ /** 宿主收敛成一个可见 Temporal,倚音展开成局部时间列,然后整体折叠进一个复合节点 */
209
212
  loweringEnter(ctx, track) {
210
- if (!this.host || !this.grace) {
213
+ const host = this.host;
214
+ const grace = this.grace;
215
+ if (!host || !grace) {
211
216
  throw new ErrorDiagnostic("E_GRACE_MISSING_ARGS", "@grace 需要同时给出宿主和倚音", this.sourceSpan);
212
217
  }
213
- let graces = [];
214
- let host = null;
218
+ // 倚音内容是一个子域:在私有根轨上展开,根轨不挂进宿主轨的分组,其中的并行结构另开声部
219
+ const root = new Track(track);
220
+ let hostEvents = [];
221
+ let columns = [];
222
+ const attachments = [];
223
+ const lower = (content, lane) => ctx.trackedEvents(content, new Fraction(), lane);
215
224
  // 成员不是外层分组的成员,复合节点才是;否则 voice 的歌词会按下标错位
225
+ // 按发声顺序展开,事件序号随之有序
216
226
  ctx.isolateFromLoweringGroups(() => {
217
- const order = this.side === "pre"
218
- ? [this.grace, this.host]
219
- : [this.host, this.grace];
220
- for (const content of order) {
221
- const events = ctx.trackedEvents(content, new Fraction(), track).flat();
222
- const visible = events.filter(isVisualTemporalNode);
223
- // 并行分支的纵向关系由引擎解 Track 树,而折叠成员进不了引擎
224
- if (events.some(event => event.track !== track))
225
- throw new ErrorDiagnostic("E_GRACE_PARALLEL_CONTENT", "@grace 的内容不能包含多声部结构(& / @voices);要在倚音里叠音请用 ^", content.sourceSpan);
226
- if (content === this.host) {
227
- if (visible.length !== 1 || visible.length !== events.length) {
228
- throw new ErrorDiagnostic("E_GRACE_INVALID_HOST", "@grace 的宿主必须恰好产生一个可见 Temporal", content.sourceSpan);
229
- }
230
- host = visible[0];
231
- }
232
- else {
233
- if (visible.length === 0 || visible.length !== events.length) {
234
- throw new ErrorDiagnostic("E_GRACE_INVALID_CONTENT", "@grace 的倚音必须只产生可见 Temporal,且至少一个", content.sourceSpan);
235
- }
236
- graces = visible;
237
- }
238
- }
227
+ if (this.side === "post")
228
+ hostEvents = lower(host, track).flat();
229
+ ctx.beginLoweringGroup(this, { onAttachment(attachment) { attachments.push(attachment); } });
230
+ columns = lower(grace, root);
231
+ ctx.endLoweringGroup(this);
232
+ if (this.side === "pre")
233
+ hostEvents = lower(host, track).flat();
239
234
  });
240
- const composite = new GraceTemporal(this, host, graces, this.side);
235
+ const [hostNode] = hostEvents;
236
+ if (hostEvents.length !== 1 || !isVisualTemporalNode(hostNode)) {
237
+ throw new ErrorDiagnostic("E_GRACE_INVALID_HOST", "@grace 的宿主必须恰好产生一个可见 Temporal", host.sourceSpan);
238
+ }
239
+ const events = columns.flat();
240
+ if (!events.some(isVisualTemporalNode) || events.some(event => event.breakBefore > 0)) {
241
+ throw new ErrorDiagnostic("E_GRACE_INVALID_CONTENT", "@grace 的倚音至少产生一个可见对象,且不能换行", grace.sourceSpan);
242
+ }
243
+ const composite = new GraceTemporal(this, hostNode, columns, root, attachments, this.side);
241
244
  // 倚音同段无条件全部相连,只被零时长标记切断,所以 grace 一定认识 beam,允许耦合
242
245
  // 折叠成员不进全局时间列,autobeam 看不到它们,要手动调用且强制连接
243
246
  for (const run of composite.graceRuns) {
244
247
  if (run.length < 2)
245
248
  continue;
246
- ctx.addAttachment(createBeamLayoutAttachment([...run], false, this.grace.sourceSpan));
249
+ ctx.addAttachment(createBeamLayoutAttachment([...run], false, grace.sourceSpan));
247
250
  }
248
251
  return [composite];
249
252
  }
@@ -262,27 +265,39 @@ const HOOK_COMMANDS = [
262
265
  { op: "C", cx1: -0.01, cy1: 0.26, cx2: 0.14, cy2: 0.42, x: 0.29, y: 0.36 },
263
266
  ];
264
267
  const HOOK_WIDTH = 0.07;
265
- /** 倚音块底边到宿主顶边的视觉间隙;倚音线会探进这段空间指向宿主 */
268
+ /** 倚音块底边到宿主肩线的视觉间隙;倚音线会探进这段空间指向宿主 */
266
269
  const GRACE_RISE = 0.18;
267
- /** 倪音向宿主借时值的上限,防止宿主被偷光;只读 */
270
+ /** 倚音向宿主借时值的上限,防止宿主被偷光;只读 */
268
271
  const MAX_STEAL_RATIO = new Fraction(3, 4);
269
272
  /** 倚音复合体:宿主与倚音都折叠在这一个盒子里,对外只是一个可见事件 */
270
273
  export class GraceTemporal extends TemporalNodeBase {
271
274
  host;
275
+ /** 可见倚音按局部时间成列,同列成员分属不同声部 */
276
+ graceColumns;
277
+ /** graceColumns 按列展开 */
272
278
  graces;
273
- /** 承担节奏的倚音成员,按零时长标记切段;同段视觉上首尾相接,无条件连成一束减时线 */
279
+ /** 承担节奏的倚音成员,按声部与零时长标记切段;同段视觉上首尾相接,无条件连成一束减时线 */
274
280
  graceRuns;
275
281
  side;
282
+ /** 倚音子域的根轨:由宿主轨分出,不挂进它的分组,子域之外不可见 */
283
+ root;
284
+ /** 倚音内容里声明的附件,随子域排版 */
285
+ attachments;
286
+ /** 倚音内容的全部事件,含不可见的状态事件,按局部时间列展开 */
287
+ events;
288
+ /** 与 events 一一对应的局部起点,已随时值减半 */
289
+ starts;
276
290
  /** 成员相对本盒左上角的局部偏移,onPlaced 时同步为绝对坐标 */
277
291
  hostOffset = { x: 0, y: 0 };
278
292
  graceOffsets = [];
279
293
  /** 倚音线起点,同样是局部偏移 */
280
294
  hookOrigin = null;
281
- constructor(ast, host, graces, side) {
295
+ constructor(ast, host, columns, root, attachments, side) {
282
296
  super();
283
297
  this.ast = ast;
284
298
  this.host = host;
285
- this.graces = graces;
299
+ this.root = root;
300
+ this.attachments = attachments;
286
301
  this.side = side;
287
302
  this.T.copyFrom(host.T);
288
303
  this.mergeKey = host.mergeKey;
@@ -293,37 +308,54 @@ export class GraceTemporal extends TemporalNodeBase {
293
308
  host.addon = void 0;
294
309
  // 成员不进入全局 columns,对外由复合体代表:写在成员上的标签仍可做关系端点
295
310
  host.foldedInto = this;
296
- const runs = [];
297
- let run = [];
298
- for (const grace of graces) {
299
- grace.foldedInto = this;
300
- // 调号、速度这类零时长标记不承担节奏,还会在视觉上把倚音串切断
311
+ const graceColumns = [];
312
+ const events = [];
313
+ const starts = [];
314
+ for (const column of columns) {
315
+ // 倚音默认就是八分音符,局部时间整体减半;成员的 t 随后与宿主同步,所以局部起点另存
316
+ const start = column[0].t.clone().divPow2();
317
+ const visible = [];
318
+ for (const event of column) {
319
+ event.foldedInto = this;
320
+ events.push(event);
321
+ starts.push(start);
322
+ if (isVisualTemporalNode(event))
323
+ visible.push(event);
324
+ }
325
+ if (visible.length > 0)
326
+ graceColumns.push(visible);
327
+ }
328
+ this.graceColumns = graceColumns;
329
+ this.graces = graceColumns.flat();
330
+ this.events = events;
331
+ this.starts = starts;
332
+ const runs = new Map();
333
+ const graceRuns = [];
334
+ for (const grace of this.graces) {
335
+ // 调号、速度这类零时长标记不承担节奏,还会在视觉上把本声部的倚音串切断
301
336
  if (grace.T.isZero()) {
302
- if (run.length > 0)
303
- runs.push(run);
304
- run = [];
337
+ runs.delete(grace.track);
305
338
  continue;
306
339
  }
340
+ let run = runs.get(grace.track);
341
+ if (!run) {
342
+ runs.set(grace.track, run = []);
343
+ graceRuns.push(run);
344
+ }
307
345
  run.push(grace);
308
- // 倚音默认就是八分音符:补一条减时线,书面时值随之减半
346
+ // 补一条减时线,书面时值随之减半
309
347
  const addon = grace.addon = { ...grace.addon };
310
348
  addon[DIV_ADDON_KEY] = (Number(addon[DIV_ADDON_KEY]) || 0) + 1;
311
349
  grace.T.divPow2();
312
350
  }
313
- if (run.length > 0)
314
- runs.push(run);
315
- this.graceRuns = runs;
351
+ this.graceRuns = graceRuns;
316
352
  }
317
353
  /** 成员共享全局时间状态,按发声顺序固化 */
318
354
  onTimeState(state) {
319
355
  // 同步时间的修改。比如tuplet修改的是GraceTemporal.T,这里要把它传给成员
320
356
  this.host.T.copyFrom(this.T);
321
- const members = this.side === "pre"
322
- ? [...this.graces, this.host]
323
- : [this.host, ...this.graces];
324
- for (const member of members) {
357
+ for (const member of this.side === "pre" ? [...this.events, this.host] : [this.host, ...this.events]) {
325
358
  member.t.copyFrom(this.t);
326
- member.track = this.track;
327
359
  member.layoutLine = this.layoutLine;
328
360
  member.onTimeState?.(state);
329
361
  }
@@ -331,43 +363,37 @@ export class GraceTemporal extends TemporalNodeBase {
331
363
  /**
332
364
  * 播放时倚音从宿主借走的时值(前倚音从开头、后倚音从末尾)
333
365
  *
334
- * 比例 = 倚音字面总时值 / 四分音符,而四分音符 T=1,所以直接累加成员的 T。
366
+ * 比例 = 倚音块字面时长 / 四分音符,而四分音符 T=1,所以直接取各声部最晚的局部终点。
335
367
  * 基准取宿主经过 div 与 dot 后的实际时值;延时线是独立事件、tie 不改 T,天然不计入。
368
+ * 局部时间按同一比例映射进借走的时值,各声部因此同时起奏。
336
369
  */
337
370
  emitPlayback(emitter) {
338
371
  const written = new Fraction();
339
- for (const grace of this.graces)
340
- written.add(grace.T);
372
+ const end = new Fraction();
373
+ this.events.forEach((event, index) => {
374
+ end.copyFrom(this.starts[index]).add(event.T);
375
+ if (end.compare(written) > 0)
376
+ written.copyFrom(end);
377
+ });
341
378
  const ratio = written.compare(MAX_STEAL_RATIO) > 0 ? MAX_STEAL_RATIO : written;
342
379
  const total = emitter.end.clone().sub(emitter.start);
343
380
  const steal = total.clone().mul(ratio);
344
381
  const hostDuration = total.sub(steal);
345
- const start = emitter.start.clone();
346
- const playGraces = (cursor) => {
347
- for (const grace of this.graces) {
348
- if (grace.T.isZero() || written.isZero()) {
349
- emitter.play(grace, cursor, new Fraction());
350
- continue;
351
- }
352
- const duration = steal.clone().mul(grace.T).div(written);
353
- emitter.play(grace, cursor, duration);
354
- cursor.add(duration);
355
- }
356
- };
357
- if (this.side === "pre") {
358
- const cursor = start.clone();
359
- playGraces(cursor);
360
- emitter.play(this.host, cursor, hostDuration);
361
- }
362
- else {
363
- emitter.play(this.host, start, hostDuration);
364
- playGraces(start.clone().add(hostDuration));
365
- }
382
+ // 全是零时长标记时块长为 0,成员都落在借时起点
383
+ const scale = written.isZero() ? new Fraction() : steal.clone().div(written);
384
+ const base = this.side === "pre" ? emitter.start.clone() : emitter.start.clone().add(hostDuration);
385
+ if (this.side === "post")
386
+ emitter.play(this.host, emitter.start.clone(), hostDuration);
387
+ this.events.forEach((event, index) => {
388
+ emitter.play(event, this.starts[index].clone().mul(scale).add(base), event.T.clone().mul(scale));
389
+ });
390
+ if (this.side === "pre")
391
+ emitter.play(this.host, base.add(steal), hostDuration);
366
392
  }
367
393
  /**
368
394
  * 宿主留在轨道基线上,倚音整体抬到它的左上或右上角
369
395
  *
370
- * 倚音成员之间自己紧排,不参与横向弹簧;整块的宽度计入复合盒,
396
+ * 倚音内容作为子域先排成一个刚性块,块内的附件同时就位;含约束留白的宽度计入复合盒,
371
397
  * 因此左右邻居会被固有宽度推开,不会在空间紧张时被压穿。
372
398
  */
373
399
  prepareLayout(context) {
@@ -377,44 +403,26 @@ export class GraceTemporal extends TemporalNodeBase {
377
403
  this.host.addon = this.addon;
378
404
  this.addon = void 0;
379
405
  }
380
- for (const grace of this.graces)
381
- prepareLayoutHost(grace, context);
382
- prepareLayoutHost(this.host, context);
383
- const em = this.ast.size;
384
- const graceEm = em * GRACE_SCALE;
385
- const memberGap = graceEm * 0.16;
406
+ const block = context.layoutSubdomain(this, this.graceColumns, this.root, this.attachments);
407
+ const hostWidth = layoutLocalSequence([this.host], context);
408
+ const graceEm = this.ast.size * GRACE_SCALE;
386
409
  const sideGap = graceEm * 0.2;
387
410
  const rise = graceEm * GRACE_RISE;
388
- let graceWidth = 0;
389
- let graceAxis = 0;
390
- let graceHeight = 0;
391
- // 倚音之间按视觉轴对齐,否则带下八度点的成员会把数字顶得比旁边高
392
- for (const grace of this.graces)
393
- graceAxis = Math.max(graceAxis, grace.box.visualAxis);
394
- this.graceOffsets = this.graces.map(grace => {
395
- const x = graceWidth;
396
- graceWidth += grace.box.w + memberGap;
397
- const y = graceAxis - grace.box.visualAxis;
398
- graceHeight = Math.max(graceHeight, y + grace.box.h);
399
- return { x, y };
400
- });
401
- if (this.graces.length > 0)
402
- graceWidth -= memberGap;
403
411
  // 倚音贴着宿主的肩线而不是宿主盒顶:宿主本身也是复合体时,
404
412
  // 肩线由它转发上来,所以两侧倚音会落在同一高度而不是层层叠高
405
413
  const shoulder = this.host.ports[SHOULDER_PORT]?.y ?? 0;
406
- const graceTop = shoulder - rise - graceHeight;
414
+ const graceTop = shoulder - rise - block.height;
407
415
  const lift = Math.max(0, -graceTop);
408
- const graceX = this.side === "pre" ? 0 : this.host.box.w + sideGap;
416
+ const graceX = this.side === "pre" ? 0 : hostWidth + sideGap;
409
417
  this.hostOffset = {
410
- x: this.side === "pre" ? graceWidth + sideGap : 0,
418
+ x: this.host.box.x + (this.side === "pre" ? block.width + sideGap : 0),
411
419
  y: lift,
412
420
  };
413
- for (const offset of this.graceOffsets) {
414
- offset.x += graceX;
415
- offset.y += graceTop + lift;
416
- }
417
- this.box.w = this.host.box.w + sideGap + graceWidth;
421
+ this.graceOffsets = block.positions.map(position => ({
422
+ x: graceX + position.x,
423
+ y: graceTop + lift + position.y,
424
+ }));
425
+ this.box.w = hostWidth + sideGap + block.width;
418
426
  this.box.h = lift + this.host.box.h;
419
427
  this.box.anchor = this.hostOffset.x + this.host.box.anchor;
420
428
  this.box.visualAxis = lift + this.host.box.visualAxis;
@@ -422,19 +430,19 @@ export class GraceTemporal extends TemporalNodeBase {
422
430
  for (const name in this.host.ports) {
423
431
  const port = this.host.ports[name];
424
432
  this.ports[name] = {
433
+ ...port,
425
434
  x: this.hostOffset.x + port.x,
426
435
  y: this.hostOffset.y + port.y,
427
436
  };
428
437
  }
429
438
  // 宿主没有肩线时它自己的盒顶就是肩线;有则上面那轮转发已经带偏移抬好了
430
439
  this.ports[SHOULDER_PORT] ??= { x: this.box.anchor, y: this.hostOffset.y };
431
- // 钩形曲线挂在靠近宿主的那个倚音成员下方,零时长标记不承接它
432
- const near = this.side === "pre"
433
- ? this.graceRuns.at(-1)?.at(-1)
434
- : this.graceRuns[0]?.[0];
440
+ // 钩形曲线挂在靠近宿主的那个倚音成员下方,零时长标记不承接它;高度取成员的最低下沿,不含块内附件
441
+ const rhythmic = this.graces.filter(grace => !grace.T.isZero());
442
+ const near = this.side === "pre" ? rhythmic.at(-1) : rhythmic[0];
435
443
  this.hookOrigin = near ? {
436
444
  x: this.graceOffsets[this.graces.indexOf(near)].x + near.box.anchor,
437
- y: graceTop + lift + graceHeight,
445
+ y: Math.max(...this.graces.map((grace, index) => this.graceOffsets[index].y + grace.box.h)),
438
446
  } : null;
439
447
  }
440
448
  /** 引擎每次改变本节点坐标后,按准备阶段保存的局部偏移重算成员绝对坐标 */
@@ -17,7 +17,7 @@ function normalizeTonality(tonality) {
17
17
  }
18
18
  catch { /* 落到下面归一化 */ }
19
19
  const parsed = parseNoteName(tonality.replace(/^[a-g]/, letter => letter.toUpperCase()));
20
- if (parsed instanceof Diagnostic)
20
+ if (parsed instanceof Diagnostic || parsed.next !== tonality.length)
21
21
  return null;
22
22
  const pitchClass = NoteNameMap[parsed.name];
23
23
  if (pitchClass === undefined)
@@ -87,9 +87,22 @@ class MeterFunction extends ASTFunctionNode {
87
87
  }
88
88
  measureStart.copyFrom(end);
89
89
  };
90
+ const metersByHost = new Map();
91
+ for (const nodes of result.astToTemporal.values()) {
92
+ for (const node of nodes) {
93
+ if (!(node instanceof MeterTemporal))
94
+ continue;
95
+ let host = node;
96
+ while (host.foldedInto)
97
+ host = host.foldedInto;
98
+ if (!metersByHost.has(host))
99
+ metersByHost.set(host, node);
100
+ }
101
+ }
90
102
  for (const column of result.columns) {
91
103
  const time = column[0].t;
92
- const meter = column.find(node => node instanceof MeterTemporal);
104
+ const host = column.find(node => metersByHost.has(node));
105
+ const meter = host && metersByHost.get(host);
93
106
  if (meter) {
94
107
  closeMeasure(time, meter.ast.sourceSpan.start);
95
108
  active = meter.ast;
@@ -1,2 +1,7 @@
1
- import { ASTFunctionClass } from "../ASTtypes.js";
1
+ import { SourceSpan, ASTFunctionClass } from "../ASTtypes.js";
2
+ import type { LoweringResult } from "../../lowering/types.js";
3
+ import { type NoteTransform, type SourceEdit } from "./source-transform.js";
4
+ export type { NoteTransform, SourceEdit } from "./source-transform.js";
5
+ /** 根据同一源码的 lowering 生成局部修改;传入 ranges 时只处理完整落入任一选区的音符 */
6
+ export declare function transformNotes(source: string, lowering: LoweringResult, operation: NoteTransform, ranges?: readonly SourceSpan[]): SourceEdit[];
2
7
  export declare const NoteNode: ASTFunctionClass;
@@ -2,6 +2,19 @@ import { ASTTextNode, ASTFunctionNode } from "../ASTtypes.js";
2
2
  import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
3
3
  import { parseNoteName } from "./noteNameFSM.js";
4
4
  import { paintAccidental, placeAccidentals } from "./accidentals.js";
5
+ import { rewriteNotes } from "./source-transform.js";
6
+ /** 根据同一源码的 lowering 生成局部修改;传入 ranges 时只处理完整落入任一选区的音符 */
7
+ export function transformNotes(source, lowering, operation, ranges) {
8
+ const error = lowering.diagnostics.find(item => item instanceof ErrorDiagnostic);
9
+ if (error)
10
+ throw error;
11
+ const notes = [...lowering.astToTemporal.values()].flat()
12
+ .filter((node) => node instanceof NoteTemporalNode);
13
+ const invalid = lowering.diagnostics.find(item => notes.some(note => item.span.start < note.ast.sourceSpan.end && item.span.end > note.ast.sourceSpan.start));
14
+ if (invalid)
15
+ throw invalid;
16
+ return rewriteNotes(source, notes, operation, ranges);
17
+ }
5
18
  const JE_OCTAVE_OFFSET = "note.jeOctaveOffset";
6
19
  class NoteFunction extends ASTFunctionNode {
7
20
  static def = {
@@ -12,8 +25,9 @@ class NoteFunction extends ASTFunctionNode {
12
25
  @note(A, acc=#, octave=3, color=#c33)
13
26
  ~~~
14
27
  **简写**:数字音名按“升降号、音名、相对八度”书写;字母音名按“音名、升降号、绝对八度”书写。\`1,,\` 比当前调性基准低两个八度,\`1'\` 高一个八度。
15
- - \`A#3\` 等价于 \`@note(A#3)\` 或 \`@note(A, #, 3)\`
16
- - \`#1'\` 等价于 \`@note("#1'")\` 或 \`@note(1, #, 1)\`
28
+ - 简写的升降号完全由自身决定,省略时为空,不继承 \`@set(note.acc=...)\`;显式调用省略 \`acc\` 时仍继承默认值
29
+ - \`A#3\` 等价于 \`@note(A, #, 3)\`,默认 \`acc\` 为空时也等价于 \`@note(A#3)\`
30
+ - \`#1'\` 等价于 \`@note(1, #, 1)\`,默认 \`acc\` 为空时也等价于 \`@note("#1'")\`
17
31
  - 支持组合升降号,如 \`A##bn99\`;无歧义时也接受后置写法,如 \`A3#\`、\`6#,,\`
18
32
  - 升降号后紧跟数字时归入下一音符:\`6#3\` 解析为 \`6\` 和 \`#3\``,
19
33
  allowExtraArgs: false,
@@ -75,8 +89,7 @@ class NoteFunction extends ASTFunctionNode {
75
89
  argMap.set("name", parseResult.name);
76
90
  if (parseResult.octave !== null)
77
91
  argMap.set("octave", parseResult.octave);
78
- if (parseResult.acc)
79
- argMap.set("acc", parseResult.acc);
92
+ argMap.set("acc", parseResult.acc ?? ""); // 必须覆盖不然会用到 set 的默认值
80
93
  const node = {
81
94
  kind: "call",
82
95
  typed: true,
@@ -110,8 +123,11 @@ class NoteFunction extends ASTFunctionNode {
110
123
  font;
111
124
  // JE 八度偏移量
112
125
  jeOctaveOffset;
126
+ // 源码改写时判断是否需要覆盖默认升降号
127
+ hasDefaultAcc;
113
128
  constructor(sourceSpan, args, ctx, parent = null) {
114
129
  super(sourceSpan, parent);
130
+ this.hasDefaultAcc = Boolean(ctx.variables["note.acc"]);
115
131
  [this.name, this.acc, this.octave, this.color] = this.getArgValue(args, ctx);
116
132
  this.font = ctx.variables.numberfont;
117
133
  this.size = ctx.variables.fontsize;
@@ -144,7 +160,7 @@ class NoteFunction extends ASTFunctionNode {
144
160
  this.acc = parseResult.acc + this.acc;
145
161
  }
146
162
  toString() {
147
- return `@n(${this.name}, ${this.acc}, ${this.octave}, ${this.color})`;
163
+ return `@n(${this.name}, ${this.acc || '""'}, ${this.octave}, ${this.color})`;
148
164
  }
149
165
  }
150
166
  export const NoteNode = NoteFunction;
@@ -155,6 +171,7 @@ const NOTE_GLYPH = { "8": "", "9": "X" };
155
171
  class NoteTemporalNode extends TemporalNodeBase {
156
172
  // 时间固化后的参数
157
173
  resolvedMidi = null; // MIDI音高 name是数字则需要在onTimeState中基于当前调性偏移 播放的音高
174
+ keySignature = "C4"; // 用于转调时记录大环境
158
175
  transposeDiatonic;
159
176
  name; // 数字
160
177
  acc; // 升降号
@@ -191,7 +208,7 @@ class NoteTemporalNode extends TemporalNodeBase {
191
208
  const { size, color } = this.ast;
192
209
  const mainMetrics = context.textMeasurer.measureText("0", this.numberStyle);
193
210
  const dotCount = Math.abs(this.octave);
194
- this.octaveDotRadius = size * 0.065;
211
+ this.octaveDotRadius = size * 0.075;
195
212
  const dotGap = size * 0.08;
196
213
  const dotStep = this.octaveDotRadius * 2 + dotGap;
197
214
  const octaveSpace = dotCount === 0
@@ -211,6 +228,7 @@ class NoteTemporalNode extends TemporalNodeBase {
211
228
  // 升降号和附点参与完整盒布局,但不计入数字主体范围,减时线因此只画在数字下
212
229
  this.ports["body.left"] = { x: this.box.anchor - mainMetrics.w / 2, y: this.box.visualAxis };
213
230
  this.ports["body.right"] = { x: this.box.anchor + mainMetrics.w / 2, y: this.box.visualAxis };
231
+ this.ports["shoulder"] = { x: this.box.anchor, y: mainY };
214
232
  // 覆盖 dot 的默认“右边界 + 视觉轴”,让附点贴合数字字形的视觉位置
215
233
  this.ports["dot"] = {
216
234
  x: this.box.w,
@@ -265,8 +283,9 @@ class NoteTemporalNode extends TemporalNodeBase {
265
283
  painter.drawCircle(this.box.x + this.box.anchor, this.box.y + y, this.octaveDotRadius, { fill: color });
266
284
  }
267
285
  }
286
+ /** 固化记谱位置的音高、力度和音色,并保留基于该调性的相对移调能力 */
268
287
  onTimeState(state) {
269
- const keySignature = state.keySignature;
288
+ const keySignature = this.keySignature = state.keySignature;
270
289
  this.playbackState = { bpm: state.bpm, velocity: state.velocity, program: state.program };
271
290
  this.resolvedMidi = resolveNoteMidi(this.name, this.acc, this.octave, keySignature);
272
291
  this.transposeDiatonic = createDiatonicTranspose(this.name, this.acc, this.octave, keySignature);
@@ -287,20 +306,24 @@ class NoteTemporalNode extends TemporalNodeBase {
287
306
  }
288
307
  }
289
308
  }
309
+ /** 发布完整音段或无声区间,实际 NoteOn/NoteOff 留到声音展开完成后生成 */
290
310
  emitPlayback(emitter) {
291
311
  const percussion = this.ast.name === "9";
292
312
  const midi = percussion ? 37 : this.resolvedMidi;
293
- if (midi === null || emitter.end.compare(emitter.start) <= 0)
313
+ if (emitter.end.compare(emitter.start) <= 0)
314
+ return;
315
+ // 休止符和占位符也要保留结构边界,速度效果与后续延长才能覆盖这段时间。
316
+ if (midi === null) {
317
+ emitter.span({ start: emitter.start, end: emitter.end });
294
318
  return;
295
- const noteId = emitter.nextNoteId();
296
- emitter.emit({
297
- kind: "note-on",
298
- at: emitter.start,
299
- noteId,
319
+ }
320
+ // 这里只提供发声属性;轨道、来源和最终音符身份由核心统一补齐。
321
+ emitter.note({
322
+ start: emitter.start,
323
+ end: emitter.end,
300
324
  midi,
301
325
  velocity: this.playbackState?.velocity ?? DEFAULT_VELOCITY,
302
326
  ...(percussion ? { percussion: true } : { transpose: this.transposeDiatonic }),
303
327
  });
304
- emitter.emit({ kind: "note-off", at: emitter.end, noteId });
305
328
  }
306
329
  }
@@ -0,0 +1,21 @@
1
+ import type { ASTNodeBase } from "../ASTtypes.js";
2
+ import type { SourceSpan } from "../../parser/types.js";
3
+ export type NoteTransform = "to-absolute" | "to-relative" | "semitone-up" | "semitone-down";
4
+ export interface SourceEdit {
5
+ span: SourceSpan;
6
+ text: string;
7
+ }
8
+ interface NoteSource {
9
+ ast: ASTNodeBase & {
10
+ name: string;
11
+ acc: string;
12
+ octave: number;
13
+ hasDefaultAcc: boolean;
14
+ jeOctaveOffset: number;
15
+ };
16
+ resolvedMidi: number | null;
17
+ keySignature: string;
18
+ }
19
+ /** edits 始终引用原文;参数只改值,默认参数只在当前调用覆盖,避免影响其他音符 */
20
+ export declare function rewriteNotes(source: string, notes: readonly NoteSource[], operation: NoteTransform, ranges?: readonly SourceSpan[]): SourceEdit[];
21
+ export {};