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
@@ -88,7 +88,6 @@ function fillPlaceholders(columns, F = DEFAULT_F) {
88
88
  if (!sortedCol[rIdx]) {
89
89
  // 保证 margin_L = mexLeft, margin_R = maxRight, 实际宽度为0
90
90
  const elPlaceholder = layoutElement({
91
- anchor: 0,
92
91
  alpha_L: maxLeft,
93
92
  alpha_R: maxRight,
94
93
  }, {
@@ -164,7 +163,6 @@ function normalizeSolverOptions(options) {
164
163
  function solveHorizontal(mat, rows, X, limit, options) {
165
164
  const { damping, maxIter, eps, crossPunish } = options;
166
165
  const numCols = mat.length;
167
- // if (numCols === 0 || rows === 0) return false; layoutHorizontalRegion 已经判断过了
168
166
  // 预排列(仅用前 rows 个元素建立无约束时的位置)
169
167
  const row_x = new Float64Array(rows);
170
168
  for (let c = 0; c < numCols; c++) {
@@ -187,19 +185,18 @@ function solveHorizontal(mat, rows, X, limit, options) {
187
185
  x0 = limit / x0;
188
186
  for (let c = 0; c < numCols; c++)
189
187
  X[c] *= x0;
190
- // --- 预分配物理引擎所需的全部静态缓存空间,杜绝主循环内的 GC 损耗 ---
191
188
  const F_vec = new Float64Array(numCols);
192
- const stiffnessCache = new Float32Array(rows * (numCols + 1));
193
- // 计算全局合力,并就地填充刚度缓存
189
+ // 各声部共享列坐标,刚度按左墙、相邻列、右墙汇总。
190
+ const stiffness = new Float64Array(numCols + 1);
194
191
  function computeForces(cols_X) {
195
192
  F_vec.fill(0);
193
+ stiffness.fill(0);
196
194
  for (let r = 0; r < rows; r++) {
197
- const rowOffset = r * (numCols + 1);
198
195
  // 左墙
199
196
  const el_first = mat[0][r];
200
197
  const res_left = calcLeftWall(el_first, cols_X[0], crossPunish);
201
198
  F_vec[0] += res_left.force;
202
- stiffnessCache[rowOffset] = res_left.stiffness; // 缓存左墙刚度
199
+ stiffness[0] += res_left.stiffness;
203
200
  // 内部链弹簧力传导
204
201
  for (let c = 1; c < numCols; c++) {
205
202
  const el_l = mat[c - 1][r];
@@ -207,74 +204,33 @@ function solveHorizontal(mat, rows, X, limit, options) {
207
204
  const res = calcPairForceAndStiffness(el_l, el_r, cols_X[c - 1], cols_X[c]);
208
205
  F_vec[c - 1] -= res.force;
209
206
  F_vec[c] += res.force;
210
- stiffnessCache[rowOffset + c] = res.stiffness; // 缓存链弹簧刚度
207
+ stiffness[c] += res.stiffness;
211
208
  }
212
209
  // 右墙
213
210
  const el_last = mat[numCols - 1][r];
214
211
  const res_right = calcRightWall(el_last, cols_X[numCols - 1], limit, crossPunish);
215
212
  F_vec[numCols - 1] -= res_right.force;
216
- stiffnessCache[rowOffset + numCols] = res_right.stiffness; // 缓存右墙刚度
213
+ stiffness[numCols] += res_right.stiffness;
217
214
  }
218
215
  return F_vec;
219
216
  }
220
- const Hp = new Float64Array(numCols);
221
- // Hessian 矩阵切向刚度乘以位移向量 p (精简参数,移除了无用的 cols_X)
222
- function multiplyH(p) {
223
- Hp.fill(0);
224
- for (let r = 0, rowOffset = 0; r < rows; r++, rowOffset += (numCols + 1)) {
225
- // 左墙刚度
226
- Hp[0] += stiffnessCache[rowOffset] * p[0];
227
- // 链弹簧二阶切线刚度
228
- for (let c = 1; c < numCols; c++) {
229
- const Kdp = stiffnessCache[rowOffset + c] * (p[c] - p[c - 1]);
230
- Hp[c - 1] -= Kdp;
231
- Hp[c] += Kdp;
232
- }
233
- // 右墙刚度
234
- Hp[numCols - 1] += stiffnessCache[rowOffset + numCols] * p[numCols - 1];
235
- }
236
- // L-M 正则阻尼,保证矩阵严格正定,避免奇异性
237
- const lambda = 1e-4;
238
- for (let i = 0; i < p.length; i++)
239
- Hp[i] += lambda * p[i];
240
- return Hp;
241
- }
242
- function dot(a, b) {
243
- let sum = 0;
244
- for (let i = 0; i < a.length; i++)
245
- sum += a[i] * b[i];
246
- return sum;
247
- }
248
- // 必须用 Float64Array 不然影响收敛
217
+ const diagonal = new Float64Array(numCols);
249
218
  const dx = new Float64Array(numCols);
250
- const R = new Float64Array(numCols);
251
- const P = new Float64Array(numCols);
252
- // 共轭梯度线性解算
253
- function solveCG(F_vec, maxCGIter = 8) {
254
- dx.fill(0);
255
- R.set(F_vec);
256
- P.set(R);
257
- let rsold = dot(R, R);
258
- if (rsold < 1e-12)
259
- return dx;
260
- for (let iter = 0; iter < maxCGIter; iter++) {
261
- const Hp = multiplyH(P);
262
- const p_Hp = dot(P, Hp);
263
- if (Math.abs(p_Hp) < 1e-12)
264
- break;
265
- const alpha = rsold / p_Hp;
266
- for (let i = 0; i < numCols; i++) {
267
- dx[i] += alpha * P[i];
268
- R[i] -= alpha * Hp[i];
269
- }
270
- const rsnew = dot(R, R);
271
- if (Math.sqrt(rsnew) < 1e-6)
272
- break;
273
- const beta = rsnew / rsold;
274
- for (let i = 0; i < numCols; i++) {
275
- P[i] = R[i] + beta * P[i];
219
+ function solveTridiagonal() {
220
+ // H[i,i] = K[i] + K[i+1] + lambda,H[i-1,i] = -K[i]。
221
+ const lambda = 1e-4;
222
+ for (let i = 0; i < numCols; i++) {
223
+ const factor = i === 0 ? 0 : stiffness[i] / diagonal[i - 1];
224
+ const pivot = stiffness[i] + stiffness[i + 1] + lambda - factor * stiffness[i];
225
+ if (!(pivot > 0) || !Number.isFinite(pivot)) {
226
+ throw new Error("Horizontal spring stiffness must produce a finite positive definite system");
276
227
  }
277
- rsold = rsnew;
228
+ diagonal[i] = pivot;
229
+ dx[i] = F_vec[i] + (i === 0 ? 0 : factor * dx[i - 1]);
230
+ }
231
+ dx[numCols - 1] /= diagonal[numCols - 1];
232
+ for (let i = numCols - 2; i >= 0; i--) {
233
+ dx[i] = (dx[i] + stiffness[i + 1] * dx[i + 1]) / diagonal[i];
278
234
  }
279
235
  return dx;
280
236
  }
@@ -290,7 +246,7 @@ function solveHorizontal(mat, rows, X, limit, options) {
290
246
  }
291
247
  if (f_max < eps)
292
248
  break;
293
- const dx = solveCG(F_vec);
249
+ const dx = solveTridiagonal();
294
250
  for (let i = 0; i < numCols; i++) {
295
251
  X[i] += damping * dx[i];
296
252
  }
@@ -5,10 +5,10 @@ export class PageLayoutError extends Error {
5
5
  availableHeight;
6
6
  constructor(line, requiredHeight, availableHeight) {
7
7
  super(`Page cannot fit layout line ${line}: requires ${requiredHeight}px, available ${availableHeight}px`);
8
- this.name = "PageLayoutError";
9
8
  this.line = line;
10
9
  this.requiredHeight = requiredHeight;
11
10
  this.availableHeight = availableHeight;
11
+ this.name = "PageLayoutError";
12
12
  }
13
13
  }
14
14
  /** 没有 page 函数时使用的默认 A4 近似页面配置 */
@@ -20,6 +20,7 @@ export const DEFAULT_PAGE_CONFIG = {
20
20
  marginLeft: 40,
21
21
  marginRight: 40,
22
22
  lineGap: 22,
23
+ fillRatio: 0.5,
23
24
  };
24
25
  /**
25
26
  * 补齐页面配置并保证返回值可直接用于布局
@@ -34,6 +35,7 @@ export function normalizePageConfig(source = {}) {
34
35
  marginLeft: Math.max(0, source.marginLeft ?? DEFAULT_PAGE_CONFIG.marginLeft),
35
36
  marginRight: Math.max(0, source.marginRight ?? DEFAULT_PAGE_CONFIG.marginRight),
36
37
  lineGap: Math.max(0, source.lineGap ?? DEFAULT_PAGE_CONFIG.lineGap),
38
+ fillRatio: source.fillRatio ?? DEFAULT_PAGE_CONFIG.fillRatio,
37
39
  };
38
40
  if (!Number.isFinite(page.width) || page.width <= 0) {
39
41
  throw new Error(`Page width must be a positive finite number, got ${page.width}`);
@@ -0,0 +1,26 @@
1
+ import type { Track } from "../lowering/track.js";
2
+ import type { HorizontalLineView, LayoutHost, LayoutRange } from "./types.js";
3
+ export type QueryLine = Omit<HorizontalLineView, "registerHorizontalLayoutHook">;
4
+ /** 范围在本域视图中覆盖的闭区间列,start > end 表示空 */
5
+ interface ResolvedRange {
6
+ start: number;
7
+ end: number;
8
+ /** 省略范围即整行,附件占用不再按所选主体的横向范围筛选 */
9
+ wholeLine: boolean;
10
+ }
11
+ /**
12
+ * 把轨归入以 root 为根的 Track 树
13
+ *
14
+ * 复合体的私有根轨从它所在的轨分出却不挂进分组,所以沿 Track.parent 上溯总会回到外层的树
15
+ */
16
+ export declare function liftInto(root: Track): (track: Track) => Track;
17
+ /**
18
+ * 在正文行或子域的视图里解析一次范围查询
19
+ *
20
+ * 数字端点是本视图的列下标;对象端点可以逆序或跨行,按本行截取。
21
+ * 指定 track 时两个端点都必须位于该轨,私有轨先经 lift 归入本域
22
+ */
23
+ export declare function resolveRange(view: QueryLine, range: LayoutRange | undefined, track: Track | undefined, lift: (track: Track) => Track): ResolvedRange;
24
+ /** 范围内的列;指定 track 时只保留该轨主体,空列照样保留 */
25
+ export declare function rangeColumns(view: QueryLine | undefined, range: LayoutRange | undefined, track: Track | undefined, lift: (track: Track) => Track): readonly (readonly LayoutHost[])[];
26
+ export {};
@@ -0,0 +1,75 @@
1
+ import { isVisualTemporalNode, TemporalNodeBase } from "../functions/temporal.js";
2
+ const EMPTY = { start: 0, end: -1, wholeLine: false };
3
+ /**
4
+ * 把轨归入以 root 为根的 Track 树
5
+ *
6
+ * 复合体的私有根轨从它所在的轨分出却不挂进分组,所以沿 Track.parent 上溯总会回到外层的树
7
+ */
8
+ export function liftInto(root) {
9
+ const tracks = new Set();
10
+ const collect = (track) => {
11
+ tracks.add(track);
12
+ for (const group of track.groups) {
13
+ for (const member of group.members)
14
+ collect(member);
15
+ }
16
+ };
17
+ collect(root);
18
+ return track => {
19
+ for (let lane = track; lane; lane = lane.parent) {
20
+ if (tracks.has(lane))
21
+ return lane;
22
+ }
23
+ return track;
24
+ };
25
+ }
26
+ /** 本域里代表 host 的列:折叠成员沿 foldedInto 上溯到本域的主体 */
27
+ function columnOf(view, host) {
28
+ for (let node = host; node;) {
29
+ const column = view.columnOf(node);
30
+ if (column >= 0)
31
+ return column;
32
+ const folded = node instanceof TemporalNodeBase ? node.foldedInto : undefined;
33
+ node = folded && isVisualTemporalNode(folded) ? folded : undefined;
34
+ }
35
+ return -1;
36
+ }
37
+ /**
38
+ * 在正文行或子域的视图里解析一次范围查询
39
+ *
40
+ * 数字端点是本视图的列下标;对象端点可以逆序或跨行,按本行截取。
41
+ * 指定 track 时两个端点都必须位于该轨,私有轨先经 lift 归入本域
42
+ */
43
+ export function resolveRange(view, range, track, lift) {
44
+ if (!range)
45
+ return { start: 0, end: view.columns.length - 1, wholeLine: true };
46
+ if (typeof range[0] === "number") {
47
+ return { start: Math.max(0, range[0]), end: Math.min(view.columns.length - 1, range[1]), wholeLine: false };
48
+ }
49
+ let [from, to] = range;
50
+ if (from.layoutLine > to.layoutLine)
51
+ [from, to] = [to, from];
52
+ if (view.index < from.layoutLine || view.index > to.layoutLine)
53
+ return EMPTY;
54
+ const target = track && lift(track);
55
+ if (target && (lift(from.track) !== target || lift(to.track) !== target)) {
56
+ throw new Error("Range endpoints must belong to the selected track");
57
+ }
58
+ const start = from.layoutLine < view.index ? 0 : columnOf(view, from);
59
+ const end = to.layoutLine > view.index ? view.columns.length - 1 : columnOf(view, to);
60
+ if (start < 0 || end < 0)
61
+ return EMPTY;
62
+ return { start: Math.min(start, end), end: Math.max(start, end), wholeLine: false };
63
+ }
64
+ /** 范围内的列;指定 track 时只保留该轨主体,空列照样保留 */
65
+ export function rangeColumns(view, range, track, lift) {
66
+ if (!view)
67
+ return [];
68
+ const { start, end } = resolveRange(view, range, track, lift);
69
+ const columns = view.columns.slice(start, end + 1);
70
+ if (!track)
71
+ return columns;
72
+ const target = lift(track);
73
+ const onTarget = (host) => host.track === target;
74
+ return columns.every(column => column.every(onTarget)) ? columns : columns.map(column => column.filter(onTarget));
75
+ }
@@ -1,9 +1,10 @@
1
1
  import type { Painter, TextMeasurer } from "../render/types.js";
2
2
  import type { Track } from "../lowering/track.js";
3
3
  import type { Fraction } from "../fraction.js";
4
+ import type { TemporalNodeBase, VisualTemporalNode } from "../functions/temporal.js";
4
5
  import type { SourceSpan } from "../parser/types.js";
5
6
  import type { HorizontalLayoutHook } from "./model.js";
6
- import type { LoweringAttachment } from "../lowering/types.js";
7
+ import type { LoweringAttachment, LoweringContent } from "../lowering/types.js";
7
8
  /** 轴对齐矩形,是所有排版几何的公共部分 */
8
9
  export interface Rect {
9
10
  x: number;
@@ -20,7 +21,7 @@ export interface Extent {
20
21
  bottom: number;
21
22
  }
22
23
  /**
23
- * 一个排版对象的完整矩形和两个对齐基准
24
+ * 一个排版对象的定位矩形和两个对齐基准
24
25
  *
25
26
  * prepareLayout 负责填写 w、h、anchor、visualAxis
26
27
  * layout 负责原地修改 x、y
@@ -55,6 +56,7 @@ export interface PageConfig {
55
56
  marginLeft: number;
56
57
  marginRight: number;
57
58
  lineGap: number;
59
+ fillRatio: number;
58
60
  }
59
61
  /**
60
62
  * 排版前的共享资源
@@ -65,9 +67,29 @@ export interface PageConfig {
65
67
  export interface LayoutPrepareContext {
66
68
  textMeasurer: TextMeasurer;
67
69
  decorationHandlers: ReadonlyMap<string, LayoutDecorationHandler>;
70
+ /**
71
+ * 按正文规则排版复合体内部的子域,排完后它就是一个刚性块
72
+ *
73
+ * columns 非空,外层表示先后、内层是同列的不同声部,成员位于 root 的 Track 树上。
74
+ * 子域附件包括 attachments 里没有端点的内容附件,以及端点全部落在成员上的关系附件,后者写在哪里都算。
75
+ * 它们在块内测量并参与局部重排,最终几何随块平移;外层只看得到 owner,私有轨归入 owner 所在的轨。
76
+ *
77
+ * 由 layoutDocument 在主体准备阶段注入;调用方创建的上下文没有它。
78
+ */
79
+ layoutSubdomain?(owner: TemporalNodeBase, columns: readonly (readonly VisualTemporalNode[])[], root: Track, attachments: readonly LoweringAttachment[]): SubdomainLayout;
68
80
  }
81
+ /** 子域块的尺寸与成员位置,坐标以块的左上角为原点 */
82
+ export interface SubdomainLayout {
83
+ width: number;
84
+ height: number;
85
+ /** 与 columns.flat() 一一对应,不含成员 onPlaced 追加的平移 */
86
+ positions: readonly LayoutPoint[];
87
+ }
88
+ export type LayoutRange = readonly [from: number, to: number] | readonly [from: LayoutHost, to: LayoutHost];
69
89
  /** attachment 根据当前视觉轴生成几何时需要的完整页面信息 */
70
90
  export interface AttachmentLayoutContext extends LayoutPrepareContext {
91
+ /** 占用测量使用布局位置,最终绘制才应用后置平移 */
92
+ readonly layoutOnly?: boolean;
71
93
  width: number;
72
94
  originX: number;
73
95
  pages: readonly Rect[];
@@ -75,17 +97,26 @@ export interface AttachmentLayoutContext extends LayoutPrepareContext {
75
97
  getVisualAxis(line: number, track: Track): number;
76
98
  /** 只包含可见主体的轴局部占用(top 通常为负),不受 attachment 或最终分页坐标影响 */
77
99
  getHostExtent(line: number, track: Track): Readonly<Extent> | undefined;
100
+ /** 获取本行范围内的列;对象端点沿 foldedInto 上溯到本域的列 */
101
+ getRangeColumns(line: number, range?: LayoutRange, track?: Track): readonly (readonly LayoutHost[])[];
78
102
  /**
79
- * 闭区间列 [from, to] 内按轨分组的已定占用
103
+ * 本行闭区间内的已定占用;全轨返回按 Track 分组的 Map,单轨直接返回 Extent 或 undefined
80
104
  *
81
- * 主体按时间列精确筛选;attachment 按这些列最终盒子的横向范围筛选。
105
+ * 数字端点表示本域的列下标;对象端点沿 foldedInto 上溯到本域的列,跨行对象区间自动截取本行部分。
106
+ * 子域对外是一个主体,正文查询不进入它的内部。
107
+ * 主体按查询列筛选;attachment 按这些列最终盒子的横向范围筛选,并遵守 track 过滤。
82
108
  * attachment 部分与 getAttachmentBox 同一条可见性规则:只看得见比自己先注册的,
83
109
  * 也就是「后声明的排在外层」。避让型 attachment 用它把自己排到已有内容之外。
84
110
  * 省略列号表示整行,供跨行 attachment 查询没有可见列的中间行。
85
111
  */
86
- getRangeExtents(line: number, columns?: readonly [from: number, to: number]): ReadonlyMap<Track, Readonly<Extent>>;
112
+ getRangeExtents(line: number, columns?: LayoutRange): ReadonlyMap<Track, Readonly<Extent>>;
113
+ getRangeExtents(line: number, columns: LayoutRange | undefined, track: Track): Readonly<Extent> | undefined;
87
114
  /** 读取本轮已完成的 attachment 边界;分组在 endLoweringGroup 才注册,因而组内对象必然排在分组之前 */
88
115
  getAttachmentBox(attachment: LayoutAttachment): Readonly<Rect>;
116
+ /** 读取已测附件的有效占用,保留显式空数组;尚未测量时返回 undefined */
117
+ getAttachmentOccupancy(attachment: LayoutAttachment): readonly LayoutRegion[] | undefined;
118
+ /** 内容的实际几何并集;只包含作用域内主体与此前已测附件,不代表撑行占用 */
119
+ getContentBounds(content: LoweringContent): Readonly<Rect> | undefined;
89
120
  }
90
121
  /**
91
122
  * 装饰所依附的主体
@@ -99,6 +130,10 @@ export interface AttachmentLayoutContext extends LayoutPrepareContext {
99
130
  export interface LayoutHost extends TimeLineEvent {
100
131
  box: LayoutBox;
101
132
  springConfig: HorizontalSpringConfig;
133
+ /**
134
+ * 内置端口:body.left / body.right、decoration.below、shoulder、tie.top、
135
+ * div.{level}.left / div.{level}.right、dot、lyric;用途与缺省值见 {@link TemporalNodeBase.ports}。
136
+ */
102
137
  ports: Record<string, LayoutPoint>;
103
138
  readonly mergeKey: number;
104
139
  readonly layoutLine: number;
@@ -126,7 +161,7 @@ export interface HorizontalLineView {
126
161
  }
127
162
  /**
128
163
  * 相对于对象 LayoutBox 左上角的局部坐标
129
- * tie、beam 等关系函数通过命名端口获取几何位置
164
+ * 装饰布局与 tie、beam 等关系函数通过命名端口获取几何位置
130
165
  */
131
166
  export interface LayoutPoint {
132
167
  x: number;
@@ -140,58 +175,33 @@ context: LayoutPrepareContext) => LayoutDecoration | null;
140
175
  *
141
176
  * 实例有两种来源:Temporal.prepareLayout 可以直接加入;addon 对应的 LayoutDecorationHandler 也可以在主体 prepareLayout 后创建
142
177
  * 两者都在创建时就拿到了宿主,因此回调不再重复传入它;实例可以在返回前调整 host.box,例如 dot 先扩张主体宽度
143
- * 被 arrangeBelowDecorations 使用
144
- *
145
- * 通用部分只有 paint:主体绘制完成后,引擎调用它绘制当前装饰。
178
+ * 由引擎统一分配上下空间,place 的坐标相对主体定位矩形
146
179
  *
147
- * below 是可选的“主体下方空间”子协议,只向下扩张 box.h,不管理主体上方空间
148
- * 上方内容若会改变主体 visualAxis 或内部绘制坐标,应由具体 Temporal 在 prepareLayout 中处理。
180
+ * paint 可省略,此时只预留空间,不进入内容边界
149
181
  *
150
182
  * 当前内置示例:
151
183
  * - dot:handler 生成只负责横向扩宽和绘制的装饰,不声明 below;
152
184
  * - div:handler 生成减时线装饰,使用 order=0,排在主体下方最内层;
153
- * - note 下八度点:prepareLayout 直接加入装饰,使用 order=100,排在减时线之后;
154
- * - note 上八度点不使用 LayoutDecoration,而是主体 prepareLayout 的一部分。
185
+ * - note 八度点:prepareLayout 直接加入装饰,使用 order=100
155
186
  *
156
187
  * LayoutDecoration 不是 addon 语义本身。实例可以用闭包保存本次测量参数和 place 结果,因此必须由 Temporal.decorations 持有到当前 paint 结束。
157
188
  */
158
189
  export interface LayoutDecoration {
159
- paint(painter: Painter): void;
160
- /** 声明后进入主体下方空间管理,引擎只理解这四个字段,不知道空间来自哪个函数 */
161
- below?: {
162
- order: number;
163
- gap?: number;
164
- height?: number;
165
- /**
166
- * 引擎分配好本装饰的下方区域后调用一次,y 是该区域 **顶边到 host.box 顶部** 的距离
167
- *
168
- * 该做的:把这一刻才确定的局部几何存进闭包供 paint 使用(note 存下八度点的 y),
169
- * 以及发布依赖这个位置的端口(div 在这里建 div.N.left/right)。只占位不绘制时可以不实现。
170
- *
171
- * 不该做的:改 box.h(引擎会按 height 统一扩张)、读 box.y 或 box.h (前者尚未求解、后者正在向下累加)。
172
- * 此时只有 box.w/anchor 和 ports 是最终值,因此一律记录相对盒顶的局部坐标,绘制时再加 host.box.x / host.box.y。
173
- *
174
- * 例(一条减时线):
175
- * ```ts
176
- * let lineY = 0; // 闭包保存本轮测量结果
177
- * return {
178
- * below: {
179
- * order: 0,
180
- * height: strokeWidth,
181
- * place(y) {
182
- * lineY = y + strokeWidth / 2;
183
- * host.ports["div.0.left"] = { x: 0, y: lineY };
184
- * },
185
- * },
186
- * paint(painter) {
187
- * const y = host.box.y + lineY; // 此时 box.y 才有意义
188
- * painter.drawLine(host.box.x, y, host.box.x + host.box.w, y, { stroke: "#000", strokeWidth });
189
- * },
190
- * };
191
- * ```
192
- */
193
- place?(y: number): void;
194
- };
190
+ paint?(painter: Painter): void;
191
+ above?: LayoutDecorationSpace;
192
+ below?: LayoutDecorationSpace;
193
+ }
194
+ /** 上下装饰共用由内向外的排列协议 */
195
+ export interface LayoutDecorationSpace {
196
+ order: number;
197
+ gap?: number;
198
+ height?: number;
199
+ /**
200
+ * y 是区域顶边相对 host.box 顶部的坐标,上方区域通常为负数
201
+ * 只保存局部几何并发布端口,不读写正在排列的 box.h 或尚未放置的 box.y
202
+ * 绘制时再加 host.box.x/y,纯留白可以省略 place
203
+ */
204
+ place?(y: number): void;
195
205
  }
196
206
  /**
197
207
  * 一次 attachment 放置产生的完整几何
@@ -211,6 +221,10 @@ export interface AttachmentGeometry {
211
221
  * 实例只保存语义输入和一次横向准备状态,不保存最终 box、regions 或绘制几何。
212
222
  */
213
223
  export interface LayoutAttachment extends LoweringAttachment {
224
+ /** 后置平移仅影响绘制,不参与占用求解 */
225
+ placementOffset?: LayoutPoint;
226
+ /** 几何端点;端点全部落在同一子域的成员上时,附件属于该子域。不表示内容包含或播放端点投影 */
227
+ readonly endPoints?: readonly TemporalNodeBase[];
214
228
  /** 相对于 Temporal 主体的绘制层;background 比内容先绘制 */
215
229
  readonly layer: "background" | "foreground";
216
230
  /** 对应的源码范围;自动生成图形可覆盖其首末宿主的源码 */
@@ -57,7 +57,7 @@ export declare class LoweringContext {
57
57
  */
58
58
  lowerDocument(node: ASTNodeBase): LoweringResult;
59
59
  /**
60
- * 固化谱面行号并进行时间状态固化
60
+ * 固化谱面行号、时间状态和最终时长
61
61
  */
62
62
  private solidifyColumns;
63
63
  /**
@@ -75,7 +75,7 @@ export class LoweringContext {
75
75
  const rootTrack = new Track();
76
76
  const duration = new Fraction();
77
77
  const columns = this.trackedEvents(node, duration, rootTrack);
78
- this.solidifyColumns(columns);
78
+ this.solidifyColumns(columns, duration);
79
79
  return this.postprocessResult({
80
80
  diagnostics: this.diagnostics,
81
81
  columns,
@@ -88,9 +88,9 @@ export class LoweringContext {
88
88
  });
89
89
  }
90
90
  /**
91
- * 固化谱面行号并进行时间状态固化
91
+ * 固化谱面行号、时间状态和最终时长
92
92
  */
93
- solidifyColumns(columns) {
93
+ solidifyColumns(columns, duration) {
94
94
  // 同时刻跨轨的 br 已经合成一列,所以取最大;同轨连写仍是多个列,因而累加
95
95
  let line = 0;
96
96
  for (const column of columns) {
@@ -115,14 +115,44 @@ export class LoweringContext {
115
115
  const programs = new Map();
116
116
  const velocityOf = (track) => velocities.get(track) ?? (track.parent ? velocityOf(track.parent) : DEFAULT_VELOCITY);
117
117
  const programOf = (track) => programs.get(track) ?? (track.parent ? programOf(track.parent) : DEFAULT_PROGRAM);
118
+ const timeOffset = new Fraction();
118
119
  for (const column of columns) {
120
+ if (!timeOffset.isZero())
121
+ column.shiftTime(timeOffset);
122
+ let insertion;
119
123
  for (const node of column) {
120
124
  state.velocity = velocityOf(node.track);
121
125
  state.program = programOf(node.track);
122
- node.onTimeState?.(state);
126
+ const offset = node.onTimeState?.(state);
127
+ if (offset && !offset.isZero() && (!insertion || offset.compare(insertion) > 0)) {
128
+ (insertion ??= new Fraction()).copyFrom(offset);
129
+ }
123
130
  velocities.set(node.track, state.velocity);
124
131
  programs.set(node.track, state.program);
125
132
  }
133
+ // 同列声部一起开始,只在整列固化后累加一次偏移
134
+ if (insertion)
135
+ timeOffset.add(insertion);
136
+ }
137
+ if (timeOffset.isZero())
138
+ return;
139
+ // 偏移非负、同轨时序前进,只需各轨尾节点;programs 已记录全部全局轨道
140
+ const tracks = new Set(programs.keys());
141
+ const end = new Fraction();
142
+ duration.set(0);
143
+ for (let i = columns.length - 1; i >= 0 && tracks.size > 0; i--) {
144
+ const column = columns[i];
145
+ for (let j = column.length - 1; j >= 0; j--) {
146
+ const node = column[j];
147
+ if (!tracks.delete(node.track))
148
+ continue;
149
+ const T = node.T;
150
+ end.copyFrom(node.t);
151
+ if (!T.isZero())
152
+ end.add(T);
153
+ if (end.compare(duration) > 0)
154
+ duration.copyFrom(end);
155
+ }
126
156
  }
127
157
  }
128
158
  /**
@@ -9,6 +9,11 @@ import type { Track, TrackArrangement } from "./track.js";
9
9
  export interface LoweringAttachment {
10
10
  readonly sourceSpan?: SourceSpan;
11
11
  }
12
+ /** 按现有分组可见性捕获的内容身份;只保存引用,不含布局结果 */
13
+ export interface LoweringContent {
14
+ nodes: TemporalNodeBase[];
15
+ attachments: LoweringAttachment[];
16
+ }
12
17
  /** 时间流固化后生成额外 attachment;读取统一追加前的结果,不直接修改结果 */
13
18
  export type LoweringAugmenter = (result: LoweringResult) => Iterable<LoweringAttachment>;
14
19
  /** 所有 augmenter 结果追加完成后的最终处理;按注册顺序执行,可修改完整结果或抛出语义错误 */
@@ -6,6 +6,8 @@ export function parseLength(value) {
6
6
  if (!match)
7
7
  return Diagnostic.warning.InvalidLength(value, { start: 0, end: value.length });
8
8
  const num = parseFloat(match[1]);
9
+ if (!Number.isFinite(num))
10
+ return Diagnostic.warning.InvalidLength(value, { start: 0, end: value.length });
9
11
  if (match[2]) {
10
12
  const unit = match[2].toLowerCase();
11
13
  if (availableUnits.includes(unit))
@@ -1,3 +1,5 @@
1
+ export declare const SHARP_NOTE_NAMES: readonly ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
2
+ export declare const FLAT_NOTE_NAMES: readonly ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"];
1
3
  /** 同一音高的两种拼写升在前、降在后,反查拼写时依赖这个顺序 */
2
4
  export declare const NoteNameMap: Record<string, number>;
3
5
  export interface RelativeJianpuPitch {
@@ -1,4 +1,6 @@
1
1
  import { Diagnostic } from "../../diagnostic.js";
2
+ export const SHARP_NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
3
+ export const FLAT_NOTE_NAMES = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"];
2
4
  /** 同一音高的两种拼写升在前、降在后,反查拼写时依赖这个顺序 */
3
5
  export const NoteNameMap = {
4
6
  "C": 0,
@@ -41,9 +43,11 @@ export function tonality2Midi(tonality, defaultOctave) {
41
43
  throw Diagnostic.error.InvalidTonality(tonality, { start: 0, end: i });
42
44
  // 解析八度
43
45
  if (i < tonality.length) {
44
- defaultOctave = parseInt(tonality.slice(i), 10);
45
- if (isNaN(defaultOctave))
46
+ const octave = tonality.slice(i);
47
+ defaultOctave = Number(octave);
48
+ if (!/^-?\d+$/.test(octave) || !Number.isSafeInteger(defaultOctave)) {
46
49
  throw Diagnostic.error.InvalidTonality(tonality, { start: i, end: tonality.length });
50
+ }
47
51
  }
48
52
  return (defaultOctave + 1) * 12 + noteValue;
49
53
  }
@@ -408,7 +408,7 @@ export class ParserContext {
408
408
  const key = name ?? i;
409
409
  if (type === void 0) {
410
410
  if (!def.allowExtraArgs) {
411
- this.diagnostics.push(Diagnostic.warning.TooManyPosArgs(callNode.name, defArgs.length, i + 1, arg.valueSpan));
411
+ this.diagnostics.push(Diagnostic.warning.TooManyPosArgs(callNode.name, defArgs.filter(arg => !arg.namedOnly).length, i + 1, arg.valueSpan));
412
412
  }
413
413
  else
414
414
  args.set(key, arg);
@@ -439,15 +439,14 @@ export class ParserContext {
439
439
  switch (type) {
440
440
  case "number":
441
441
  const num = Number(text);
442
- if (isNaN(num)) {
442
+ if (!Number.isFinite(num)) { // NaN or Infinity 的判断
443
443
  this.diagnostics.push(Diagnostic.warning.InvalidNumber(text, r));
444
444
  return null;
445
445
  }
446
446
  return num;
447
447
  case "boolean":
448
- const boolText = text;
449
- if (BOOL_RE.test(boolText)) {
450
- return boolText === "true";
448
+ if (BOOL_RE.test(text)) {
449
+ return text === "true";
451
450
  }
452
451
  else {
453
452
  this.diagnostics.push(Diagnostic.warning.InvalidBoolean(text, r));
@@ -509,11 +508,8 @@ export class ParserContext {
509
508
  return l;
510
509
  // 其他类型一律视为string
511
510
  default:
512
- // 去除首尾引号(单引号或双引号),如果存在
513
- let result = text;
514
- return removeQuote(result);
511
+ return removeQuote(text);
515
512
  }
516
- return null;
517
513
  }
518
514
  length2px(length) {
519
515
  // 不进行错误判断了: 来自 parseArgWithType 的不会出问题