jpfun 0.6.0 → 0.7.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 (64) hide show
  1. package/dist/converter/midi/convert.d.ts +3 -1
  2. package/dist/converter/midi/convert.js +78 -66
  3. package/dist/converter/musicxml/features.d.ts +19 -5
  4. package/dist/converter/musicxml/features.js +46 -8
  5. package/dist/converter/musicxml/index.js +142 -23
  6. package/dist/converter/musicxml/model.d.ts +15 -0
  7. package/dist/diagnostic.js +1 -1
  8. package/dist/functions/arpeggio/index.js +2 -5
  9. package/dist/functions/arpeggio/shape.d.ts +1 -1
  10. package/dist/functions/arpeggio/shape.js +27 -21
  11. package/dist/functions/bar/index.js +37 -36
  12. package/dist/functions/beam/auto.js +16 -13
  13. package/dist/functions/beam/layout.js +15 -23
  14. package/dist/functions/br/index.js +3 -4
  15. package/dist/functions/default.js +8 -4
  16. package/dist/functions/gliss/index.d.ts +2 -0
  17. package/dist/functions/gliss/index.js +180 -0
  18. package/dist/functions/grace/index.js +3 -6
  19. package/dist/functions/head/index.js +40 -59
  20. package/dist/functions/meter/index.js +19 -18
  21. package/dist/functions/note/accidentals.js +10 -16
  22. package/dist/functions/note/index.js +13 -3
  23. package/dist/functions/ottava/index.d.ts +2 -0
  24. package/dist/functions/ottava/index.js +217 -0
  25. package/dist/functions/page/index.js +3 -3
  26. package/dist/functions/pagebreak/index.d.ts +2 -0
  27. package/dist/functions/pagebreak/index.js +36 -0
  28. package/dist/functions/rest/index.js +12 -14
  29. package/dist/functions/slide/index.d.ts +2 -0
  30. package/dist/functions/slide/index.js +132 -0
  31. package/dist/functions/stack/index.js +8 -15
  32. package/dist/functions/symbol/index.d.ts +9 -0
  33. package/dist/functions/symbol/index.js +41 -12
  34. package/dist/functions/symbol/ornament.js +14 -19
  35. package/dist/functions/symbol/shape.js +4 -1
  36. package/dist/functions/symbol/symbols/fine.js +1 -1
  37. package/dist/functions/symbol/symbols/tr.js +46 -1
  38. package/dist/functions/temporal.d.ts +16 -6
  39. package/dist/functions/temporal.js +16 -6
  40. package/dist/functions/tie/index.js +35 -25
  41. package/dist/functions/up/index.js +5 -7
  42. package/dist/functions/voice/connections.js +7 -5
  43. package/dist/functions/voice/index.js +2 -1
  44. package/dist/functions/volta/index.js +41 -21
  45. package/dist/jpfun.core.min.js +44 -68
  46. package/dist/jpfun.from-midi.min.js +5 -5
  47. package/dist/jpfun.from-musicxml.min.js +8 -8
  48. package/dist/jpfun.min.js +53 -77
  49. package/dist/layout/engine.d.ts +1 -0
  50. package/dist/layout/engine.js +42 -11
  51. package/dist/layout/page.d.ts +3 -2
  52. package/dist/layout/page.js +6 -5
  53. package/dist/layout/types.d.ts +4 -0
  54. package/dist/lowering/loweringContext.js +7 -167
  55. package/dist/parser/parserContext.d.ts +2 -0
  56. package/dist/parser/parserContext.js +27 -6
  57. package/dist/playback/compile.js +11 -2
  58. package/dist/playback/types.d.ts +4 -2
  59. package/dist/render/svg.js +1 -0
  60. package/dist/render/text.d.ts +1 -1
  61. package/dist/render/text.js +3 -2
  62. package/dist/render/types.d.ts +1 -0
  63. package/grammar.md +30 -9
  64. package/package.json +1 -1
@@ -4,8 +4,10 @@ import { DIV_ADDON_KEY, DivNode, } from "../div/index.js";
4
4
  import { collectExplicitBeamEndpoints, createBeamLayoutAttachment, } from "./layout.js";
5
5
  /** 只返回实际参与当前事件 div addon 的 div,先沿祖先链找,不够再按书写顺序向下补 */
