jpfun 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/README.md +69 -11
  2. package/dist/diagnostic.js +5 -2
  3. package/dist/fraction.d.ts +24 -0
  4. package/dist/fraction.js +132 -0
  5. package/dist/functions/ASTtypes.d.ts +24 -7
  6. package/dist/functions/ASTtypes.js +35 -16
  7. package/dist/functions/adjust/index.d.ts +2 -0
  8. package/dist/functions/adjust/index.js +193 -0
  9. package/dist/functions/bar/index.d.ts +8 -0
  10. package/dist/functions/bar/index.js +39 -10
  11. package/dist/functions/beam/auto.js +32 -15
  12. package/dist/functions/beam/index.js +10 -6
  13. package/dist/functions/beam/layout.d.ts +3 -2
  14. package/dist/functions/beam/layout.js +42 -64
  15. package/dist/functions/box/index.js +35 -34
  16. package/dist/functions/br/index.js +9 -7
  17. package/dist/functions/dash/index.js +33 -1
  18. package/dist/functions/default.js +14 -7
  19. package/dist/functions/div/index.d.ts +16 -0
  20. package/dist/functions/div/index.js +45 -17
  21. package/dist/functions/dot/index.js +11 -3
  22. package/dist/functions/grace/index.d.ts +8 -11
  23. package/dist/functions/grace/index.js +82 -76
  24. package/dist/functions/head/index.d.ts +2 -0
  25. package/dist/functions/head/index.js +492 -0
  26. package/dist/functions/key/index.js +97 -3
  27. package/dist/functions/meter/index.d.ts +2 -0
  28. package/dist/functions/meter/index.js +154 -0
  29. package/dist/functions/note/accidentals.d.ts +24 -3
  30. package/dist/functions/note/accidentals.js +31 -1
  31. package/dist/functions/note/index.js +45 -65
  32. package/dist/functions/page/index.d.ts +9 -2
  33. package/dist/functions/page/index.js +50 -4
  34. package/dist/functions/set/index.js +37 -29
  35. package/dist/functions/stack/index.js +26 -22
  36. package/dist/functions/symbol/index.d.ts +21 -0
  37. package/dist/functions/symbol/index.js +94 -0
  38. package/dist/functions/symbol/ornament.d.ts +15 -0
  39. package/dist/functions/symbol/ornament.js +73 -0
  40. package/dist/functions/symbol/shape.d.ts +22 -0
  41. package/dist/functions/symbol/shape.js +48 -0
  42. package/dist/functions/symbol/symbols/accent.d.ts +2 -0
  43. package/dist/functions/symbol/symbols/accent.js +24 -0
  44. package/dist/functions/symbol/symbols/f.d.ts +2 -0
  45. package/dist/functions/symbol/symbols/f.js +55 -0
  46. package/dist/functions/symbol/symbols/fermata.d.ts +2 -0
  47. package/dist/functions/symbol/symbols/fermata.js +24 -0
  48. package/dist/functions/symbol/symbols/mordent.d.ts +2 -0
  49. package/dist/functions/symbol/symbols/mordent.js +43 -0
  50. package/dist/functions/symbol/symbols/p.d.ts +2 -0
  51. package/dist/functions/symbol/symbols/p.js +61 -0
  52. package/dist/functions/symbol/symbols/tr.d.ts +2 -0
  53. package/dist/functions/symbol/symbols/tr.js +75 -0
  54. package/dist/functions/tempo/glyph.d.ts +12 -0
  55. package/dist/functions/tempo/glyph.js +30 -0
  56. package/dist/functions/tempo/index.js +53 -2
  57. package/dist/functions/text/index.js +76 -24
  58. package/dist/functions/tie/index.js +102 -127
  59. package/dist/functions/tuplet/index.d.ts +2 -0
  60. package/dist/functions/tuplet/index.js +211 -0
  61. package/dist/functions/up/index.d.ts +1 -0
  62. package/dist/functions/up/index.js +245 -171
  63. package/dist/functions/voice/index.js +86 -68
  64. package/dist/functions/volta/index.d.ts +2 -0
  65. package/dist/functions/volta/index.js +227 -0
  66. package/dist/index.d.ts +4 -0
  67. package/dist/index.js +4 -0
  68. package/dist/jpfun.min.js +143 -0
  69. package/dist/layout/engine.d.ts +4 -11
  70. package/dist/layout/engine.js +65 -59
  71. package/dist/layout/model.d.ts +8 -1
  72. package/dist/layout/model.js +16 -6
  73. package/dist/layout/path.d.ts +19 -0
  74. package/dist/layout/path.js +101 -0
  75. package/dist/layout/types.d.ts +51 -18
  76. package/dist/layout/types.js +3 -1
  77. package/dist/lowering/loweringContext.d.ts +18 -20
  78. package/dist/lowering/loweringContext.js +132 -94
  79. package/dist/lowering/track.d.ts +1 -1
  80. package/dist/lowering/track.js +1 -1
  81. package/dist/lowering/types.d.ts +49 -12
  82. package/dist/lowering/types.js +9 -3
  83. package/dist/parser/parse-utils/call-utils.d.ts +0 -2
  84. package/dist/parser/parse-utils/call-utils.js +0 -6
  85. package/dist/parser/parse-utils/note-utils.d.ts +8 -0
  86. package/dist/parser/parse-utils/note-utils.js +35 -13
  87. package/dist/parser/parse-utils/string-utils.d.ts +8 -0
  88. package/dist/parser/parse-utils/string-utils.js +20 -0
  89. package/dist/parser/parserContext.d.ts +8 -5
  90. package/dist/parser/parserContext.js +38 -33
  91. package/dist/parser/preprocess.js +17 -11
  92. package/dist/playback/compile.d.ts +18 -0
  93. package/dist/playback/compile.js +401 -0
  94. package/dist/playback/event.d.ts +91 -0
  95. package/dist/playback/event.js +87 -0
  96. package/dist/playback/time.d.ts +14 -0
  97. package/dist/playback/time.js +81 -0
  98. package/dist/playback/types.d.ts +128 -0
  99. package/dist/playback/types.js +3 -0
  100. package/dist/render/canvas.d.ts +4 -4
  101. package/dist/render/canvas.js +20 -5
  102. package/dist/render/index.d.ts +1 -0
  103. package/dist/render/index.js +1 -0
  104. package/dist/render/paint.d.ts +8 -0
  105. package/dist/render/paint.js +101 -0
  106. package/dist/render/svg.d.ts +3 -3
  107. package/dist/render/svg.js +10 -8
  108. package/dist/render/text.d.ts +17 -0
  109. package/dist/render/text.js +35 -0
  110. package/dist/render/types.d.ts +1 -1
  111. package/grammar.md +93 -10
  112. package/package.json +10 -6
