jpfun 0.6.0 → 0.8.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 (134) hide show
  1. package/Bravura-LICENSE.txt +93 -0
  2. package/README.md +49 -146
  3. package/dist/Bravura-LICENSE.txt +93 -0
  4. package/dist/converter/midi/convert.d.ts +3 -11
  5. package/dist/converter/midi/convert.js +89 -67
  6. package/dist/converter/musicxml/features.d.ts +34 -12
  7. package/dist/converter/musicxml/features.js +131 -24
  8. package/dist/converter/musicxml/index.js +221 -54
  9. package/dist/converter/musicxml/model.d.ts +24 -0
  10. package/dist/core.d.ts +1 -0
  11. package/dist/core.js +1 -0
  12. package/dist/diagnostic.d.ts +7 -1
  13. package/dist/diagnostic.js +40 -88
  14. package/dist/fraction.js +3 -2
  15. package/dist/functions/ASTtypes.d.ts +2 -18
  16. package/dist/functions/ASTtypes.js +0 -16
  17. package/dist/functions/arpeggio/index.js +17 -22
  18. package/dist/functions/arpeggio/shape.d.ts +1 -1
  19. package/dist/functions/arpeggio/shape.js +27 -21
  20. package/dist/functions/bar/index.d.ts +8 -0
  21. package/dist/functions/bar/index.js +139 -36
  22. package/dist/functions/beam/auto.d.ts +1 -2
  23. package/dist/functions/beam/auto.js +44 -27
  24. package/dist/functions/beam/index.js +2 -3
  25. package/dist/functions/beam/layout.d.ts +1 -1
  26. package/dist/functions/beam/layout.js +16 -24
  27. package/dist/functions/br/index.d.ts +34 -2
  28. package/dist/functions/br/index.js +8 -8
  29. package/dist/functions/dash/index.js +6 -6
  30. package/dist/functions/default.js +10 -5
  31. package/dist/functions/div/index.d.ts +1 -0
  32. package/dist/functions/div/index.js +8 -4
  33. package/dist/functions/dot/index.js +2 -2
  34. package/dist/functions/dyn/index.js +49 -31
  35. package/dist/functions/gliss/index.d.ts +2 -0
  36. package/dist/functions/gliss/index.js +202 -0
  37. package/dist/functions/grace/index.d.ts +1 -7
  38. package/dist/functions/grace/index.js +11 -19
  39. package/dist/functions/head/index.js +41 -60
  40. package/dist/functions/key/index.js +8 -10
  41. package/dist/functions/meter/index.d.ts +56 -1
  42. package/dist/functions/meter/index.js +30 -24
  43. package/dist/functions/note/accidentals.js +10 -16
  44. package/dist/functions/note/index.js +18 -8
  45. package/dist/functions/note/noteName.d.ts +16 -0
  46. package/dist/functions/note/noteName.js +88 -0
  47. package/dist/functions/note/source-transform.js +6 -5
  48. package/dist/functions/ottava/index.d.ts +2 -0
  49. package/dist/functions/ottava/index.js +233 -0
  50. package/dist/functions/page/index.d.ts +1 -0
  51. package/dist/functions/page/index.js +22 -13
  52. package/dist/functions/pagebreak/index.d.ts +2 -0
  53. package/dist/functions/pagebreak/index.js +36 -0
  54. package/dist/functions/rest/index.js +15 -15
  55. package/dist/functions/set/index.js +4 -4
  56. package/dist/functions/slide/index.d.ts +2 -0
  57. package/dist/functions/slide/index.js +132 -0
  58. package/dist/functions/stack/index.js +8 -15
  59. package/dist/functions/symbol/index.d.ts +30 -2
  60. package/dist/functions/symbol/index.js +93 -19
  61. package/dist/functions/symbol/ornament.d.ts +1 -2
  62. package/dist/functions/symbol/ornament.js +14 -19
  63. package/dist/functions/symbol/shape.d.ts +6 -0
  64. package/dist/functions/symbol/shape.js +20 -4
  65. package/dist/functions/symbol/symbols/coda.d.ts +4 -0
  66. package/dist/functions/symbol/symbols/coda.js +56 -0
  67. package/dist/functions/symbol/symbols/dynamics.d.ts +1 -1
  68. package/dist/functions/symbol/symbols/dynamics.js +18 -8
  69. package/dist/functions/symbol/symbols/fine.js +1 -1
  70. package/dist/functions/symbol/symbols/harmonic.d.ts +2 -0
  71. package/dist/functions/symbol/symbols/harmonic.js +11 -0
  72. package/dist/functions/symbol/symbols/marcato.d.ts +2 -0
  73. package/dist/functions/symbol/symbols/marcato.js +22 -0
  74. package/dist/functions/symbol/symbols/staccato.d.ts +2 -0
  75. package/dist/functions/symbol/symbols/staccato.js +24 -0
  76. package/dist/functions/symbol/symbols/tenuto.d.ts +2 -0
  77. package/dist/functions/symbol/symbols/tenuto.js +11 -0
  78. package/dist/functions/symbol/symbols/tocoda.d.ts +2 -0
  79. package/dist/functions/symbol/symbols/tocoda.js +16 -0
  80. package/dist/functions/symbol/symbols/tr.js +46 -1
  81. package/dist/functions/symbol/symbols/turn.d.ts +3 -0
  82. package/dist/functions/symbol/symbols/turn.js +50 -0
  83. package/dist/functions/symbol/symbols/wheel.d.ts +2 -0
  84. package/dist/functions/symbol/symbols/wheel.js +36 -0
  85. package/dist/functions/temporal.d.ts +17 -6
  86. package/dist/functions/temporal.js +17 -6
  87. package/dist/functions/text/index.js +15 -6
  88. package/dist/functions/tie/index.js +64 -30
  89. package/dist/functions/tremolo/index.d.ts +2 -0
  90. package/dist/functions/tremolo/index.js +319 -0
  91. package/dist/functions/tuplet/index.js +4 -8
  92. package/dist/functions/up/index.js +7 -9
  93. package/dist/functions/voice/connections.js +7 -5
  94. package/dist/functions/voice/index.js +19 -11
  95. package/dist/functions/volta/index.js +41 -21
  96. package/dist/jpfun.core.min.js +64 -80
  97. package/dist/jpfun.from-midi.min.js +5 -5
  98. package/dist/jpfun.from-musicxml.min.js +8 -8
  99. package/dist/jpfun.min.js +69 -85
  100. package/dist/layout/default.d.ts +0 -1
  101. package/dist/layout/default.js +0 -1
  102. package/dist/layout/engine.d.ts +1 -0
  103. package/dist/layout/engine.js +42 -11
  104. package/dist/layout/page.d.ts +3 -2
  105. package/dist/layout/page.js +6 -5
  106. package/dist/layout/types.d.ts +4 -0
  107. package/dist/lowering/loweringContext.d.ts +11 -13
  108. package/dist/lowering/loweringContext.js +30 -197
  109. package/dist/lowering/types.d.ts +1 -3
  110. package/dist/parser/parse-utils/note-utils.d.ts +1 -1
  111. package/dist/parser/parse-utils/note-utils.js +8 -9
  112. package/dist/parser/parse-utils/string-utils.d.ts +3 -2
  113. package/dist/parser/parse-utils/string-utils.js +16 -3
  114. package/dist/parser/parserContext.d.ts +2 -0
  115. package/dist/parser/parserContext.js +36 -8
  116. package/dist/pipeline.js +0 -1
  117. package/dist/playback/compile.js +131 -72
  118. package/dist/playback/event.d.ts +1 -1
  119. package/dist/playback/event.js +9 -9
  120. package/dist/playback/time.js +42 -31
  121. package/dist/playback/types.d.ts +7 -3
  122. package/dist/render/canvas.d.ts +2 -0
  123. package/dist/render/canvas.js +25 -22
  124. package/dist/render/recording.js +1 -4
  125. package/dist/render/svg.js +1 -0
  126. package/dist/render/text.d.ts +1 -1
  127. package/dist/render/text.js +3 -2
  128. package/dist/render/translate.d.ts +0 -1
  129. package/dist/render/translate.js +6 -23
  130. package/dist/render/types.d.ts +1 -0
  131. package/grammar.md +52 -25
  132. package/package.json +3 -3
  133. package/dist/functions/note/noteNameFSM.d.ts +0 -8
  134. package/dist/functions/note/noteNameFSM.js +0 -181
