jpfun 0.9.0 → 1.1.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 (125) hide show
  1. package/README.md +11 -16
  2. package/dist/diagnostic.d.ts +29 -2
  3. package/dist/diagnostic.js +5 -4
  4. package/dist/functions/arpeggio/index.js +2 -3
  5. package/dist/functions/bar/index.d.ts +3 -0
  6. package/dist/functions/bar/index.js +21 -3
  7. package/dist/functions/beam/layout.js +3 -2
  8. package/dist/functions/box/index.js +1 -0
  9. package/dist/functions/dash/index.js +5 -2
  10. package/dist/functions/default.js +2 -1
  11. package/dist/functions/div/index.d.ts +1 -1
  12. package/dist/functions/div/index.js +4 -2
  13. package/dist/functions/dyn/index.js +1 -0
  14. package/dist/functions/gliss/index.js +85 -9
  15. package/dist/functions/grace/index.d.ts +1 -8
  16. package/dist/functions/grace/index.js +23 -53
  17. package/dist/functions/head/index.js +23 -30
  18. package/dist/functions/key/index.js +5 -7
  19. package/dist/functions/meter/index.d.ts +1 -0
  20. package/dist/functions/meter/index.js +3 -0
  21. package/dist/functions/meter/shape.d.ts +1 -1
  22. package/dist/functions/note/accidentals.d.ts +3 -3
  23. package/dist/functions/note/accidentals.js +29 -16
  24. package/dist/functions/note/index.d.ts +5 -2
  25. package/dist/functions/note/index.js +168 -25
  26. package/dist/functions/note/source-transform.d.ts +23 -2
  27. package/dist/functions/note/source-transform.js +95 -74
  28. package/dist/functions/ottava/index.js +1 -0
  29. package/dist/functions/page/index.d.ts +1 -36
  30. package/dist/functions/page/index.js +8 -7
  31. package/dist/functions/rest/index.js +8 -6
  32. package/dist/functions/set/index.js +2 -2
  33. package/dist/functions/slide/index.js +1 -0
  34. package/dist/functions/stack/index.js +6 -4
  35. package/dist/functions/temporal.d.ts +12 -3
  36. package/dist/functions/temporal.js +15 -2
  37. package/dist/functions/text/index.js +2 -2
  38. package/dist/functions/tie/index.js +28 -4
  39. package/dist/functions/tremolo/index.js +1 -0
  40. package/dist/functions/tuplet/index.js +1 -0
  41. package/dist/functions/up/index.js +12 -12
  42. package/dist/functions/voice/connections.d.ts +1 -1
  43. package/dist/functions/voice/connections.js +2 -2
  44. package/dist/functions/voice/lyrics.d.ts +11 -5
  45. package/dist/functions/voice/lyrics.js +151 -47
  46. package/dist/functions/voice/voice.d.ts +6 -2
  47. package/dist/functions/voice/voice.js +51 -19
  48. package/dist/functions/voice/voices.d.ts +2 -1
  49. package/dist/functions/voice/voices.js +4 -3
  50. package/dist/functions/volta/index.js +1 -0
  51. package/dist/index.d.ts +69 -3
  52. package/dist/index.js +69 -3
  53. package/dist/jpfun.min.js +47 -60
  54. package/dist/layout/engine.d.ts +4 -3
  55. package/dist/layout/engine.js +173 -27
  56. package/dist/layout/model.d.ts +13 -4
  57. package/dist/layout/model.js +15 -7
  58. package/dist/layout/page.js +2 -2
  59. package/dist/layout/path.js +1 -1
  60. package/dist/layout/types.d.ts +12 -3
  61. package/dist/lowering/accidentalMemory.d.ts +33 -0
  62. package/dist/lowering/accidentalMemory.js +84 -0
  63. package/dist/lowering/loweringContext.js +4 -0
  64. package/dist/parser/grammarType.d.ts +8 -3
  65. package/dist/parser/parse-utils/brace-utils.js +7 -17
  66. package/dist/parser/parse-utils/call-utils.d.ts +3 -1
  67. package/dist/parser/parse-utils/call-utils.js +17 -32
  68. package/dist/parser/parse-utils/note-utils.d.ts +4 -0
  69. package/dist/parser/parse-utils/note-utils.js +8 -12
  70. package/dist/parser/parse-utils/string-utils.d.ts +1 -1
  71. package/dist/parser/parse-utils/string-utils.js +1 -1
  72. package/dist/parser/parserContext.d.ts +32 -26
  73. package/dist/parser/parserContext.js +104 -194
  74. package/dist/parser/preprocess.d.ts +7 -0
  75. package/dist/parser/preprocess.js +31 -42
  76. package/dist/parser/syntax.d.ts +9 -0
  77. package/dist/parser/syntax.js +109 -0
  78. package/dist/pipeline.d.ts +1 -1
  79. package/dist/pipeline.js +3 -2
  80. package/dist/playback/compile.js +5 -7
  81. package/dist/playback/event.d.ts +1 -2
  82. package/dist/playback/event.js +2 -3
  83. package/dist/render/canvas.js +50 -35
  84. package/dist/render/index.d.ts +2 -1
  85. package/dist/render/index.js +2 -1
  86. package/dist/render/paint.d.ts +7 -0
  87. package/dist/render/paint.js +70 -20
  88. package/dist/render/recording.d.ts +8 -1
  89. package/dist/render/recording.js +12 -0
  90. package/dist/render/svg.d.ts +5 -1
  91. package/dist/render/svg.js +37 -17
  92. package/dist/render/text.d.ts +2 -2
  93. package/dist/render/text.js +7 -6
  94. package/dist/render/translate.d.ts +3 -1
  95. package/dist/render/translate.js +6 -0
  96. package/dist/render/types.d.ts +9 -0
  97. package/grammar.md +7 -5
  98. package/package.json +8 -18
  99. package/dist/converter/midi/convert.d.ts +0 -42
  100. package/dist/converter/midi/convert.js +0 -682
  101. package/dist/converter/midi/index.d.ts +0 -5
  102. package/dist/converter/midi/index.js +0 -11
  103. package/dist/converter/midi/json.d.ts +0 -38
  104. package/dist/converter/midi/json.js +0 -1
  105. package/dist/converter/midi/triplet.d.ts +0 -30
  106. package/dist/converter/midi/triplet.js +0 -75
  107. package/dist/converter/musicxml/dom.d.ts +0 -25
  108. package/dist/converter/musicxml/dom.js +0 -65
  109. package/dist/converter/musicxml/features.d.ts +0 -114
  110. package/dist/converter/musicxml/features.js +0 -501
  111. package/dist/converter/musicxml/index.d.ts +0 -14
  112. package/dist/converter/musicxml/index.js +0 -1285
  113. package/dist/converter/musicxml/model.d.ts +0 -176
  114. package/dist/converter/musicxml/model.js +0 -1
  115. package/dist/converter/musicxml/resolve.d.ts +0 -10
  116. package/dist/converter/musicxml/resolve.js +0 -152
  117. package/dist/converter/source.d.ts +0 -19
  118. package/dist/converter/source.js +0 -53
  119. package/dist/core.d.ts +0 -24
  120. package/dist/core.js +0 -24
  121. package/dist/functions/voice/index.d.ts +0 -2
  122. package/dist/functions/voice/index.js +0 -2
  123. package/dist/jpfun.core.min.js +0 -132
  124. package/dist/jpfun.from-midi.min.js +0 -9
  125. package/dist/jpfun.from-musicxml.min.js +0 -12
