jpfun 1.1.0 → 1.2.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 (54) hide show
  1. package/dist/diagnostic.d.ts +1 -0
  2. package/dist/diagnostic.js +1 -0
  3. package/dist/functions/ASTtypes.d.ts +2 -3
  4. package/dist/functions/ASTtypes.js +2 -3
  5. package/dist/functions/adjust/index.js +15 -67
  6. package/dist/functions/bar/index.js +8 -7
  7. package/dist/functions/beam/auto.js +15 -11
  8. package/dist/functions/beam/layout.js +22 -48
  9. package/dist/functions/br/index.d.ts +9 -3
  10. package/dist/functions/br/index.js +20 -16
  11. package/dist/functions/dash/index.js +13 -11
  12. package/dist/functions/div/index.d.ts +2 -2
  13. package/dist/functions/div/index.js +5 -9
  14. package/dist/functions/dot/index.js +5 -9
  15. package/dist/functions/dyn/index.js +125 -53
  16. package/dist/functions/grace/index.d.ts +2 -2
  17. package/dist/functions/grace/index.js +5 -9
  18. package/dist/functions/head/index.js +6 -7
  19. package/dist/functions/meter/index.js +7 -5
  20. package/dist/functions/note/index.js +5 -7
  21. package/dist/functions/ottava/index.js +8 -7
  22. package/dist/functions/page/index.js +8 -12
  23. package/dist/functions/pagebreak/index.js +2 -1
  24. package/dist/functions/rest/index.js +5 -5
  25. package/dist/functions/stack/index.js +1 -3
  26. package/dist/functions/symbol/symbols/dynamics.d.ts +3 -0
  27. package/dist/functions/symbol/symbols/dynamics.js +10 -1
  28. package/dist/functions/tempo/index.js +8 -3
  29. package/dist/functions/temporal.d.ts +18 -6
  30. package/dist/functions/temporal.js +1 -1
  31. package/dist/functions/text/index.js +1 -3
  32. package/dist/functions/up/index.js +29 -28
  33. package/dist/functions/voice/voice.d.ts +2 -1
  34. package/dist/functions/voice/voice.js +7 -13
  35. package/dist/functions/voice/voices.d.ts +4 -3
  36. package/dist/functions/voice/voices.js +8 -8
  37. package/dist/jpfun.min.js +48 -45
  38. package/dist/layout/engine.js +224 -211
  39. package/dist/layout/page.d.ts +2 -2
  40. package/dist/layout/page.js +8 -22
  41. package/dist/layout/types.d.ts +2 -4
  42. package/dist/lowering/loweringContext.d.ts +12 -7
  43. package/dist/lowering/loweringContext.js +50 -51
  44. package/dist/lowering/types.d.ts +2 -3
  45. package/dist/parser/grammarType.d.ts +4 -3
  46. package/dist/parser/parse-utils/brace-utils.js +4 -3
  47. package/dist/parser/parse-utils/call-utils.js +7 -7
  48. package/dist/parser/parserContext.d.ts +5 -9
  49. package/dist/parser/parserContext.js +24 -36
  50. package/dist/parser/types.d.ts +2 -1
  51. package/dist/playback/compile.js +23 -13
  52. package/dist/playback/types.d.ts +0 -1
  53. package/grammar.md +7 -6
  54. package/package.json +2 -2
