jpfun 0.2.0 → 0.4.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 (167) hide show
  1. package/README.md +141 -11
  2. package/dist/converter/midi/convert.d.ts +50 -0
  3. package/dist/converter/midi/convert.js +700 -0
  4. package/dist/converter/midi/index.d.ts +5 -0
  5. package/dist/converter/midi/index.js +11 -0
  6. package/dist/converter/midi/json.d.ts +38 -0
  7. package/dist/converter/midi/json.js +1 -0
  8. package/dist/converter/midi/triplet.d.ts +30 -0
  9. package/dist/converter/midi/triplet.js +75 -0
  10. package/dist/converter/musicxml/dom.d.ts +25 -0
  11. package/dist/converter/musicxml/dom.js +65 -0
  12. package/dist/converter/musicxml/features.d.ts +51 -0
  13. package/dist/converter/musicxml/features.js +232 -0
  14. package/dist/converter/musicxml/index.d.ts +9 -0
  15. package/dist/converter/musicxml/index.js +1140 -0
  16. package/dist/converter/musicxml/model.d.ts +123 -0
  17. package/dist/converter/musicxml/model.js +1 -0
  18. package/dist/converter/source.d.ts +22 -0
  19. package/dist/converter/source.js +51 -0
  20. package/dist/core.d.ts +22 -0
  21. package/dist/core.js +22 -0
  22. package/dist/diagnostic.js +5 -2
  23. package/dist/fraction.d.ts +24 -0
  24. package/dist/fraction.js +132 -0
  25. package/dist/functions/ASTtypes.d.ts +51 -31
  26. package/dist/functions/ASTtypes.js +59 -38
  27. package/dist/functions/adjust/index.d.ts +2 -0
  28. package/dist/functions/adjust/index.js +193 -0
  29. package/dist/functions/arpeggio/index.d.ts +2 -0
  30. package/dist/functions/arpeggio/index.js +180 -0
  31. package/dist/functions/arpeggio/shape.d.ts +7 -0
  32. package/dist/functions/arpeggio/shape.js +122 -0
  33. package/dist/functions/bar/index.d.ts +8 -0
  34. package/dist/functions/bar/index.js +62 -25
  35. package/dist/functions/beam/auto.d.ts +1 -1
  36. package/dist/functions/beam/auto.js +33 -16
  37. package/dist/functions/beam/index.js +10 -6
  38. package/dist/functions/beam/layout.d.ts +4 -3
  39. package/dist/functions/beam/layout.js +43 -65
  40. package/dist/functions/box/index.js +37 -36
  41. package/dist/functions/br/index.js +10 -8
  42. package/dist/functions/dash/index.js +40 -7
  43. package/dist/functions/default.js +19 -8
  44. package/dist/functions/div/index.d.ts +16 -0
  45. package/dist/functions/div/index.js +45 -17
  46. package/dist/functions/dot/index.js +23 -25
  47. package/dist/functions/dyn/index.d.ts +2 -0
  48. package/dist/functions/dyn/index.js +242 -0
  49. package/dist/functions/grace/index.d.ts +8 -11
  50. package/dist/functions/grace/index.js +84 -79
  51. package/dist/functions/head/index.d.ts +2 -0
  52. package/dist/functions/head/index.js +496 -0
  53. package/dist/functions/key/index.js +98 -3
  54. package/dist/functions/meter/index.d.ts +2 -0
  55. package/dist/functions/meter/index.js +155 -0
  56. package/dist/functions/note/accidentals.d.ts +24 -3
  57. package/dist/functions/note/accidentals.js +31 -1
  58. package/dist/functions/note/index.js +106 -79
  59. package/dist/functions/note/noteNameFSM.js +52 -63
  60. package/dist/functions/page/index.d.ts +11 -2
  61. package/dist/functions/page/index.js +65 -4
  62. package/dist/functions/program/index.d.ts +2 -0
  63. package/dist/functions/program/index.js +30 -0
  64. package/dist/functions/set/index.js +43 -32
  65. package/dist/functions/stack/index.js +26 -22
  66. package/dist/functions/symbol/index.d.ts +31 -0
  67. package/dist/functions/symbol/index.js +139 -0
  68. package/dist/functions/symbol/ornament.d.ts +15 -0
  69. package/dist/functions/symbol/ornament.js +73 -0
  70. package/dist/functions/symbol/shape.d.ts +24 -0
  71. package/dist/functions/symbol/shape.js +52 -0
  72. package/dist/functions/symbol/symbols/accent.d.ts +2 -0
  73. package/dist/functions/symbol/symbols/accent.js +24 -0
  74. package/dist/functions/symbol/symbols/dc.d.ts +4 -0
  75. package/dist/functions/symbol/symbols/dc.js +82 -0
  76. package/dist/functions/symbol/symbols/ds.d.ts +2 -0
  77. package/dist/functions/symbol/symbols/ds.js +93 -0
  78. package/dist/functions/symbol/symbols/dynamics.d.ts +3 -0
  79. package/dist/functions/symbol/symbols/dynamics.js +168 -0
  80. package/dist/functions/symbol/symbols/fermata.d.ts +2 -0
  81. package/dist/functions/symbol/symbols/fermata.js +24 -0
  82. package/dist/functions/symbol/symbols/fine.d.ts +2 -0
  83. package/dist/functions/symbol/symbols/fine.js +12 -0
  84. package/dist/functions/symbol/symbols/mordent.d.ts +2 -0
  85. package/dist/functions/symbol/symbols/mordent.js +56 -0
  86. package/dist/functions/symbol/symbols/prall.d.ts +2 -0
  87. package/dist/functions/symbol/symbols/prall.js +42 -0
  88. package/dist/functions/symbol/symbols/segno.d.ts +4 -0
  89. package/dist/functions/symbol/symbols/segno.js +82 -0
  90. package/dist/functions/symbol/symbols/tr.d.ts +2 -0
  91. package/dist/functions/symbol/symbols/tr.js +71 -0
  92. package/dist/functions/tempo/glyph.d.ts +12 -0
  93. package/dist/functions/tempo/glyph.js +30 -0
  94. package/dist/functions/tempo/index.js +57 -4
  95. package/dist/functions/temporal.d.ts +138 -0
  96. package/dist/functions/temporal.js +101 -0
  97. package/dist/functions/text/index.js +86 -27
  98. package/dist/functions/tie/index.js +136 -152
  99. package/dist/functions/tuplet/index.d.ts +2 -0
  100. package/dist/functions/tuplet/index.js +218 -0
  101. package/dist/functions/up/index.d.ts +1 -0
  102. package/dist/functions/up/index.js +258 -182
  103. package/dist/functions/voice/index.js +203 -109
  104. package/dist/functions/volta/index.d.ts +2 -0
  105. package/dist/functions/volta/index.js +230 -0
  106. package/dist/iife/core.d.ts +1 -0
  107. package/dist/iife/core.js +3 -0
  108. package/dist/iife/from-midi.d.ts +1 -0
  109. package/dist/iife/from-midi.js +15 -0
  110. package/dist/iife/from-musicxml.d.ts +1 -0
  111. package/dist/iife/from-musicxml.js +3 -0
  112. package/dist/iife/full.d.ts +1 -0
  113. package/dist/iife/full.js +3 -0
  114. package/dist/index.d.ts +3 -17
  115. package/dist/index.js +3 -17
  116. package/dist/jpfun.core.min.js +153 -0
  117. package/dist/jpfun.from-midi.min.js +9 -0
  118. package/dist/jpfun.from-musicxml.min.js +12 -0
  119. package/dist/jpfun.min.js +166 -0
  120. package/dist/layout/default.js +2 -3
  121. package/dist/layout/engine.d.ts +6 -12
  122. package/dist/layout/engine.js +115 -64
  123. package/dist/layout/model.d.ts +12 -5
  124. package/dist/layout/model.js +31 -18
  125. package/dist/layout/page.js +5 -4
  126. package/dist/layout/path.d.ts +19 -0
  127. package/dist/layout/path.js +101 -0
  128. package/dist/layout/types.d.ts +71 -20
  129. package/dist/layout/types.js +3 -1
  130. package/dist/lowering/loweringContext.d.ts +20 -20
  131. package/dist/lowering/loweringContext.js +153 -101
  132. package/dist/lowering/track.d.ts +5 -9
  133. package/dist/lowering/track.js +7 -2
  134. package/dist/lowering/types.d.ts +26 -112
  135. package/dist/lowering/types.js +1 -92
  136. package/dist/parser/parse-utils/call-utils.d.ts +0 -2
  137. package/dist/parser/parse-utils/call-utils.js +0 -6
  138. package/dist/parser/parse-utils/note-utils.d.ts +8 -0
  139. package/dist/parser/parse-utils/note-utils.js +35 -13
  140. package/dist/parser/parse-utils/string-utils.d.ts +10 -0
  141. package/dist/parser/parse-utils/string-utils.js +24 -0
  142. package/dist/parser/parserContext.d.ts +11 -9
  143. package/dist/parser/parserContext.js +65 -55
  144. package/dist/parser/preprocess.js +17 -11
  145. package/dist/pipeline.d.ts +6 -5
  146. package/dist/pipeline.js +4 -5
  147. package/dist/playback/compile.d.ts +18 -0
  148. package/dist/playback/compile.js +414 -0
  149. package/dist/playback/event.d.ts +105 -0
  150. package/dist/playback/event.js +105 -0
  151. package/dist/playback/time.d.ts +14 -0
  152. package/dist/playback/time.js +81 -0
  153. package/dist/playback/types.d.ts +129 -0
  154. package/dist/playback/types.js +3 -0
  155. package/dist/render/canvas.d.ts +4 -4
  156. package/dist/render/canvas.js +20 -5
  157. package/dist/render/index.d.ts +1 -0
  158. package/dist/render/index.js +1 -0
  159. package/dist/render/paint.d.ts +8 -0
  160. package/dist/render/paint.js +101 -0
  161. package/dist/render/svg.d.ts +3 -3
  162. package/dist/render/svg.js +10 -8
  163. package/dist/render/text.d.ts +22 -0
  164. package/dist/render/text.js +42 -0
  165. package/dist/render/types.d.ts +1 -1
  166. package/grammar.md +132 -13
  167. package/package.json +19 -6