@@ -8,8 +8,6 @@ export interface DocumentLayoutOptions extends SolverOptions {
8
8
  rowGap?: number;
9
9
  horizontalOnly?: boolean;
10
10
  }
11
- export { PageLayoutError } from "./page.js";
12
- export type { DocumentLayoutPage } from "./page.js";
13
11
  export interface DocumentLayoutResult {
14
12
  diagnostics: Diagnostic[];
15
13
  objects: VisualTemporalNode[];
@@ -48,7 +46,10 @@ export declare function layoutDocument(result: LoweringResult, context: LayoutPr
48
46
  */
49
47
  export declare function prepareHorizontalLine(columns: readonly (readonly VisualTemporalNode[])[], index: number, options?: SolverOptions, compact?: boolean): {
50
48
  view: HorizontalLineView;
51
- layout(limit: number, fillMinRatio?: number): import("./model.js").LayoutElement[][];
49
+ layout(limit: number, fillMinRatio?: number): import("./model.js").LayoutElement[][] & {
50
+ extra: number;
51
+ groupOf: Uint32Array<ArrayBufferLike> | undefined;
52
+ };
52
53
  };
53
54
  /** 局部序列按给定顺序完成尺寸、约束与零间隙自然横排,归零占位左沿并返回完整宽度 */
54
55
  export declare function layoutLocalSequence(nodes: readonly VisualTemporalNode[], context: LayoutPrepareContext): number;
@@ -1,12 +1,10 @@
1
1
  import { Diagnostic } from "../diagnostic.js";
2
- import { isVisualTemporalNode, } from "../functions/temporal.js";
2
+ import { ANCHOR_KEY, 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
6
  import { liftInto, rangeColumns, resolveRange } from "./range.js";
7
7
  import { TranslatingPainter } from "../render/translate.js";
8
- // 兼容旧导入路径;布局入口会把正常页面溢出转换为 ErrorDiagnostic
9
- export { PageLayoutError } from "./page.js";
10
8
  /** 轨道间距相对行内最大字号的比例;正文行与子域共用 */
11
9
  const ROW_GAP_RATIO = 0.75;
12
10
  // 装饰边界是本轮排列结果,不作为主体上的第二套空间协议
@@ -110,6 +108,7 @@ export function layoutDocument(result, context, options = {}) {
110
108
  };
111
109
  context = {
112
110
  ...context,
111
+ solverOptions: options,
113
112
  layoutSubdomain(owner, columns, root, attachments) {
114
113
  // 横排时内层子域先排版并认领关系,这里只取剩下的
115
114
  const line = layoutLocalLine(columns, context);
@@ -150,8 +149,9 @@ export function layoutDocument(result, context, options = {}) {
150
149
  const views = horizontal.map(line => line.view);
151
150
  for (const attachment of documentAttachments)
152
151
  attachment.prepareHorizontal?.(views, context);
152
+ const regions = horizontal.map(line => line.layout(contentWidth, page.fillRatio));
153
+ alignHorizontalBars(views, regions, contentWidth, pageBreaks);
153
154
  for (const line of horizontal) {
154
- line.layout(contentWidth, page.fillRatio);
155
155
  for (const column of line.view.columns) {
156
156
  for (const node of column)
157
157
  node.box.x += originX;
@@ -246,6 +246,7 @@ export function layoutDocument(result, context, options = {}) {
246
246
  const item = subdomainItems.get(attachment);
247
247
  const { geometry } = item ? moveSubdomainItem(item) : measured.items[next++];
248
248
  return {
249
+ kind: attachment.kind,
249
250
  regions: geometry.regions,
250
251
  layer: attachment.layer,
251
252
  sourceSpan: attachment.sourceSpan,
@@ -426,11 +427,165 @@ export function prepareHorizontalLine(columns, index, options = {}, compact = fa
426
427
  element.margin_L = element.margin_R = 0;
427
428
  return element;
428
429
  }));
429
- layoutHorizontal(elements, limit, options, hooks, fillMinRatio);
430
- return elements;
430
+ const solved = layoutHorizontal(elements, limit, options, hooks, fillMinRatio);
431
+ return Object.assign(elements, { extra: solved.extra, groupOf: solved.groupOf });
431
432
  },
432
433
  };
433
434
  }
435
+ /** 利用无挤压撑满行的剩余宽度,向同小节数或成倍数邻行的公共台阶做水位填充,使行间小节线对齐 */
436
+ function alignHorizontalBars(views, regions, contentWidth, pageBreaks) {
437
+ // 1. 提取每行的内部小节线,并扣除单行撑满时平摊的 extra,还原各小节的自然宽度底线 minW
438
+ const states = views.map(({ columns }, i) => {
439
+ const { extra, groupOf } = regions[i];
440
+ if (extra < 0 || !columns.length)
441
+ return;
442
+ const bars = [];
443
+ let hasMusic = false;
444
+ for (let c = 0; c < columns.length; c++) {
445
+ if (columns[c].some(n => n.mergeKey === ANCHOR_KEY)) {
446
+ if (hasMusic) {
447
+ bars.push(c);
448
+ hasMusic = false;
449
+ }
450
+ }
451
+ else if (columns[c].some(n => !n.T.isZero()))
452
+ hasMusic = true;
453
+ }
454
+ // 丢弃右侧没有正时值事件的行尾小节线;行首记号与 |: 因左侧尚无音符已在上面自动跳过
455
+ if (!hasMusic)
456
+ bars.pop();
457
+ if (!bars.length)
458
+ return;
459
+ // groupAt 将原始列映射到合并后的自由虚拟列;两列之差即其间的自由间隙数
460
+ const groupAt = (c) => groupOf ? groupOf[c] : c;
461
+ const totalGaps = groupAt(columns.length - 1);
462
+ const ends = [...bars.map(groupAt), totalGaps];
463
+ let prevX = 0, prevG = 0;
464
+ const gaps = ends.map(g => (g -= prevG, prevG += g, g));
465
+ const minW = ends.map((_, m) => {
466
+ const x = m < bars.length ? columns[bars[m]][0].box.x + columns[bars[m]][0].box.anchor : contentWidth;
467
+ const w = x - prevX;
468
+ prevX = x;
469
+ return totalGaps > 0 ? w - extra * (gaps[m] / totalGaps) : w;
470
+ });
471
+ return { columns, extra, groupAt, totalGaps, ends, gaps, minW };
472
+ });
473
+ const divides = (a, b) => a % b === 0 || b % a === 0;
474
+ const gcd = (a, b) => b ? gcd(b, a % b) : a;
475
+ for (let l = 0; l < states.length; l++) {
476
+ const s = states[l];
477
+ if (!s || s.extra <= 0 || !s.totalGaps)
478
+ continue;
479
+ const M = s.minW.length;
480
+ // 2. 向两侧扩展收集连续行段:新行小节数须与本行及段内最大小节数都成整数倍,从而段内各行都整除最大小节数
481
+ // (如 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);
488
+ if (start === end)
489
+ 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);
538
+ // 若整段公共台阶总和超出行宽,退回只与上下紧邻行对齐;与本行台阶相同的相邻行视为一体共用窗口,避免相同行逐行错开
539
+ if (target.reduce((a, b) => a + b, 0) > contentWidth + 1e-6) {
540
+ const same = (n) => n?.minW.length === M
541
+ && 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;
543
+ while (lo > start && same(states[lo - 1]))
544
+ lo--;
545
+ while (hi < end && same(states[hi + 1]))
546
+ hi++;
547
+ ({ group, target } = env(Math.max(start, lo - 1), Math.min(end, hi + 1)));
548
+ }
549
+ // 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);
551
+ if (!free.some(Boolean))
552
+ for (let m = 0; m < M; m++)
553
+ free[m] = Number(s.gaps[m] > 0);
554
+ for (let step = 0; step < M; step++) {
555
+ let rem = contentWidth, remTarget = 0, freeSum = 0;
556
+ for (let m = 0; m < M; m++) {
557
+ if (free[m]) {
558
+ remTarget += target[m];
559
+ freeSum++;
560
+ }
561
+ else
562
+ rem -= target[m];
563
+ }
564
+ if (!freeSum || Math.abs(rem - remTarget) <= 1e-6)
565
+ break;
566
+ const shift = (rem - remTarget) / freeSum;
567
+ if (!target.some((w, m) => free[m] && w + shift < s.minW[m] && (target[m] = s.minW[m], free[m] = 0, true))) {
568
+ for (let m = 0; m < M; m++)
569
+ if (free[m])
570
+ target[m] += shift;
571
+ break;
572
+ }
573
+ }
574
+ // 4. 将每小节新分到的空白与原平摊空白之差均摊到小节内各自由间隙,累加写回 box.x
575
+ const shift = new Float64Array(s.totalGaps + 1);
576
+ for (let m = 0, k = 0; m < M; m++) {
577
+ const delta = s.gaps[m] > 0 ? (target[m] - s.minW[m]) / s.gaps[m] - s.extra / s.totalGaps : 0;
578
+ for (; k < s.ends[m]; k++)
579
+ shift[k + 1] = shift[k] + delta;
580
+ }
581
+ for (let c = 0; c < s.columns.length; c++) {
582
+ const dx = shift[s.groupAt(c)];
583
+ if (dx)
584
+ for (const node of s.columns[c])
585
+ node.box.x += dx;
586
+ }
587
+ }
588
+ }
434
589
  /** 局部序列按给定顺序完成尺寸、约束与零间隙自然横排,归零占位左沿并返回完整宽度 */
435
590
  export function layoutLocalSequence(nodes, context) {
436
591
  return nodes.length === 0 ? 0 : layoutLocalLine(nodes.map(node => [node]), context).width;
@@ -441,7 +596,7 @@ function layoutLocalLine(columns, context) {
441
596
  for (const node of column)
442
597
  prepareLayoutHost(node, context);
443
598
  }
444
- const line = prepareHorizontalLine(columns, columns[0][0].layoutLine, {}, true);
599
+ const line = prepareHorizontalLine(columns, columns[0][0].layoutLine, context.solverOptions, true);
445
600
  let left = Infinity;
446
601
  let right = -Infinity;
447
602
  for (const column of line.layout(Infinity)) {
@@ -516,18 +671,14 @@ function layoutSubdomainBlock(columns, { width, view }, root, attachments, conte
516
671
  return { height: solved.height, positions, items };
517
672
  }
518
673
  /**
519
- * 关系附件按同时包含全部端点的复合体分组,由内到外逐层登记
674
+ * 关系附件按首端点所在的各层复合体建立候选索引,由内到外逐层登记
520
675
  *
521
- * 端点都在正文的附件不进分组;子域从这里认领端点全部落在自己成员上的关系,不论它写在哪里
676
+ * 端点都在正文的附件不进索引;子域从这里取候选,再认领端点全部落在自己成员上的关系,不论它写在哪里
522
677
  */
523
678
  function groupRelations(attachments) {
524
679
  const groups = new Map();
525
680
  for (const attachment of attachments) {
526
- const [first, ...rest] = attachment.endPoints ?? [];
527
- for (let owner = first?.foldedInto; owner; owner = owner.foldedInto) {
528
- const candidate = owner;
529
- if (!rest.every(point => encloses(candidate, point)))
530
- continue;
681
+ for (let owner = attachment.endPoints?.[0]?.foldedInto; owner; owner = owner.foldedInto) {
531
682
  const group = groups.get(owner);
532
683
  if (group)
533
684
  group.push(attachment);
@@ -537,13 +688,6 @@ function groupRelations(attachments) {
537
688
  }
538
689
  return groups;
539
690
  }
540
- function encloses(owner, node) {
541
- for (let host = node.foldedInto; host; host = host.foldedInto) {
542
- if (host === owner)
543
- return true;
544
- }
545
- return false;
546
- }
547
691
  /** 子域是刚性块:按参照成员的位移平移块内测得的几何 */
548
692
  function moveSubdomainItem(item, layoutOnly = false) {
549
693
  const measured = layoutOnly ? item.layout ?? item : item;
@@ -677,10 +821,9 @@ function measureAttachmentPass(attachments, baseContext, lines, lift, measuredEl
677
821
  if (host.box.x + host.box.w > right)
678
822
  right = host.box.x + host.box.w;
679
823
  }
680
- const decoration = decorationExtents.get(host);
681
- const top = decoration?.top ?? 0;
824
+ const { top, height } = hostSpan(host);
682
825
  const hostTop = host.box.y + top - baseContext.getVisualAxis(line, host.track);
683
- include(host.track, hostTop, hostTop + (host.box.h - top + (decoration?.bottom ?? 0)));
826
+ include(host.track, hostTop, hostTop + height);
684
827
  }
685
828
  }
686
829
  for (const range of occupancy[line] ?? []) {
@@ -766,11 +909,14 @@ function measureAttachmentPass(attachments, baseContext, lines, lift, measuredEl
766
909
  });
767
910
  return { items, needsRelayout };
768
911
  }
769
- /** 固有占用只需轴局部边界,不必创建全局矩形 */
770
- function includeHostExtent(extents, host) {
912
+ /** 主体完整占用相对盒顶的上沿与高度;调用方各自换算到轴局部或行坐标,不必创建全局矩形 */
913
+ function hostSpan(host) {
771
914
  const decoration = decorationExtents.get(host);
772
915
  const top = decoration?.top ?? 0;
773
- const height = host.box.h - top + (decoration?.bottom ?? 0);
916
+ return { top, height: host.box.h - top + (decoration?.bottom ?? 0) };
917
+ }
918
+ function includeHostExtent(extents, host) {
919
+ const { top, height } = hostSpan(host);
774
920
  const axisTop = top - host.box.visualAxis;
775
921
  includeTrackExtent(extents, host.track, axisTop, axisTop + height);
776
922
  }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 基于弹簧的有时长物体排版模型 原理参考 apps/docs/src/content/docs/docs/developer/layout.md
2
+ * 基于弹簧的有时长物体排版模型 原理参考 apps/docs/src/content/docs/docs/developer/layout-algorithm.mdx
3
3
  * 基本使用: 借助 layoutElement() 构建 LayoutElement[][],调用 layout() 函数进行排版
4
4
  */
5
5
  import type { HorizontalSpringConfig, LayoutBox, TimeLineEvent } from "./types.js";
@@ -65,15 +65,24 @@ export interface HorizontalLayoutHookEntry {
65
65
  * @param limit 当前区间左右墙之间的可用宽度
66
66
  * @param options 已补齐默认值的求解参数
67
67
  * @param fillMinRatio 自然宽度至少占可用宽度的比例时才 fill;省略表示不 fill,0 表示无条件 fill。fill 表示是否精确将左右拉到可用宽度,包括宽度不足和弹簧导致的溢出
68
+ * @returns
69
+ * - `extra`:撑满状态与剩余可调宽度:`> 0` 表示无挤压撑满时平摊到自由间隙的剩余宽度(`limit - naturalWidth`),`= 0` 表示已撑满但经过压缩或恰好贴合(无剩余宽度可调),`-1` 表示未撑满
70
+ * - `groupOf`:存在固定间隙时,记录每个原始列所属的合并虚拟列下标(两列的虚拟列下标之差即其间的自由间隙数);无固定间隙时为 `undefined`
68
71
  */
69
- export declare function layoutHorizontalRegion(columns: LayoutElement[][], rows: number, X: Float64Array, fixed: Uint8Array, limit: number, options: Required<SolverOptions>, fillMinRatio?: number): void;
72
+ export declare function layoutHorizontalRegion(columns: LayoutElement[][], rows: number, X: Float64Array, fixed: Uint8Array, limit: number, options: Required<SolverOptions>, fillMinRatio?: number): {
73
+ extra: number;
74
+ groupOf?: Uint32Array;
75
+ };
70
76
  /**
71
77
  * 纯扁平化物理排版解算入口
72
78
  *
73
79
  * @param columns 二维数组,第一维为列,第二维为行,元素包含物理属性和状态属性
74
80
  * @param limit 宽度约束
75
81
  * @param options 排版物理配置
76
- * @returns 同一个解算完成的二维矩阵,所有盒子的绝对 box.x (左侧x坐标) 已就地更新
82
+ * @returns 解算并补齐占位后的二维矩阵(所有盒子的 `box.x` 已就地更新),同时在返回数组上附带 {@link layoutHorizontalRegion} 返回的 `extra` 与 `groupOf`
77
83
  */
78
- export declare function layoutHorizontal(columns: LayoutElement[][], limit: number, options?: SolverOptions, horizontalLayoutHooks?: readonly HorizontalLayoutHookEntry[], fillMinRatio?: number): LayoutElement[][];
84
+ export declare function layoutHorizontal(columns: LayoutElement[][], limit: number, options?: SolverOptions, horizontalLayoutHooks?: readonly HorizontalLayoutHookEntry[], fillMinRatio?: number): LayoutElement[][] & {
85
+ extra: number;
86
+ groupOf?: Uint32Array;
87
+ };
79
88
  export {};
@@ -1,6 +1,6 @@
1
1
  import { Fraction } from "../fraction.js";
2
2
  const DEFAULT_F = 1.0; // 多大力让一行的 margin 全变为 0
3
- const DEFAULT_ALPHA = 6; // 控制无约束时元素的margin
3
+ const DEFAULT_ALPHA = 8; // 控制无约束时元素的margin
4
4
  const DEFAULT_MU = 16;
5
5
  const DEFAULT_CROSS_PUNISH = 32;
6
6
  const MIN_ALPHA = 1e-6;
@@ -268,13 +268,16 @@ function solveHorizontal(mat, rows, X, limit, options) {
268
268
  * @param limit 当前区间左右墙之间的可用宽度
269
269
  * @param options 已补齐默认值的求解参数
270
270
  * @param fillMinRatio 自然宽度至少占可用宽度的比例时才 fill;省略表示不 fill,0 表示无条件 fill。fill 表示是否精确将左右拉到可用宽度,包括宽度不足和弹簧导致的溢出
271
+ * @returns
272
+ * - `extra`:撑满状态与剩余可调宽度:`> 0` 表示无挤压撑满时平摊到自由间隙的剩余宽度(`limit - naturalWidth`),`= 0` 表示已撑满但经过压缩或恰好贴合(无剩余宽度可调),`-1` 表示未撑满
273
+ * - `groupOf`:存在固定间隙时,记录每个原始列所属的合并虚拟列下标(两列的虚拟列下标之差即其间的自由间隙数);无固定间隙时为 `undefined`
271
274
  */
272
275
  export function layoutHorizontalRegion(columns, rows, X, fixed, limit, options, fillMinRatio) {
273
276
  if (X.length !== columns.length || fixed.length !== Math.max(0, X.length - 1)) {
274
277
  throw new Error("Horizontal region state does not match its columns");
275
278
  }
276
279
  if (X.length === 0 || rows === 0)
277
- return;
280
+ return { extra: -1 };
278
281
  const hasFixed = fixed.some(value => value !== 0);
279
282
  let groupOf, offsets;
280
283
  let solvedColumns = columns;
@@ -327,6 +330,7 @@ export function layoutHorizontalRegion(columns, rows, X, fixed, limit, options,
327
330
  }
328
331
  const hasRoom = solveHorizontal(solvedColumns, rows, solvedX, limit, options);
329
332
  fixed.fill(1);
333
+ let extra = -1;
330
334
  if (fillMinRatio !== void 0) {
331
335
  let leftWidth = 0;
332
336
  let rightWidth = 0;
@@ -338,18 +342,22 @@ export function layoutHorizontalRegion(columns, rows, X, fixed, limit, options,
338
342
  if (!hasRoom || naturalWidth >= limit * fillMinRatio) {
339
343
  // 让首尾贴墙,并把余量平均分到自由间隙
340
344
  const shift = leftWidth - solvedX[0];
341
- const extra = limit - naturalWidth;
345
+ const spare = limit - naturalWidth;
342
346
  for (let i = 0; i < solvedX.length; i++) {
343
347
  solvedX[i] += shift + (solvedX.length > 1
344
- ? extra * i / (solvedX.length - 1)
348
+ ? spare * i / (solvedX.length - 1)
345
349
  : 0);
346
350
  }
351
+ if (solvedX.length > 1 || Math.abs(spare) <= 1e-6) {
352
+ extra = hasRoom && solvedX.length > 1 && spare > 0 ? spare : 0;
353
+ }
347
354
  }
348
355
  }
349
356
  if (hasFixed) { // 把虚拟列的求解结果写回原始列
350
357
  for (let i = 0; i < X.length; i++)
351
358
  X[i] = solvedX[groupOf[i]] + offsets[i];
352
359
  }
360
+ return { extra, groupOf };
353
361
  }
354
362
  /**
355
363
  * 纯扁平化物理排版解算入口
@@ -357,7 +365,7 @@ export function layoutHorizontalRegion(columns, rows, X, fixed, limit, options,
357
365
  * @param columns 二维数组,第一维为列,第二维为行,元素包含物理属性和状态属性
358
366
  * @param limit 宽度约束
359
367
  * @param options 排版物理配置
360
- * @returns 同一个解算完成的二维矩阵,所有盒子的绝对 box.x (左侧x坐标) 已就地更新
368
+ * @returns 解算并补齐占位后的二维矩阵(所有盒子的 `box.x` 已就地更新),同时在返回数组上附带 {@link layoutHorizontalRegion} 返回的 `extra` 与 `groupOf`
361
369
  */
362
370
  export function layoutHorizontal(columns, limit, options = {}, horizontalLayoutHooks = [], fillMinRatio) {
363
371
  const normalizedOptions = normalizeSolverOptions(options);
@@ -378,11 +386,11 @@ export function layoutHorizontal(columns, limit, options = {}, horizontalLayoutH
378
386
  options: normalizedOptions,
379
387
  });
380
388
  }
381
- layoutHorizontalRegion(mat, rows, X, fixed, limit, normalizedOptions, fillMinRatio);
389
+ const region = layoutHorizontalRegion(mat, rows, X, fixed, limit, normalizedOptions, fillMinRatio);
382
390
  // 坐标写回
383
391
  for (let c = 0; c < mat.length; c++) {
384
392
  for (const el of mat[c])
385
393
  el.box.x = X[c] - el.box.anchor;
386
394
  }
387
- return mat;
395
+ return Object.assign(mat, region);
388
396
  }
@@ -19,8 +19,8 @@ export const DEFAULT_PAGE_CONFIG = {
19
19
  marginBottom: 48,
20
20
  marginLeft: 40,
21
21
  marginRight: 40,
22
- lineGap: 22,
23
- minLineGap: 11,
22
+ lineGap: 18,
23
+ minLineGap: 7.2,
24
24
  fillRatio: 0.5,
25
25
  };
26
26
  /**
@@ -20,7 +20,7 @@ class MinMax {
20
20
  }
21
21
  /** 提成模块级而不是写成 cubicExtrema 内部的箭头函数:那里每次调用分配一个闭包,实测占了 96% 的耗时 */
22
22
  function cubicAt(t, p0, p1, p2, p3, extent) {
23
- if (!(t > 0 && t < 1))
23
+ if (!(t > 1e-9 && t < 1 - 1e-9))
24
24
  return;
25
25
  const u = 1 - t;
26
26
  extent.add(u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3);
@@ -3,7 +3,7 @@ import type { Extent, Track } from "../lowering/track.js";
3
3
  import type { Fraction } from "../fraction.js";
4
4
  import type { TemporalNodeBase, VisualTemporalNode } from "../functions/temporal.js";
5
5
  import type { SourceSpan } from "../parser/types.js";
6
- import type { HorizontalLayoutHook } from "./model.js";
6
+ import type { HorizontalLayoutHook, SolverOptions } from "./model.js";
7
7
  import type { LoweringAttachment, LoweringContent, PageConfig } from "../lowering/types.js";
8
8
  export type { Extent, PageConfig };
9
9
  /** 轴对齐矩形,是所有排版几何的公共部分 */
@@ -59,6 +59,7 @@ export interface LayoutPrepareContext {
59
59
  * 由 layoutDocument 在主体准备阶段注入;调用方创建的上下文没有它。
60
60
  */
61
61
  layoutSubdomain?(owner: TemporalNodeBase, columns: readonly (readonly VisualTemporalNode[])[], root: Track, attachments: readonly LoweringAttachment[]): SubdomainLayout;
62
+ solverOptions?: SolverOptions;
62
63
  }
63
64
  /** 子域块的尺寸与成员位置,坐标以块的左上角为原点 */
64
65
  export interface SubdomainLayout {
@@ -207,6 +208,11 @@ export interface AttachmentGeometry {
207
208
  * 实例只保存语义输入和一次横向准备状态,不保存最终 box、regions 或绘制几何。
208
209
  */
209
210
  export interface LayoutAttachment extends LoweringAttachment {
211
+ /**
212
+ * 绘制分组的语义类型,SVG 输出为 `<g data-kind>`;缺省或空串表示不开组
213
+ * 同一个值只对应一种图形,不应与时值对象的 kind 重名;取值规则见 render 文档
214
+ */
215
+ readonly kind?: string;
210
216
  /** 后置平移仅影响绘制,不参与占用求解 */
211
217
  placementOffset?: LayoutPoint;
212
218
  /** 几何端点;端点全部落在同一子域的成员上时,附件属于该子域。不表示内容包含或播放端点投影 */
@@ -217,7 +223,6 @@ export interface LayoutAttachment extends LoweringAttachment {
217
223
  readonly sourceSpan?: SourceSpan;
218
224
  /**
219
225
  * 横向求解前:可测量资源、调整弹簧参数或注册横向布局 hook,不得改变对象/列顺序
220
- *
221
226
  * 此时 box 的固有尺寸 w/h/anchor/visualAxis 已是终值,只有 x/y 未定
222
227
  */
223
228
  prepareHorizontal?(lines: HorizontalLineView[], context: LayoutPrepareContext): void;
@@ -226,6 +231,8 @@ export interface LayoutAttachment extends LoweringAttachment {
226
231
  export declare function isLayoutAttachment(attachment: LoweringAttachment): attachment is LayoutAttachment;
227
232
  /** layoutDocument 输出的最终 attachment 快照 */
228
233
  export interface PlacedAttachment {
234
+ /** 取自 LayoutAttachment.kind */
235
+ readonly kind?: string;
229
236
  readonly regions: readonly LayoutRegion[];
230
237
  /** 相对于 Temporal 主体的绘制层;background 比内容先绘制 */
231
238
  readonly layer: "background" | "foreground";
@@ -238,7 +245,9 @@ export interface PlacedAttachment {
238
245
  * 总是计入外接盒;同时声明 line 和 track 时,还会折算成该轨道的纵向占用
239
246
  * 只想影响画布边界、不想撑高行的图形(括线、边框)省略归属即可
240
247
  */
241
- export type LayoutRegion = Rect & ({
248
+ export type LayoutRegion = Rect & {
249
+ sourceSpan?: SourceSpan;
250
+ } & ({
242
251
  line: number;
243
252
  track: Track;
244
253
  } | {
@@ -0,0 +1,33 @@
1
+ import type { Track } from "./track.js";
2
+ /**
3
+ * 一个音在记忆中的位置:key 为「级数:八度」;bar 只作小节的身份;seq 是读谱顺序;
4
+ * prior 是读到的半音偏移。升降半音补记时按 (bar, key) 分组,按 seq 找第一个
5
+ */
6
+ export interface AccidentalReading {
7
+ key: string;
8
+ bar: object;
9
+ seq: number;
10
+ prior: number;
11
+ }
12
+ /**
13
+ * 小节内变音记忆,作用按时间先后:后发生的音读得到先发生的写入,同一时刻的音互不影响。
14
+ * 处理顺序不等于时间顺序(如 ^ 从后往前处理),所以一列里的读写和清空先登记,列末按时刻结算
15
+ */
16
+ export declare class AccidentalMemory {
17
+ private readonly memory;
18
+ private readonly events;
19
+ private readonly staged;
20
+ private readonly now;
21
+ private reads;
22
+ /** 在列内时刻 time 处理 run。一列默认都在时刻 0,倚音成员在宿主之前或之后;嵌套时逐级细分,缺省的级为 0 */
23
+ at<T>(time: number, run: () => T): T;
24
+ /** 登记一个音:结算时读到前文,resolve 返回要写入的半音偏移,不写返回 undefined */
25
+ read(track: Track, key: string, resolve: (reading: AccidentalReading) => number | undefined): void;
26
+ /** 小节线清本轨及其子孙轨道(stack 的分支轨道跨小节复用);转调不传 track,全部清空 */
27
+ clear(track?: Track): void;
28
+ /** 列末按时刻结算;同一时刻按处理顺序执行 */
29
+ commit(): void;
30
+ private flush;
31
+ /** 当前小节的记忆;清空后会换成新的 Map,因此也作为小节的身份 */
32
+ private scope;
33
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * 小节内变音记忆,作用按时间先后:后发生的音读得到先发生的写入,同一时刻的音互不影响。
3
+ * 处理顺序不等于时间顺序(如 ^ 从后往前处理),所以一列里的读写和清空先登记,列末按时刻结算
4
+ */
5
+ export class AccidentalMemory {
6
+ memory = new Map(); // 每个声部本小节的变音:声部轨道 → (键 → 半音偏移,# 为 +1、n 为 0)
7
+ events = []; // 本列登记的读写与清空
8
+ staged = []; // 当前时刻的写入,时刻推进时才提交
9
+ now = [];
10
+ reads = 0;
11
+ /** 在列内时刻 time 处理 run。一列默认都在时刻 0,倚音成员在宿主之前或之后;嵌套时逐级细分,缺省的级为 0 */
12
+ at(time, run) {
13
+ this.now.push(time);
14
+ try {
15
+ return run();
16
+ }
17
+ finally {
18
+ this.now.pop();
19
+ }
20
+ }
21
+ /** 登记一个音:结算时读到前文,resolve 返回要写入的半音偏移,不写返回 undefined */
22
+ read(track, key, resolve) {
23
+ const owner = voiceOf(track);
24
+ this.events.push({ time: [...this.now], run: () => {
25
+ const bar = this.scope(owner);
26
+ const offset = resolve({ key, bar, seq: this.reads++, prior: bar.get(key) ?? 0 });
27
+ if (offset !== undefined)
28
+ this.staged.push([owner, key, offset]);
29
+ } });
30
+ }
31
+ /** 小节线清本轨及其子孙轨道(stack 的分支轨道跨小节复用);转调不传 track,全部清空 */
32
+ clear(track) {
33
+ this.events.push({ time: [...this.now], run: () => {
34
+ if (!track)
35
+ return this.memory.clear();
36
+ for (const owner of this.memory.keys())
37
+ if (within(owner, track))
38
+ this.memory.delete(owner);
39
+ } });
40
+ }
41
+ /** 列末按时刻结算;同一时刻按处理顺序执行 */
42
+ commit() {
43
+ const events = this.events.splice(0).sort((a, b) => compareTime(a.time, b.time));
44
+ events.forEach(({ time, run }, i) => {
45
+ if (i > 0 && compareTime(events[i - 1].time, time))
46
+ this.flush();
47
+ run();
48
+ });
49
+ this.flush();
50
+ }
51
+ flush() {
52
+ for (const [owner, key, offset] of this.staged.splice(0))
53
+ this.scope(owner).set(key, offset);
54
+ }
55
+ /** 当前小节的记忆;清空后会换成新的 Map,因此也作为小节的身份 */
56
+ scope(owner) {
57
+ let map = this.memory.get(owner);
58
+ if (!map)
59
+ this.memory.set(owner, map = new Map());
60
+ return map;
61
+ }
62
+ }
63
+ /** 列内时刻逐级比较,缺省的级视为 0 */
64
+ function compareTime(a, b) {
65
+ for (let i = 0; i < a.length || i < b.length; i++) {
66
+ const diff = (a[i] ?? 0) - (b[i] ?? 0);
67
+ if (diff)
68
+ return diff;
69
+ }
70
+ return 0;
71
+ }
72
+ /** 记忆按声部归属:分组里的分支各成声部;不在父轨分组里的子轨(如倚音的私有根轨)只是排版子域,延续父轨的声部 */
73
+ function voiceOf(track) {
74
+ while (track.parent && !track.parent.groups.some(group => group.members.includes(track)))
75
+ track = track.parent;
76
+ return track;
77
+ }
78
+ function within(track, root) {
79
+ for (let current = track; current; current = current.parent) {
80
+ if (current === root)
81
+ return true;
82
+ }
83
+ return false;
84
+ }
@@ -2,6 +2,7 @@ import { Diagnostic } from "../diagnostic.js";
2
2
  import { Fraction } from "../fraction.js";
3
3
  import { ANCHOR_KEY, DEFAULT_BPM, DEFAULT_PROGRAM, DEFAULT_TONALITY, DEFAULT_VELOCITY, } from "../functions/temporal.js";
4
4
  import { Track } from "./track.js";
5
+ import { AccidentalMemory } from "./accidentalMemory.js";
5
6
  /**
6
7
  * 把 AST 展开并固化为时间列、attachment 和页面配置
7
8
  *
@@ -94,6 +95,7 @@ export class LoweringContext {
94
95
  velocity: DEFAULT_VELOCITY,
95
96
  keySignature: DEFAULT_TONALITY,
96
97
  program: DEFAULT_PROGRAM,
98
+ accidentals: new AccidentalMemory(),
97
99
  };
98
100
  // 力度和音色按音轨各自流动,新分叉的声部继承分叉处父轨的值
99
101
  const velocities = new Map();
@@ -115,6 +117,8 @@ export class LoweringContext {
115
117
  velocities.set(node.track, state.velocity);
116
118
  programs.set(node.track, state.program);
117
119
  }
120
+ // 整列登记完再按时间先后结算变音,同一时刻的音互不影响
121
+ state.accidentals.commit();
118
122
  // 同列声部一起开始,只在整列固化后累加一次偏移
119
123
  if (insertion)
120
124
  timeOffset.add(insertion);