@@ -92,15 +92,9 @@ export function layoutDocument(result, context, options = {}) {
92
92
  // 子域在主体准备时就排版完毕;它认领的附件保留块内几何,随块平移
93
93
  const order = new Map(layoutAttachments.map((attachment, index) => [attachment, index]));
94
94
  const relations = groupRelations(layoutAttachments);
95
- let hosts = [];
96
- if (layoutAttachments.length) {
97
- for (const nodes of result.astToTemporal.values()) {
98
- if (!nodes.some(node => node.placementOffset?.x || node.placementOffset?.y))
99
- continue;
100
- hosts = [...new Set([...result.astToTemporal.values()].flat().filter(isVisualTemporalNode))];
101
- break;
102
- }
103
- }
95
+ const displaced = collectDisplaced(result);
96
+ // 块内(含内层块)有平移的复合体:外层可能依赖它的附件,也要分开测量布局与绘制
97
+ const displacedBlocks = [];
104
98
  const subdomainItems = new Map();
105
99
  const subdomainGeometry = (attachment, layoutOnly = false) => {
106
100
  const item = subdomainItems.get(attachment);
@@ -127,7 +121,11 @@ export function layoutDocument(result, context, options = {}) {
127
121
  own.push(relation);
128
122
  }
129
123
  own.sort((left, right) => order.get(left) - order.get(right));
130
- const block = layoutSubdomainBlock(columns, line, root, own, context, subdomainGeometry, hosts.length ? hosts.filter(within) : hosts, owner);
124
+ const nodes = displaced.filter(within);
125
+ const layoutOnly = nodes.length > 0 || own.some(isDisplaced) || displacedBlocks.some(within);
126
+ if (layoutOnly)
127
+ displacedBlocks.push(owner);
128
+ const block = layoutSubdomainBlock(columns, line, root, own, context, subdomainGeometry, { nodes, layoutOnly });
131
129
  own.forEach((attachment, index) => subdomainItems.set(attachment, block.items[index]));
132
130
  return { width: line.width, height: block.height, positions: block.positions };
133
131
  },
@@ -176,26 +174,29 @@ export function layoutDocument(result, context, options = {}) {
176
174
  }
177
175
  // 根据配置得到行距
178
176
  const rowGaps = measureRowGaps(lines.length, objects, options.rowGap);
179
- /** 按当前主体与 attachment 占用求轴、分页并放置所有主体 */
177
+ const domain = { lines, views, lift };
178
+ let pages = [];
179
+ /** 按当前主体与 attachment 占用求轴、分页并放置所有主体,返回本轮的附件上下文 */
180
180
  const placeVertically = () => {
181
181
  const heights = [];
182
- const headrooms = [];
182
+ const gaps = [];
183
183
  const axes = lines.map((line, i) => {
184
184
  const solved = solveVerticalAxes(line, result.rootTrack, rowGaps[i]);
185
185
  heights.push(solved.height);
186
+ // 行顶高出主旋律上沿(基线 - 半字高)的外扩先借用行距,再保留 minGap
186
187
  let top = Infinity;
187
188
  for (const column of line.columns) {
188
189
  for (const node of column) {
189
190
  top = Math.min(top, (solved.axes.get(node.track) ?? 0) - node.ast.size / 2);
190
191
  }
191
192
  }
192
- headrooms.push(top < Infinity ? top : 0);
193
+ const { gap = 0, minGap = 0 } = line.breakBefore ?? {};
194
+ gaps.push(Math.max(gap - (top < Infinity ? Math.max(0, top) : 0), Math.min(gap, minGap)));
193
195
  return solved.axes;
194
196
  });
195
- let pages;
196
197
  let lineTops;
197
198
  try {
198
- ({ pages, lineTops } = paginateLayoutLines(heights, page, pageBreaks, headrooms));
199
+ ({ pages, lineTops } = paginateLayoutLines(heights, page, pageBreaks, gaps));
199
200
  }
200
201
  catch (error) {
201
202
  if (!(error instanceof PageLayoutError))
@@ -220,31 +221,15 @@ export function layoutDocument(result, context, options = {}) {
220
221
  node.box.y = visualAxisOf(node.layoutLine, node.track) - node.box.visualAxis;
221
222
  node.onPlaced?.();
222
223
  }
223
- const attachmentContext = {
224
- ...context,
225
- width: contentWidth,
226
- originX,
227
- pages: pages.map(item => item.bounds),
228
- lines: views,
229
- // 子域的私有轨在正文里归入复合体所在的轨
230
- getVisualAxis: (line, track) => visualAxisOf(line, lift(track)),
231
- getHostExtent: (line, track) => lines[line]?.hostExtents.get(lift(track)),
232
- getRangeColumns: (line, range, track) => rangeColumns(views[line], range, track, lift),
233
- };
234
- return { pages, attachmentContext };
224
+ return attachmentContext(context, domain, { width: contentWidth, originX, pages: pages.map(item => item.bounds) }, visualAxisOf);
235
225
  };
236
- // 3. 首次纵向放置后测量 attachment;只有有效轨道占用扩张时才重新求解
237
- let placement = placeVertically();
238
- let measured = measureAttachments(documentAttachments, placement.attachmentContext, lines, lift, subdomainGeometry, hosts);
239
- if (measured.needsRelayout) {
240
- placement = placeVertically();
241
- measured = measureAttachmentPass(documentAttachments, placement.attachmentContext, lines, lift, subdomainGeometry, false);
242
- }
243
- const pages = placement.pages;
226
+ // 3. 放置并测量正文 attachment,扩张有效轨道占用时重排一次,最后施加后置平移
227
+ // 正文的作用域是全文:子域认领的附件有平移时,正文依赖它也只能读布局快照
228
+ const displacement = { nodes: displaced, layoutOnly: displaced.length > 0 || layoutAttachments.some(isDisplaced) };
229
+ const { items } = placeAndMeasure(domain, placeVertically, documentAttachments, subdomainGeometry, displacement);
244
230
  let next = 0;
245
231
  const attachments = layoutAttachments.map(attachment => {
246
- const item = subdomainItems.get(attachment);
247
- const { geometry } = item ? moveSubdomainItem(item) : measured.items[next++];
232
+ const { geometry } = subdomainGeometry(attachment) ?? items[next++];
248
233
  return {
249
234
  kind: attachment.kind,
250
235
  regions: geometry.regions,
@@ -339,7 +324,7 @@ function splitLayoutLines(result) {
339
324
  for (const column of result.columns) {
340
325
  const visibleColumn = []; // 从列中提取可见元素
341
326
  // 空行
342
- while (lines.length < column[0].layoutLine) {
327
+ while (lines.length < column.layoutLine) {
343
328
  lines.push(currentLine);
344
329
  currentLine = createLine();
345
330
  }
@@ -348,6 +333,9 @@ function splitLayoutLines(result) {
348
333
  if (pageBreak !== undefined) {
349
334
  pageBreaks[lines.length] = (pageBreaks[lines.length] ?? true) && pageBreak;
350
335
  }
336
+ const brk = node.addon?.breakBefore, prev = currentLine.breakBefore;
337
+ if (brk)
338
+ currentLine.breakBefore = prev ? { gap: Math.max(prev.gap, brk.gap), minGap: Math.max(prev.minGap, brk.minGap) } : brk;
351
339
  if (isVisualTemporalNode(node))
352
340
  visibleColumn.push(node);
353
341
  }
@@ -472,6 +460,67 @@ function alignHorizontalBars(views, regions, contentWidth, pageBreaks) {
472
460
  });
473
461
  const divides = (a, b) => a % b === 0 || b % a === 0;
474
462
  const gcd = (a, b) => b ? gcd(b, a % b) : a;
463
+ // 在各行小节数最小公倍数 L 的细网格上求公共台阶(整段时 L 即最大小节数,回退子窗口时也保证整除),并通过水位填充(涨水填谷)补足剩余空白
464
+ const buildGrid = (lo, hi) => {
465
+ const group = states.slice(lo, hi + 1);
466
+ const L = group.reduce((acc, n) => acc / gcd(acc, n.minW.length) * n.minW.length, 1);
467
+ const grid = new Array(L).fill(0);
468
+ // 先填细网格行,再把粗网格行(如 2 小节行)超出对应细格之和的差额平摊进去
469
+ for (const n of [...group].sort((a, b) => b.minW.length - a.minW.length)) {
470
+ const step = L / n.minW.length;
471
+ for (let m = 0; m < n.minW.length; m++) {
472
+ const w = n.minW[m];
473
+ let sum = 0;
474
+ for (let j = 0; j < step; j++)
475
+ sum += grid[m * step + j];
476
+ if (w > sum)
477
+ for (let j = 0; j < step; j++)
478
+ grid[m * step + j] += (w - sum) / step;
479
+ }
480
+ }
481
+ // 公共台阶总和不超过行宽时,把水位拉到 avg,只填平低于水位的窄格,不拉大已高于水位的宽格
482
+ // open 记录段内所有行在该细格均有自由间隙,供第 3 步复用
483
+ const open = grid.map((_, g) => Number(group.every(n => n.gaps[Math.floor(g * n.minW.length / L)] > 0)));
484
+ const free = open.slice();
485
+ let rem = contentWidth;
486
+ for (let g = 0; g < L; g++)
487
+ if (!free[g])
488
+ rem -= grid[g];
489
+ for (let step = 0; step < L; step++) {
490
+ const freeSum = free.reduce((a, b) => a + b, 0);
491
+ if (!freeSum || rem <= 0)
492
+ break;
493
+ const avg = rem / freeSum;
494
+ if (!grid.some((w, g) => free[g] && w > avg && (rem -= w, free[g] = 0, true))) {
495
+ for (let g = 0; g < L; g++)
496
+ if (free[g])
497
+ grid[g] = avg;
498
+ break;
499
+ }
500
+ }
501
+ return { L, grid, open };
502
+ };
503
+ // 公共台阶只取决于窗口,按窗口缓存,避免段内每行重建网格导致 O(行数²);每行只把每 r 个细格合回自己的 1 个小节目标宽度
504
+ const grids = new Map();
505
+ const targetOf = (s, lo, hi) => {
506
+ const key = lo * states.length + hi;
507
+ let cell = grids.get(key);
508
+ if (!cell)
509
+ grids.set(key, cell = buildGrid(lo, hi));
510
+ const { L, grid, open } = cell, r = L / s.minW.length;
511
+ // 本行被 @rest 等完全锁死的小节保持原宽
512
+ const target = s.minW.map((w, m) => {
513
+ if (!s.gaps[m])
514
+ return w;
515
+ let sum = 0;
516
+ for (let j = 0; j < r; j++)
517
+ sum += grid[m * r + j];
518
+ return sum;
519
+ });
520
+ return { r, open, target };
521
+ };
522
+ // 同小节数且被上一行段覆盖的行,两侧扩展与相同行窗口的扫描都与上一行一致,从上一行结果续扫以免每行重扫整段
523
+ let prev;
475
524
  for (let l = 0; l < states.length; l++) {
476
525
  const s = states[l];
477
526
  if (!s || s.extra <= 0 || !s.totalGaps)
@@ -479,75 +528,36 @@ function alignHorizontalBars(views, regions, contentWidth, pageBreaks) {
479
528
  const M = s.minW.length;
480
529
  // 2. 向两侧扩展收集连续行段:新行小节数须与本行及段内最大小节数都成整数倍,从而段内各行都整除最大小节数
481
530
  // (如 2、6 小节行成段后不再并入 4 小节行);遇到 extra = 0 的挤压行或强制换页即作为刚性边界停下
482
- let start = l, end = l, maxM = M;
483
- const joins = (n) => !!n && divides(n.minW.length, M) && divides(n.minW.length, maxM);
484
- while (states[start].extra > 0 && pageBreaks[start] === undefined && joins(states[start - 1]))
485
- maxM = Math.max(maxM, states[--start].minW.length);
486
- while (states[end].extra > 0 && pageBreaks[end + 1] === undefined && joins(states[end + 1]))
487
- maxM = Math.max(maxM, states[++end].minW.length);
531
+ const last = prev?.l === l - 1 && prev.s.minW.length === M && prev.end >= l ? prev : undefined;
532
+ let start = last?.start ?? l, end = last?.end ?? l, maxM = M;
533
+ if (!last) {
534
+ const joins = (n) => !!n && divides(n.minW.length, M) && divides(n.minW.length, maxM);
535
+ while (states[start].extra > 0 && pageBreaks[start] === undefined && joins(states[start - 1]))
536
+ maxM = Math.max(maxM, states[--start].minW.length);
537
+ while (states[end].extra > 0 && pageBreaks[end + 1] === undefined && joins(states[end + 1]))
538
+ maxM = Math.max(maxM, states[++end].minW.length);
539
+ }
540
+ prev = { l, s, start, end };
488
541
  if (start === end)
489
542
  continue;
490
- // 在各行小节数最小公倍数 L 的细网格上求公共台阶(整段时 L 即最大小节数,回退子窗口时也保证整除),并通过水位填充(涨水填谷)补足剩余空白
491
- const env = (lo, hi) => {
492
- const group = states.slice(lo, hi + 1);
493
- const L = group.reduce((acc, n) => acc / gcd(acc, n.minW.length) * n.minW.length, 1), r = L / M;
494
- const grid = new Array(L).fill(0);
495
- // 先填细网格行,再把粗网格行(如 2 小节行)超出对应细格之和的差额平摊进去
496
- for (const n of [...group].sort((a, b) => b.minW.length - a.minW.length)) {
497
- const step = L / n.minW.length;
498
- for (let m = 0; m < n.minW.length; m++) {
499
- const w = n.minW[m];
500
- let sum = 0;
501
- for (let j = 0; j < step; j++)
502
- sum += grid[m * step + j];
503
- if (w > sum)
504
- for (let j = 0; j < step; j++)
505
- grid[m * step + j] += (w - sum) / step;
506
- }
507
- }
508
- // 公共台阶总和不超过行宽时,把水位拉到 avg,只填平低于水位的窄格,不拉大已高于水位的宽格
509
- const free = grid.map((_, g) => Number(group.every(n => n.gaps[Math.floor(g * n.minW.length / L)] > 0)));
510
- let rem = contentWidth;
511
- for (let g = 0; g < L; g++)
512
- if (!free[g])
513
- rem -= grid[g];
514
- for (let step = 0; step < L; step++) {
515
- const freeSum = free.reduce((a, b) => a + b, 0);
516
- if (!freeSum || rem <= 0)
517
- break;
518
- const avg = rem / freeSum;
519
- if (!grid.some((w, g) => free[g] && w > avg && (rem -= w, free[g] = 0, true))) {
520
- for (let g = 0; g < L; g++)
521
- if (free[g])
522
- grid[g] = avg;
523
- break;
524
- }
525
- }
526
- // 将每 r 个细格合回本行的 1 个小节目标宽度(本行被 @rest 等完全锁死的小节保持原宽)
527
- const target = s.minW.map((w, m) => {
528
- if (!s.gaps[m])
529
- return w;
530
- let sum = 0;
531
- for (let j = 0; j < r; j++)
532
- sum += grid[m * r + j];
533
- return sum;
534
- });
535
- return { group, target };
536
- };
537
- let { group, target } = env(start, end);
543
+ let { r, open, target } = targetOf(s, start, end);
538
544
  // 若整段公共台阶总和超出行宽,退回只与上下紧邻行对齐;与本行台阶相同的相邻行视为一体共用窗口,避免相同行逐行错开
539
545
  if (target.reduce((a, b) => a + b, 0) > contentWidth + 1e-6) {
540
546
  const same = (n) => n?.minW.length === M
541
547
  && n.minW.every((w, m) => Math.abs(w - s.minW[m]) <= 1e-6 && !n.gaps[m] === !s.gaps[m]);
542
- let lo = l, hi = l;
548
+ // 与上一行逐值相同时 same 判定不变,上一行窗口的两端必然停在扫描终点,从那里续扫即可
549
+ let [lo, hi] = last?.win && last.win[1] >= l
550
+ && last.s.minW.every((w, m) => w === s.minW[m] && last.s.gaps[m] === s.gaps[m]) ? last.win : [l, l];
543
551
  while (lo > start && same(states[lo - 1]))
544
552
  lo--;
545
553
  while (hi < end && same(states[hi + 1]))
546
554
  hi++;
547
- ({ group, target } = env(Math.max(start, lo - 1), Math.min(end, hi + 1)));
555
+ prev.win = [lo, hi];
556
+ ({ r, open, target } = targetOf(s, Math.max(start, lo - 1), Math.min(end, hi + 1)));
548
557
  }
549
558
  // 3. 退水触底:若目标总宽仍超出行宽(空白不够追平邻行),同步回缩并在碰到本行底线 minW 时锁死
550
- const free = s.gaps.map((g, m) => g > 0 ? Number(group.every(n => n.gaps[Math.floor(m * n.minW.length / M)] > 0)) : 0);
559
+ // 本行第 m 小节对应细格 m·r,段内各行在该细格的自由标记即 open[m·r]
560
+ const free = s.gaps.map((g, m) => g > 0 ? open[m * r] : 0);
551
561
  if (!free.some(Boolean))
552
562
  for (let m = 0; m < M; m++)
553
563
  free[m] = Number(s.gaps[m] > 0);
@@ -615,10 +625,10 @@ function layoutLocalLine(columns, context) {
615
625
  /**
616
626
  * 把已横排的子域按正文规则纵向排版,坐标以块的左上角为原点
617
627
  *
618
- * 与正文行的流程相同:沿 root 的 Track 树求轴放置,按登记顺序测量附件,
619
- * 附件扩张占用时重排一次。positions 是放置时写入的块内位置,不含成员 onPlaced 追加的平移
628
+ * 与正文行共用 placeAndMeasure:沿 root 的 Track 树求轴放置,按登记顺序测量附件,
629
+ * 附件扩张占用时重排一次,最后施加块内的后置平移。positions 是放置时写入的块内布局位置,不含后置平移
620
630
  */
621
- function layoutSubdomainBlock(columns, { width, view }, root, attachments, context, measuredElsewhere, hosts, owner) {
631
+ function layoutSubdomainBlock(columns, { width, view }, root, attachments, context, lookup, displacement) {
622
632
  const members = columns.flat();
623
633
  const extents = { hostExtents: new Map(), attachmentExtents: new Map() };
624
634
  let gap = 0;
@@ -626,49 +636,82 @@ function layoutSubdomainBlock(columns, { width, view }, root, attachments, conte
626
636
  includeHostExtent(extents.hostExtents, member);
627
637
  gap = Math.max(gap, member.ast.size * ROW_GAP_RATIO);
628
638
  }
639
+ const lines = [];
640
+ const views = [];
641
+ lines[view.index] = extents;
642
+ views[view.index] = view;
643
+ const domain = { lines, views, lift: liftInto(root) };
629
644
  const positions = members.map(member => ({ x: member.box.x, y: 0 }));
630
- const place = () => {
631
- const solved = solveVerticalAxes(extents, root, gap);
645
+ let solved;
646
+ const blockContext = attachmentContext(context, domain, { width, originX: 0, pages: [] }, (_line, track) => solved.axes.get(track) ?? 0);
647
+ const { items, layoutItems } = placeAndMeasure(domain, () => {
648
+ solved = solveVerticalAxes(extents, root, gap);
632
649
  members.forEach((member, index) => {
633
650
  member.box.y = positions[index].y = solved.axes.get(member.track) - member.box.visualAxis;
634
651
  member.onPlaced?.();
635
652
  });
636
- return solved;
653
+ return blockContext;
654
+ }, attachments, lookup, displacement, true);
655
+ // 以首个成员为参照:布局快照就是它的块内位置,绘制快照取平移后的位置
656
+ const reference = members[0];
657
+ const painted = { x: reference.box.x, y: reference.box.y };
658
+ return {
659
+ height: solved.height,
660
+ positions,
661
+ items: items.map(({ geometry }, index) => {
662
+ const paint = { geometry, position: painted };
663
+ const layout = layoutItems ? { geometry: layoutItems[index].geometry, position: positions[0] } : paint;
664
+ return { reference, paint, layout };
665
+ }),
637
666
  };
638
- let solved = place();
639
- if (attachments.length === 0)
640
- return { height: solved.height, positions, items: [] };
641
- const lift = liftInto(root);
642
- // 附件按行号查询,子域只占自己所在的那一行
643
- const lines = [];
644
- const views = [];
645
- lines[view.index] = extents;
646
- views[view.index] = view;
647
- const measure = () => measureAttachments(attachments, {
667
+ }
668
+ /** 正文与子域的附件上下文只差页面坐标系与视觉轴来源 */
669
+ function attachmentContext(context, { lines, views, lift }, frame, axisOf) {
670
+ return {
648
671
  ...context,
649
- width,
650
- originX: 0,
651
- pages: [],
672
+ ...frame,
652
673
  lines: views,
653
- getVisualAxis: (_line, track) => solved.axes.get(lift(track)) ?? 0,
674
+ getVisualAxis: (line, track) => axisOf(line, lift(track)),
654
675
  getHostExtent: (line, track) => lines[line]?.hostExtents.get(lift(track)),
655
676
  getRangeColumns: (line, range, track) => rangeColumns(views[line], range, track, lift),
656
- }, lines, lift, measuredElsewhere, hosts, owner);
657
- let measured = measure();
658
- if (measured.needsRelayout) {
659
- solved = place();
660
- measured = measure();
661
- }
662
- const reference = members[0];
663
- const position = { x: reference.box.x, y: reference.box.y };
664
- const offset = measured.layoutItems && placementOffset(reference, owner);
665
- const layoutPosition = offset && (offset.x !== 0 || offset.y !== 0)
666
- ? { x: position.x - offset.x, y: position.y - offset.y } : position;
667
- const items = measured.items.map((item, index) => ({
668
- ...item, reference, position,
669
- ...(measured.layoutItems && { layout: { ...measured.layoutItems[index], position: layoutPosition } }),
670
- }));
671
- return { height: solved.height, positions, items };
677
+ };
678
+ }
679
+ /**
680
+ * 正文与子域共用的纵向流程:放置 → 测占用 → [重排一次] → 后置平移 → 测绘制几何
681
+ *
682
+ * place 写入主体坐标并返回本轮附件上下文。有后置平移时首轮只测布局位置的占用,平移后再生成绘制几何;
683
+ * 既无平移也未重排时首轮几何就是最终结果。keepLayout 时另留一份最终布局位置下的占用几何,供外层读取。
684
+ */
685
+ function placeAndMeasure(domain, place, attachments, lookup, { nodes, layoutOnly }, keepLayout = false) {
686
+ const measure = (context, layoutOnly) => measureAttachmentPass(attachments, context, domain.lift, lookup, layoutOnly);
687
+ let context = place();
688
+ let measured = measure(context, layoutOnly);
689
+ const relayout = reserveOccupancy(domain.lines, measured.occupancy);
690
+ if (relayout)
691
+ context = place();
692
+ const layoutItems = keepLayout && layoutOnly ? (relayout ? measure(context, true) : measured).items : undefined;
693
+ displace(nodes);
694
+ if (relayout || layoutOnly)
695
+ measured = measure(context, false);
696
+ return { items: measured.items, layoutItems };
697
+ }
698
+ /**
699
+ * 首轮占用并入各行的附件占用,供重排时求轴;任一块越出主体占用就需要重排
700
+ *
701
+ * 与逐块比较「主体 ∪ 此前各块」等价:第一个越界块之前的块都落在主体占用之内
702
+ */
703
+ function reserveOccupancy(lines, occupancy) {
704
+ let needsRelayout = false;
705
+ occupancy.forEach((ranges, line) => {
706
+ const { hostExtents, attachmentExtents } = lines[line];
707
+ for (const { track, top, bottom } of ranges) {
708
+ const host = hostExtents.get(track);
709
+ if (!host || top < host.top || bottom > host.bottom)
710
+ needsRelayout = true;
711
+ includeTrackExtent(attachmentExtents, track, top, bottom);
712
+ }
713
+ });
714
+ return needsRelayout;
672
715
  }
673
716
  /**
674
717
  * 关系附件按首端点所在的各层复合体建立候选索引,由内到外逐层登记
@@ -689,22 +732,47 @@ function groupRelations(attachments) {
689
732
  return groups;
690
733
  }
691
734
  /** 子域是刚性块:按参照成员的位移平移块内测得的几何 */
692
- function moveSubdomainItem(item, layoutOnly = false) {
693
- const measured = layoutOnly ? item.layout ?? item : item;
694
- const { position, geometry } = measured;
695
- const dx = item.reference.box.x - position.x;
696
- const dy = item.reference.box.y - position.y;
697
- if (dx === 0 && dy === 0)
698
- return measured;
735
+ function moveSubdomainItem({ reference, paint, layout }, layoutOnly = false) {
736
+ const { geometry, position } = layoutOnly ? layout : paint;
737
+ const dx = reference.box.x - position.x;
738
+ const dy = reference.box.y - position.y;
739
+ return { geometry: dx === 0 && dy === 0 ? geometry : translateGeometry(geometry, dx, dy) };
740
+ }
741
+ function translateGeometry(geometry, dx, dy) {
699
742
  const move = (rect) => ({ ...rect, x: rect.x + dx, y: rect.y + dy });
700
743
  return {
701
- geometry: {
702
- regions: geometry.regions.map(move),
703
- occupancy: geometry.occupancy?.map(move),
704
- paint: painter => geometry.paint(new TranslatingPainter(painter, dx, dy)),
705
- },
744
+ regions: geometry.regions.map(move),
745
+ occupancy: geometry.occupancy?.map(move),
746
+ // attachment 的绘制大多用闭包保存几何,只能代理 painter
747
+ paint: painter => geometry.paint(new TranslatingPainter(painter, dx, dy)),
706
748
  };
707
749
  }
750
+ function isDisplaced(target) {
751
+ return !!(target.placementOffset?.x || target.placementOffset?.y);
752
+ }
753
+ /** 按 foldedInto 深度排序,外层先平移:复合体的 onPlaced 带动成员,成员再叠加自己的平移 */
754
+ function collectDisplaced(result) {
755
+ const depths = new Map();
756
+ for (const nodes of result.astToTemporal.values()) {
757
+ for (const node of nodes) {
758
+ if (!isVisualTemporalNode(node) || !isDisplaced(node))
759
+ continue;
760
+ let depth = 0;
761
+ for (let host = node.foldedInto; host; host = host.foldedInto)
762
+ depth++;
763
+ depths.set(node, depth);
764
+ }
765
+ }
766
+ return [...depths.keys()].sort((left, right) => depths.get(left) - depths.get(right));
767
+ }
768
+ /** 占用测量完成后施加后置平移;之后不得再放置,否则复合体会把成员同步回布局位置 */
769
+ function displace(nodes) {
770
+ for (const node of nodes) {
771
+ node.box.x += node.placementOffset.x;
772
+ node.box.y += node.placementOffset.y;
773
+ node.onPlaced?.();
774
+ }
775
+ }
708
776
  /** 行距取该行最大字号的 ROW_GAP_RATIO 倍;没有可见对象的行回退到全文档最大字号 */
709
777
  function measureRowGaps(lineCount, objects, override) {
710
778
  if (override !== void 0)
@@ -722,67 +790,19 @@ function measureRowGaps(lineCount, objects, override) {
722
790
  gaps[i] ||= documentGap;
723
791
  return gaps;
724
792
  }
725
- /** 折叠成员继承外层平移,子域只累加当前复合体内部的平移 */
726
- function placementOffset(node, owner) {
727
- let x = 0;
728
- let y = 0;
729
- for (let host = node; host && host !== owner; host = host.foldedInto) {
730
- x += host.placementOffset?.x ?? 0;
731
- y += host.placementOffset?.y ?? 0;
732
- }
733
- return { x, y };
734
- }
735
- /** 后置平移只改变绘制几何,占用始终在未平移的布局位置测量 */
736
- function measureAttachments(attachments, baseContext, lines, lift, measuredElsewhere, hosts, owner) {
737
- if (attachments.length === 0)
738
- return { items: [], needsRelayout: false };
739
- const shifts = [];
740
- for (const node of hosts) {
741
- const { x, y } = placementOffset(node, owner);
742
- if (x !== 0 || y !== 0)
743
- shifts.push({ node, x, y, boxX: node.box.x, boxY: node.box.y });
744
- }
745
- const displaced = shifts.length > 0 || attachments.some(attachment => attachment.placementOffset?.x || attachment.placementOffset?.y);
746
- let layout;
747
- if (displaced) {
748
- for (const { node, x, y } of shifts) {
749
- node.box.x -= x;
750
- node.box.y -= y;
751
- }
752
- try {
753
- layout = measureAttachmentPass(attachments, { ...baseContext, layoutOnly: true }, lines, lift, measuredElsewhere, true);
754
- }
755
- finally {
756
- for (const { node, boxX, boxY } of shifts) {
757
- node.box.x = boxX;
758
- node.box.y = boxY;
759
- }
760
- }
761
- }
762
- else
763
- layout = measureAttachmentPass(attachments, baseContext, lines, lift, measuredElsewhere, true);
764
- if (!displaced)
765
- return layout;
766
- // 试测结果若被重排丢弃,就不再为它生成绘制几何
767
- let painted;
768
- return {
769
- needsRelayout: layout.needsRelayout,
770
- layoutItems: layout.items,
771
- get items() {
772
- return painted ??= measureAttachmentPass(attachments, baseContext, lines, lift, measuredElsewhere, false).items;
773
- },
774
- };
775
- }
776
- /** 按声明顺序测量几何,后注册的附件可以查询此前的区域和占用 */
777
- function measureAttachmentPass(attachments, baseContext, lines, lift, measuredElsewhere, reserve) {
793
+ /**
794
+ * 按声明顺序测量几何,后注册的附件可以查询此前的区域和占用;只读主体坐标,不改写行占用
795
+ *
796
+ * layoutOnly 用于有后置平移时的占用测量:主体尚未平移,附件自身的平移也不施加,依赖的子域附件取布局快照
797
+ */
798
+ function measureAttachmentPass(attachments, baseContext, lift, lookup, layoutOnly) {
778
799
  const measured = new Map();
779
800
  const occupancy = [];
780
- let needsRelayout = false;
781
801
  // 同一测量轮坐标不变,子域几何只需平移一次
782
802
  function resolveAttachment(dependency) {
783
803
  let item = measured.get(dependency);
784
804
  if (!item) {
785
- item = measuredElsewhere(dependency, baseContext.layoutOnly);
805
+ item = lookup(dependency, layoutOnly);
786
806
  if (item)
787
807
  measured.set(dependency, item);
788
808
  }
@@ -878,36 +898,29 @@ function measureAttachmentPass(attachments, baseContext, lines, lift, measuredEl
878
898
  },
879
899
  };
880
900
  const items = attachments.map(attachment => {
881
- const geometry = attachment.createGeometry(context);
901
+ let geometry = attachment.createGeometry(context);
902
+ if (!layoutOnly && isDisplaced(attachment)) {
903
+ geometry = translateGeometry(geometry, attachment.placementOffset.x, attachment.placementOffset.y);
904
+ }
882
905
  const item = { geometry };
883
906
  measured.set(attachment, item);
884
907
  // 当前项立即登记,保证后注册的 attachment 能看到并避让它
885
908
  for (const region of geometry.occupancy ?? geometry.regions) {
886
909
  if (region.line === void 0)
887
910
  continue;
888
- const line = lines[region.line];
889
911
  const track = lift(region.track);
890
912
  const top = region.y - baseContext.getVisualAxis(region.line, track);
891
- const bottom = top + region.h;
892
- const hostExtent = line.hostExtents.get(track);
893
- const attachmentExtent = line.attachmentExtents.get(track);
894
- if (reserve && (top < Math.min(hostExtent?.top ?? Infinity, attachmentExtent?.top ?? Infinity)
895
- || bottom > Math.max(hostExtent?.bottom ?? -Infinity, attachmentExtent?.bottom ?? -Infinity))) {
896
- needsRelayout = true;
897
- }
898
- if (reserve)
899
- includeTrackExtent(line.attachmentExtents, track, top, bottom);
900
913
  (occupancy[region.line] ??= []).push({
901
914
  track,
902
915
  left: region.x,
903
916
  right: region.x + region.w,
904
917
  top,
905
- bottom,
918
+ bottom: top + region.h,
906
919
  });
907
920
  }
908
921
  return item;
909
922
  });
910
- return { items, needsRelayout };
923
+ return { items, occupancy };
911
924
  }
912
925
  /** 主体完整占用相对盒顶的上沿与高度;调用方各自换算到轴局部或行坐标,不必创建全局矩形 */
913
926
  function hostSpan(host) {
@@ -21,9 +21,9 @@ export declare function normalizePageConfig(source?: Partial<PageConfig>): PageC
21
21
  /**
22
22
  * 把已经测好自然高度的谱面行分页,并给出每行的全局顶部坐标。
23
23
  * pageBreaks 按行号索引:undefined 不强制换页,true/false 强制换页并指定上一页是否拉伸。
24
- * headrooms 按行号索引:每行顶部高出主旋律上沿(基线 - 半字高)的外扩高度,优先借用上一行下方的行距留白。
24
+ * gaps 按行号索引:该行完整盒与上一行完整盒之间的自然间距,缺省为 0;页首行忽略。
25
25
  */
26
- export declare function paginateLayoutLines(heights: readonly number[], page: PageConfig, pageBreaks?: readonly (boolean | undefined)[], headrooms?: readonly number[]): {
26
+ export declare function paginateLayoutLines(heights: readonly number[], page: PageConfig, pageBreaks?: readonly (boolean | undefined)[], gaps?: readonly number[]): {
27
27
  pages: DocumentLayoutPage[];
28
28
  lineTops: number[];
29
29
  };