@@ -4,7 +4,6 @@ import type { LayoutPrepareContext } from "./types.js";
4
4
  /**
5
5
  * 从函数类声明创建排版上下文
6
6
  *
7
- * 与 LoweringContext.registerFunctions 使用相同的注册思想
8
7
  * 新增装饰函数只修改自己的类,不修改 layout 引擎
9
8
  */
10
9
  export declare function createLayoutPrepareContext(functionClasses: Iterable<ASTFunctionClass>, options?: {
@@ -3,7 +3,6 @@ import { defaultTextMeasurer } from "../render/text.js";
3
3
  /**
4
4
  * 从函数类声明创建排版上下文
5
5
  *
6
- * 与 LoweringContext.registerFunctions 使用相同的注册思想
7
6
  * 新增装饰函数只修改自己的类,不修改 layout 引擎
8
7
  */
9
8
  export function createLayoutPrepareContext(functionClasses, options = {}) {
@@ -6,6 +6,7 @@ import { type DocumentLayoutPage } from "./page.js";
6
6
  import type { HorizontalLineView, LayoutHost, LayoutPrepareContext, PlacedAttachment, Rect } from "./types.js";
7
7
  export interface DocumentLayoutOptions extends SolverOptions {
8
8
  rowGap?: number;
9
+ horizontalOnly?: boolean;
9
10
  }
10
11
  export { PageLayoutError } from "./page.js";
11
12
  export type { DocumentLayoutPage } from "./page.js";
@@ -134,7 +134,7 @@ export function layoutDocument(result, context, options = {}) {
134
134
  },
135
135
  };
136
136
  // 1. 按 layoutLine 切行,并生成固有尺寸与装饰尺寸
137
- const lines = splitLayoutLines(result);
137
+ const { lines, pageBreaks } = splitLayoutLines(result);
138
138
  const objects = [];
139
139
  for (const line of lines) {
140
140
  for (const column of line.columns) {
@@ -157,6 +157,17 @@ export function layoutDocument(result, context, options = {}) {
157
157
  node.box.x += originX;
158
158
  }
159
159
  }
160
+ // midi 导入进行自动断行的快通道
161
+ if (options.horizontalOnly) {
162
+ return {
163
+ diagnostics: result.diagnostics,
164
+ objects,
165
+ attachments: [],
166
+ bounds: { x: 0, y: 0, w: 0, h: 0 },
167
+ lineCount: lines.length,
168
+ pages: [],
169
+ };
170
+ }
160
171
  // host 申报纵向占用
161
172
  // 主体占用只依赖固有尺寸,整个纵向布局中保持不变
162
173
  for (const node of objects) {
@@ -176,7 +187,7 @@ export function layoutDocument(result, context, options = {}) {
176
187
  let pages;
177
188
  let lineTops;
178
189
  try {
179
- ({ pages, lineTops } = paginateLayoutLines(heights, page));
190
+ ({ pages, lineTops } = paginateLayoutLines(heights, page, pageBreaks));
180
191
  }
181
192
  catch (error) {
182
193
  if (!(error instanceof PageLayoutError))
@@ -315,6 +326,7 @@ function splitLayoutLines(result) {
315
326
  attachmentExtents: new Map(),
316
327
  });
317
328
  const lines = [];
329
+ const pageBreaks = [];
318
330
  let currentLine = createLine();
319
331
  for (const column of result.columns) {
320
332
  const visibleColumn = []; // 从列中提取可见元素
@@ -324,16 +336,20 @@ function splitLayoutLines(result) {
324
336
  currentLine = createLine();
325
337
  }
326
338
  for (const node of column) {
339
+ const pageBreak = node.addon?.pageBreakBefore;
340
+ if (pageBreak !== undefined) {
341
+ pageBreaks[lines.length] = (pageBreaks[lines.length] ?? true) && pageBreak;
342
+ }
327
343
  if (isVisualTemporalNode(node))
328
344
  visibleColumn.push(node);
329
345
  }
330
346
  if (visibleColumn.length)
331
347
  currentLine.columns.push(visibleColumn);
332
348
  }
333
- // 至少要有一行,哪怕它没有任何可见对象
334
- if (currentLine.columns.length > 0 || lines.length === 0)
349
+ // 至少保留一行;强制换页新开的尾页也不能因没有可见内容而丢弃
350
+ if (currentLine.columns.length > 0 || pageBreaks[lines.length] !== undefined || lines.length === 0)
335
351
  lines.push(currentLine);
336
- return lines;
352
+ return { lines, pageBreaks };
337
353
  }
338
354
  /** 把新的上下界原地并入已有纵向占用范围 */
339
355
  function includeExtent(extent, top, bottom) {
@@ -355,6 +371,7 @@ export function prepareHorizontalLine(columns, index, options = {}, compact = fa
355
371
  const hooks = [];
356
372
  const columnIndex = new Map();
357
373
  const trackRuns = new Map();
374
+ let trackIndex;
358
375
  for (let column = 0; column < columns.length; column++) {
359
376
  for (const node of columns[column]) {
360
377
  columnIndex.set(node, column);
@@ -371,6 +388,16 @@ export function prepareHorizontalLine(columns, index, options = {}, compact = fa
371
388
  columns,
372
389
  trackRuns,
373
390
  columnOf: host => columnIndex.get(host) ?? -1,
391
+ trackIndexOf(host) {
392
+ if (!trackIndex) {
393
+ trackIndex = new Map();
394
+ for (const run of trackRuns.values()) {
395
+ for (let i = 0; i < run.length; i++)
396
+ trackIndex.set(run[i], i);
397
+ }
398
+ }
399
+ return trackIndex.get(host) ?? -1;
400
+ },
374
401
  registerHorizontalLayoutHook(from, to, hook) {
375
402
  const start = columnIndex.get(from);
376
403
  const end = columnIndex.get(to);
@@ -611,11 +638,12 @@ function measureAttachmentPass(attachments, baseContext, lines, lift, measuredEl
611
638
  }
612
639
  return item;
613
640
  }
614
- function getRangeExtents(line, columns, track) {
641
+ function getExtents(line, range, track) {
615
642
  const view = baseContext.lines[line];
616
643
  const extents = track === undefined ? new Map() : undefined;
617
644
  let extent;
618
- if (!view)
645
+ const horizontal = range && "left" in range ? range : undefined;
646
+ if (!view || (horizontal && horizontal.left >= horizontal.right))
619
647
  return extents;
620
648
  const include = (owner, top, bottom) => {
621
649
  if (extents)
@@ -626,14 +654,16 @@ function measureAttachmentPass(attachments, baseContext, lines, lift, measuredEl
626
654
  extent = { top, bottom };
627
655
  };
628
656
  // 主体和附件共用范围筛选,仅累加结果的容器随查询模式变化。
629
- const { start, end, wholeLine } = resolveRange(view, columns, track, lift);
657
+ const { start, end, wholeLine } = resolveRange(view, range && !("left" in range) ? range : undefined, track, lift);
630
658
  const target = track && lift(track);
631
- let left = wholeLine ? baseContext.originX : Infinity;
632
- let right = wholeLine ? baseContext.originX + baseContext.width : -Infinity;
659
+ let left = horizontal?.left ?? (wholeLine ? baseContext.originX : Infinity);
660
+ let right = horizontal?.right ?? (wholeLine ? baseContext.originX + baseContext.width : -Infinity);
633
661
  for (let column = start; column <= end; column++) {
634
662
  for (const host of view.columns[column]) {
635
663
  if (target && host.track !== target)
636
664
  continue;
665
+ if (horizontal && (host.box.x + host.box.w <= left || host.box.x >= right))
666
+ continue;
637
667
  if (!wholeLine) {
638
668
  if (host.box.x < left)
639
669
  left = host.box.x;
@@ -657,7 +687,8 @@ function measureAttachmentPass(attachments, baseContext, lines, lift, measuredEl
657
687
  }
658
688
  const context = {
659
689
  ...baseContext,
660
- getRangeExtents,
690
+ getRangeExtents: getExtents,
691
+ getHorizontalExtents: (line, left, right) => getExtents(line, { left, right }),
661
692
  getAttachmentOccupancy(dependency) {
662
693
  const geometry = resolveAttachment(dependency)?.geometry;
663
694
  return geometry && (geometry.occupancy ?? geometry.regions);
@@ -19,9 +19,10 @@ export declare const DEFAULT_PAGE_CONFIG: Readonly<PageConfig>;
19
19
  */
20
20
  export declare function normalizePageConfig(source?: Partial<PageConfig>): PageConfig;
21
21
  /**
22
- * 把已经测好自然高度的谱面行分页,并给出每行的全局顶部坐标
22
+ * 把已经测好自然高度的谱面行分页,并给出每行的全局顶部坐标。
23
+ * pageBreaks 按行号索引:undefined 不强制换页,true/false 强制换页并指定上一页是否拉伸。
23
24
  */
24
- export declare function paginateLayoutLines(heights: readonly number[], page: PageConfig): {
25
+ export declare function paginateLayoutLines(heights: readonly number[], page: PageConfig, pageBreaks?: readonly (boolean | undefined)[]): {
25
26
  pages: DocumentLayoutPage[];
26
27
  lineTops: number[];
27
28
  };
@@ -64,9 +64,10 @@ export function normalizePageConfig(source = {}) {
64
64
  return page;
65
65
  }
66
66
  /**
67
- * 把已经测好自然高度的谱面行分页,并给出每行的全局顶部坐标
67
+ * 把已经测好自然高度的谱面行分页,并给出每行的全局顶部坐标。
68
+ * pageBreaks 按行号索引:undefined 不强制换页,true/false 强制换页并指定上一页是否拉伸。
68
69
  */
69
- export function paginateLayoutLines(heights, page) {
70
+ export function paginateLayoutLines(heights, page, pageBreaks = []) {
70
71
  const availableHeight = page.height - page.marginTop - page.marginBottom;
71
72
  const pages = [];
72
73
  const lineTops = new Array(heights.length).fill(0);
@@ -111,9 +112,9 @@ export function paginateLayoutLines(heights, page) {
111
112
  if (Number.isFinite(page.height) && height > availableHeight + 1e-6) {
112
113
  throw new PageLayoutError(i, height, availableHeight);
113
114
  }
114
- // 当前行放不下时先封口已有内容;每页因此至少包含一行
115
- if (Number.isFinite(page.height) && i > start && used + page.lineGap + height > availableHeight + 1e-6) {
116
- closePage(i, true);
115
+ // 强制边界与自然溢出统一封页;无限页高不分配余白
116
+ if (i > start && (pageBreaks[i] !== undefined || Number.isFinite(page.height) && used + page.lineGap + height > availableHeight + 1e-6)) {
117
+ closePage(i, Number.isFinite(page.height) && (pageBreaks[i] ?? true));
117
118
  }
118
119
  used += (i > start ? page.lineGap : 0) + height;
119
120
  contentHeight += height;
@@ -111,6 +111,8 @@ export interface AttachmentLayoutContext extends LayoutPrepareContext {
111
111
  */
112
112
  getRangeExtents(line: number, columns?: LayoutRange): ReadonlyMap<Track, Readonly<Extent>>;
113
113
  getRangeExtents(line: number, columns: LayoutRange | undefined, track: Track): Readonly<Extent> | undefined;
114
+ /** 按全局 x 区间筛选横向相交的主体及已测附件,返回各轨轴局部占用;空区间返回空 Map */
115
+ getHorizontalExtents(line: number, left: number, right: number): ReadonlyMap<Track, Readonly<Extent>>;
114
116
  /** 读取本轮已完成的 attachment 边界;分组在 endLoweringGroup 才注册,因而组内对象必然排在分组之前 */
115
117
  getAttachmentBox(attachment: LayoutAttachment): Readonly<Rect>;
116
118
  /** 读取已测附件的有效占用,保留显式空数组;尚未测量时返回 undefined */
@@ -156,6 +158,8 @@ export interface HorizontalLineView {
156
158
  readonly trackRuns: ReadonlyMap<Track, readonly LayoutHost[]>;
157
159
  /** 主体所在时间列下标;不在本行时返回 -1 */
158
160
  columnOf(host: LayoutHost): number;
161
+ /** 主体在所属 Track 可见序列中的下标;不在本行时返回 -1 */
162
+ trackIndexOf(host: LayoutHost): number;
159
163
  /** 注册横向布局 hook;同一行内按跨度从小到大执行 */
160
164
  registerHorizontalLayoutHook(from: LayoutHost, to: LayoutHost, hook: HorizontalLayoutHook): void;
161
165
  }
@@ -1,31 +1,28 @@
1
1
  import { Diagnostic } from "../diagnostic.js";
2
2
  import { Fraction } from "../fraction.js";
3
- import { ASTFunctionClass, ASTNodeBase } from "../functions/ASTtypes.js";
3
+ import { ASTNodeBase } from "../functions/ASTtypes.js";
4
4
  import type { PageConfig } from "../layout/types.js";
5
5
  import { TemporalNodeBase } from "../functions/temporal.js";
6
- import type { LoweringGroup, LoweringAttachment, LoweringResult } from "./types.js";
6
+ import type { LoweringFinalizer, LoweringGroup, LoweringAttachment, LoweringResult } from "./types.js";
7
7
  import { Track } from "./track.js";
8
8
  /**
9
9
  * 把 AST 展开并固化为时间列、attachment 和页面配置
10
10
  *
11
11
  * 标准用法:
12
12
  * 1. 创建 LoweringContext
13
- * 2. 调用 registerFunctions,传入与 parser 相同的函数类列表
14
- * 3. 调用 lowerDocument(root),得到 LoweringResult
15
- * 4. 把结果交给 layoutDocument
13
+ * 2. 调用 lowerDocument(root),得到 LoweringResult
14
+ * 3. 把结果交给 layoutDocument
16
15
  *
17
16
  * 大多数 AST 函数通过以下入口参与 lowering(按时间顺序):
18
17
  * - [hook] loweringEnter/loweringExit:进入或离开节点时生成 TemporalNode、管理作用域
19
18
  * - [API] LoweringContext.beginLoweringGroup/endLoweringGroup:通常在 enter/exit 中被调用,以栈方式观察当前子树产生的 TemporalNode 和 attachment
20
19
  * - [API] LoweringContext.addAttachment:注册不推进时间的附属对象;当前外层分组会收到该对象
20
+ * - [API] LoweringContext.deferFinalize:在 enter/exit 中按需登记本轮收尾回调,支持通过 order 指定执行优先级
21
21
  * - [config] timeFlowModel:声明子节点按 sequence 或 parallel 推进时间;parallel 还要声明音轨复用键与纵向排列策略
22
22
  * - [hook] Temporal.onTimeState:锚点归并后固化调性、速度等状态
23
- * - [hook] loweringAugment:最终列和 layoutLine 固化后扫描结果并生成要追加的 attachment
24
- * - [hook] loweringFinalize:所有派生 attachment 追加完成后,按注册顺序处理完整结果
25
23
  */
26
24
  export declare class LoweringContext {
27
- private loweringAugmenters;
28
- private loweringFinalizers;
25
+ private activeFinalizers;
29
26
  private cnt;
30
27
  private usedTracks;
31
28
  /** 不推进时间的附属对象 */
@@ -45,8 +42,6 @@ export declare class LoweringContext {
45
42
  /** 收集本轮 lowering 产生的诊断信息 */
46
43
  readonly diagnostics: Diagnostic[];
47
44
  constructor(diagnostics?: Diagnostic[]);
48
- /** 供外部调用: 初始化 hook */
49
- registerFunctions(functionClasses: ASTFunctionClass[]): void;
50
45
  /** 供 page 函数调用 */
51
46
  setPageConfig(page: PageConfig): void;
52
47
  /**
@@ -70,8 +65,10 @@ export declare class LoweringContext {
70
65
  * 嵌套分组按退出顺序注册,因此天然是由内向外计算边界
71
66
  */
72
67
  endLoweringGroup(owner: ASTNodeBase): LoweringGroup;
73
- /** 先统一生成派生 attachment,再按注册顺序执行最终处理 */
68
+ /** 按显式 order 升序执行本轮登记的收尾回调 */
74
69
  private postprocessResult;
70
+ /** 登记本轮需要执行的收尾回调;order 越小越先执行,默认 0 */
71
+ deferFinalize(finalize: LoweringFinalizer, order?: number): void;
75
72
  /**
76
73
  * 注册不推进时间的排版对象
77
74
  * 被 tie、beam、box 等函数使用
@@ -95,8 +92,9 @@ export declare class LoweringContext {
95
92
  * 递归展开一棵子树,得到它的时间列与结束时间
96
93
  * @param timeOffset 当前节点的时间偏移量(单位QN) 由父节点传入,会被原地修改
97
94
  * @param track 当前所在的纵向音轨
95
+ * @param columns 当前时间列数组,会被原地修改
98
96
  */
99
- trackedEvents(node: ASTNodeBase, timeOffset: Fraction, track: Track): TimeColumn[];
97
+ trackedEvents(node: ASTNodeBase, timeOffset: Fraction, track: Track, columns?: TimeColumn[]): TimeColumn[];
100
98
  /**
101
99
  * 将 hook 返回的事件规范化、加入索引与分组,再追加到时间列
102
100
  * 原地修改 timeOffset
@@ -7,22 +7,19 @@ import { Track } from "./track.js";
7
7
  *
8
8
  * 标准用法:
9
9
  * 1. 创建 LoweringContext
10
- * 2. 调用 registerFunctions,传入与 parser 相同的函数类列表
11
- * 3. 调用 lowerDocument(root),得到 LoweringResult
12
- * 4. 把结果交给 layoutDocument
10
+ * 2. 调用 lowerDocument(root),得到 LoweringResult
11
+ * 3. 把结果交给 layoutDocument
13
12
  *
14
13
  * 大多数 AST 函数通过以下入口参与 lowering(按时间顺序):
15
14
  * - [hook] loweringEnter/loweringExit:进入或离开节点时生成 TemporalNode、管理作用域
16
15
  * - [API] LoweringContext.beginLoweringGroup/endLoweringGroup:通常在 enter/exit 中被调用,以栈方式观察当前子树产生的 TemporalNode 和 attachment
17
16
  * - [API] LoweringContext.addAttachment:注册不推进时间的附属对象;当前外层分组会收到该对象
17
+ * - [API] LoweringContext.deferFinalize:在 enter/exit 中按需登记本轮收尾回调,支持通过 order 指定执行优先级
18
18
  * - [config] timeFlowModel:声明子节点按 sequence 或 parallel 推进时间;parallel 还要声明音轨复用键与纵向排列策略
19
19
  * - [hook] Temporal.onTimeState:锚点归并后固化调性、速度等状态
20
- * - [hook] loweringAugment:最终列和 layoutLine 固化后扫描结果并生成要追加的 attachment
21
- * - [hook] loweringFinalize:所有派生 attachment 追加完成后,按注册顺序处理完整结果
22
20
  */
23
21
  export class LoweringContext {
24
- loweringAugmenters = [];
25
- loweringFinalizers = [];
22
+ activeFinalizers = new Map();
26
23
  cnt = 0; // 生成唯一id的计数器
27
24
  usedTracks = new Set();
28
25
  /** 不推进时间的附属对象 */
@@ -44,17 +41,6 @@ export class LoweringContext {
44
41
  constructor(diagnostics = []) {
45
42
  this.diagnostics = diagnostics;
46
43
  }
47
- /** 供外部调用: 初始化 hook */
48
- registerFunctions(functionClasses) {
49
- const augmenters = this.loweringAugmenters = [];
50
- const finalizers = this.loweringFinalizers = [];
51
- for (const functionClass of functionClasses) {
52
- if (functionClass.loweringAugment)
53
- augmenters.push(functionClass.loweringAugment);
54
- if (functionClass.loweringFinalize)
55
- finalizers.push(functionClass.loweringFinalize);
56
- }
57
- }
58
44
  /** 供 page 函数调用 */
59
45
  setPageConfig(page) {
60
46
  this.page = page;
@@ -68,6 +54,7 @@ export class LoweringContext {
68
54
  lowerDocument(node) {
69
55
  this.cnt = 0;
70
56
  this.usedTracks.clear();
57
+ this.activeFinalizers.clear();
71
58
  this.attachments = [];
72
59
  this.page = void 0;
73
60
  this.astToTemporal = new Map();
@@ -96,8 +83,9 @@ export class LoweringContext {
96
83
  for (const column of columns) {
97
84
  let offset = 0;
98
85
  for (const node of column) {
99
- if (node.breakBefore > offset)
100
- offset = node.breakBefore;
86
+ const requested = node.addon?.breakBefore ?? 0;
87
+ if (requested > offset)
88
+ offset = requested;
101
89
  }
102
90
  line += offset;
103
91
  // 换行列本身归属于换行之后的那一行
@@ -121,6 +109,7 @@ export class LoweringContext {
121
109
  column.shiftTime(timeOffset);
122
110
  let insertion;
123
111
  for (const node of column) {
112
+ state.currentEvent = node;
124
113
  state.velocity = velocityOf(node.track);
125
114
  state.program = programOf(node.track);
126
115
  const offset = node.onTimeState?.(state);
@@ -176,22 +165,30 @@ export class LoweringContext {
176
165
  this.addAttachment(active.group.attachment);
177
166
  return active.group;
178
167
  }
179
- /** 先统一生成派生 attachment,再按注册顺序执行最终处理 */
168
+ /** 按显式 order 升序执行本轮登记的收尾回调 */
180
169
  postprocessResult(result) {
181
170
  if (this.activeLoweringGroups.length > 0)
182
171
  throw new Error("Lowering groups must be closed before post-processing");
183
- const additions = [];
184
- for (const augment of this.loweringAugmenters) {
185
- for (const attachment of augment(result))
186
- additions.push(attachment);
172
+ const size = this.activeFinalizers.size;
173
+ if (size === 0)
174
+ return result;
175
+ if (size === 1) {
176
+ this.activeFinalizers.keys().next().value(result);
177
+ return result;
187
178
  }
188
- for (const attachment of additions)
189
- this.addAttachment(attachment);
190
- // 进行校验或者其他动作
191
- for (const finalize of this.loweringFinalizers)
179
+ const scheduled = [...this.activeFinalizers.entries()]
180
+ .sort((left, right) => left[1] - right[1]);
181
+ for (const [finalize] of scheduled)
192
182
  finalize(result);
193
183
  return result;
194
184
  }
185
+ /** 登记本轮需要执行的收尾回调;order 越小越先执行,默认 0 */
186
+ deferFinalize(finalize, order = 0) {
187
+ const current = this.activeFinalizers.get(finalize);
188
+ if (current === undefined || order < current) {
189
+ this.activeFinalizers.set(finalize, order);
190
+ }
191
+ }
195
192
  /**
196
193
  * 注册不推进时间的排版对象
197
194
  * 被 tie、beam、box 等函数使用
@@ -239,9 +236,9 @@ export class LoweringContext {
239
236
  * 递归展开一棵子树,得到它的时间列与结束时间
240
237
  * @param timeOffset 当前节点的时间偏移量(单位QN) 由父节点传入,会被原地修改
241
238
  * @param track 当前所在的纵向音轨
239
+ * @param columns 当前时间列数组,会被原地修改
242
240
  */
243
- trackedEvents(node, timeOffset, track) {
244
- const columns = [];
241
+ trackedEvents(node, timeOffset, track, columns = []) {
245
242
  this.appendEvents(node.loweringEnter(this, track), node, timeOffset, track, columns);
246
243
  // 处理子元素
247
244
  const model = node.timeFlowModel(this);
@@ -250,8 +247,7 @@ export class LoweringContext {
250
247
  case "sequence":
251
248
  {
252
249
  for (const c of model.children) {
253
- for (const column of this.trackedEvents(c, timeOffset, track))
254
- columns.push(column);
250
+ this.trackedEvents(c, timeOffset, track, columns);
255
251
  }
256
252
  }
257
253
  break;
@@ -342,171 +338,8 @@ export class LoweringContext {
342
338
  if (l === 1)
343
339
  return tracks[0];
344
340
  const result = [];
345
- if (l === 2) {
346
- // 双轨特化:与下面的堆归并语义等价,改规则必须两边同时改
347
- const track0 = tracks[0], track1 = tracks[1];
348
- const l0 = track0.length, l1 = track1.length;
349
- let i = 0, j = 0;
350
- const idt = new Fraction(), jdt = new Fraction(); // 应用时间偏移一定要紧在 push 前
351
- let a = track0[0], b = track1[0];
352
- const t0 = a.t.clone(), t1 = b.t.clone();
353
- while (true) {
354
- if (a.mergeKey === ANCHOR_KEY) {
355
- // 等待b也遇到anchor
356
- if (b.mergeKey !== ANCHOR_KEY) {
357
- result.push(b);
358
- b = track1[++j];
359
- while (j < l1 && b.mergeKey !== ANCHOR_KEY) {
360
- if (!jdt.isZero())
361
- b.shiftTime(jdt);
362
- result.push(b);
363
- b = track1[++j];
364
- }
365
- if (b) {
366
- b.shiftTime(jdt);
367
- t1.copyFrom(b.t);
368
- }
369
- }
370
- if (j < l1) { // b 也是 anchor
371
- const maxT = t0.compare(t1) >= 0 ? t0 : t1;
372
- idt.add(maxT).sub(t0);
373
- jdt.add(maxT).sub(t1);
374
- a.push(...b);
375
- a.t = maxT;
376
- b = track1[++j];
377
- }
378
- result.push(a);
379
- a = track0[++i];
380
- // 准备下一个
381
- if (a) {
382
- a.shiftTime(idt);
383
- t0.copyFrom(a.t);
384
- }
385
- if (b) {
386
- b.shiftTime(jdt);
387
- t1.copyFrom(b.t);
388
- }
389
- if (!a || !b)
390
- break;
391
- }
392
- if (b.mergeKey === ANCHOR_KEY) {
393
- if (a.mergeKey !== ANCHOR_KEY) {
394
- result.push(a);
395
- a = track0[++i];
396
- while (i < l0 && a.mergeKey !== ANCHOR_KEY) {
397
- if (!idt.isZero())
398
- a.shiftTime(idt);
399
- result.push(a);
400
- a = track0[++i];
401
- }
402
- if (a) {
403
- a.shiftTime(idt);
404
- t0.copyFrom(a.t);
405
- }
406
- }
407
- if (i < l0) {
408
- const maxT = t0.compare(t1) >= 0 ? t0 : t1;
409
- idt.add(maxT).sub(t0);
410
- jdt.add(maxT).sub(t1);
411
- b.push(...a);
412
- b.t = maxT;
413
- a = track0[++i];
414
- }
415
- result.push(b);
416
- b = track1[++j];
417
- if (a) {
418
- a.shiftTime(idt);
419
- t0.copyFrom(a.t);
420
- }
421
- if (b) {
422
- b.shiftTime(jdt);
423
- t1.copyFrom(b.t);
424
- }
425
- if (!a || !b)
426
- break;
427
- }
428
- if (t0.equals(t1)) {
429
- if (a.mergeKey === b.mergeKey) {
430
- a.push(...b);
431
- result.push(a);
432
- a = track0[++i];
433
- b = track1[++j];
434
- if (a) {
435
- a.shiftTime(idt);
436
- t0.copyFrom(a.t);
437
- }
438
- if (b) {
439
- b.shiftTime(jdt);
440
- t1.copyFrom(b.t);
441
- }
442
- if (!a || !b)
443
- break;
444
- }
445
- else if (a.mergeKey < b.mergeKey) {
446
- result.push(a);
447
- a = track0[++i];
448
- if (a) {
449
- a.shiftTime(idt);
450
- t0.copyFrom(a.t);
451
- }
452
- else
453
- break;
454
- }
455
- else {
456
- result.push(b);
457
- b = track1[++j];
458
- if (b) {
459
- b.shiftTime(jdt);
460
- t1.copyFrom(b.t);
461
- }
462
- else
463
- break;
464
- }
465
- continue;
466
- }
467
- if (t0.compare(t1) < 0) {
468
- result.push(a);
469
- a = track0[++i];
470
- if (a) {
471
- a.shiftTime(idt);
472
- t0.copyFrom(a.t);
473
- continue;
474
- }
475
- else
476
- break;
477
- }
478
- if (t1.compare(t0) < 0) {
479
- result.push(b);
480
- b = track1[++j];
481
- if (b) {
482
- b.shiftTime(jdt);
483
- t1.copyFrom(b.t);
484
- continue;
485
- }
486
- else
487
- break;
488
- }
489
- }
490
- if (a)
491
- result.push(a);
492
- while (++i < l0) {
493
- a = track0[i];
494
- if (!idt.isZero())
495
- a.shiftTime(idt);
496
- result.push(a);
497
- }
498
- if (b)
499
- result.push(b);
500
- while (++j < l1) {
501
- b = track1[j];
502
- if (!jdt.isZero())
503
- b.shiftTime(jdt);
504
- result.push(b);
505
- }
506
- return result;
507
- }
508
341
  // 归并多个轨道
509
- const p = new Uint16Array(l); // 当前指向第几个
342
+ const p = new Uint32Array(l); // 当前指向第几个
510
343
  const dt = Array.from({ length: l }, () => new Fraction()); // 每个轨道的偏移量
511
344
  const anchorBuffer = [];
512
345
  const heap = new HeapSort(l); // 保证每个轨在堆里最多一个
@@ -14,9 +14,7 @@ export interface LoweringContent {
14
14
  nodes: TemporalNodeBase[];
15
15
  attachments: LoweringAttachment[];
16
16
  }
17
- /** 时间流固化后生成额外 attachment;读取统一追加前的结果,不直接修改结果 */
18
- export type LoweringAugmenter = (result: LoweringResult) => Iterable<LoweringAttachment>;
19
- /** 所有 augmenter 结果追加完成后的最终处理;按注册顺序执行,可修改完整结果或抛出语义错误 */
17
+ /** 收尾阶段回调;按显式 order 升序执行,可追加派生 attachment、修改结果或抛出语义错误 */
20
18
  export type LoweringFinalizer = (result: LoweringResult) => void;
21
19
  /**
22
20
  * lowering 的输出
@@ -7,7 +7,7 @@ export interface RelativeJianpuPitch {
7
7
  renderAcc: string;
8
8
  renderOctave: number;
9
9
  }
10
- export declare function tonality2Midi(tonality: string, defaultOctave: number): number;
10
+ export declare function tonality2Midi(tonality: string, defaultOctave?: number): number | null;
11
11
  export declare function acc2Offset(acc: string, ignoreNatural?: boolean, initOffset?: number): number;
12
12
  export declare function resolveNoteMidi(name: string, acc: string, octave: number, keySignature: string): number | null;
13
13
  /**