jpfun 0.4.1 → 0.6.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 (89) hide show
  1. package/README.md +53 -113
  2. package/dist/converter/midi/convert.js +14 -7
  3. package/dist/converter/musicxml/features.d.ts +57 -16
  4. package/dist/converter/musicxml/features.js +204 -42
  5. package/dist/converter/musicxml/index.d.ts +7 -2
  6. package/dist/converter/musicxml/index.js +256 -268
  7. package/dist/converter/musicxml/model.d.ts +36 -7
  8. package/dist/converter/musicxml/resolve.d.ts +10 -0
  9. package/dist/converter/musicxml/resolve.js +152 -0
  10. package/dist/core.d.ts +1 -0
  11. package/dist/core.js +1 -0
  12. package/dist/fraction.js +7 -1
  13. package/dist/functions/ASTtypes.d.ts +6 -3
  14. package/dist/functions/ASTtypes.js +30 -23
  15. package/dist/functions/adjust/index.js +10 -50
  16. package/dist/functions/arpeggio/index.js +40 -25
  17. package/dist/functions/beam/auto.js +2 -11
  18. package/dist/functions/box/index.js +132 -82
  19. package/dist/functions/dash/index.js +20 -11
  20. package/dist/functions/default.js +2 -1
  21. package/dist/functions/div/index.d.ts +1 -1
  22. package/dist/functions/div/index.js +9 -10
  23. package/dist/functions/dot/index.js +4 -5
  24. package/dist/functions/dyn/index.js +28 -32
  25. package/dist/functions/grace/index.d.ts +23 -8
  26. package/dist/functions/grace/index.js +138 -119
  27. package/dist/functions/head/index.js +11 -4
  28. package/dist/functions/key/index.js +1 -1
  29. package/dist/functions/meter/index.js +40 -7
  30. package/dist/functions/meter/shape.d.ts +3 -0
  31. package/dist/functions/meter/shape.js +43 -0
  32. package/dist/functions/note/index.d.ts +6 -1
  33. package/dist/functions/note/index.js +60 -57
  34. package/dist/functions/note/source-transform.d.ts +21 -0
  35. package/dist/functions/note/source-transform.js +164 -0
  36. package/dist/functions/page/index.d.ts +5 -0
  37. package/dist/functions/page/index.js +8 -5
  38. package/dist/functions/rest/index.d.ts +2 -0
  39. package/dist/functions/rest/index.js +233 -0
  40. package/dist/functions/set/index.js +5 -1
  41. package/dist/functions/symbol/index.d.ts +2 -0
  42. package/dist/functions/symbol/index.js +1 -1
  43. package/dist/functions/symbol/ornament.d.ts +3 -3
  44. package/dist/functions/symbol/ornament.js +21 -35
  45. package/dist/functions/symbol/symbols/accent.js +5 -5
  46. package/dist/functions/symbol/symbols/fermata.js +5 -4
  47. package/dist/functions/temporal.d.ts +21 -7
  48. package/dist/functions/temporal.js +14 -4
  49. package/dist/functions/tie/index.js +36 -42
  50. package/dist/functions/tuplet/index.js +20 -24
  51. package/dist/functions/up/index.js +54 -34
  52. package/dist/functions/voice/connections.d.ts +19 -0
  53. package/dist/functions/voice/connections.js +88 -0
  54. package/dist/functions/voice/index.js +248 -102
  55. package/dist/functions/volta/index.js +7 -12
  56. package/dist/jpfun.core.min.js +61 -41
  57. package/dist/jpfun.from-midi.min.js +5 -5
  58. package/dist/jpfun.from-musicxml.min.js +8 -8
  59. package/dist/jpfun.min.js +70 -50
  60. package/dist/layout/engine.d.ts +13 -1
  61. package/dist/layout/engine.js +458 -129
  62. package/dist/layout/model.js +22 -66
  63. package/dist/layout/page.js +3 -1
  64. package/dist/layout/range.d.ts +26 -0
  65. package/dist/layout/range.js +75 -0
  66. package/dist/layout/types.d.ts +63 -49
  67. package/dist/lowering/loweringContext.d.ts +1 -1
  68. package/dist/lowering/loweringContext.js +34 -4
  69. package/dist/lowering/types.d.ts +5 -0
  70. package/dist/parser/parse-utils/length-utils.js +2 -0
  71. package/dist/parser/parse-utils/note-utils.d.ts +2 -0
  72. package/dist/parser/parse-utils/note-utils.js +6 -2
  73. package/dist/parser/parserContext.js +5 -9
  74. package/dist/parser/preprocess.js +4 -6
  75. package/dist/playback/compile.d.ts +2 -9
  76. package/dist/playback/compile.js +297 -186
  77. package/dist/playback/event.d.ts +8 -16
  78. package/dist/playback/event.js +13 -3
  79. package/dist/playback/types.d.ts +76 -18
  80. package/dist/playback/types.js +1 -0
  81. package/dist/render/index.d.ts +1 -1
  82. package/dist/render/index.js +1 -1
  83. package/dist/render/paint.js +1 -1
  84. package/dist/render/recording.d.ts +1 -0
  85. package/dist/render/recording.js +21 -0
  86. package/dist/render/translate.d.ts +14 -0
  87. package/dist/render/translate.js +48 -0
  88. package/grammar.md +200 -250
  89. package/package.json +4 -4