6
6
  function findActiveDivs(node) {
7
- const result = [];
8
7
  let remainingLevels = Math.max(0, Math.floor(Number(node.addon?.[DIV_ADDON_KEY]) || 0));
8
+ if (remainingLevels <= 0)
9
+ return [];
10
+ const result = [];
9
11
  const take = (div) => {
10
12
  result.push(div);
11
13
  remainingLevels -= Math.max(0, div.n);
@@ -16,6 +18,8 @@ function findActiveDivs(node) {
16
18
  take(ast);
17
19
  ast = ast.parent;
18
20
  }
21
+ if (remainingLevels <= 0)
22
+ return result;
19
23
  // 复合节点(如 up)把代表成员的修饰提升成了自己的,提供层级的 div 在子树里
20
24
  const descend = (parent) => {
21
25
  for (const child of parent.children ?? []) {
@@ -71,24 +75,21 @@ function outermostScopes(scopes) {
71
75
  return true;
72
76
  });
73
77
  }
74
- function sourceSpanForAutoBeam(nodes) {
78
+ function createAutoBeam(nodes, nodeScopes) {
75
79
  let start = Infinity;
76
80
  let end = -Infinity;
77
81
  for (const node of nodes) {
78
82
  start = Math.min(start, node.ast.sourceSpan.start);
79
83
  end = Math.max(end, node.ast.sourceSpan.end);
80
- for (const div of findActiveDivs(node)) {
81
- start = Math.min(start, div.sourceSpan.start);
82
- end = Math.max(end, div.sourceSpan.end);
84
+ for (const { owner } of nodeScopes.get(node) ?? []) {
85
+ start = Math.min(start, owner.sourceSpan.start);
86
+ end = Math.max(end, owner.sourceSpan.end);
83
87
  }
84
88
  }
85
- return { start, end };
86
- }
87
- function createAutoBeam(nodes) {
88
- return createBeamLayoutAttachment(nodes, false, sourceSpanForAutoBeam(nodes));
89
+ return createBeamLayoutAttachment(nodes, false, { start, end });
89
90
  }
90
91
  /** 同一个 div 内部始终按轨道连接,手工 beam 端点会截断自动片段 */
91
- function createScopeBeams(scopes, explicitEndpoints) {
92
+ function createScopeBeams(scopes, nodeScopes, explicitEndpoints) {
92
93
  const attachments = [];
93
94
  for (const scope of outermostScopes(scopes)) {
94
95
  const tracks = new Map();
@@ -103,7 +104,7 @@ function createScopeBeams(scopes, explicitEndpoints) {
103
104
  let segment = [];
104
105
  const flush = () => {
105
106
  if (segment.length >= 2)
106
- attachments.push(createAutoBeam(segment));
107
+ attachments.push(createAutoBeam(segment, nodeScopes));
107
108
  segment = [];
108
109
  };
109
110
  for (const node of nodes) {
@@ -147,7 +148,7 @@ function createAdjacentBeams(result, nodeScopes, explicitEndpoints) {
147
148
  return;
148
149
  groups.delete(track);
149
150
  if (group.nodes.length >= 2)
150
- attachments.push(createAutoBeam(group.nodes));
151
+ attachments.push(createAutoBeam(group.nodes, nodeScopes));
151
152
  };
152
153
  const flushAll = () => {
153
154
  for (const track of [...groups.keys()])
@@ -202,9 +203,11 @@ function createAdjacentBeams(result, nodeScopes, explicitEndpoints) {
202
203
  /** beam 域在 lowering 固化后统一生成作用域连接和相邻自动连接 */
203
204
  export function createAutomaticBeamAttachments(result) {
204
205
  const { scopes, nodeScopes } = collectDivScopes(result);
206
+ if (scopes.length === 0)
207
+ return [];
205
208
  const explicitEndpoints = collectExplicitBeamEndpoints(result.attachments);
206
209
  return [
207
- ...createScopeBeams(scopes, explicitEndpoints),
210
+ ...createScopeBeams(scopes, nodeScopes, explicitEndpoints),
208
211
  ...createAdjacentBeams(result, nodeScopes, explicitEndpoints),
209
212
  ];
210
213
  }
@@ -8,6 +8,7 @@ export function createBeamLayoutAttachment(endPoints, explicit, sourceSpan) {
8
8
  /** 显式 beam 连接同轨同谱面行中的相邻可见主体,忽略零时长小节线 */
9
9
  export function validateExplicitBeamAttachments(result) {
10
10
  const tracks = new Map();
11
+ const positions = new Map();
11
12
  for (const column of result.columns) {
12
13
  for (const node of column) {
13
14
  if (!isVisualTemporalNode(node))
@@ -19,19 +20,9 @@ export function validateExplicitBeamAttachments(result) {
19
20
  lineTracks = new Map();
20
21
  tracks.set(node.layoutLine, lineTracks);
21
22
  }
22
- const sequence = lineTracks.get(node.track);
23
- if (sequence)
24
- sequence.push(node);
25
- else
26
- lineTracks.set(node.track, [node]);
27
- }
28
- }
29
- const positions = new Map();
30
- for (const [line, lineTracks] of tracks) {
31
- for (const [track, sequence] of lineTracks) {
32
- for (let index = 0; index < sequence.length; index++) {
33
- positions.set(sequence[index], { line, track, index });
34
- }
23
+ const index = lineTracks.get(node.track) ?? 0;
24
+ positions.set(node, { line: node.layoutLine, track: node.track, index });
25
+ lineTracks.set(node.track, index + 1);
35
26
  }
36
27
  }
37
28
  for (const attachment of result.attachments) {
@@ -84,18 +75,19 @@ class BeamLayoutAttachment {
84
75
  }
85
76
  /** 同一 beam 组内的相邻元素使用更短的自然弹簧间距 */
86
77
  prepareHorizontal(context) {
87
- const endPoints = new Set(this.endPoints);
88
- for (const line of context) {
89
- for (const run of line.trackRuns.values()) {
90
- for (let i = 1; i < run.length; i++) {
91
- const left = run[i - 1];
92
- const right = run[i];
93
- if (!endPoints.has(left) || !endPoints.has(right))
94
- continue;
95
- left.springConfig.alpha_R = left.springConfig.alpha_R * 0.8;
96
- right.springConfig.alpha_L = right.springConfig.alpha_L * 0.8;
78
+ let left;
79
+ for (const node of this.endPoints) {
80
+ if (!isVisualTemporalNode(node))
81
+ continue;
82
+ if (left && left.layoutLine === node.layoutLine && left.track === node.track) {
83
+ const line = context[left.layoutLine];
84
+ const index = line ? line.trackIndexOf(left) : -1;
85
+ if (index >= 0 && index + 1 === line.trackIndexOf(node)) {
86
+ left.springConfig.alpha_R *= 0.8;
87
+ node.springConfig.alpha_L *= 0.8;
97
88
  }
98
89
  }
90
+ left = node;
99
91
  }
100
92
  }
101
93
  createGeometry(context) {
@@ -50,19 +50,18 @@ class BrFunction extends ASTFunctionNode {
50
50
  const br = new TemporalNodeBase();
51
51
  br.ast = this;
52
52
  br.mergeKey = -1;
53
- br.breakBefore = this.offset;
53
+ br.addon = { breakBefore: this.offset };
54
54
  return [br];
55
55
  }
56
56
  /**
57
- * 检查换行是否切断了持续事件
58
- * 换行会把整条时间线切开,因此跨越换行点的持续事件无法被完整绘制
57
+ * 换行与换页共享校验;边界会切开全谱,不能截断持续事件
59
58
  */
60
59
  static loweringFinalize = (result) => {
61
60
  const latestEnd = new Fraction();
62
61
  const candidateEnd = new Fraction();
63
62
  let latestNode = null;
64
63
  for (const column of result.columns) {
65
- if (latestNode && latestEnd.compare(column[0].t) > 0 && column.some(node => node.breakBefore > 0)) {
64
+ if (latestNode && latestEnd.compare(column[0].t) > 0 && column.some(node => (node.addon?.breakBefore ?? 0) > 0)) {
66
65
  throw Diagnostic.error.BreakInsideEvent(latestNode.ast.sourceSpan);
67
66
  }
68
67
  for (const node of column) {
@@ -8,14 +8,18 @@ import { DivNode } from "./div/index.js";
8
8
  import { DotNode } from "./dot/index.js";
9
9
  import { DynNode } from "./dyn/index.js";
10
10
  import { GraceNode } from "./grace/index.js";
11
+ import { GlissNode } from "./gliss/index.js";
12
+ import { SlideNode } from "./slide/index.js";
11
13
  import { HeadNode } from "./head/index.js";
12
14
  import { KeyNode } from "./key/index.js";
13
15
  import { MeterNode } from "./meter/index.js";
14
16
  import { BrNode } from "./br/index.js";
15
17
  import { NoteNode } from "./note/index.js";
18
+ import { OttavaNode } from "./ottava/index.js";
16
19
  import { RestNode } from "./rest/index.js";
17
20
  import { UpNode, DownNode } from "./up/index.js";
18
21
  import { PageNode } from "./page/index.js";
22
+ import { PageBreakNode } from "./pagebreak/index.js";
19
23
  import { ProgramNode } from "./program/index.js";
20
24
  import { StackNode } from "./stack/index.js";
21
25
  import { SymbolNode } from "./symbol/index.js";
@@ -30,14 +34,14 @@ export const defaultFunctions = [
30
34
  NoteNode, DashNode, RestNode, BarNode,
31
35
  DivNode, DotNode, TupletNode, // 装饰性
32
36
  VoiceNode, VoicesNode, // 歌词和声部
33
- BrNode, // 排版
37
+ BrNode, PageBreakNode, // 排版
34
38
  PageNode, HeadNode, // 文档页面与谱头
35
39
  StackNode, // 时间同步
36
40
  UpNode, DownNode,
37
41
  ArpeggioNode,
38
- GraceNode, // 倚音
39
- TieNode, BeamNode, DynNode,
40
- BoxNode, VoltaNode,
42
+ GraceNode, SlideNode, // 倚音与滑入滑出
43
+ TieNode, BeamNode, GlissNode, DynNode,
44
+ BoxNode, VoltaNode, OttavaNode,
41
45
  AdjustNode, // 手工微调
42
46
  SetNode, KeyNode, MeterNode, TempoNode, ProgramNode, // 设置
43
47
  TextNode, SymbolNode,
@@ -0,0 +1,2 @@
1
+ import { type ASTFunctionClass } from "../ASTtypes.js";
2
+ export declare const GlissNode: ASTFunctionClass;
@@ -0,0 +1,180 @@
1
+ import { ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
2
+ import { pathBounds } from "../../layout/path.js";
3
+ import { ASTFunctionNode, } from "../ASTtypes.js";
4
+ import { isVisualTemporalNode } from "../temporal.js";
5
+ // gliss 判断音高的准则是 resolvedMidi 属性
6
+ function pitchOf(node) {
7
+ const { resolvedMidi } = node;
8
+ return typeof resolvedMidi === "number" ? resolvedMidi : undefined;
9
+ }
10
+ class GlissFunction extends ASTFunctionNode {
11
+ static def = {
12
+ name: ["gliss"],
13
+ description: "滑音连线",
14
+ details: `\
15
+ ~~~jpfun
16
+ 1 -@a 5@b @gliss(a, b)
17
+ ~~~
18
+ 若附属对象无音高,将使用前面最近的的同轨有音高对象的音高`,
19
+ allowExtraArgs: false,
20
+ args: [
21
+ {
22
+ type: "label",
23
+ default: null,
24
+ description: "一个端点的标签,先后按谱面时间确定"
25
+ },
26
+ {
27
+ type: "label",
28
+ default: null,
29
+ description: "另一个端点的标签"
30
+ },
31
+ ],
32
+ };
33
+ from;
34
+ to;
35
+ constructor(span, args, ctx, parent = null) {
36
+ super(span, parent);
37
+ [this.from, this.to] = this.getArgValue(args, ctx);
38
+ }
39
+ loweringEnter(ctx) {
40
+ const from = ctx.getTemporalNodes(this.from).at(-1);
41
+ const to = ctx.getTemporalNodes(this.to).at(-1);
42
+ if (!from || !to || !isVisualTemporalNode(from) || !isVisualTemporalNode(to)) {
43
+ throw new ErrorDiagnostic("E_GLISS_ENDPOINT", "@gliss 的标签必须指向已生成且具有排版盒子的对象", this.sourceSpan);
44
+ }
45
+ ctx.addAttachment(new GlissAttachment(from, to, this.sourceSpan, ctx.diagnostics));
46
+ return [];
47
+ }
48
+ toString(source) {
49
+ const from = this.from instanceof ASTFunctionNode ? this.from.label : undefined;
50
+ const to = this.to instanceof ASTFunctionNode ? this.to.label : undefined;
51
+ return from && to ? `@gliss(${from}, ${to})` : source.slice(this.sourceSpan.start, this.sourceSpan.end);
52
+ }
53
+ }
54
+ export const GlissNode = GlissFunction;
55
+ function layoutHost(node, line) {
56
+ while (node.foldedInto && isVisualTemporalNode(node.foldedInto) && (!line || line.columnOf(node) < 0)) {
57
+ node = node.foldedInto;
58
+ }
59
+ return node;
60
+ }
61
+ class GlissAttachment {
62
+ from;
63
+ to;
64
+ sourceSpan;
65
+ diagnostics;
66
+ layer = "foreground";
67
+ endPoints;
68
+ direction;
69
+ warned = false;
70
+ constructor(from, to, sourceSpan, diagnostics) {
71
+ this.from = from;
72
+ this.to = to;
73
+ this.sourceSpan = sourceSpan;
74
+ this.diagnostics = diagnostics;
75
+ this.endPoints = [from, to];
76
+ }
77
+ get orderedEndpoints() {
78
+ const [a, b] = this.endPoints;
79
+ const fromHost = layoutHost(a);
80
+ const toHost = layoutHost(b);
81
+ const { sourceSpan } = this;
82
+ if (fromHost.t.equals(toHost.t))
83
+ throw new ErrorDiagnostic("E_GLISS_ORDER", "@gliss 两个端点不能位于同一时刻", sourceSpan);
84
+ if (fromHost.layoutLine !== toHost.layoutLine)
85
+ throw new ErrorDiagnostic("E_GLISS_CROSS_LINE", "@gliss 不支持跨谱面行", sourceSpan);
86
+ return fromHost.t.compare(toHost.t) > 0 ? [b, a] : [a, b];
87
+ }
88
+ /** 定位端点所在时间列,按需解析音高,并为箭头登记水平留白 */
89
+ prepareHorizontal(lines) {
90
+ const [endpoint, target] = this.orderedEndpoints;
91
+ const { sourceSpan } = this;
92
+ const index = endpoint.layoutLine;
93
+ const line = lines[index];
94
+ const from = line && layoutHost(endpoint, line);
95
+ const to = line && layoutHost(target, line);
96
+ const start = from ? line.columnOf(from) : -1;
97
+ const end = to ? line.columnOf(to) : -1;
98
+ if (!line || start < 0 || end <= start) {
99
+ throw new ErrorDiagnostic("E_GLISS_DOMAIN", "@gliss 的端点必须位于同一排版域的不同时间列", sourceSpan);
100
+ }
101
+ const resolvePitch = (node, column) => {
102
+ if ("resolvedMidi" in node)
103
+ return pitchOf(node);
104
+ const track = layoutHost(node, line).track;
105
+ // 当前行找不到时继续查找前面的谱面行,不要求时值连续
106
+ for (let i = index; i >= 0; i--) {
107
+ const columns = lines[i].columns;
108
+ // 从端点前一列倒查同轨对象;首个带音高属性的对象即终止搜索,空值也不跳过
109
+ for (let j = i === index ? column - 1 : columns.length - 1; j >= 0; j--) {
110
+ const previous = columns[j].find(item => item.track === track && "resolvedMidi" in item);
111
+ if (previous)
112
+ return pitchOf(previous);
113
+ }
114
+ }
115
+ };
116
+ const sourcePitch = resolvePitch(endpoint, start);
117
+ const targetPitch = resolvePitch(target, end);
118
+ this.direction = sourcePitch === undefined || targetPitch === undefined
119
+ ? undefined : Math.sign(targetPitch - sourcePitch);
120
+ if (this.direction === undefined && !this.warned) {
121
+ this.diagnostics.push(new WarningDiagnostic("W_GLISS_NO_PITCH", "@gliss 端点没有可用音高", sourceSpan));
122
+ this.warned = true; // prepareHorizontal 不一定只执行一次 所以要防抖
123
+ }
124
+ const right = from.box.w - from.box.anchor + this.size * 1.4;
125
+ // 只扩张求解器占位,不改变端点图形、附点位置或下一轮的 box
126
+ line.registerHorizontalLayoutHook(from, to, ({ columns }) => {
127
+ // 留白作用于起点整列;取最大值,避免多条关系重复累加占位。
128
+ for (const element of columns[start])
129
+ element.WR = Math.max(element.WR, right);
130
+ });
131
+ }
132
+ get size() {
133
+ return Math.max(this.from.ast.size, this.to.ast.size);
134
+ }
135
+ createGeometry() {
136
+ // 子域附件可能直接进入几何测量,未经过 prepareHorizontal
137
+ const [from, to] = this.orderedEndpoints;
138
+ const size = this.size;
139
+ const gap = size * 0.12;
140
+ const start = { x: from.box.x + from.box.w + gap, y: from.box.y + from.box.visualAxis };
141
+ const end = { x: to.box.x - gap, y: to.box.y + to.box.visualAxis };
142
+ if (from.track === to.track) {
143
+ if (this.direction === undefined) {
144
+ end.y = start.y;
145
+ }
146
+ else {
147
+ start.y += this.direction * size * 0.24;
148
+ end.y -= this.direction * size * 0.24;
149
+ }
150
+ }
151
+ if (end.x <= start.x) {
152
+ throw new ErrorDiagnostic("E_GLISS_SPACE", "@gliss 的端点之间没有可用的水平绘制空间", this.sourceSpan);
153
+ }
154
+ const angle = Math.atan2(end.y - start.y, end.x - start.x);
155
+ const length = Math.min(size * 0.3, Math.hypot(end.x - start.x, end.y - start.y) * 0.35);
156
+ const wing = (offset) => ({
157
+ x: end.x - length * Math.cos(angle + offset),
158
+ y: end.y - length * Math.sin(angle + offset),
159
+ });
160
+ const commands = [
161
+ { op: "M", ...start }, { op: "L", ...end },
162
+ { op: "M", ...wing(-Math.PI / 6) }, { op: "L", ...end },
163
+ { op: "L", ...wing(Math.PI / 6) },
164
+ ];
165
+ const strokeWidth = size * 0.05;
166
+ const bounds = pathBounds(commands);
167
+ const region = {
168
+ x: bounds.x - strokeWidth / 2, y: bounds.y - strokeWidth / 2,
169
+ w: bounds.w + strokeWidth, h: bounds.h + strokeWidth,
170
+ };
171
+ return {
172
+ regions: [{ ...region, line: from.layoutLine, track: from.track }],
173
+ // 跨轨连线不把整段高度算到起点轨,否则纵向求解会反复撑开两轨
174
+ occupancy: from.track === to.track ? [{ ...region, line: from.layoutLine, track: from.track }] : [],
175
+ paint: (painter) => {
176
+ painter.drawPath(commands, { fill: "none", stroke: "#000", strokeWidth });
177
+ },
178
+ };
179
+ }
180
+ }
@@ -2,7 +2,7 @@ import { ErrorDiagnostic } from "../../diagnostic.js";
2
2
  import { getLayoutBounds, layoutLocalSequence } from "../../layout/engine.js";
3
3
  import { Fraction } from "../../fraction.js";
4
4
  import { Track } from "../../lowering/track.js";
5
- import { isVisualTemporalNode, TemporalNodeBase, } from "../temporal.js";
5
+ import { transferFunctionAddons, isVisualTemporalNode, TemporalNodeBase, } from "../temporal.js";
6
6
  import { ASTBraceNode, ASTFunctionNode, ASTLabelNode, ASTTextNode, } from "../ASTtypes.js";
7
7
  import { createBeamLayoutAttachment } from "../beam/layout.js";
8
8
  import { DIV_ADDON_KEY } from "../div/index.js";
@@ -237,7 +237,7 @@ class GraceFunction extends ASTFunctionNode {
237
237
  throw new ErrorDiagnostic("E_GRACE_INVALID_HOST", "@grace 的宿主必须恰好产生一个可见 Temporal", host.sourceSpan);
238
238
  }
239
239
  const events = columns.flat();
240
- if (!events.some(isVisualTemporalNode) || events.some(event => event.breakBefore > 0)) {
240
+ if (!events.some(isVisualTemporalNode) || events.some(event => (event.addon?.breakBefore ?? 0) > 0)) {
241
241
  throw new ErrorDiagnostic("E_GRACE_INVALID_CONTENT", "@grace 的倚音至少产生一个可见对象,且不能换行", grace.sourceSpan);
242
242
  }
243
243
  const composite = new GraceTemporal(this, hostNode, columns, root, attachments, this.side);
@@ -408,10 +408,7 @@ export class GraceTemporal extends TemporalNodeBase {
408
408
  prepareLayout(context) {
409
409
  // lowering 期间修饰挂在复合体上(augmenter 要看到整体节奏),渲染时交给宿主:
410
410
  // 减时线要落在宿主数字与下八度点之间,而不是压在整个倚音盒下面
411
- if (this.addon) {
412
- this.host.addon = this.addon;
413
- this.addon = void 0;
414
- }
411
+ transferFunctionAddons(this, this.host);
415
412
  const block = context.layoutSubdomain(this, this.graceColumns, this.root, this.attachments);
416
413
  const hostWidth = layoutLocalSequence([this.host], context);
417
414
  this.springConfig = { ...this.host.springConfig, ...this.springConfig };
@@ -53,30 +53,11 @@ function layoutHeadSlot({ columns, rows, start, end, X, fixed, options }, occupi
53
53
  else
54
54
  X[end] = X[start];
55
55
  }
56
- /** 行从上到下按 gap 排列;capture 让 Head 在同一遍测量里取得整组范围 */
57
- function measureRows(members, gap, capture) {
58
- const placements = [];
59
- let top;
60
- let cursor;
61
- for (const extent of members) {
62
- if (!extent) {
63
- placements.push(null);
64
- continue;
65
- }
66
- const offset = cursor === void 0 ? 0 : cursor + gap - extent.top;
67
- placements.push({ offset, extent });
68
- top ??= offset + extent.top;
69
- cursor = offset + extent.bottom;
70
- }
71
- capture?.(top === void 0 || cursor === void 0 ? null : { top, bottom: cursor });
72
- return placements;
73
- }
74
56
  class HeadBoundaryTemporal extends TemporalNodeBase {
75
57
  members = [];
76
58
  slots = [];
77
59
  titleBottom = 0;
78
- leftExtent = null;
79
- rightExtent = null;
60
+ sideExtents = { left: null, right: null };
80
61
  constructor(ast) {
81
62
  super();
82
63
  this.ast = ast;
@@ -99,31 +80,40 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
99
80
  if (this.slots.length > 0)
100
81
  this.alignHead();
101
82
  }
83
+ onTemporal(node) { this.members.push(node); }
102
84
  createTracks(slot) {
103
85
  const { name, owner } = slot;
104
86
  return {
105
87
  laneKey: `head/rows/${owner.sourceSpan.start}/${name}`,
106
88
  hostIndex: null,
107
89
  measure: members => {
108
- if (name === "center") {
109
- const placements = measureRows(members, owner.gap);
110
- const first = placements.find(placement => placement !== null);
111
- this.titleBottom = first ? first.offset + first.extent.bottom : 0;
112
- return placements;
113
- }
114
- return measureRows(members, owner.gap, extent => {
115
- if (name === "left")
116
- this.leftExtent = extent;
117
- else
118
- this.rightExtent = extent;
90
+ // 行从上到下排列,同一遍取得标题首行底边和侧栏整组范围
91
+ let top;
92
+ let bottom;
93
+ if (name === "center")
94
+ this.titleBottom = 0;
95
+ const placements = members.map(extent => {
96
+ if (!extent)
97
+ return null;
98
+ const offset = bottom === void 0 ? 0 : bottom + owner.gap - extent.top;
99
+ if (bottom === void 0 && name === "center")
100
+ this.titleBottom = extent.bottom;
101
+ top ??= offset + extent.top;
102
+ bottom = offset + extent.bottom;
103
+ return { offset, extent };
119
104
  });
105
+ if (name !== "center") {
106
+ this.sideExtents[name] = top === void 0 || bottom === void 0 ? null : { top, bottom };
107
+ }
108
+ return placements;
120
109
  },
121
110
  place: name === "center" ? undefined : () => {
122
- const extent = name === "left" ? this.leftExtent : this.rightExtent;
111
+ const extent = this.sideExtents[name];
123
112
  if (!extent)
124
113
  return this.titleBottom;
125
- const leftHeight = this.leftExtent ? this.leftExtent.bottom - this.leftExtent.top : 0;
126
- const rightHeight = this.rightExtent ? this.rightExtent.bottom - this.rightExtent.top : 0;
114
+ const { left, right } = this.sideExtents;
115
+ const leftHeight = left ? left.bottom - left.top : 0;
116
+ const rightHeight = right ? right.bottom - right.top : 0;
127
117
  // 两侧共享底边;以较高侧定总高度,使它的顶部恰好贴标题底边
128
118
  const targetBottom = this.titleBottom + Math.max(leftHeight, rightHeight);
129
119
  return targetBottom - extent.bottom;
@@ -162,8 +152,8 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
162
152
  cells.set(cell, [member]);
163
153
  }
164
154
  const [left, , right] = this.slots;
165
- this.packRows(left.ast, left.start.box.x, "left", cells);
166
- this.packRows(right.ast, right.end.box.x, "right", cells);
155
+ this.packRows(left.ast, left.start.box.x, cells);
156
+ this.packRows(right.ast, right.end.box.x, cells);
167
157
  }
168
158
  stretch(node, side) {
169
159
  const alpha = side === "L" ? "alpha_L" : "alpha_R";
@@ -172,9 +162,9 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
172
162
  node.springConfig[alpha] = node.springConfig[alpha] * HEAD_STRETCH;
173
163
  node.springConfig[beta] = node.springConfig[beta] * 3 / HEAD_STRETCH;
174
164
  }
175
- packRows(slot, target, side, cells) {
165
+ packRows(slot, target, cells) {
176
166
  const gap = this.ast.owner.size * ITEM_GAP_EM;
177
- const fromLeft = side === "left";
167
+ const fromLeft = slot.name === "left";
178
168
  const direction = fromLeft ? 1 : -1;
179
169
  for (const row of slot.rows) {
180
170
  const rowCells = row instanceof ASTBraceNode ? row.content : [row];
@@ -242,8 +232,12 @@ class HeadSlotNode extends ASTNodeBase {
242
232
  tracks: head.createTracks(this),
243
233
  };
244
234
  }
245
- loweringEnter() {
246
- return [new HeadBoundaryTemporal(this)];
235
+ loweringEnter(ctx) {
236
+ const boundary = new HeadBoundaryTemporal(this);
237
+ // 首边界收集真实全局事件,供末边界校验和放置后的对齐
238
+ if (this.name === "left")
239
+ ctx.beginLoweringGroup(this.owner, boundary);
240
+ return [boundary];
247
241
  }
248
242
  loweringExit() {
249
243
  return [new HeadBoundaryTemporal(this)];
@@ -403,7 +397,8 @@ H.tempo: 94
403
397
  ? previous
404
398
  : new HeadFunction(sugar.span, new Map(), ctx, null);
405
399
  head.createdBySugar = true;
406
- head.addSugarRow(FIELD_SLOT[field], HeadFunction.parseSugarRow(ctx, field, span, text, parsed));
400
+ head.slots.find(slot => slot.name === FIELD_SLOT[field])
401
+ .addRow(HeadFunction.parseSugarRow(ctx, field, span, text, parsed));
407
402
  head.sourceSpan.end = span.end;
408
403
  if (head !== previous)
409
404
  ctx.pushNode(head);
@@ -461,19 +456,8 @@ H.tempo: 94
461
456
  new HeadSlotNode(span, this, "right", rows("right", 2)),
462
457
  ];
463
458
  }
464
- loweringEnter(ctx) {
465
- // 收集真实全局事件,供末边界校验时值和放置后的横向对齐
466
- const group = {
467
- members: [],
468
- onTemporal(node) { this.members.push(node); },
469
- };
470
- ctx.beginLoweringGroup(this, group);
471
- return [];
472
- }
473
459
  loweringExit(ctx) {
474
- const { members } = ctx.endLoweringGroup(this);
475
- const head = ctx.getTemporalNodes(this.slots[0])[0];
476
- head.members = members;
460
+ const head = ctx.endLoweringGroup(this);
477
461
  head.slots = this.slots.map(ast => {
478
462
  const [start, end] = ctx.getTemporalNodes(ast);
479
463
  return { ast, start, end };
@@ -481,16 +465,13 @@ H.tempo: 94
481
465
  // right.end 是整个 Head 的末边界,按三槽的 sequence 排在所有内容之后
482
466
  // 此时 rest 等延迟时值已固化,只检查当前 Head 的成员,无须再扫描全谱索引
483
467
  head.slots[2].end.onTimeState = () => head.validateDuration();
484
- for (const node of members) {
485
- if (node.breakBefore > 0) {
486
- throw new ErrorDiagnostic("E_HEAD_INTERNAL_BREAK", "@head 的内部不能使用 @br;第一层内容已经表示视觉行", node.ast.sourceSpan);
468
+ for (const node of head.members) {
469
+ if ((node.addon?.breakBefore ?? 0) > 0) {
470
+ throw new ErrorDiagnostic("E_HEAD_INTERNAL_BREAK", "@head 的内部不能换行或换页;第一层内容已经表示视觉行", node.ast.sourceSpan);
487
471
  }
488
472
  }
489
473
  return [];
490
474
  }
491
- addSugarRow(name, row) {
492
- this.slots.find(slot => slot.name === name).addRow(row);
493
- }
494
475
  toString(source) {
495
476
  const slots = this.slots
496
477
  .filter(slot => slot.rows.length > 0)
@@ -4,6 +4,17 @@ import { ANCHOR_KEY, TemporalNodeBase } from "../temporal.js";
4
4
  import { paintSymbol } from "../symbol/shape.js";
5
5
  import { sanbanBounds, sanbanShapes } from "./shape.js";
6
6
  import { ASTFunctionNode, } from "../ASTtypes.js";
7
+ // 同一执行位置只关闭一次旧小节,保留最终拍号和最后源码边界。
8
+ const changesByPosition = new WeakMap();
9
+ function recordMeasureChange(state, node, meter) {
10
+ const position = state.currentEvent ?? node;
11
+ const span = node.ast.sourceSpan;
12
+ let change = changesByPosition.get(position);
13
+ if (!change)
14
+ changesByPosition.set(position, change = { start: span.start, end: span.end, meter });
15
+ change.end = span.end;
16
+ change.meter = meter;
17
+ }
7
18
  class MeterFunction extends ASTFunctionNode {
8
19
  static def = {
9
20
  name: ["meter"],
@@ -91,27 +102,16 @@ class MeterFunction extends ASTFunctionNode {
91
102
  }
92
103
  measureStart.copyFrom(end);
93
104
  };
94
- const metersByHost = new Map();
95
- for (const nodes of result.astToTemporal.values()) {
96
- for (const node of nodes) {
97
- if (!(node instanceof MeterTemporal))
98
- continue;
99
- let host = node;
100
- while (host.foldedInto)
101
- host = host.foldedInto;
102
- if (!metersByHost.has(host))
103
- metersByHost.set(host, node);
104
- }
105
- }
106
105
  for (const column of result.columns) {
107
106
  const time = column[0].t;
108
- const host = column.find(node => metersByHost.has(node));
109
- const meter = host && metersByHost.get(host);
110
- if (meter) {
111
- closeMeasure(time, meter.ast.sourceSpan.start);
112
- active = meter.ast;
107
+ for (const node of column) {
108
+ const change = changesByPosition.get(node);
109
+ if (!change)
110
+ continue;
111
+ closeMeasure(time, change.start);
112
+ active = change.meter;
113
113
  measureStart.copyFrom(time);
114
- sourceStart = meter.ast.sourceSpan.end;
114
+ sourceStart = change.end;
115
115
  }
116
116
  const anchor = column.find(node => node.mergeKey === ANCHOR_KEY);
117
117
  if (anchor) {
@@ -149,6 +149,7 @@ class MeterTemporal extends TemporalNodeBase {
149
149
  }
150
150
  onTimeState(state) {
151
151
  state.meter = this.ast.measureDuration;
152
+ recordMeasureChange(state, this, this.ast);
152
153
  }
153
154
  emitPlayback(emitter) {
154
155
  if (!this.ast.measureDuration)