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
@@ -1,7 +1,9 @@
1
1
  import { Diagnostic, ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
2
2
  import { lineEntryX, lineRightX } from "../../layout/range.js";
3
3
  import { isVisualTemporalNode, } from "../temporal.js";
4
+ import { dynamicMarkVelocity } from "../symbol/symbols/dynamics.js";
4
5
  import { ASTFunctionNode, } from "../ASTtypes.js";
6
+ const clampVelocity = (velocity) => Math.max(1, Math.min(127, velocity));
5
7
  function findRecordBoundary(records, time, after = false) {
6
8
  let low = 0;
7
9
  let high = records.length;
@@ -15,6 +17,33 @@ function findRecordBoundary(records, time, after = false) {
15
17
  }
16
18
  return low;
17
19
  }
20
+ function addIncrement(track, start, end, offset, slope = 0) {
21
+ if (start >= end)
22
+ return;
23
+ track.offset[start] += offset;
24
+ track.offset[end] -= offset;
25
+ track.slope[start] += slope;
26
+ track.slope[end] -= slope;
27
+ }
28
+ /** 在 [from, endStart) 的音符上叠加从 0 线性变化到 delta 的增量 */
29
+ function addRamp(track, dynamic, endStart, delta) {
30
+ const from = dynamic.fromHost.t;
31
+ const slope = delta / dynamic.toHost.t.clone().sub(from).toNumber();
32
+ addIncrement(track, findRecordBoundary(track.records, from), endStart, -slope * from.toNumber(), slope);
33
+ }
34
+ /** 把差分数组结算进 increments,并按可听范围限幅 */
35
+ function settle({ records, times, increments, offset, slope }) {
36
+ let a = 0;
37
+ let k = 0;
38
+ for (let i = 0; i < records.length; i++) {
39
+ a += offset[i];
40
+ k += slope[i];
41
+ const velocity = records[i].velocity;
42
+ increments[i] = clampVelocity(velocity + increments[i] + a + k * times[i]) - velocity;
43
+ }
44
+ offset.fill(0);
45
+ slope.fill(0);
46
+ }
18
47
  class DynFunction extends ASTFunctionNode {
19
48
  static def = {
20
49
  name: ["dyn"],
@@ -24,7 +53,9 @@ class DynFunction extends ASTFunctionNode {
24
53
  1 ^ $p 2@a 3 4@b
25
54
  @dyn(a, b, 24)
26
55
  ~~~
27
- 端点须位于同一音轨、不同时间;变化量沿区间线性增加,叠加在每个音符原有力度上。本例从 \`a\` 到 \`b\` 渐强,终点增加 24 的力度。
56
+ 端点须位于同一音轨、不同时间;变化量沿区间线性增加,叠加在每个音符原有力度上,并保持到下一个力度记号。本例从 \`a\` 到 \`b\` 渐强,终点增加 24 的力度。
57
+
58
+ 终点同一时刻有力度记号时,以该记号为目标线性过渡,不再叠加 \`dv\`。
28
59
 
29
60
  端点也可标在增时线上。终点没有力度时,取同轨、不晚于终点的最后一个原始力度作为保持基准;找不到时给出警告并仅绘制。增时线延续的音符保持起音时的力度。`,
30
61
  allowExtraArgs: false,
@@ -35,61 +66,91 @@ class DynFunction extends ASTFunctionNode {
35
66
  ],
36
67
  };
37
68
  static loweringFinalize(result) {
38
- const dynamics = result.attachments.filter((attachment) => attachment instanceof DynAttachment);
69
+ const dynamics = result.attachments.filter((attachment) => attachment instanceof DynAttachment && attachment.orient());
39
70
  if (dynamics.length === 0)
40
71
  return;
41
72
  // 仅收集存在 @dyn 的音轨上的记录,避免无关声部也分配包装对象与排序
42
- const recordsByTrack = new Map(dynamics.map(d => [d.track, []]));
73
+ const lists = new Map(dynamics.map(d => [d.track, { records: [], marks: [] }]));
43
74
  for (const nodes of result.astToTemporal.values()) {
44
75
  for (const node of nodes) {
45
- const velocity = node.playbackState?.velocity;
46
- if (velocity === undefined)
47
- continue;
48
76
  const host = node.rootHost;
49
- recordsByTrack.get(host.track)?.push({ node, host, velocity, increment: 0 });
77
+ const list = lists.get(host.track);
78
+ if (!list)
79
+ continue;
80
+ const velocity = node.playbackState?.velocity;
81
+ if (velocity !== undefined)
82
+ list.records.push({ node, host, velocity });
83
+ const mark = dynamicMarkVelocity(node);
84
+ if (mark !== undefined)
85
+ list.marks.push({ node, host, velocity: mark });
50
86
  }
51
87
  }
52
- for (const list of recordsByTrack.values()) {
53
- list.sort((left, right) => left.host.t.compare(right.host.t) || left.node.order - right.node.order);
88
+ const byTime = (left, right) => left.host.t.compare(right.host.t) || left.node.order - right.node.order;
89
+ const tracks = new Map();
90
+ for (const [track, { records, marks }] of lists) {
91
+ records.sort(byTime);
92
+ marks.sort(byTime);
93
+ const length = records.length;
94
+ const runEnd = new Int32Array(length);
95
+ for (let i = length - 1; i >= 0; i--) {
96
+ runEnd[i] = i + 1 < length && records[i + 1].velocity === records[i].velocity ? runEnd[i + 1] : i + 1;
97
+ }
98
+ tracks.set(track, {
99
+ records,
100
+ marks,
101
+ runEnd,
102
+ times: Float64Array.from(records, record => record.host.t.toNumber()),
103
+ increments: new Float64Array(length),
104
+ offset: new Float64Array(length + 1),
105
+ slope: new Float64Array(length + 1),
106
+ });
54
107
  }
55
- // 先累计全部 dyn 的贡献,最后统一写回,避免声明顺序改变后续 dyn 读取的原始力度
108
+ // 先结算没有终点记号的渐变;以记号为目标的渐变要从这些增量生效后的力度出发
109
+ const targeted = [];
56
110
  for (const dynamic of dynamics) {
57
- const records = recordsByTrack.get(dynamic.track);
58
- const endStart = findRecordBoundary(records, dynamic.toHost.t);
59
- const afterEnd = findRecordBoundary(records, dynamic.toHost.t, true);
60
- let endVelocity = dynamic.end.playbackState?.velocity;
61
- for (let i = endStart; endVelocity === undefined && i < afterEnd; i++) {
62
- if (records[i].host === dynamic.toHost)
63
- endVelocity = records[i].velocity;
64
- }
65
- endVelocity ??= records[afterEnd - 1]?.velocity;
66
- if (endVelocity === undefined) {
111
+ const track = tracks.get(dynamic.track);
112
+ const { records, marks, runEnd } = track;
113
+ const to = dynamic.toHost.t;
114
+ const endStart = findRecordBoundary(records, to);
115
+ const afterEnd = findRecordBoundary(records, to, true);
116
+ if (afterEnd === 0) {
67
117
  result.diagnostics.push(new WarningDiagnostic("W_DYN_NO_VELOCITY", "@dyn 终点及此前同轨没有可用的力度基准,仅绘制渐变线", dynamic.sourceSpan));
68
118
  continue;
69
119
  }
70
- // 终点后保持完整增量,直到原始力度相对终点再次发生变化
71
- let stopIndex = records.length;
72
- for (let i = afterEnd; i < records.length; i++) {
73
- if (records[i].velocity !== endVelocity) {
74
- stopIndex = findRecordBoundary(records, records[i].host.t);
75
- break;
76
- }
77
- }
78
- const startIndex = findRecordBoundary(records, dynamic.fromHost.t);
79
- const duration = dynamic.toHost.t.clone().sub(dynamic.fromHost.t);
80
- for (let i = startIndex; i < stopIndex; i++) {
81
- const progress = i >= endStart ? 1
82
- : records[i].host.t.clone().sub(dynamic.fromHost.t).div(duration).toNumber();
83
- records[i].increment += dynamic.dv * progress;
120
+ const mark = marks[findRecordBoundary(marks, to, true) - 1];
121
+ if (mark?.host.t.equals(to)) {
122
+ // 同刻的记号与折叠成员先后不定,以终点最后取样的力度为目标
123
+ const sampled = records[afterEnd - 1];
124
+ targeted.push([dynamic, sampled.host.t.equals(to) ? sampled.velocity : mark.velocity]);
125
+ continue;
84
126
  }
127
+ // 保持到下一个力度记号(同值重写也算)或原始力度变化(兼顾其他写入力度的函数)
128
+ let stopIndex = runEnd[afterEnd - 1];
129
+ if (stopIndex < records.length)
130
+ stopIndex = findRecordBoundary(records, records[stopIndex].host.t);
131
+ const nextMark = marks[findRecordBoundary(marks, to, true)];
132
+ if (nextMark)
133
+ stopIndex = Math.min(stopIndex, findRecordBoundary(records, nextMark.host.t));
134
+ addRamp(track, dynamic, endStart, dynamic.dv);
135
+ addIncrement(track, endStart, stopIndex, dynamic.dv);
85
136
  }
86
- for (const records of recordsByTrack.values()) {
87
- for (const record of records) {
88
- if (record.increment === 0)
89
- continue;
90
- const velocity = Math.max(1, Math.min(127, record.velocity + record.increment));
91
- record.node.playbackState = { ...record.node.playbackState, velocity };
92
- }
137
+ for (const track of tracks.values())
138
+ settle(track);
139
+ for (const [dynamic, target] of targeted) {
140
+ const track = tracks.get(dynamic.track);
141
+ const last = findRecordBoundary(track.records, dynamic.toHost.t) - 1;
142
+ if (last < 0)
143
+ continue;
144
+ addRamp(track, dynamic, last + 1, target - track.records[last].velocity - track.increments[last]);
145
+ }
146
+ for (const track of tracks.values()) {
147
+ settle(track);
148
+ track.records.forEach((record, i) => {
149
+ // 容差吸收差分累加的浮点误差,避免半整数被算成略小于 .5
150
+ const velocity = Math.round(record.velocity + track.increments[i] + 1e-9);
151
+ if (velocity !== record.velocity)
152
+ record.node.playbackState = { ...record.node.playbackState, velocity };
153
+ });
93
154
  }
94
155
  }
95
156
  from;
@@ -112,15 +173,11 @@ class DynFunction extends ASTFunctionNode {
112
173
  if (fromHost.track !== toHost.track) {
113
174
  throw new ErrorDiagnostic("E_DYN_CROSS_TRACK", "@dyn 的两个端点必须位于同一音轨", this.sourceSpan);
114
175
  }
115
- if (fromHost.t.equals(toHost.t)) {
116
- throw new ErrorDiagnostic("E_DYN_ZERO_SPAN", "@dyn 的两个端点必须位于不同时间", this.sourceSpan);
117
- }
118
- if (fromHost.t.compare(toHost.t) < 0) {
119
- ctx.addAttachment(new DynAttachment(this, to, fromHost, toHost));
120
- }
121
- else {
122
- ctx.addAttachment(new DynAttachment(this, from, toHost, fromHost));
123
- }
176
+ // 此时的先后已可信(插入偏移只推后后续列);同刻端点留到时间固化后再判断
177
+ const order = fromHost.t.compare(toHost.t);
178
+ ctx.addAttachment(order > 0
179
+ ? new DynAttachment(this, toHost, fromHost, false)
180
+ : new DynAttachment(this, fromHost, toHost, order === 0));
124
181
  ctx.deferFinalize(DynFunction.loweringFinalize);
125
182
  return [];
126
183
  }
@@ -148,16 +205,31 @@ class DynFunction extends ASTFunctionNode {
148
205
  export const DynNode = DynFunction;
149
206
  class DynAttachment {
150
207
  ast;
151
- end;
152
208
  fromHost;
153
209
  toHost;
210
+ unordered;
154
211
  kind = "dyn";
155
212
  layer = "foreground";
156
- constructor(ast, end, fromHost, toHost) {
213
+ constructor(ast, fromHost, toHost,
214
+ /** lowering 时两端同刻,方向要等时间固化后才能确定 */
215
+ unordered) {
157
216
  this.ast = ast;
158
- this.end = end;
159
217
  this.fromHost = fromHost;
160
218
  this.toHost = toHost;
219
+ this.unordered = unordered;
220
+ }
221
+ /**
222
+ * 按最终时间确定方向,返回是否影响播放
223
+ * 倚音序列等局部时间轴上的渐变会投影到同一宿主时刻,只绘制
224
+ */
225
+ orient() {
226
+ const cmp = this.fromHost.t.compare(this.toHost.t);
227
+ if (cmp === 0 && this.unordered) {
228
+ throw new ErrorDiagnostic("E_DYN_ZERO_SPAN", "@dyn 的两个端点必须位于不同时间", this.sourceSpan);
229
+ }
230
+ if (cmp > 0)
231
+ [this.fromHost, this.toHost] = [this.toHost, this.fromHost];
232
+ return cmp !== 0;
161
233
  }
162
234
  get sourceSpan() { return this.ast.sourceSpan; }
163
235
  get endPoints() { return [this.fromHost, this.toHost]; }
@@ -4,7 +4,7 @@ import type { LoweringAttachment } from "../../lowering/types.js";
4
4
  import { Fraction } from "../../fraction.js";
5
5
  import { Track } from "../../lowering/track.js";
6
6
  import { TemporalNodeBase, type TimeState, type VisualTemporalNode } from "../temporal.js";
7
- import { GrammarNode, GrammarSugarNode } from "../../parser/grammarType.js";
7
+ import { GrammarSugarNode } from "../../parser/grammarType.js";
8
8
  import { ParserContext } from "../../parser/parserContext.js";
9
9
  import type { Painter } from "../../render/types.js";
10
10
  import type { PlaybackEmitter } from "../../playback/types.js";
@@ -17,7 +17,7 @@ declare class GraceFunction extends ASTFunctionNode {
17
17
  next: number;
18
18
  node: GrammarSugarNode;
19
19
  } | null;
20
- static deSugarRelation(ctx: ParserContext, nodes: (GrammarNode | number)[], at: number): number | null;
20
+ private static deSugarRelation;
21
21
  host: ASTNodeBase;
22
22
  grace: ASTNodeBase;
23
23
  side: GraceSide;
@@ -90,20 +90,16 @@ class GraceFunction extends ASTFunctionNode {
90
90
  next: start + 1,
91
91
  node: {
92
92
  kind: "sugar",
93
- data: {
94
- class: GraceFunction,
95
- side: char
96
- },
97
- span: { start, end: start + 1 }
93
+ data: char,
94
+ span: { start, end: start + 1 },
95
+ relation: GraceFunction.deSugarRelation,
98
96
  }
99
97
  };
100
98
  }
101
99
  // 取左右操作数的流程同 stack / up
102
100
  static deSugarRelation(ctx, nodes, at) {
103
101
  const n = nodes[at++];
104
- if (n.kind !== "sugar" || n.data?.class !== GraceFunction)
105
- return null;
106
- const side = n.data.side;
102
+ const side = n.data;
107
103
  // 箭头指向宿主:`1>2>3` 是 `{1>2}>3`,所以 `>` 登记 chain 左结合;`1<2<3` 是 `1<{2<3}`,`<` 保持右结合
108
104
  const chain = side === "pre" ? GraceFunction : undefined;
109
105
  const leftNode = ctx.takeLeftOperand(chain);
@@ -169,7 +165,7 @@ class GraceFunction extends ASTFunctionNode {
169
165
  throw new ErrorDiagnostic("E_GRACE_INVALID_HOST", "@grace 的宿主必须恰好产生一个可见 Temporal", host.sourceSpan);
170
166
  }
171
167
  const events = columns.flat();
172
- if (!events.some(isVisualTemporalNode) || events.some(event => (event.addon?.breakBefore ?? 0) > 0)) {
168
+ if (!events.some(isVisualTemporalNode) || events.some(event => event.addon?.breakBefore)) {
173
169
  throw new ErrorDiagnostic("E_GRACE_INVALID_CONTENT", "@grace 的倚音至少产生一个可见对象,且不能换行", grace.sourceSpan);
174
170
  }
175
171
  return [new GraceTemporal(this, hostNode, columns, root, attachments, ctx)];
@@ -57,7 +57,7 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
57
57
  members = [];
58
58
  slots = [];
59
59
  titleBottom = 0;
60
- aligned = false; // 侧栏横向重排在一轮布局中只执行一次,避免二次 onPlaced 把成员微调后的 box.x 当成未偏移基准
60
+ aligned = false; // 侧栏横向重排在一轮布局中只执行一次:后置平移后的 onPlaced 里成员已含各自平移,不能再作为基准
61
61
  sideExtents = { left: null, right: null };
62
62
  constructor(ast) {
63
63
  super();
@@ -158,7 +158,7 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
158
158
  cells.set(cell, [member]);
159
159
  }
160
160
  const [left, , right] = this.slots;
161
- this.packRows(left.ast, left.start.box.x - (left.start.placementOffset?.x ?? 0), cells);
161
+ this.packRows(left.ast, left.start.box.x, cells);
162
162
  this.packRows(right.ast, right.end.box.x, cells);
163
163
  }
164
164
  stretch(node, side) {
@@ -352,8 +352,9 @@ H.tempo: 94
352
352
  next: explicitContent ? pos : lineEnd,
353
353
  node: {
354
354
  kind: "sugar",
355
- data: { class: HeadFunction, field, contentSpan },
355
+ data: { field, contentSpan },
356
356
  span: { start, end: pos },
357
+ relation: HeadFunction.deSugarRelation,
357
358
  syntaxKind: contentSpan && field !== "signature" && field !== "tempo" && contentSpan.start < contentSpan.end
358
359
  ? [{ kind: "operator", span: { start, end: pos } }, { kind: "string", span: contentSpan }]
359
360
  : undefined,
@@ -362,8 +363,6 @@ H.tempo: 94
362
363
  }
363
364
  static deSugarRelation(ctx, nodes, at) {
364
365
  const sugar = nodes[at++];
365
- if (sugar.data?.class !== HeadFunction)
366
- return null;
367
366
  const field = sugar.data.field;
368
367
  let breakAt = at;
369
368
  let span = sugar.data.contentSpan;
@@ -373,7 +372,7 @@ H.tempo: 94
373
372
  const node = nodes[breakAt];
374
373
  if (typeof node === "number" && (ctx.source[node] === "\r" || ctx.source[node] === "\n"))
375
374
  break;
376
- if (typeof node !== "number" && node.kind === "sugar" && node.data?.class === HeadFunction)
375
+ if (typeof node !== "number" && node.kind === "sugar" && node.relation === HeadFunction.deSugarRelation)
377
376
  break;
378
377
  }
379
378
  const sub = new ParserContext(ctx);
@@ -462,7 +461,7 @@ H.tempo: 94
462
461
  // 此时 rest 等延迟时值已固化,只检查当前 Head 的成员,无须再扫描全谱索引
463
462
  head.slots[2].end.onTimeState = () => head.validateDuration();
464
463
  for (const node of head.members) {
465
- if ((node.addon?.breakBefore ?? 0) > 0) {
464
+ if (node.addon?.breakBefore) {
466
465
  throw new ErrorDiagnostic("E_HEAD_INTERNAL_BREAK", "@head 的内部不能换行或换页;第一层内容已经表示视觉行", node.ast.sourceSpan);
467
466
  }
468
467
  }
@@ -110,7 +110,7 @@ class MeterFunction extends ASTFunctionNode {
110
110
  measureStart.copyFrom(end);
111
111
  };
112
112
  for (const column of result.columns) {
113
- const time = column[0].t;
113
+ const time = column.t;
114
114
  for (const node of column) {
115
115
  const change = changesByPosition.get(node);
116
116
  if (!change)
@@ -120,10 +120,10 @@ class MeterFunction extends ASTFunctionNode {
120
120
  measureStart.copyFrom(time);
121
121
  sourceStart = change.end;
122
122
  }
123
- const anchor = column.find(node => node.mergeKey === ANCHOR_KEY);
124
- if (anchor) {
125
- closeMeasure(time, anchor.ast.sourceSpan.end);
126
- sourceStart = anchor.ast.sourceSpan.end;
123
+ if (column.mergeKey === ANCHOR_KEY) {
124
+ const end = column[0].ast.sourceSpan.end;
125
+ closeMeasure(time, end);
126
+ sourceStart = end;
127
127
  validationStarted = true;
128
128
  }
129
129
  }
@@ -157,6 +157,8 @@ class MeterTemporal extends TemporalNodeBase {
157
157
  }
158
158
  onTimeState(state) {
159
159
  state.meter = this.ast.measureDuration;
160
+ const { measureDuration, numerator, denominator } = this.ast;
161
+ state.timeSignature = measureDuration && { numerator, denominator };
160
162
  recordMeasureChange(this, this.ast);
161
163
  }
162
164
  emitPlayback(emitter) {
@@ -86,7 +86,7 @@ function pinnedSemitone(source, notes, operation, ranges, relower) {
86
86
  const offset = target - resolveNoteMidi(node.name, "", node.octave, node.keySignature);
87
87
  const acc = offsetToAccidental(offset) || "n";
88
88
  // 同一 AST 的多个实例要求不同记号时无解
89
- if (Math.abs(offset) > 2 || (pins.get(ast) ?? acc) !== acc)
89
+ if ((pins.get(ast) ?? acc) !== acc)
90
90
  fail(ast.sourceSpan);
91
91
  pins.set(ast, acc);
92
92
  }
@@ -173,9 +173,10 @@ class NoteFunction extends ASTFunctionNode {
173
173
  next: start + 1,
174
174
  node: {
175
175
  kind: "sugar",
176
- data: { jeOffset },
176
+ data: jeOffset,
177
177
  span: { start, end: start + 1 },
178
178
  syntaxKind: "punctuation",
179
+ relation: NoteFunction.deSugarRelation,
179
180
  },
180
181
  };
181
182
  // 解析音符名
@@ -204,10 +205,7 @@ class NoteFunction extends ASTFunctionNode {
204
205
  }
205
206
  static deSugarRelation(ctx, nodes, at) {
206
207
  const node = nodes[at];
207
- const jeOffset = node.data?.jeOffset;
208
- if (typeof jeOffset !== "number")
209
- return null;
210
- ctx.variables[JE_OCTAVE_OFFSET] = (ctx.variables[JE_OCTAVE_OFFSET] ?? 0) + jeOffset;
208
+ ctx.variables[JE_OCTAVE_OFFSET] = (ctx.variables[JE_OCTAVE_OFFSET] ?? 0) + node.data;
211
209
  // JE 谱兼容:保留括号源码,并让关系语法糖像跳过普通文本一样跳过它。
212
210
  ctx.nodes.push(new ASTTextNode(node.span));
213
211
  return at + 1;
@@ -392,7 +390,7 @@ class NoteTemporalNode extends TemporalNodeBase {
392
390
  /** 固化记谱位置的音高、力度和音色,并保留基于该调性的相对移调能力 */
393
391
  onTimeState(state) {
394
392
  const keySignature = this.keySignature = state.keySignature;
395
- this.playbackState = { bpm: state.bpm, velocity: state.velocity, program: state.program };
393
+ this.playbackState = { velocity: state.velocity, program: state.program };
396
394
  this.resolvedMidi = resolveNoteMidi(this.name, this.acc, this.octave, keySignature);
397
395
  // 数字音名本身就是简谱显示形式,直接保留原始数字和相对八度
398
396
  if (this.name >= "0" && this.name <= "9") {
@@ -171,18 +171,19 @@ class OttavaAttachment {
171
171
  parts.push(part(right - halfStroke, above ? -halfStroke : -hook - halfStroke, strokeWidth, hook + strokeWidth));
172
172
  const region = part(0, 0, 0, 0);
173
173
  unionLayoutBoxes(region, parts);
174
+ // 八度号只属于本轨:其他轨由纵向求解按占用推开,不在这里避让
175
+ const axis = context.getVisualAxis(line, track);
174
176
  let lineY = above ? Infinity : -Infinity;
175
177
  for (const part of parts) {
176
- for (const [lane, extent] of context.getHorizontalExtents(line, part.x, part.x + part.w)) {
177
- const axis = context.getVisualAxis(line, lane);
178
- lineY = above
179
- ? Math.min(lineY, axis + extent.top - gap - part.y - part.h)
180
- : Math.max(lineY, axis + extent.bottom + gap - part.y);
181
- }
178
+ const extent = context.getHorizontalExtents(line, part.x, part.x + part.w).get(track);
179
+ if (!extent)
180
+ continue;
181
+ lineY = above
182
+ ? Math.min(lineY, axis + extent.top - gap - part.y - part.h)
183
+ : Math.max(lineY, axis + extent.bottom + gap - part.y);
182
184
  }
183
185
  if (!Number.isFinite(lineY)) {
184
186
  const extent = context.getRangeExtents(line, first || last ? this.endPoints : undefined, track);
185
- const axis = context.getVisualAxis(line, track);
186
187
  lineY = above
187
188
  ? axis + (extent?.top ?? 0) - gap - (region.y + region.h)
188
189
  : axis + (extent?.bottom ?? 0) + gap - region.y;
@@ -52,11 +52,11 @@ class PageFunction extends ASTFunctionNode {
52
52
  ~~~jpfun
53
53
  @page(
54
54
  width=794px, height=1123px, top=48px, bottom=48px,
55
- left=40px, right=40px, gap=1em, minGap=0.4em, fillRatio=0.5,
55
+ left=40px, right=40px, fillRatio=0.5,
56
56
  numbering="1/1", barNumbering="(1)"
57
57
  )
58
58
  ~~~
59
- 页边距和行距须非负;左右边距之和须小于页宽,固定页高时上下边距之和须小于页高。`,
59
+ 页边距须非负;左右边距之和须小于页宽,固定页高时上下边距之和须小于页高。行距由 \`@br\` 的 \`gap\`、\`minGap\` 设置。`,
60
60
  allowExtraArgs: false,
61
61
  args: [
62
62
  { name: "width", description: "页面宽度,须大于左右页边距之和", type: "length", default: px(DEFAULT_PAGE_CONFIG.width) },
@@ -65,8 +65,6 @@ class PageFunction extends ASTFunctionNode {
65
65
  { name: "bottom", description: "页面下边距,启用页码时至少为 `16px`", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginBottom) },
66
66
  { name: "left", description: "页面左边距", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginLeft) },
67
67
  { name: "right", description: "页面右边距", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginRight) },
68
- { name: "gap", description: "谱面行主旋律之间的标准间距", type: "length", default: { value: 1, unit: "em" } },
69
- { name: "minGap", description: "行间保留的最小间距", type: "length", default: { value: 0.4, unit: "em" } },
70
68
  { name: "numbering", description: "页码格式,空值隐藏;`1`:当前页,`1/1`:显示当前页/总页数", type: "string", default: "" },
71
69
  { name: "barNumbering", description: "行首小节号格式,默认空值隐藏;`1` 显示当前小节号,`(1)` 显示带括号的小节号", type: "string", default: "" },
72
70
  { name: "font", description: "页码/小节号字体,空值沿用当前字体设置", type: "string", default: "" },
@@ -91,15 +89,15 @@ class PageFunction extends ASTFunctionNode {
91
89
  return;
92
90
  }
93
91
  ctx.documentDeclarations["page"] = true;
94
- const [w, h, t, b, l, r, g, mg, numbering, barNumbering, font, fillRatio,] = this.getArgValue(args, ctx);
92
+ const [w, h, t, b, l, r, numbering, barNumbering, font, fillRatio,] = this.getArgValue(args, ctx);
95
93
  this.font = font || ctx.variables.font;
96
- const [width, height, top, bottom, left, right, gap, minGap] = [w, h, t, b, l, r, g, mg].map(value => ctx.length2px(value));
94
+ const [width, height, top, bottom, left, right] = [w, h, t, b, l, r].map(value => ctx.length2px(value));
97
95
  if (!Number.isFinite(width) || width <= 0)
98
96
  throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的 width 必须是正有限长度", sourceSpan);
99
97
  if (!Number.isFinite(height))
100
98
  throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的 height 必须是有限长度;小于等于 0 表示不自动分页", sourceSpan);
101
- if ([top, bottom, left, right, gap, minGap].some(value => !Number.isFinite(value) || value < 0))
102
- throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的边距、gap 和 minGap 必须是非负有限长度", sourceSpan);
99
+ if ([top, bottom, left, right].some(value => !Number.isFinite(value) || value < 0))
100
+ throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的边距必须是非负有限长度", sourceSpan);
103
101
  if (left + right >= width)
104
102
  throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的左右边距没有留下可用内容宽度", sourceSpan);
105
103
  if (height > 0 && top + bottom >= height)
@@ -113,8 +111,6 @@ class PageFunction extends ASTFunctionNode {
113
111
  marginBottom: bottom,
114
112
  marginLeft: left,
115
113
  marginRight: right,
116
- lineGap: gap,
117
- minLineGap: minGap,
118
114
  fillRatio,
119
115
  });
120
116
  this.numbering = numbering;
@@ -134,8 +130,8 @@ class PageFunction extends ASTFunctionNode {
134
130
  toString() {
135
131
  if (!this.config)
136
132
  return "@page()";
137
- const { width, height, marginTop, marginBottom, marginLeft, marginRight, lineGap, minLineGap, fillRatio } = this.config;
138
- return `@page(width=${width}px, height=${Number.isFinite(height) ? height : 0}px, top=${marginTop}px, bottom=${marginBottom}px, left=${marginLeft}px, right=${marginRight}px, gap=${lineGap}px, minGap=${minLineGap}px, numbering=${quoteSourceString(this.numbering)}, barNumbering=${quoteSourceString(this.barNumbering)}, font=${quoteSourceString(this.font)}, fillRatio=${fillRatio})`;
133
+ const { width, height, marginTop, marginBottom, marginLeft, marginRight, fillRatio } = this.config;
134
+ return `@page(width=${width}px, height=${Number.isFinite(height) ? height : 0}px, top=${marginTop}px, bottom=${marginBottom}px, left=${marginLeft}px, right=${marginRight}px, numbering=${quoteSourceString(this.numbering)}, barNumbering=${quoteSourceString(this.barNumbering)}, font=${quoteSourceString(this.font)}, fillRatio=${fillRatio})`;
139
135
  }
140
136
  }
141
137
  export const PageNode = PageFunction;
@@ -28,7 +28,8 @@ class PageBreakFunction extends ASTFunctionNode {
28
28
  const node = new TemporalNodeBase();
29
29
  node.ast = this;
30
30
  node.mergeKey = -1;
31
- node.addon = { breakBefore: 1, pageBreakBefore: this.justify };
31
+ // 新页首行没有行距
32
+ node.addon = { breakBefore: { gap: 0, minGap: 0 }, pageBreakBefore: this.justify };
32
33
  return [node];
33
34
  }
34
35
  toString() { return `@pagebreak(justify=${this.justify})`; }
@@ -1,5 +1,6 @@
1
1
  import { ErrorDiagnostic } from "../../diagnostic.js";
2
2
  import { Fraction } from "../../fraction.js";
3
+ import { TimeColumn } from "../../lowering/loweringContext.js";
3
4
  import { ASTFunctionNode, ASTNodeBase, } from "../ASTtypes.js";
4
5
  import { ANCHOR_KEY, isVisualTemporalNode, TemporalNodeBase } from "../temporal.js";
5
6
  // 同刻状态先固化,休止只与休止合列,普通音符随后进入
@@ -65,7 +66,7 @@ class RestFunction extends ASTFunctionNode {
65
66
  }
66
67
  static loweringFinalize(result) {
67
68
  // 没有全局休止列时,跳过索引扫描和边界补入
68
- if (!result.columns.some(column => column.some(node => node.mergeKey === REST_KEY)))
69
+ if (!result.columns.some(column => column.mergeKey === REST_KEY))
69
70
  return;
70
71
  let order = 0;
71
72
  const onsets = new Map();
@@ -110,7 +111,7 @@ class RestFunction extends ASTFunctionNode {
110
111
  }
111
112
  if (!longest)
112
113
  continue;
113
- const time = longest.t.clone();
114
+ const time = column.t.clone();
114
115
  // 按小节时长补入 n−1 个不可见边界;时间已固化,不再参与声部归并
115
116
  for (let index = 1; index < longest.ast.count; index++) {
116
117
  time.add(longest.measureDuration);
@@ -118,11 +119,11 @@ class RestFunction extends ASTFunctionNode {
118
119
  boundary.ast = new ASTNodeBase(longest.ast.sourceSpan, longest.ast);
119
120
  boundary.t.copyFrom(time);
120
121
  boundary.track = longest.track;
121
- boundary.layoutLine = longest.layoutLine;
122
+ boundary.layoutLine = column.layoutLine;
122
123
  boundary.order = order++;
123
124
  boundary.mergeKey = ANCHOR_KEY;
124
125
  result.astToTemporal.set(boundary.ast, [boundary]);
125
- columns.push([boundary]);
126
+ columns.push(new TimeColumn(boundary, column.bpm));
126
127
  }
127
128
  }
128
129
  result.columns = columns;
@@ -160,7 +161,6 @@ class RestTemporal extends TemporalNodeBase {
160
161
  if (!rest || this.order < rest.order)
161
162
  restsByHost.set(host, this);
162
163
  }
163
- this.playbackState = { bpm: state.bpm };
164
164
  return this.T;
165
165
  }
166
166
  emitPlayback(emitter) {
@@ -54,8 +54,8 @@ class StackFunction extends ASTFunctionNode {
54
54
  if (source[start] === '&') {
55
55
  const node = {
56
56
  kind: "sugar",
57
- data: StackFunction,
58
57
  span: { start, end: start + 1 },
58
+ relation: StackFunction.deSugarRelation,
59
59
  };
60
60
  return { next: start + 1, node };
61
61
  }
@@ -63,8 +63,6 @@ class StackFunction extends ASTFunctionNode {
63
63
  }
64
64
  static deSugarRelation(ctx, nodes, at) {
65
65
  const n = nodes[at++];
66
- if (!(n.kind === "sugar" && n.data === StackFunction))
67
- return null;
68
66
  const leftNode = ctx.takeLeftOperand();
69
67
  if (!leftNode) {
70
68
  throw new ErrorDiagnostic("E_STACK_NO_TARGET", "@stack语法糖错误: 左边没有找到可叠加的目标", n.span);
@@ -1,3 +1,6 @@
1
+ import type { TemporalNodeBase } from "../../temporal.js";
1
2
  import type { SymbolDefinition } from "../index.js";
3
+ /** 节点是力度记号时返回它设置的力度 */
4
+ export declare function dynamicMarkVelocity(node: TemporalNodeBase): number | undefined;
2
5
  /** 默认力度与 MuseScore 一致;mf 恰好等于 DEFAULT_VELOCITY */
3
6
  export declare const dynamicSymbols: readonly SymbolDefinition[];
@@ -142,7 +142,16 @@ const INK = { fill: "#000" };
142
142
  const P_WEIGHT = 0.79341;
143
143
  const P_VELOCITIES = [49, 33, 16, 10, 5, 1];
144
144
  const F_VELOCITIES = [96, 112, 126, 127];
145
+ /** 力度记号的 onTimeState → 力度;符号节点直接引用定义里的回调,因而可按引用识别 */
146
+ const markVelocities = new WeakMap();
147
+ /** 节点是力度记号时返回它设置的力度 */
148
+ export function dynamicMarkVelocity(node) {
149
+ const onTimeState = node.onTimeState;
150
+ return onTimeState && markVelocities.get(onTimeState);
151
+ }
145
152
  function dynamic(name, velocity, description) {
153
+ const onTimeState = (state) => { state.velocity = velocity; };
154
+ markVelocities.set(onTimeState, velocity);
146
155
  let dx = 0;
147
156
  const shapes = Array.from(name, (letter, index) => {
148
157
  const shape = { path: GLYPHS[letter], style: INK, dx };
@@ -154,7 +163,7 @@ function dynamic(name, velocity, description) {
154
163
  description,
155
164
  shapes,
156
165
  weight: name.includes("f") ? 1 : P_WEIGHT,
157
- onTimeState: state => { state.velocity = velocity; },
166
+ onTimeState,
158
167
  };
159
168
  }
160
169
  /** 默认力度与 MuseScore 一致;mf 恰好等于 DEFAULT_VELOCITY */