@@ -2,6 +2,7 @@ import { Diagnostic } from "../diagnostic.js";
2
2
  import { isVisualTemporalNode, } from "../lowering/types.js";
3
3
  import { completeSpringConfig, layoutElement, layoutHorizontal, } from "./model.js";
4
4
  import { normalizePageConfig, paginateLayoutLines, PageLayoutError, } from "./page.js";
5
+ import { isLayoutAttachment } from "./types.js";
5
6
  // 兼容旧导入路径;布局入口会把正常页面溢出转换为 ErrorDiagnostic
6
7
  export { PageLayoutError } from "./page.js";
7
8
  /**
@@ -35,7 +36,8 @@ export function unionLayoutBoxes(target, boxes) {
35
36
  * box 的尺寸、命名端口及装饰几何都尚未生成。
36
37
  *
37
38
  * 执行后,box 的 x/y 仍只是局部初值;固有宽高、弹簧参数、端口和装饰均已对应本轮 context 冻结,可以进入横向求解。
38
- * ports 和 decorations 在本次 pass 中从空容器开始建立。
39
+ *
40
+ * ports 和 decorations 每轮从空容器重建,因此端口上的一次性标记(如 div 的 claimed)不会跨 pass 残留。
39
41
  *
40
42
  * 具有内部几何的复合节点(例如 up 的和弦成员)可以对自己的子对象调用同一个函数,
41
43
  * 从而保证子对象与顶层对象经过完全一致的准备流程。
@@ -64,6 +66,7 @@ export function prepareLayoutHost(node, context) {
64
66
  * 完成 lowering 结果的全部几何计算
65
67
  */