@@ -3,8 +3,24 @@ 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
5
  import { isLayoutAttachment } from "./types.js";
6
+ import { liftInto, rangeColumns, resolveRange } from "./range.js";
7
+ import { TranslatingPainter } from "../render/translate.js";
6
8
  // 兼容旧导入路径;布局入口会把正常页面溢出转换为 ErrorDiagnostic
7
9
  export { PageLayoutError } from "./page.js";
10
+ /** 轨道间距相对行内最大字号的比例;正文行与子域共用 */
11
+ const ROW_GAP_RATIO = 0.75;
12
+ // 装饰边界是本轮排列结果,不作为主体上的第二套空间协议
13
+ const decorationExtents = new WeakMap();
14
+ /** 内容边界不含纯留白,完整占用还包含装饰预留的上下空间 */
15
+ export function getLayoutBounds(host, contentOnly = false) {
16
+ const { box } = host;
17
+ const extent = decorationExtents.get(host);
18
+ if (!extent)
19
+ return box;
20
+ const top = contentOnly ? extent.contentTop : extent.top;
21
+ const bottom = contentOnly ? 0 : extent.bottom;
22
+ return { x: box.x, y: box.y + top, w: box.w, h: box.h - top + bottom };
23
+ }
8
24
  /**
9
25
  * 把多个已经定位的盒子合并到 target
10
26
  */