@@ -10,11 +10,10 @@ export function createLayoutPrepareContext(functionClasses, options = {}) {
10
10
  const handlers = new Map();
11
11
  const uniqueClasses = new Set(functionClasses);
12
12
  for (const functionClass of uniqueClasses) {
13
- const staticClass = functionClass;
14
- const handler = staticClass.layoutDecorationHandler;
13
+ const handler = functionClass.layoutDecorationHandler;
15
14
  if (!handler)
16
15
  continue;
17
- const names = staticClass.def?.name;
16
+ const names = functionClass.def?.name;
18
17
  if (!names)
19
18
  continue;
20
19
  const primaryName = Array.isArray(names) ? names[0] : names;
@@ -1,9 +1,9 @@
1
1
  import { Diagnostic } from "../diagnostic.js";
2
- import { type LoweringResult, type VisualTemporalNode } from "../lowering/types.js";
3
- import type { Painter } from "../render/types.js";
2
+ import { type VisualTemporalNode } from "../functions/temporal.js";
3
+ import type { LoweringResult } from "../lowering/types.js";
4
4
  import { type SolverOptions } from "./model.js";
5
5
  import { type DocumentLayoutPage } from "./page.js";
6
- import type { LayoutAttachment, LayoutPrepareContext, Rect } from "./types.js";
6
+ import type { LayoutPrepareContext, PlacedAttachment, Rect } from "./types.js";
7
7
  export interface DocumentLayoutOptions extends SolverOptions {
8
8
  rowGap?: number;
9
9
  }
@@ -12,7 +12,7 @@ export type { DocumentLayoutPage } from "./page.js";
12
12
  export interface DocumentLayoutResult {
13
13
  diagnostics: Diagnostic[];
14
14
  objects: VisualTemporalNode[];
15
- attachments: LayoutAttachment[];
15
+ attachments: PlacedAttachment[];
16
16
  bounds: Rect;
17
17
  lineCount: number;
18
18
  pages: DocumentLayoutPage[];
@@ -28,7 +28,8 @@ export declare function unionLayoutBoxes(target: Rect, boxes: Iterable<Rect>): b
28
28
  * box 的尺寸、命名端口及装饰几何都尚未生成。
29
29
  *
30
30
  * 执行后,box 的 x/y 仍只是局部初值;固有宽高、弹簧参数、端口和装饰均已对应本轮 context 冻结,可以进入横向求解。
31
- * ports 和 decorations 在本次 pass 中从空容器开始建立。
31
+ *
32
+ * ports 和 decorations 每轮从空容器重建,因此端口上的一次性标记(如 div 的 claimed)不会跨 pass 残留。
32
33
  *
33
34
  * 具有内部几何的复合节点(例如 up 的和弦成员)可以对自己的子对象调用同一个函数,
34
35
  * 从而保证子对象与顶层对象经过完全一致的准备流程。
@@ -38,10 +39,3 @@ export declare function prepareLayoutHost(node: VisualTemporalNode, context: Lay
38
39
  * 完成 lowering 结果的全部几何计算
39
40
  */
40
41
  export declare function layoutDocument(result: LoweringResult, context: LayoutPrepareContext, options?: DocumentLayoutOptions): DocumentLayoutResult;
41
- /**
42
- * 按固定层级绘制已经完成布局的结果
43
- *
44
- * background 先于 temporal 对象绘制
45
- * foreground 用于 tie、beam 等覆盖在线符号之上的对象
46
- */
47
- export declare function paintLayout(result: DocumentLayoutResult, painter: Painter): void;
@@ -1,7 +1,8 @@
1
1
  import { Diagnostic } from "../diagnostic.js";
2
- import { isVisualTemporalNode, } from "../lowering/types.js";
2
+ import { isVisualTemporalNode, } from "../functions/temporal.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,11 +85,12 @@ 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);
87
- for (const line of lines) {
88
+ for (const attachment of layoutAttachments)
89
+ attachment.prepareHorizontal?.(views, context);
90
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
91
+ const line = lines[lineIndex];
88
92
  const elements = line.columns.map(column => column.map(node => layoutElement(node.springConfig, node.box, node, options.globalC)));
89
- layoutHorizontal(elements, contentWidth, options, line.horizontalLayoutHooks);
93
+ layoutHorizontal(elements, contentWidth, options, line.horizontalLayoutHooks, 0.5);
90
94
  for (const column of line.columns) {
91
95
  for (const node of column)
92
96
  node.box.x += originX;
@@ -141,6 +145,8 @@ export function layoutDocument(result, context, options = {}) {
141
145
  ...context,
142
146
  width: contentWidth,
143
147
  originX,
148
+ pages: pages.map(item => item.bounds),
149
+ lines: views,
144
150
  getVisualAxis: visualAxisOf,
145
151
  getHostExtent: (line, track) => lines[line]?.hostExtents.get(track),
146
152
  };
@@ -148,19 +154,22 @@ export function layoutDocument(result, context, options = {}) {
148
154
  };
149
155
  // 3. 首次纵向放置后测量 attachment;只有有效轨道占用扩张时才重新求解
150
156
  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) {
157
+ let measured = measureAttachments(layoutAttachments, placement.attachmentContext, lines);
158
+ if (measured.needsRelayout) {
157
159
  placement = placeVertically();
158
- // 最终区域只更新绘制外接盒,不再累计没有后续消费者的轨道占用
159
- for (const attachment of result.attachments) {
160
- unionLayoutBoxes(attachment.box, attachment.layout?.(placement.attachmentContext) ?? []);
161
- }
160
+ measured = measureAttachments(layoutAttachments, placement.attachmentContext, lines);
162
161
  }
163
162
  const pages = placement.pages;
163
+ const attachments = layoutAttachments.map((attachment, index) => {
164
+ const { geometry, box } = measured.items[index];
165
+ return {
166
+ box,
167
+ regions: geometry.regions,
168
+ layer: attachment.layer,
169
+ sourceSpan: attachment.sourceSpan,
170
+ paint(painter) { geometry.paint(painter); },
171
+ };
172
+ });
164
173
  const bounds = {
165
174
  x: 0, y: 0,
166
175
  w: 0, h: 0,
@@ -171,14 +180,14 @@ export function layoutDocument(result, context, options = {}) {
171
180
  yield pageResult.bounds;
172
181
  for (const node of objects)
173
182
  yield node.box;
174
- for (const attachment of result.attachments)
183
+ for (const attachment of attachments)
175
184
  yield attachment.box;
176
185
  }
177
186
  unionLayoutBoxes(bounds, layoutBoxes());
178
187
  return {
179
188
  diagnostics: result.diagnostics,
180
189
  objects,
181
- attachments: result.attachments,
190
+ attachments,
182
191
  bounds,
183
192
  lineCount: lines.length,
184
193
  pages,
@@ -215,6 +224,7 @@ function splitLayoutLines(result) {
215
224
  horizontalLayoutHooks: [],
216
225
  hostExtents: new Map(),
217
226
  attachmentExtents: new Map(),
227
+ attachmentRanges: [],
218
228
  });
219
229
  const lines = [];
220
230
  let currentLine = createLine();
@@ -254,7 +264,7 @@ function includeTrackExtent(extents, track, top, bottom) {
254
264
  */
255
265
  function buildLineViews(lines, force) {
256
266
  return lines.map((line, index) => {
257
- const columnIndex = new Map();
267
+ const columnIndex = new Map(); // 不考虑被折叠的。要查询的话需要从 foldedInto 追溯到宿主
258
268
  const trackRuns = new Map();
259
269
  for (let i = 0; i < line.columns.length; i++) {
260
270
  for (const node of line.columns[i]) {
@@ -269,6 +279,7 @@ function buildLineViews(lines, force) {
269
279
  }
270
280
  return {
271
281
  index,
282
+ columns: line.columns,
272
283
  trackRuns,
273
284
  columnOf: host => columnIndex.get(host) ?? -1,
274
285
  registerHorizontalLayoutHook(from, to, hook) {
@@ -303,53 +314,93 @@ function measureRowGaps(lineCount, objects, override) {
303
314
  return gaps;
304
315
  }
305
316
  /**
306
- * 把一个 attachment 首次报出的区域折算成外接盒与轨道占用
307
- *
308
- * 只声明了矩形的区域仅影响画布边界;同时声明 line 与 track 才会撑开谱面行。
309
- * 返回值表示区域是否扩张了主体与先前区域的合并占用,因而需要最终重排。
310
- */
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;
332
- }
333
- /**
334
- * 按固定层级绘制已经完成布局的结果
317
+ * 按 lowering 注册顺序原子生成本轮几何,并同步登记轨道占用
335
318
  *
336
- * background 先于 temporal 对象绘制
337
- * foreground 用于 tie、beam 等覆盖在线符号之上的对象
319
+ * 分组的 attachment 总在组内对象之后注册,所以读取依赖不需要额外排序;
320
+ * 占用逐条累加,后注册者因此能通过 getRangeExtents 避让先注册者。
321
+ * 返回的 needsRelayout 表示本轮占用超出了主体与先前区域的合并范围。
338
322
  */
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);
352
- }
323
+ function measureAttachments(attachments, baseContext, lines) {
324
+ const measured = new Map();
325
+ let needsRelayout = false;
326
+ // 避让基准逐轮重建,避免首轮试排结果污染最终几何;attachmentExtents 反之,见字段注释
327
+ for (const line of lines)
328
+ line.attachmentRanges.length = 0;
329
+ const context = {
330
+ ...baseContext,
331
+ getAttachmentBox(dependency) {
332
+ const resolved = measured.get(dependency);
333
+ if (!resolved)
334
+ throw new Error("Layout attachment dependency has not been measured");
335
+ return resolved.box;
336
+ },
337
+ getRangeExtents(line, columns) {
338
+ const target = lines[line];
339
+ const extents = new Map();
340
+ if (!target)
341
+ return extents;
342
+ // 主体按列精确选取;先完成的 attachment 再按这些列的最终横向范围相交选取
343
+ const wholeLine = columns === undefined;
344
+ if (columns && columns[0] > columns[1])
345
+ return extents;
346
+ const start = wholeLine ? 0 : Math.max(0, columns[0]);
347
+ const end = wholeLine ? target.columns.length - 1 : Math.min(columns[1], target.columns.length - 1);
348
+ if (!wholeLine && start > end)
349
+ return extents;
350
+ let left = wholeLine ? baseContext.originX : Infinity;
351
+ let right = wholeLine ? baseContext.originX + baseContext.width : -Infinity;
352
+ for (let column = start; column <= end; column++) {
353
+ for (const host of target.columns[column]) {
354
+ if (!wholeLine) {
355
+ if (host.box.x < left)
356
+ left = host.box.x;
357
+ if (host.box.x + host.box.w > right)
358
+ right = host.box.x + host.box.w;
359
+ }
360
+ const hostTop = host.box.y - baseContext.getVisualAxis(line, host.track);
361
+ const hostBottom = hostTop + host.box.h;
362
+ includeTrackExtent(extents, host.track, hostTop, hostBottom);
363
+ }
364
+ }
365
+ for (const range of target.attachmentRanges) {
366
+ if (range.right <= left || range.left >= right)
367
+ continue;
368
+ includeTrackExtent(extents, range.track, range.top, range.bottom);
369
+ }
370
+ return extents;
371
+ },
372
+ };
373
+ const items = attachments.map(attachment => {
374
+ const geometry = attachment.createGeometry(context);
375
+ const box = { x: 0, y: 0, w: 0, h: 0 };
376
+ unionLayoutBoxes(box, geometry.regions);
377
+ const item = { geometry, box };
378
+ measured.set(attachment, item);
379
+ // 当前项立即登记,保证后注册的 attachment 能看到并避让它
380
+ for (const region of geometry.occupancy ?? geometry.regions) {
381
+ if (region.line === void 0)
382
+ continue;
383
+ const line = lines[region.line];
384
+ const top = region.y - baseContext.getVisualAxis(region.line, region.track);
385
+ const bottom = top + region.h;
386
+ const hostExtent = line.hostExtents.get(region.track);
387
+ const attachmentExtent = line.attachmentExtents.get(region.track);
388
+ if (top < Math.min(hostExtent?.top ?? Infinity, attachmentExtent?.top ?? Infinity)
389
+ || bottom > Math.max(hostExtent?.bottom ?? -Infinity, attachmentExtent?.bottom ?? -Infinity)) {
390
+ needsRelayout = true;
391
+ }
392
+ includeTrackExtent(line.attachmentExtents, region.track, top, bottom);
393
+ line.attachmentRanges.push({
394
+ track: region.track,
395
+ left: region.x,
396
+ right: region.x + region.w,
397
+ top,
398
+ bottom,
399
+ });
400
+ }
401
+ return item;
402
+ });
403
+ return { items, needsRelayout };
353
404
  }
354
405
  /**
355
406
  * 沿 Track 树自内向外求出一条谱面行里所有音轨的纵向轴
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 基于弹簧的有时长物体排版模型 原理参考 docs/layout.md
2
+ * 基于弹簧的有时长物体排版模型 原理参考 apps/docs/src/content/docs/docs/developer/layout.md
3
3
  * 基本使用: 借助 layoutElement() 构建 LayoutElement[][],调用 layout() 函数进行排版
4
4
  */
5
5
  import type { HorizontalSpringConfig, LayoutBox, TimeLineEvent } from "./types.js";
@@ -52,15 +52,22 @@ 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
- * @param fill 空间有余量时,是否让首尾贴墙并把余量平均分到自由间隙
68
+ * @param fillMinRatio 自然宽度至少占可用宽度的比例时才 fill;省略表示不 fill,0 表示无条件 fill。fill 表示是否精确将左右拉到可用宽度,包括宽度不足和弹簧导致的溢出
62
69
  */
63
- export declare function layoutHorizontalRegion(columns: LayoutElement[][], rows: number, X: Float64Array, fixed: Uint8Array, limit: number, options: Required<SolverOptions>, fill?: boolean): void;
70
+ export declare function layoutHorizontalRegion(columns: LayoutElement[][], rows: number, X: Float64Array, fixed: Uint8Array, limit: number, options: Required<SolverOptions>, fillMinRatio?: number): void;
64
71
  /**
65
72
  * 纯扁平化物理排版解算入口
66
73
  *
@@ -69,5 +76,5 @@ export declare function layoutHorizontalRegion(columns: LayoutElement[][], rows:
69
76
  * @param options 排版物理配置
70
77
  * @returns 同一个解算完成的二维矩阵,所有盒子的绝对 box.x (左侧x坐标) 已就地更新
71
78
  */
72
- export declare function layoutHorizontal(columns: LayoutElement[][], limit: number, options?: SolverOptions, horizontalLayoutHooks?: readonly HorizontalLayoutHookEntry[]): LayoutElement[][];
79
+ export declare function layoutHorizontal(columns: LayoutElement[][], limit: number, options?: SolverOptions, horizontalLayoutHooks?: readonly HorizontalLayoutHookEntry[], fillMinRatio?: number): LayoutElement[][];
73
80
  export {};
@@ -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,15 +300,22 @@ 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
- * @param fill 空间有余量时,是否让首尾贴墙并把余量平均分到自由间隙
316
+ * @param fillMinRatio 自然宽度至少占可用宽度的比例时才 fill;省略表示不 fill,0 表示无条件 fill。fill 表示是否精确将左右拉到可用宽度,包括宽度不足和弹簧导致的溢出
307
317
  */
308
- export function layoutHorizontalRegion(columns, rows, X, fixed, limit, options, fill = false) {
318
+ export function layoutHorizontalRegion(columns, rows, X, fixed, limit, options, fillMinRatio) {
309
319
  if (X.length !== columns.length || fixed.length !== Math.max(0, X.length - 1)) {
310
320
  throw new Error("Horizontal region state does not match its columns");
311
321
  }
@@ -364,20 +374,23 @@ export function layoutHorizontalRegion(columns, rows, X, fixed, limit, options,
364
374
  }
365
375
  const hasRoom = solveHorizontal(solvedColumns, rows, solvedX, limit, options);
366
376
  fixed.fill(1);
367
- if (fill && hasRoom) {
368
- // 让首尾贴墙,并把余量平均分到自由间隙
377
+ if (fillMinRatio !== void 0) {
369
378
  let leftWidth = 0;
370
379
  let rightWidth = 0;
371
380
  for (let row = 0; row < rows; row++) {
372
381
  leftWidth = Math.max(leftWidth, solvedColumns[0][row].WL);
373
382
  rightWidth = Math.max(rightWidth, solvedColumns[solvedColumns.length - 1][row].WR);
374
383
  }
375
- const shift = leftWidth - solvedX[0];
376
- const extra = limit - rightWidth - solvedX[solvedX.length - 1] - shift;
377
- for (let i = 0; i < solvedX.length; i++) {
378
- solvedX[i] += shift + (extra > 0 && solvedX.length > 1
379
- ? extra * i / (solvedX.length - 1)
380
- : 0);
384
+ const naturalWidth = solvedX[solvedX.length - 1] + rightWidth - solvedX[0] + leftWidth;
385
+ if (!hasRoom || naturalWidth >= limit * fillMinRatio) {
386
+ // 让首尾贴墙,并把余量平均分到自由间隙
387
+ const shift = leftWidth - solvedX[0];
388
+ const extra = limit - naturalWidth;
389
+ for (let i = 0; i < solvedX.length; i++) {
390
+ solvedX[i] += shift + (solvedX.length > 1
391
+ ? extra * i / (solvedX.length - 1)
392
+ : 0);
393
+ }
381
394
  }
382
395
  }
383
396
  if (hasFixed) { // 把虚拟列的求解结果写回原始列
@@ -393,7 +406,7 @@ export function layoutHorizontalRegion(columns, rows, X, fixed, limit, options,
393
406
  * @param options 排版物理配置
394
407
  * @returns 同一个解算完成的二维矩阵,所有盒子的绝对 box.x (左侧x坐标) 已就地更新
395
408
  */
396
- export function layoutHorizontal(columns, limit, options = {}, horizontalLayoutHooks = []) {
409
+ export function layoutHorizontal(columns, limit, options = {}, horizontalLayoutHooks = [], fillMinRatio) {
397
410
  const normalizedOptions = normalizeSolverOptions(options);
398
411
  const { mat, rows } = fillPlaceholders(columns, normalizedOptions.globalC);
399
412
  const X = new Float64Array(mat.length);
@@ -412,7 +425,7 @@ export function layoutHorizontal(columns, limit, options = {}, horizontalLayoutH
412
425
  options: normalizedOptions,
413
426
  });
414
427
  }
415
- layoutHorizontalRegion(mat, rows, X, fixed, limit, normalizedOptions);
428
+ layoutHorizontalRegion(mat, rows, X, fixed, limit, normalizedOptions, fillMinRatio);
416
429
  // 坐标写回
417
430
  for (let c = 0; c < mat.length; c++) {
418
431
  for (const el of mat[c])
@@ -73,12 +73,13 @@ export function paginateLayoutLines(heights, page) {
73
73
  // used 含最小行距,用于判断下一行能否装入;contentHeight 不含行距,用于封页后拉伸
74
74
  let used = 0;
75
75
  let contentHeight = 0;
76
- /** 写出 [start, end) 这一页;完整页拉伸行距,末页保留最小行距 */
76
+ /** 写出 [start, end) 这一页;完整页把剩余高度均分到每行下方,末页保留最小行距 */
77
77
  const closePage = (end, justify) => {
78
78
  const count = end - start;
79
- const gap = justify && count > 1
80
- ? (availableHeight - contentHeight) / (count - 1)
81
- : page.lineGap;
79
+ const remaining = justify
80
+ ? Math.max(0, availableHeight - contentHeight - page.lineGap * (count - 1))
81
+ : 0;
82
+ const gap = page.lineGap + remaining / count;
82
83
  let lineTop = pageTop + page.marginTop;
83
84
  for (let i = start; i < end; i++) {
84
85
  lineTops[i] = lineTop;
@@ -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 MinMax {
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 MinMax();
68
+ const y = new MinMax();
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
+ }