66
68
  export function layoutDocument(result, context, options = {}) {
69
+ const layoutAttachments = result.attachments.filter(isLayoutAttachment);
67
70
  const page = normalizePageConfig(result.page);
68
71
  const contentWidth = page.width - page.marginLeft - page.marginRight;
69
72
  const originX = page.marginLeft;
@@ -82,8 +85,8 @@ export function layoutDocument(result, context, options = {}) {
82
85
  const views = buildLineViews(lines, options.globalC);
83
86
  for (const object of objects)
84
87
  object.prepareHorizontal?.(views[object.layoutLine]);
85
- for (const attachment of result.attachments)
86
- attachment.prepareHorizontal?.(views);
88
+ for (const attachment of layoutAttachments)
89
+ attachment.prepareHorizontal?.(views, context);
87
90
  for (const line of lines) {
88
91
  const elements = line.columns.map(column => column.map(node => layoutElement(node.springConfig, node.box, node, options.globalC)));
89
92
  layoutHorizontal(elements, contentWidth, options, line.horizontalLayoutHooks);
@@ -141,6 +144,7 @@ export function layoutDocument(result, context, options = {}) {
141
144
  ...context,
142
145
  width: contentWidth,
143
146
  originX,
147
+ pages: pages.map(item => item.bounds),
144
148
  getVisualAxis: visualAxisOf,
145
149
  getHostExtent: (line, track) => lines[line]?.hostExtents.get(track),
146
150
  };
@@ -148,19 +152,22 @@ export function layoutDocument(result, context, options = {}) {
148
152
  };
149
153
  // 3. 首次纵向放置后测量 attachment;只有有效轨道占用扩张时才重新求解
150
154
  let placement = placeVertically();
151
- let needsRelayout = false;
152
- for (const attachment of result.attachments) {
153
- if (registerAttachmentRegions(attachment, attachment.layout?.(placement.attachmentContext), lines, placement.attachmentContext.getVisualAxis))
154
- needsRelayout = true;
155
- }
156
- if (needsRelayout) {
155
+ let measured = measureAttachments(layoutAttachments, placement.attachmentContext);
156
+ if (registerAttachmentOccupancy(measured, lines, placement.attachmentContext.getVisualAxis)) {
157
157
  placement = placeVertically();
158
- // 最终区域只更新绘制外接盒,不再累计没有后续消费者的轨道占用
159
- for (const attachment of result.attachments) {
160
- unionLayoutBoxes(attachment.box, attachment.layout?.(placement.attachmentContext) ?? []);
161
- }
158
+ measured = measureAttachments(layoutAttachments, placement.attachmentContext);
162
159
  }
163
160
  const pages = placement.pages;
161
+ const attachments = layoutAttachments.map((attachment, index) => {
162
+ const { geometry, box } = measured[index];
163
+ return {
164
+ box,
165
+ regions: geometry.regions,
166
+ layer: attachment.layer,
167
+ sourceSpan: attachment.sourceSpan,
168
+ paint(painter) { geometry.paint(painter); },
169
+ };
170
+ });
164
171
  const bounds = {
165
172
  x: 0, y: 0,
166
173
  w: 0, h: 0,
@@ -171,14 +178,14 @@ export function layoutDocument(result, context, options = {}) {
171
178
  yield pageResult.bounds;
172
179
  for (const node of objects)
173
180
  yield node.box;
174
- for (const attachment of result.attachments)
181
+ for (const attachment of attachments)
175
182
  yield attachment.box;
176
183
  }
177
184
  unionLayoutBoxes(bounds, layoutBoxes());
178
185
  return {
179
186
  diagnostics: result.diagnostics,
180
187
  objects,
181
- attachments: result.attachments,
188
+ attachments,
182
189
  bounds,
183
190
  lineCount: lines.length,
184
191
  pages,
@@ -254,7 +261,7 @@ function includeTrackExtent(extents, track, top, bottom) {
254
261
  */
255
262
  function buildLineViews(lines, force) {
256
263
  return lines.map((line, index) => {
257
- const columnIndex = new Map();
264
+ const columnIndex = new Map(); // 不考虑被折叠的。要查询的话需要从 foldedInto 追溯到宿主
258
265
  const trackRuns = new Map();
259
266
  for (let i = 0; i < line.columns.length; i++) {
260
267
  for (const node of line.columns[i]) {
@@ -269,6 +276,7 @@ function buildLineViews(lines, force) {
269
276
  }
270
277
  return {
271
278
  index,
279
+ columns: line.columns,
272
280
  trackRuns,
273
281
  columnOf: host => columnIndex.get(host) ?? -1,
274
282
  registerHorizontalLayoutHook(from, to, hook) {
@@ -303,53 +311,51 @@ function measureRowGaps(lineCount, objects, override) {
303
311
  return gaps;
304
312
  }
305
313
  /**
306
- * 把一个 attachment 首次报出的区域折算成外接盒与轨道占用
314
+ * 按 lowering 注册顺序原子生成本轮几何
307
315
  *
308
- * 只声明了矩形的区域仅影响画布边界;同时声明 line 与 track 才会撑开谱面行。
309
- * 返回值表示区域是否扩张了主体与先前区域的合并占用,因而需要最终重排。
316
+ * 分组的 attachment 总在组内对象之后注册,所以读取依赖不需要额外排序
310
317
  */
311
- function registerAttachmentRegions(attachment, regions, lines, visualAxisOf) {
312
- unionLayoutBoxes(attachment.box, regions ?? []);
313
- let expandedTrackOccupancy = false;
314
- for (const region of regions ?? []) {
315
- if (region.line === void 0 || !region.track)
316
- continue;
317
- const line = lines[region.line];
318
- if (!line)
319
- throw new Error(`Layout attachment referenced invalid line ${region.line}`);
320
- const axis = visualAxisOf(region.line, region.track);
321
- const top = region.y - axis;
322
- const bottom = region.y + region.h - axis;
323
- const hostExtent = line.hostExtents.get(region.track);
324
- const attachmentExtent = line.attachmentExtents.get(region.track);
325
- const previousTop = Math.min(hostExtent?.top ?? Infinity, attachmentExtent?.top ?? Infinity);
326
- const previousBottom = Math.max(hostExtent?.bottom ?? -Infinity, attachmentExtent?.bottom ?? -Infinity);
327
- if (top < previousTop || bottom > previousBottom)
328
- expandedTrackOccupancy = true;
329
- includeTrackExtent(line.attachmentExtents, region.track, top, bottom);
330
- }
331
- return expandedTrackOccupancy;
318
+ function measureAttachments(attachments, baseContext) {
319
+ const measured = new Map();
320
+ const context = {
321
+ ...baseContext,
322
+ getAttachmentBox(dependency) {
323
+ const resolved = measured.get(dependency);
324
+ if (!resolved)
325
+ throw new Error("Layout attachment dependency has not been measured");
326
+ return resolved.box;
327
+ },
328
+ };
329
+ return attachments.map(attachment => {
330
+ const geometry = attachment.createGeometry(context);
331
+ const box = { x: 0, y: 0, w: 0, h: 0 };
332
+ unionLayoutBoxes(box, geometry.regions);
333
+ const item = { geometry, box };
334
+ measured.set(attachment, item);
335
+ return item;
336
+ });
332
337
  }
333
- /**
334
- * 按固定层级绘制已经完成布局的结果
335
- *
336
- * background 先于 temporal 对象绘制
337
- * foreground 用于 tie、beam 等覆盖在线符号之上的对象
338
- */
339
- export function paintLayout(result, painter) {
340
- for (const attachment of result.attachments) {
341
- if (attachment.layer === "background")
342
- attachment.paint(painter);
343
- }
344
- for (const node of result.objects) {
345
- node.paint(painter);
346
- for (const decoration of node.decorations)
347
- decoration.paint(painter);
348
- }
349
- for (const attachment of result.attachments) {
350
- if (attachment.layer === "foreground")
351
- attachment.paint(painter);
338
+ /** 把首轮几何折算成轨道占用,返回它是否超出了主体与先前区域的合并占用 */
339
+ function registerAttachmentOccupancy(measured, lines, visualAxisOf) {
340
+ let needsRelayout = false;
341
+ for (const { geometry } of measured) {
342
+ for (const region of geometry.occupancy ?? geometry.regions) {
343
+ if (region.line === void 0)
344
+ continue;
345
+ const line = lines[region.line];
346
+ const axis = visualAxisOf(region.line, region.track);
347
+ const top = region.y - axis;
348
+ const bottom = region.y + region.h - axis;
349
+ const hostExtent = line.hostExtents.get(region.track);
350
+ const attachmentExtent = line.attachmentExtents.get(region.track);
351
+ const previousTop = Math.min(hostExtent?.top ?? Infinity, attachmentExtent?.top ?? Infinity);
352
+ const previousBottom = Math.max(hostExtent?.bottom ?? -Infinity, attachmentExtent?.bottom ?? -Infinity);
353
+ if (top < previousTop || bottom > previousBottom)
354
+ needsRelayout = true;
355
+ includeTrackExtent(line.attachmentExtents, region.track, top, bottom);
356
+ }
352
357
  }
358
+ return needsRelayout;
353
359
  }
354
360
  /**
355
361
  * 沿 Track 树自内向外求出一条谱面行里所有音轨的纵向轴
@@ -52,10 +52,17 @@ export interface HorizontalLayoutHookEntry {
52
52
  /**
53
53
  * 在一段已经归一化的列上排版
54
54
  *
55
+ * 三条对调用方成立的契约(`@head` 正是靠第一条声明“本段在外层链上等效于多宽”):
56
+ * - 返回时本区间的 fixed 全部置 1;连续固定列在外层合并为一根刚性列,它的物理宽度
57
+ * **只取首末列**(`WL = 首列.WL`,`WR = X[末] - X[首] + 末列.WR`),中间列的宽度不参与
58
+ * 外层求解,相对位置则原样保留。
59
+ * - limit 传 Infinity 表示不压缩,得到的是本区间的自然布局。
60
+ * - X 是区间局部坐标,从 0 开始重排,调用方自行平移。
61
+ *
55
62
  * @param columns 当前区间的归一化列矩阵,列数必须等于 X.length
56
63
  * @param rows fillPlaceholders 得到的 Track 数;每列超出 rows 的元素不参与求解
57
64
  * @param X 当前区间的 anchor 坐标;通常是全行 X 的 subarray。是求解结果
58
- * @param fixed 当前区间的 gap 是否已经固定,长度必须为 X.length - 1;通常是全行 fixed 的 subarray。fixed[i]==1 表示第 i、i+1 列只能整体移动
65
+ * @param fixed 当前区间的 gap 是否已经固定,长度必须为 X.length - 1;通常是全行 fixed 的 subarray。fixed[i]==1 表示第 i、i+1 列只能整体移动。既是输入也是输出
59
66
  * @param limit 当前区间左右墙之间的可用宽度
60
67
  * @param options 已补齐默认值的求解参数
61
68
  * @param fill 空间有余量时,是否让首尾贴墙并把余量平均分到自由间隙
@@ -1,7 +1,9 @@
1
+ import { Fraction } from "../fraction.js";
1
2
  const DEFAULT_F = 1.0; // 多大力让一行的 margin 全变为 0
2
3
  const DEFAULT_ALPHA = 6; // 控制无约束时元素的margin
3
4
  const DEFAULT_MU = 16;
4
5
  const DEFAULT_CROSS_PUNISH = 32;
6
+ const MIN_ALPHA = 1e-6;
5
7
  const MIN_DURATION = 0.01;
6
8
  /**
7
9
  * 原地补齐全部弹簧属性
@@ -16,14 +18,14 @@ export function completeSpringConfig(config, F = DEFAULT_F) {
16
18
  const defaultMu = config.mu_L ?? config.mu_R ?? DEFAULT_MU;
17
19
  config.mu_L ??= defaultMu;
18
20
  config.mu_R ??= defaultMu;
19
- config.beta_L ??= F / config.alpha_L;
20
- config.beta_R ??= F / config.alpha_R;
21
+ config.beta_L ??= F / Math.max(config.alpha_L, MIN_ALPHA);
22
+ config.beta_R ??= F / Math.max(config.alpha_R, MIN_ALPHA);
21
23
  }
22
24
  // 有副作用:确保直接调用时也能消费尚未补齐的配置
23
25
  export function layoutElement(config, box, time, F = DEFAULT_F) {
24
26
  completeSpringConfig(config, F);
25
27
  // 最小时长限制,与非线性变换(美观)
26
- const duration = Math.pow(Math.max(time.T, MIN_DURATION), 0.5);
28
+ const duration = Math.pow(Math.max(time.T.toNumber(), MIN_DURATION), 0.5);
27
29
  return {
28
30
  config, box, time,
29
31
  duration_L: duration,
@@ -68,7 +70,7 @@ function fillPlaceholders(columns, F = DEFAULT_F) {
68
70
  // 出现了同一行同一时刻的多个元素,则优先时长更大的
69
71
  // 重复的元素放到最后,不参与后续的元素比较
70
72
  const elExist = sortedCol[rIdx];
71
- if (el.time.T > elExist.time.T) {
73
+ if (el.time.T.compare(elExist.time.T) > 0) {
72
74
  sortedCol[rIdx] = el;
73
75
  sortedCol[same++] = elExist;
74
76
  }
@@ -92,7 +94,8 @@ function fillPlaceholders(columns, F = DEFAULT_F) {
92
94
  }, {
93
95
  x: 0, w: 0, anchor: 0
94
96
  }, {
95
- t: colTime, T: 1, track: rowId[0]
97
+ // 后面不会修改,所以直接引用
98
+ t: colTime, T: new Fraction(1), track: rowId[0]
96
99
  }, F);
97
100
  elPlaceholder.fake = true;
98
101
  sortedCol[rIdx] = elPlaceholder;
@@ -297,10 +300,17 @@ function solveHorizontal(mat, rows, X, limit, options) {
297
300
  /**
298
301
  * 在一段已经归一化的列上排版
299
302
  *
303
+ * 三条对调用方成立的契约(`@head` 正是靠第一条声明“本段在外层链上等效于多宽”):
304
+ * - 返回时本区间的 fixed 全部置 1;连续固定列在外层合并为一根刚性列,它的物理宽度
305
+ * **只取首末列**(`WL = 首列.WL`,`WR = X[末] - X[首] + 末列.WR`),中间列的宽度不参与
306
+ * 外层求解,相对位置则原样保留。
307
+ * - limit 传 Infinity 表示不压缩,得到的是本区间的自然布局。
308
+ * - X 是区间局部坐标,从 0 开始重排,调用方自行平移。
309
+ *
300
310
  * @param columns 当前区间的归一化列矩阵,列数必须等于 X.length
301
311
  * @param rows fillPlaceholders 得到的 Track 数;每列超出 rows 的元素不参与求解
302
312
  * @param X 当前区间的 anchor 坐标;通常是全行 X 的 subarray。是求解结果
303
- * @param fixed 当前区间的 gap 是否已经固定,长度必须为 X.length - 1;通常是全行 fixed 的 subarray。fixed[i]==1 表示第 i、i+1 列只能整体移动
313
+ * @param fixed 当前区间的 gap 是否已经固定,长度必须为 X.length - 1;通常是全行 fixed 的 subarray。fixed[i]==1 表示第 i、i+1 列只能整体移动。既是输入也是输出
304
314
  * @param limit 当前区间左右墙之间的可用宽度
305
315
  * @param options 已补齐默认值的求解参数
306
316
  * @param fill 空间有余量时,是否让首尾贴墙并把余量平均分到自由间隙
@@ -0,0 +1,19 @@
1
+ /**
2
+ * 路径几何:给一串绘制命令量出它实际占多大
3
+ *
4
+ * 放在 layout 而不是 render,是因为调用方全在布局阶段用它定尺寸和占位
5
+ * (连音线的 regions/occupancy、符号的 box),而它本身是纯函数、不依赖任何绘制后端。
6
+ *
7
+ * 注意 `render/paint.ts` 里另有一份路径遍历,那是**故意**把控制点计入的——
8
+ * 分页路由只需要一个保守超集,与这里求真实极值的目标相反,不要合并。
9
+ */
10
+ import type { PathCommand } from "../render/types.js";
11
+ import type { Rect } from "./types.js";
12
+ /**
13
+ * 按曲线真实极值求路径的外接矩形;空路径返回全 0
14
+ *
15
+ * 控制点不能直接计入:贝塞尔并不会到达控制点,用它会把弧顶高估约三分之一。
16
+ * 这个错误在连音线和符号上各犯过一次(连音线无谓推开上方轨道、延长记号的盒子高出
17
+ * 33% 且墨迹不居中),所以两边必须共用同一份判据。
18
+ */
19
+ export declare function pathBounds(commands: readonly PathCommand[]): Rect;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * 路径几何:给一串绘制命令量出它实际占多大
3
+ *
4
+ * 放在 layout 而不是 render,是因为调用方全在布局阶段用它定尺寸和占位
5
+ * (连音线的 regions/occupancy、符号的 box),而它本身是纯函数、不依赖任何绘制后端。
6
+ *
7
+ * 注意 `render/paint.ts` 里另有一份路径遍历,那是**故意**把控制点计入的——
8
+ * 分页路由只需要一个保守超集,与这里求真实极值的目标相反,不要合并。
9
+ */
10
+ /** 一维上的极值累加器 */
11
+ class Extent {
12
+ min = Infinity;
13
+ max = -Infinity;
14
+ add(value) {
15
+ if (value < this.min)
16
+ this.min = value;
17
+ if (value > this.max)
18
+ this.max = value;
19
+ }
20
+ }
21
+ /** 提成模块级而不是写成 cubicExtrema 内部的箭头函数:那里每次调用分配一个闭包,实测占了 96% 的耗时 */
22
+ function cubicAt(t, p0, p1, p2, p3, extent) {
23
+ if (!(t > 0 && t < 1))
24
+ return;
25
+ const u = 1 - t;
26
+ extent.add(u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3);
27
+ }
28
+ /** 三次曲线的真实极值:导数是二次式,取区间内的驻点而不是控制点 */
29
+ function cubicExtrema(p0, p1, p2, p3, extent) {
30
+ extent.add(p0);
31
+ extent.add(p3);
32
+ const a = -p0 + 3 * p1 - 3 * p2 + p3;
33
+ const b = 2 * (p0 - 2 * p1 + p2);
34
+ const c = p1 - p0;
35
+ if (Math.abs(a) < 1e-12) {
36
+ if (Math.abs(b) > 1e-12)
37
+ cubicAt(-c / b, p0, p1, p2, p3, extent);
38
+ return;
39
+ }
40
+ const discriminant = b * b - 4 * a * c;
41
+ if (discriminant < 0)
42
+ return;
43
+ const root = Math.sqrt(discriminant);
44
+ cubicAt((-b + root) / (2 * a), p0, p1, p2, p3, extent);
45
+ cubicAt((-b - root) / (2 * a), p0, p1, p2, p3, extent);
46
+ }
47
+ function quadraticExtrema(p0, p1, p2, extent) {
48
+ extent.add(p0);
49
+ extent.add(p2);
50
+ const denominator = p0 - 2 * p1 + p2;
51
+ if (Math.abs(denominator) < 1e-12)
52
+ return;
53
+ const t = (p0 - p1) / denominator;
54
+ if (!(t > 0 && t < 1))
55
+ return;
56
+ const u = 1 - t;
57
+ extent.add(u * u * p0 + 2 * u * t * p1 + t * t * p2);
58
+ }
59
+ /**
60
+ * 按曲线真实极值求路径的外接矩形;空路径返回全 0
61
+ *
62
+ * 控制点不能直接计入:贝塞尔并不会到达控制点,用它会把弧顶高估约三分之一。
63
+ * 这个错误在连音线和符号上各犯过一次(连音线无谓推开上方轨道、延长记号的盒子高出
64
+ * 33% 且墨迹不居中),所以两边必须共用同一份判据。
65
+ */
66
+ export function pathBounds(commands) {
67
+ const x = new Extent();
68
+ const y = new Extent();
69
+ let cursorX = 0;
70
+ let cursorY = 0;
71
+ let startX = 0;
72
+ let startY = 0;
73
+ for (const command of commands) {
74
+ if (command.op === "Z") {
75
+ cursorX = startX;
76
+ cursorY = startY;
77
+ continue;
78
+ }
79
+ if (command.op === "C") {
80
+ cubicExtrema(cursorX, command.cx1, command.cx2, command.x, x);
81
+ cubicExtrema(cursorY, command.cy1, command.cy2, command.y, y);
82
+ }
83
+ else if (command.op === "Q") {
84
+ quadraticExtrema(cursorX, command.cx, command.x, x);
85
+ quadraticExtrema(cursorY, command.cy, command.y, y);
86
+ }
87
+ else {
88
+ x.add(command.x);
89
+ y.add(command.y);
90
+ if (command.op === "M") {
91
+ startX = command.x;
92
+ startY = command.y;
93
+ }
94
+ }
95
+ cursorX = command.x;
96
+ cursorY = command.y;
97
+ }
98
+ return Number.isFinite(x.min)
99
+ ? { x: x.min, y: y.min, w: x.max - x.min, h: y.max - y.min }
100
+ : { x: 0, y: 0, w: 0, h: 0 };
101
+ }
@@ -1,6 +1,9 @@
1
1
  import type { Painter, TextMeasurer } from "../render/types.js";
2
2
  import type { Extent, Track } from "../lowering/track.js";
3
+ import type { Fraction } from "../fraction.js";
4
+ import type { SourceSpan } from "../parser/types.js";
3
5
  import type { HorizontalLayoutHook } from "./model.js";
6
+ import type { LoweringAttachment } from "../lowering/types.js";
4
7
  /** 轴对齐矩形,是所有排版几何的公共部分 */
5
8
  export interface Rect {
6
9
  x: number;
@@ -31,8 +34,8 @@ export interface HorizontalSpringConfig {
31
34
  beta_R?: number;
32
35
  }
33
36
  export interface TimeLineEvent {
34
- t: number;
35
- T: number;
37
+ t: Fraction;
38
+ T: Fraction;
36
39
  track: Track;
37
40
  }
38
41
  /** 文档页面的固化尺寸,所有值均为 px */
@@ -59,9 +62,12 @@ export interface LayoutPrepareContext {
59
62
  export interface AttachmentLayoutContext extends LayoutPrepareContext {
60
63
  width: number;
61
64
  originX: number;
65
+ pages: readonly Rect[];
62
66
  getVisualAxis(line: number, track: Track): number;
63
67
  /** 只包含可见主体的轴局部占用(top 通常为负),不受 attachment 或最终分页坐标影响 */
64
68
  getHostExtent(line: number, track: Track): Readonly<Extent> | undefined;
69
+ /** 读取本轮已完成的 attachment 边界;分组在 endLoweringGroup 才注册,因而组内对象必然排在分组之前 */
70
+ getAttachmentBox(attachment: LayoutAttachment): Readonly<Rect>;
65
71
  }
66
72
  /**
67
73
  * 装饰所依附的主体
@@ -76,6 +82,7 @@ export interface LayoutHost extends TimeLineEvent {
76
82
  box: LayoutBox;
77
83
  springConfig: HorizontalSpringConfig;
78
84
  ports: Record<string, LayoutPoint>;
85
+ readonly mergeKey: number;
79
86
  readonly layoutLine: number;
80
87
  readonly ast: {
81
88
  readonly size: number;
@@ -90,6 +97,8 @@ export interface LayoutHost extends TimeLineEvent {
90
97
  export interface HorizontalLineView {
91
98
  /** 谱面行号,与 host.layoutLine 同一坐标系 */
92
99
  readonly index: number;
100
+ /** 本行按横向顺序排列的可见时间列 */
101
+ readonly columns: readonly (readonly LayoutHost[])[];
93
102
  /** 同一 Track 上按时间列顺序排好的主体,相邻两项即视觉上的前后邻居 */
94
103
  readonly trackRuns: ReadonlyMap<Track, readonly LayoutHost[]>;
95
104
  /** 主体所在时间列下标;不在本行时返回 -1 */
@@ -167,22 +176,43 @@ export interface LayoutDecoration {
167
176
  };
168
177
  }
169
178
  /**
170
- * 不占用时间、附着于一个或多个主体对象的独立排版对象
179
+ * 一次 attachment 放置产生的完整几何
171
180
  *
172
- * tie、beam、box 和歌词都使用这个接口
173
- * 它们不进入时间列,只需要报出自己占住的矩形,外接盒与纵向占用都由引擎从中导出
181
+ * 每次 createGeometry 都必须返回一个新结果;首轮试测可能被丢弃,只有最终结果会 paint。
174
182
  */
175
- export interface LayoutAttachment {
176
- box: Rect;
177
- layer: "background" | "foreground";
178
- /** 横向求解前:调整弹簧参数或注册横向布局 hook,不得改变对象/列顺序 */
179
- prepareHorizontal?(context: HorizontalLineView[]): void;
183
+ export interface AttachmentGeometry {
184
+ /** 绘制与命中的真实边界;同时是外接盒和缺省的 Track 占用 */
185
+ readonly regions: readonly LayoutRegion[];
186
+ /** 可选的 Track 占用;缺省时直接使用 regions */
187
+ readonly occupancy?: readonly LayoutRegion[];
188
+ paint(painter: Painter): void;
189
+ }
190
+ /**
191
+ * lowering 产生的无时间关系定义
192
+ *
193
+ * 实例只保存语义输入和一次横向准备状态,不保存最终 box、regions 或绘制几何。
194
+ */
195
+ export interface LayoutAttachment extends LoweringAttachment {
196
+ /** 相对于 Temporal 主体的绘制层;background 比内容先绘制 */
197
+ readonly layer: "background" | "foreground";
198
+ /** 对应的源码范围;自动生成图形可覆盖其首末宿主的源码 */
199
+ readonly sourceSpan?: SourceSpan;
180
200
  /**
181
- * 根据当前视觉轴生成完整几何,并返回自己占住的区域
182
- * 首次返回带 line + track 且扩张主体占用的区域时,引擎会重新求轴并再次调用;
183
- * 因此实现必须幂等(每次从主体几何重算,不能做累加)
201
+ * 横向求解前:可测量资源、调整弹簧参数或注册横向布局 hook,不得改变对象/列顺序
202
+ *
203
+ * 此时 box 的固有尺寸 w/h/anchor/visualAxis 已是终值,只有 x/y 未定
184
204
  */
185
- layout?(context: AttachmentLayoutContext): readonly LayoutRegion[] | void;
205
+ prepareHorizontal?(lines: HorizontalLineView[], context: LayoutPrepareContext): void;
206
+ createGeometry(context: AttachmentLayoutContext): AttachmentGeometry;
207
+ }
208
+ export declare function isLayoutAttachment(attachment: LoweringAttachment): attachment is LayoutAttachment;
209
+ /** layoutDocument 输出的最终 attachment 快照 */
210
+ export interface PlacedAttachment {
211
+ readonly box: Readonly<Rect>;
212
+ readonly regions: readonly LayoutRegion[];
213
+ /** 相对于 Temporal 主体的绘制层;background 比内容先绘制 */
214
+ readonly layer: "background" | "foreground";
215
+ readonly sourceSpan?: SourceSpan;
186
216
  paint(painter: Painter): void;
187
217
  }
188
218
  /**
@@ -191,7 +221,10 @@ export interface LayoutAttachment {
191
221
  * 总是计入外接盒;同时声明 line 和 track 时,还会折算成该轨道的纵向占用
192
222
  * 只想影响画布边界、不想撑高行的图形(括线、边框)省略归属即可
193
223
  */
194
- export interface LayoutRegion extends Rect {
195
- line?: number;
196
- track?: Track;
197
- }
224
+ export type LayoutRegion = Rect & ({
225
+ line: number;
226
+ track: Track;
227
+ } | {
228
+ line?: never;
229
+ track?: never;
230
+ });
@@ -1 +1,3 @@
1
- export {};
1
+ export function isLayoutAttachment(attachment) {
2
+ return typeof attachment.createGeometry === "function";
3
+ }
@@ -1,7 +1,8 @@
1
1
  import { Diagnostic } from "../diagnostic.js";
2
+ import { Fraction } from "../fraction.js";
2
3
  import { ASTFunctionClass, ASTNodeBase } from "../functions/ASTtypes.js";
3
- import type { LayoutAttachment, PageConfig } from "../layout/types.js";
4
- import { TemporalNodeBase, type LoweringGroup, type LoweringResult } from "./types.js";
4
+ import type { PageConfig } from "../layout/types.js";
5
+ import { TemporalNodeBase, type LoweringGroup, type LoweringAttachment, type LoweringResult } from "./types.js";
5
6
  import { Track } from "./track.js";
6
7
  /**
7
8
  * 把 AST 展开并固化为时间列、attachment 和页面配置
@@ -15,7 +16,7 @@ import { Track } from "./track.js";
15
16
  * 大多数 AST 函数通过以下入口参与 lowering(按时间顺序):
16
17
  * - [hook] loweringEnter/loweringExit:进入或离开节点时生成 TemporalNode、管理作用域
17
18
  * - [API] LoweringContext.beginLoweringGroup/endLoweringGroup:通常在 enter/exit 中被调用,以栈方式观察当前子树产生的 TemporalNode 和 attachment
18
- * - [API] LoweringContext.addLayoutAttachment:注册不推进时间的独立排版对象,供 tie、beam 等函数使用;若当前位于分组中,其 box 也会加入外层分组
19
+ * - [API] LoweringContext.addAttachment:注册不推进时间的附属对象;当前外层分组会收到该对象
19
20
  * - [config] timeFlowModel:声明子节点按 sequence 或 parallel 推进时间;parallel 还要声明音轨复用键与纵向排列策略
20
21
  * - [hook] Temporal.onTimeState:锚点归并后固化调性、速度等状态
21
22
  * - [hook] loweringAugment:最终列和 layoutLine 固化后扫描结果并生成要追加的 attachment
@@ -25,7 +26,8 @@ export declare class LoweringContext {
25
26
  private loweringAugmenters;
26
27
  private loweringFinalizers;
27
28
  private cnt;
28
- /** 不推进时间的关系对象和分组对象 */
29
+ private usedTracks;
30
+ /** 不推进时间的附属对象 */
29
31
  private attachments;
30
32
  /** 当前完整文档的页面配置 */
31
33
  private page?;
@@ -66,20 +68,15 @@ export declare class LoweringContext {
66
68
  * 结束最近的分组并注册其辅助排版对象
67
69
  * 嵌套分组按退出顺序注册,因此天然是由内向外计算边界
68
70
  */
69
- endLoweringGroup(owner: ASTNodeBase): void;
71
+ endLoweringGroup(owner: ASTNodeBase): LoweringGroup;
70
72
  /** 先统一生成派生 attachment,再按注册顺序执行最终处理 */
71
73
  private postprocessResult;
72
74
  /**
73
75
  * 注册不推进时间的排版对象
74
76
  * 被 tie、beam、box 等函数使用
75
77
  */
76
- addLayoutAttachment(attachment: LayoutAttachment): void;
77
- /**
78
- * 查询 AST 节点在当前 lowering 中产生的所有 temporal 节点
79
- *
80
- * 被折叠进别人盒子的成员没有独立的全局位置,统一上溯到宿主,
81
- * 所以写在成员上的标签等价于写在整个复合节点上。
82
- */
78
+ addAttachment(attachment: LoweringAttachment): void;
79
+ /** 查询 AST 自己产生的 temporal;是否沿 foldedInto 投影由调用者决定 */
83
80
  getTemporalNodes(ast: ASTNodeBase): readonly TemporalNodeBase[];
84
81
  /**
85
82
  * 展开内容,但外层分组看不见它们
@@ -95,14 +92,14 @@ export declare class LoweringContext {
95
92
  private initEvent;
96
93
  /**
97
94
  * 递归展开一棵子树,得到它的时间列与结束时间
98
- * @param timeOffset 当前节点的时间偏移量(单位QN) 由父节点传入
95
+ * @param timeOffset 当前节点的时间偏移量(单位QN) 由父节点传入,会被原地修改
99
96
  * @param track 当前所在的纵向音轨
100
97
  */
101
- trackedEvents(node: ASTNodeBase, timeOffset: number, track: Track): {
102
- timeOffset: number;
103
- columns: TimeColumn[];
104
- };
105
- /** 将 hook 返回的事件规范化、加入索引与分组,再追加到时间列 */
98
+ trackedEvents(node: ASTNodeBase, timeOffset: Fraction, track: Track): TimeColumn[];
99
+ /**
100
+ * 将 hook 返回的事件规范化、加入索引与分组,再追加到时间列
101
+ * 原地修改 timeOffset
102
+ */
106
103
  private appendEvents;
107
104
  /** 记录 AST->TemporalNode 的映射 */
108
105
  private indexTemporal;
@@ -116,8 +113,9 @@ export declare class LoweringContext {
116
113
  declare class TimeColumn extends Array<TemporalNodeBase> {
117
114
  readonly mergeKey: number;
118
115
  constructor(n: TemporalNodeBase);
119
- get t(): number;
120
- set t(value: number);
116
+ get t(): Fraction;
117
+ set t(value: Fraction);
118
+ shiftTime(offset: Fraction): void;
121
119
  /** 将当前列所有事件的行号固化为 lowering 后的实际行号 */
122
120
  set layoutLine(value: number);
123
121
  }