@@ -44,21 +60,25 @@ export function unionLayoutBoxes(target, boxes) {
44
60
  */
45
61
  export function prepareLayoutHost(node, context) {
46
62
  node.springConfig ??= {};
63
+ if (node.decorations)
64
+ decorationExtents.delete(node);
47
65
  node.decorations = [];
48
66
  node.ports = {};
49
67
  node.box.x = node.box.y = 0;
50
68
  node.prepareLayout(context); // 计算大小等 layout 需要的参数
51
69
  // 把 lowering 固化在 addon 中的语义交给已注册 handler,生成本轮函数装饰
52
- for (const [key, value] of Object.entries(node.addon ?? {})) {
53
- const handler = context.decorationHandlers.get(key);
54
- if (!handler)
55
- continue;
56
- const decoration = handler(node, value, context);
57
- if (decoration)
58
- node.decorations.push(decoration);
70
+ if (node.addon) {
71
+ for (const [key, value] of Object.entries(node.addon)) {
72
+ const handler = context.decorationHandlers.get(key);
73
+ if (!handler)
74
+ continue;
75
+ const decoration = handler(node, value, context);
76
+ if (decoration)
77
+ node.decorations.push(decoration);
78
+ }
59
79
  }
60
80
  // 处理 decoration
61
- arrangeBelowDecorations(node);
81
+ arrangeDecorations(node);
62
82
  // 让节点在最终盒尺寸确定后发布依赖 box 的端口
63
83
  node.finalizeLayout?.(context);
64
84
  }
@@ -70,6 +90,49 @@ export function layoutDocument(result, context, options = {}) {
70
90
  const page = normalizePageConfig(result.page);
71
91
  const contentWidth = page.width - page.marginLeft - page.marginRight;
72
92
  const originX = page.marginLeft;
93
+ const lift = liftInto(result.rootTrack);
94
+ // 子域在主体准备时就排版完毕;它认领的附件保留块内几何,随块平移
95
+ const order = new Map(layoutAttachments.map((attachment, index) => [attachment, index]));
96
+ const relations = groupRelations(layoutAttachments);
97
+ let hosts = [];
98
+ if (layoutAttachments.length) {
99
+ for (const nodes of result.astToTemporal.values()) {
100
+ if (!nodes.some(node => node.placementOffset?.x || node.placementOffset?.y))
101
+ continue;
102
+ hosts = [...new Set([...result.astToTemporal.values()].flat().filter(isVisualTemporalNode))];
103
+ break;
104
+ }
105
+ }
106
+ const subdomainItems = new Map();
107
+ const subdomainGeometry = (attachment, layoutOnly = false) => {
108
+ const item = subdomainItems.get(attachment);
109
+ return item && moveSubdomainItem(item, layoutOnly);
110
+ };
111
+ context = {
112
+ ...context,
113
+ layoutSubdomain(owner, columns, root, attachments) {
114
+ // 横排时内层子域先排版并认领关系,这里只取剩下的
115
+ const line = layoutLocalLine(columns, context);
116
+ const members = new Set(columns.flat());
117
+ const within = (node) => {
118
+ for (let host = node; host && host !== owner; host = host.foldedInto) {
119
+ if (members.has(host))
120
+ return true;
121
+ }
122
+ return false;
123
+ };
124
+ // 内容附件跟随声明位置,关系附件跟随端点
125
+ const own = attachments.filter(isLayoutAttachment).filter(attachment => !attachment.endPoints?.length);
126
+ for (const relation of relations.get(owner) ?? []) {
127
+ if (!subdomainItems.has(relation) && relation.endPoints.every(within))
128
+ own.push(relation);
129
+ }
130
+ own.sort((left, right) => order.get(left) - order.get(right));
131
+ const block = layoutSubdomainBlock(columns, line, root, own, context, subdomainGeometry, hosts.length ? hosts.filter(within) : hosts, owner);
132
+ own.forEach((attachment, index) => subdomainItems.set(attachment, block.items[index]));
133
+ return { width: line.width, height: block.height, positions: block.positions };
134
+ },
135
+ };
73
136
  // 1. 按 layoutLine 切行,并生成固有尺寸与装饰尺寸
74
137
  const lines = splitLayoutLines(result);
75
138
  const objects = [];
@@ -81,17 +144,15 @@ export function layoutDocument(result, context, options = {}) {
81
144
  }
82
145
  }
83
146
  }
147
+ const documentAttachments = layoutAttachments.filter(attachment => !subdomainItems.has(attachment));
84
148
  // 2. 横向弹簧布局,得到 box.x
85
- const views = buildLineViews(lines, options.globalC);
86
- for (const object of objects)
87
- object.prepareHorizontal?.(views[object.layoutLine]);
88
- for (const attachment of layoutAttachments)
149
+ const horizontal = lines.map((line, index) => prepareHorizontalLine(line.columns, index, options));
150
+ const views = horizontal.map(line => line.view);
151
+ for (const attachment of documentAttachments)
89
152
  attachment.prepareHorizontal?.(views, context);
90
- for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
91
- const line = lines[lineIndex];
92
- const elements = line.columns.map(column => column.map(node => layoutElement(node.springConfig, node.box, node, options.globalC)));
93
- layoutHorizontal(elements, contentWidth, options, line.horizontalLayoutHooks, 0.5);
94
- for (const column of line.columns) {
153
+ for (const line of horizontal) {
154
+ line.layout(contentWidth, page.fillRatio);
155
+ for (const column of line.view.columns) {
95
156
  for (const node of column)
96
157
  node.box.x += originX;
97
158
  }
@@ -100,8 +161,7 @@ export function layoutDocument(result, context, options = {}) {
100
161
  // 主体占用只依赖固有尺寸,整个纵向布局中保持不变
101
162
  for (const node of objects) {
102
163
  const line = lines[node.layoutLine];
103
- const top = -node.box.visualAxis;
104
- includeTrackExtent(line.hostExtents, node.track, top, top + node.box.h);
164
+ includeHostExtent(line.hostExtents, node);
105
165
  }
106
166
  // 根据配置得到行距
107
167
  const rowGaps = measureRowGaps(lines.length, objects, options.rowGap);
@@ -147,21 +207,25 @@ export function layoutDocument(result, context, options = {}) {
147
207
  originX,
148
208
  pages: pages.map(item => item.bounds),
149
209
  lines: views,
150
- getVisualAxis: visualAxisOf,
151
- getHostExtent: (line, track) => lines[line]?.hostExtents.get(track),
210
+ // 子域的私有轨在正文里归入复合体所在的轨
211
+ getVisualAxis: (line, track) => visualAxisOf(line, lift(track)),
212
+ getHostExtent: (line, track) => lines[line]?.hostExtents.get(lift(track)),
213
+ getRangeColumns: (line, range, track) => rangeColumns(views[line], range, track, lift),
152
214
  };
153
215
  return { pages, attachmentContext };
154
216
  };
155
217
  // 3. 首次纵向放置后测量 attachment;只有有效轨道占用扩张时才重新求解
156
218
  let placement = placeVertically();
157
- let measured = measureAttachments(layoutAttachments, placement.attachmentContext, lines);
219
+ let measured = measureAttachments(documentAttachments, placement.attachmentContext, lines, lift, subdomainGeometry, hosts);
158
220
  if (measured.needsRelayout) {
159
221
  placement = placeVertically();
160
- measured = measureAttachments(layoutAttachments, placement.attachmentContext, lines);
222
+ measured = measureAttachments(documentAttachments, placement.attachmentContext, lines, lift, subdomainGeometry, hosts);
161
223
  }
162
224
  const pages = placement.pages;
163
- const attachments = layoutAttachments.map((attachment, index) => {
164
- const { geometry, box } = measured.items[index];
225
+ let next = 0;
226
+ const attachments = layoutAttachments.map(attachment => {
227
+ const item = subdomainItems.get(attachment);
228
+ const { geometry, box } = item ? moveSubdomainItem(item) : measured.items[next++];
165
229
  return {
166
230
  box,
167
231
  regions: geometry.regions,
@@ -179,7 +243,7 @@ export function layoutDocument(result, context, options = {}) {
179
243
  for (const pageResult of pages)
180
244
  yield pageResult.bounds;
181
245
  for (const node of objects)
182
- yield node.box;
246
+ yield getLayoutBounds(node);
183
247
  for (const attachment of attachments)
184
248
  yield attachment.box;
185
249
  }
@@ -194,24 +258,50 @@ export function layoutDocument(result, context, options = {}) {
194
258
  };
195
259
  }
196
260
  /**
197
- * 按 below.order 排列主体下方装饰,调用 place 并把其占高计入 box.h
261
+ * 上下分别由内向外排列,纯留白只进入占用,不改变主体绘制坐标
198
262
  */
199
- function arrangeBelowDecorations(node) {
200
- // 现代 ECMAScript 的稳定排序会保留相同 order 的注册顺序
201
- const below = node.decorations
202
- .map(decoration => decoration.below)
203
- .filter(item => item !== void 0)
204
- .sort((left, right) => left.order - right.order);
205
- if (below.length === 0)
263
+ function arrangeDecorations(node) {
264
+ if (node.decorations.length === 0)
206
265
  return;
207
- // 依次分配每个装饰的局部上边界,并累加最终盒高
208
- let y = node.box.h;
209
- for (const item of below) {
210
- y += item.gap ?? 0;
211
- item.place?.(y);
212
- y += Math.max(0, item.height ?? 0);
266
+ let contentTop = 0;
267
+ let contentBottom = -Infinity;
268
+ let top = 0;
269
+ let bottom = -Infinity;
270
+ for (const side of ["above", "below"]) {
271
+ const above = side === "above";
272
+ const decorations = node.decorations.length === 1 ? node.decorations : node.decorations.filter(item => item[side]);
273
+ if (decorations.length > 1)
274
+ decorations.sort((left, right) => left[side].order - right[side].order);
275
+ // 下方可覆盖起点,避免把字体盒的留白当成可见正文;两侧仍独立排列
276
+ let cursor = above ? 0 : (node.ports["decoration.below"]?.y ?? node.box.h);
277
+ let sideBottom = above ? -Infinity : node.box.h;
278
+ let sideContentBottom = sideBottom;
279
+ for (const decoration of decorations) {
280
+ const item = decoration[side];
281
+ if (!item)
282
+ continue;
283
+ const height = Math.max(0, item.height ?? 0);
284
+ // 纯留白包围完整内容,不能被正文盒内的装饰起点吞掉
285
+ if (!above && !decoration.paint)
286
+ cursor = Math.max(cursor, sideContentBottom);
287
+ const y = above ? cursor - (item.gap ?? 0) - height : cursor + (item.gap ?? 0);
288
+ item.place?.(y);
289
+ cursor = above ? y : y + height;
290
+ top = Math.min(top, y);
291
+ sideBottom = above ? Math.max(sideBottom, y + height) : cursor;
292
+ if (decoration.paint) {
293
+ contentTop = Math.min(contentTop, y);
294
+ sideContentBottom = above ? Math.max(sideContentBottom, y + height) : cursor;
295
+ }
296
+ }
297
+ bottom = Math.max(bottom, sideBottom);
298
+ contentBottom = Math.max(contentBottom, sideContentBottom);
299
+ }
300
+ node.box.h = contentBottom;
301
+ const extraBottom = Math.max(0, bottom - contentBottom);
302
+ if (top !== 0 || extraBottom !== 0) {
303
+ decorationExtents.set(node, { top, bottom: extraBottom, contentTop });
213
304
  }
214
- node.box.h = y;
215
305
  }
216
306
  /**
217
307
  * 按 lowering 已固化的 layoutLine 把可见事件拆成谱面行
@@ -221,10 +311,8 @@ function arrangeBelowDecorations(node) {
221
311
  function splitLayoutLines(result) {
222
312
  const createLine = () => ({
223
313
  columns: [],
224
- horizontalLayoutHooks: [],
225
314
  hostExtents: new Map(),
226
315
  attachmentExtents: new Map(),
227
- attachmentRanges: [],
228
316
  });
229
317
  const lines = [];
230
318
  let currentLine = createLine();
@@ -260,50 +348,194 @@ function includeTrackExtent(extents, track, top, bottom) {
260
348
  extents.set(track, { top, bottom });
261
349
  }
262
350
  /**
263
- * 固化每行的横向拓扑:补齐弹簧配置,并生成交给具体函数的只读视图
351
+ * 为已完成尺寸准备的成员建立横向视图并注册约束;调用 layout 时才创建输入和执行 hook
352
+ * compact 只清零本轮自然间隙,保留时值和弹簧配置;局部列顺序由调用方提供
264
353
  */
265
- function buildLineViews(lines, force) {
266
- return lines.map((line, index) => {
267
- const columnIndex = new Map(); // 不考虑被折叠的。要查询的话需要从 foldedInto 追溯到宿主
268
- const trackRuns = new Map();
269
- for (let i = 0; i < line.columns.length; i++) {
270
- for (const node of line.columns[i]) {
271
- columnIndex.set(node, i);
272
- completeSpringConfig(node.springConfig, force);
273
- const run = trackRuns.get(node.track);
274
- if (run)
275
- run.push(node);
276
- else
277
- trackRuns.set(node.track, [node]);
278
- }
354
+ export function prepareHorizontalLine(columns, index, options = {}, compact = false) {
355
+ const hooks = [];
356
+ const columnIndex = new Map();
357
+ const trackRuns = new Map();
358
+ for (let column = 0; column < columns.length; column++) {
359
+ for (const node of columns[column]) {
360
+ columnIndex.set(node, column);
361
+ completeSpringConfig(node.springConfig, options.globalC);
362
+ const run = trackRuns.get(node.track);
363
+ if (run)
364
+ run.push(node);
365
+ else
366
+ trackRuns.set(node.track, [node]);
279
367
  }
280
- return {
281
- index,
282
- columns: line.columns,
283
- trackRuns,
284
- columnOf: host => columnIndex.get(host) ?? -1,
285
- registerHorizontalLayoutHook(from, to, hook) {
286
- const start = columnIndex.get(from);
287
- const end = columnIndex.get(to);
288
- if (start === void 0 || end === void 0)
289
- return;
290
- line.horizontalLayoutHooks.push({
291
- start: Math.min(start, end),
292
- end: Math.max(start, end),
293
- hook,
294
- });
295
- },
296
- };
297
- });
368
+ }
369
+ const view = {
370
+ index,
371
+ columns,
372
+ trackRuns,
373
+ columnOf: host => columnIndex.get(host) ?? -1,
374
+ registerHorizontalLayoutHook(from, to, hook) {
375
+ const start = columnIndex.get(from);
376
+ const end = columnIndex.get(to);
377
+ if (start === void 0 || end === void 0)
378
+ return;
379
+ hooks.push({ start: Math.min(start, end), end: Math.max(start, end), hook });
380
+ },
381
+ };
382
+ for (const column of columns) {
383
+ for (const node of column)
384
+ node.prepareHorizontal?.(view);
385
+ }
386
+ return {
387
+ view,
388
+ layout(limit, fillMinRatio) {
389
+ const elements = columns.map(column => column.map(node => {
390
+ const element = layoutElement(node.springConfig, node.box, node, options.globalC);
391
+ if (compact)
392
+ element.margin_L = element.margin_R = 0;
393
+ return element;
394
+ }));
395
+ layoutHorizontal(elements, limit, options, hooks, fillMinRatio);
396
+ return elements;
397
+ },
398
+ };
399
+ }
400
+ /** 局部序列按给定顺序完成尺寸、约束与零间隙自然横排,归零占位左沿并返回完整宽度 */
401
+ export function layoutLocalSequence(nodes, context) {
402
+ return nodes.length === 0 ? 0 : layoutLocalLine(nodes.map(node => [node]), context).width;
403
+ }
404
+ /** 同 layoutLocalSequence,但同列成员按各自 Track 分行;columns 不能为空 */
405
+ function layoutLocalLine(columns, context) {
406
+ for (const column of columns) {
407
+ for (const node of column)
408
+ prepareLayoutHost(node, context);
409
+ }
410
+ const line = prepareHorizontalLine(columns, columns[0][0].layoutLine, {}, true);
411
+ let left = Infinity;
412
+ let right = -Infinity;
413
+ for (const column of line.layout(Infinity)) {
414
+ for (const element of column) {
415
+ const anchor = element.box.x + element.box.anchor;
416
+ left = Math.min(left, anchor - element.WL);
417
+ right = Math.max(right, anchor + element.WR);
418
+ }
419
+ }
420
+ for (const column of columns) {
421
+ for (const node of column)
422
+ node.box.x -= left;
423
+ }
424
+ return { width: right - left, view: line.view };
425
+ }
426
+ /**
427
+ * 把已横排的子域按正文规则纵向排版,坐标以块的左上角为原点
428
+ *
429
+ * 与正文行的流程相同:沿 root 的 Track 树求轴放置,按登记顺序测量附件,
430
+ * 附件扩张占用时重排一次。positions 是放置时写入的块内位置,不含成员 onPlaced 追加的平移
431
+ */
432
+ function layoutSubdomainBlock(columns, { width, view }, root, attachments, context, measuredElsewhere, hosts, owner) {
433
+ const members = columns.flat();
434
+ const extents = { hostExtents: new Map(), attachmentExtents: new Map() };
435
+ let gap = 0;
436
+ for (const member of members) {
437
+ includeHostExtent(extents.hostExtents, member);
438
+ gap = Math.max(gap, member.ast.size * ROW_GAP_RATIO);
439
+ }
440
+ const positions = members.map(member => ({ x: member.box.x, y: 0 }));
441
+ const place = () => {
442
+ const solved = solveVerticalAxes(extents, root, gap);
443
+ members.forEach((member, index) => {
444
+ member.box.y = positions[index].y = solved.axes.get(member.track) - member.box.visualAxis;
445
+ member.onPlaced?.();
446
+ });
447
+ return solved;
448
+ };
449
+ let solved = place();
450
+ if (attachments.length === 0)
451
+ return { height: solved.height, positions, items: [] };
452
+ const lift = liftInto(root);
453
+ // 附件按行号查询,子域只占自己所在的那一行
454
+ const lines = [];
455
+ const views = [];
456
+ lines[view.index] = extents;
457
+ views[view.index] = view;
458
+ const measure = () => measureAttachments(attachments, {
459
+ ...context,
460
+ width,
461
+ originX: 0,
462
+ pages: [],
463
+ lines: views,
464
+ getVisualAxis: (_line, track) => solved.axes.get(lift(track)) ?? 0,
465
+ getHostExtent: (line, track) => lines[line]?.hostExtents.get(lift(track)),
466
+ getRangeColumns: (line, range, track) => rangeColumns(views[line], range, track, lift),
467
+ }, lines, lift, measuredElsewhere, hosts, owner);
468
+ let measured = measure();
469
+ if (measured.needsRelayout) {
470
+ solved = place();
471
+ measured = measure();
472
+ }
473
+ const reference = members[0];
474
+ const position = { x: reference.box.x, y: reference.box.y };
475
+ const offset = measured.layoutItems && placementOffset(reference, owner);
476
+ const layoutPosition = offset && (offset.x !== 0 || offset.y !== 0)
477
+ ? { x: position.x - offset.x, y: position.y - offset.y } : position;
478
+ const items = measured.items.map((item, index) => ({
479
+ ...item, reference, position,
480
+ ...(measured.layoutItems && { layout: { ...measured.layoutItems[index], position: layoutPosition } }),
481
+ }));
482
+ return { height: solved.height, positions, items };
483
+ }
484
+ /**
485
+ * 关系附件按同时包含全部端点的复合体分组,由内到外逐层登记
486
+ *
487
+ * 端点都在正文的附件不进分组;子域从这里认领端点全部落在自己成员上的关系,不论它写在哪里
488
+ */
489
+ function groupRelations(attachments) {
490
+ const groups = new Map();
491
+ for (const attachment of attachments) {
492
+ const [first, ...rest] = attachment.endPoints ?? [];
493
+ for (let owner = first?.foldedInto; owner; owner = owner.foldedInto) {
494
+ const candidate = owner;
495
+ if (!rest.every(point => encloses(candidate, point)))
496
+ continue;
497
+ const group = groups.get(owner);
498
+ if (group)
499
+ group.push(attachment);
500
+ else
501
+ groups.set(owner, [attachment]);
502
+ }
503
+ }
504
+ return groups;
505
+ }
506
+ function encloses(owner, node) {
507
+ for (let host = node.foldedInto; host; host = host.foldedInto) {
508
+ if (host === owner)
509
+ return true;
510
+ }
511
+ return false;
512
+ }
513
+ /** 子域是刚性块:按参照成员的位移平移块内测得的几何 */
514
+ function moveSubdomainItem(item, layoutOnly = false) {
515
+ const measured = layoutOnly ? item.layout ?? item : item;
516
+ const { position, geometry, box } = measured;
517
+ const dx = item.reference.box.x - position.x;
518
+ const dy = item.reference.box.y - position.y;
519
+ if (dx === 0 && dy === 0)
520
+ return measured;
521
+ const move = (rect) => ({ ...rect, x: rect.x + dx, y: rect.y + dy });
522
+ return {
523
+ box: move(box),
524
+ geometry: {
525
+ regions: geometry.regions.map(move),
526
+ occupancy: geometry.occupancy?.map(move),
527
+ paint: painter => geometry.paint(new TranslatingPainter(painter, dx, dy)),
528
+ },
529
+ };
298
530
  }
299
- /** 行距取该行最大字号的 0.75 倍;没有可见对象的行回退到全文档最大字号 */
531
+ /** 行距取该行最大字号的 ROW_GAP_RATIO 倍;没有可见对象的行回退到全文档最大字号 */
300
532
  function measureRowGaps(lineCount, objects, override) {
301
533
  if (override !== void 0)
302
534
  return new Array(lineCount).fill(override);
303
535
  const gaps = new Array(lineCount).fill(0);
304
536
  let documentGap = 0;
305
537
  for (const node of objects) {
306
- const gap = node.ast.size * 0.75;
538
+ const gap = node.ast.size * ROW_GAP_RATIO;
307
539
  if (gap > gaps[node.layoutLine])
308
540
  gaps[node.layoutLine] = gap;
309
541
  if (gap > documentGap)
@@ -313,61 +545,148 @@ function measureRowGaps(lineCount, objects, override) {
313
545
  gaps[i] ||= documentGap;
314
546
  return gaps;
315
547
  }
316
- /**
317
- * 按 lowering 注册顺序原子生成本轮几何,并同步登记轨道占用
318
- *
319
- * 分组的 attachment 总在组内对象之后注册,所以读取依赖不需要额外排序;
320
- * 占用逐条累加,后注册者因此能通过 getRangeExtents 避让先注册者。
321
- * 返回的 needsRelayout 表示本轮占用超出了主体与先前区域的合并范围。
322
- */
323
- function measureAttachments(attachments, baseContext, lines) {
548
+ /** 折叠成员继承外层平移,子域只累加当前复合体内部的平移 */
549
+ function placementOffset(node, owner) {
550
+ let x = 0;
551
+ let y = 0;
552
+ for (let host = node; host && host !== owner; host = host.foldedInto) {
553
+ x += host.placementOffset?.x ?? 0;
554
+ y += host.placementOffset?.y ?? 0;
555
+ }
556
+ return { x, y };
557
+ }
558
+ /** 后置平移只改变绘制几何,占用始终在未平移的布局位置测量 */
559
+ function measureAttachments(attachments, baseContext, lines, lift, measuredElsewhere, hosts, owner) {
560
+ if (attachments.length === 0)
561
+ return { items: [], needsRelayout: false };
562
+ const shifts = [];
563
+ for (const node of hosts) {
564
+ const { x, y } = placementOffset(node, owner);
565
+ if (x !== 0 || y !== 0)
566
+ shifts.push({ node, x, y, boxX: node.box.x, boxY: node.box.y });
567
+ }
568
+ const displaced = shifts.length > 0 || attachments.some(attachment => attachment.placementOffset?.x || attachment.placementOffset?.y);
569
+ let layout;
570
+ if (displaced) {
571
+ for (const { node, x, y } of shifts) {
572
+ node.box.x -= x;
573
+ node.box.y -= y;
574
+ }
575
+ try {
576
+ layout = measureAttachmentPass(attachments, { ...baseContext, layoutOnly: true }, lines, lift, measuredElsewhere, true);
577
+ }
578
+ finally {
579
+ for (const { node, boxX, boxY } of shifts) {
580
+ node.box.x = boxX;
581
+ node.box.y = boxY;
582
+ }
583
+ }
584
+ }
585
+ else
586
+ layout = measureAttachmentPass(attachments, baseContext, lines, lift, measuredElsewhere, true);
587
+ if (!displaced)
588
+ return layout;
589
+ // 试测结果若被重排丢弃,就不再为它生成绘制几何
590
+ let painted;
591
+ return {
592
+ needsRelayout: layout.needsRelayout,
593
+ layoutItems: layout.items,
594
+ get items() {
595
+ return painted ??= measureAttachmentPass(attachments, baseContext, lines, lift, measuredElsewhere, false).items;
596
+ },
597
+ };
598
+ }
599
+ /** 按声明顺序测量几何,后注册的附件可以查询此前的区域和占用 */
600
+ function measureAttachmentPass(attachments, baseContext, lines, lift, measuredElsewhere, reserve) {
324
601
  const measured = new Map();
602
+ const occupancy = [];
325
603
  let needsRelayout = false;
326
- // 避让基准逐轮重建,避免首轮试排结果污染最终几何;attachmentExtents 反之,见字段注释
327
- for (const line of lines)
328
- line.attachmentRanges.length = 0;
604
+ // 同一测量轮坐标不变,子域几何只需平移一次
605
+ function resolveAttachment(dependency) {
606
+ let item = measured.get(dependency);
607
+ if (!item) {
608
+ item = measuredElsewhere(dependency, baseContext.layoutOnly);
609
+ if (item)
610
+ measured.set(dependency, item);
611
+ }
612
+ return item;
613
+ }
614
+ function getRangeExtents(line, columns, track) {
615
+ const view = baseContext.lines[line];
616
+ const extents = track === undefined ? new Map() : undefined;
617
+ let extent;
618
+ if (!view)
619
+ return extents;
620
+ const include = (owner, top, bottom) => {
621
+ if (extents)
622
+ includeTrackExtent(extents, owner, top, bottom);
623
+ else if (extent)
624
+ includeExtent(extent, top, bottom);
625
+ else
626
+ extent = { top, bottom };
627
+ };
628
+ // 主体和附件共用范围筛选,仅累加结果的容器随查询模式变化。
629
+ const { start, end, wholeLine } = resolveRange(view, columns, track, lift);
630
+ const target = track && lift(track);
631
+ let left = wholeLine ? baseContext.originX : Infinity;
632
+ let right = wholeLine ? baseContext.originX + baseContext.width : -Infinity;
633
+ for (let column = start; column <= end; column++) {
634
+ for (const host of view.columns[column]) {
635
+ if (target && host.track !== target)
636
+ continue;
637
+ if (!wholeLine) {
638
+ if (host.box.x < left)
639
+ left = host.box.x;
640
+ if (host.box.x + host.box.w > right)
641
+ right = host.box.x + host.box.w;
642
+ }
643
+ const decoration = decorationExtents.get(host);
644
+ const top = decoration?.top ?? 0;
645
+ const hostTop = host.box.y + top - baseContext.getVisualAxis(line, host.track);
646
+ include(host.track, hostTop, hostTop + (host.box.h - top + (decoration?.bottom ?? 0)));
647
+ }
648
+ }
649
+ for (const range of occupancy[line] ?? []) {
650
+ if (target && range.track !== target)
651
+ continue;
652
+ if (range.right <= left || range.left >= right)
653
+ continue;
654
+ include(range.track, range.top, range.bottom);
655
+ }
656
+ return extents ?? extent;
657
+ }
329
658
  const context = {
330
659
  ...baseContext,
660
+ getRangeExtents,
661
+ getAttachmentOccupancy(dependency) {
662
+ const geometry = resolveAttachment(dependency)?.geometry;
663
+ return geometry && (geometry.occupancy ?? geometry.regions);
664
+ },
331
665
  getAttachmentBox(dependency) {
332
- const resolved = measured.get(dependency);
666
+ const resolved = resolveAttachment(dependency);
333
667
  if (!resolved)
334
668
  throw new Error("Layout attachment dependency has not been measured");
335
669
  return resolved.box;
336
670
  },
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
- }
671
+ getContentBounds(content) {
672
+ const boxes = [];
673
+ for (const node of content.nodes) {
674
+ if (isVisualTemporalNode(node) && (node.box.w > 0 || node.box.h > 0))
675
+ boxes.push(getLayoutBounds(node, true));
364
676
  }
365
- for (const range of target.attachmentRanges) {
366
- if (range.right <= left || range.left >= right)
677
+ for (const attachment of content.attachments) {
678
+ if (!isLayoutAttachment(attachment))
367
679
  continue;
368
- includeTrackExtent(extents, range.track, range.top, range.bottom);
680
+ // 端点越出本域的关系交给外层测量,此时还没有几何
681
+ const resolved = resolveAttachment(attachment);
682
+ if (!resolved && !attachments.includes(attachment))
683
+ continue;
684
+ const box = resolved?.box ?? context.getAttachmentBox(attachment);
685
+ if (box.w > 0 || box.h > 0)
686
+ boxes.push(box);
369
687
  }
370
- return extents;
688
+ const bounds = { x: 0, y: 0, w: 0, h: 0 };
689
+ return unionLayoutBoxes(bounds, boxes) ? bounds : undefined;
371
690
  },
372
691
  };
373
692
  const items = attachments.map(attachment => {
@@ -381,17 +700,19 @@ function measureAttachments(attachments, baseContext, lines) {
381
700
  if (region.line === void 0)
382
701
  continue;
383
702
  const line = lines[region.line];
384
- const top = region.y - baseContext.getVisualAxis(region.line, region.track);
703
+ const track = lift(region.track);
704
+ const top = region.y - baseContext.getVisualAxis(region.line, track);
385
705
  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)) {
706
+ const hostExtent = line.hostExtents.get(track);
707
+ const attachmentExtent = line.attachmentExtents.get(track);
708
+ if (reserve && (top < Math.min(hostExtent?.top ?? Infinity, attachmentExtent?.top ?? Infinity)
709
+ || bottom > Math.max(hostExtent?.bottom ?? -Infinity, attachmentExtent?.bottom ?? -Infinity))) {
390
710
  needsRelayout = true;
391
711
  }
392
- includeTrackExtent(line.attachmentExtents, region.track, top, bottom);
393
- line.attachmentRanges.push({
394
- track: region.track,
712
+ if (reserve)
713
+ includeTrackExtent(line.attachmentExtents, track, top, bottom);
714
+ (occupancy[region.line] ??= []).push({
715
+ track,
395
716
  left: region.x,
396
717
  right: region.x + region.w,
397
718
  top,
@@ -402,6 +723,14 @@ function measureAttachments(attachments, baseContext, lines) {
402
723
  });
403
724
  return { items, needsRelayout };
404
725
  }
726
+ /** 固有占用只需轴局部边界,不必创建全局矩形 */
727
+ function includeHostExtent(extents, host) {
728
+ const decoration = decorationExtents.get(host);
729
+ const top = decoration?.top ?? 0;
730
+ const height = host.box.h - top + (decoration?.bottom ?? 0);
731
+ const axisTop = top - host.box.visualAxis;
732
+ includeTrackExtent(extents, host.track, axisTop, axisTop + height);
733
+ }
405
734
  /**
406
735
  * 沿 Track 树自内向外求出一条谱面行里所有音轨的纵向轴
407
736
  *