jpfun 0.2.0 → 0.3.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 (112) hide show
  1. package/README.md +69 -11
  2. package/dist/diagnostic.js +5 -2
  3. package/dist/fraction.d.ts +24 -0
  4. package/dist/fraction.js +132 -0
  5. package/dist/functions/ASTtypes.d.ts +24 -7
  6. package/dist/functions/ASTtypes.js +35 -16
  7. package/dist/functions/adjust/index.d.ts +2 -0
  8. package/dist/functions/adjust/index.js +193 -0
  9. package/dist/functions/bar/index.d.ts +8 -0
  10. package/dist/functions/bar/index.js +39 -10
  11. package/dist/functions/beam/auto.js +32 -15
  12. package/dist/functions/beam/index.js +10 -6
  13. package/dist/functions/beam/layout.d.ts +3 -2
  14. package/dist/functions/beam/layout.js +42 -64
  15. package/dist/functions/box/index.js +35 -34
  16. package/dist/functions/br/index.js +9 -7
  17. package/dist/functions/dash/index.js +33 -1
  18. package/dist/functions/default.js +14 -7
  19. package/dist/functions/div/index.d.ts +16 -0
  20. package/dist/functions/div/index.js +45 -17
  21. package/dist/functions/dot/index.js +11 -3
  22. package/dist/functions/grace/index.d.ts +8 -11
  23. package/dist/functions/grace/index.js +82 -76
  24. package/dist/functions/head/index.d.ts +2 -0
  25. package/dist/functions/head/index.js +492 -0
  26. package/dist/functions/key/index.js +97 -3
  27. package/dist/functions/meter/index.d.ts +2 -0
  28. package/dist/functions/meter/index.js +154 -0
  29. package/dist/functions/note/accidentals.d.ts +24 -3
  30. package/dist/functions/note/accidentals.js +31 -1
  31. package/dist/functions/note/index.js +45 -65
  32. package/dist/functions/page/index.d.ts +9 -2
  33. package/dist/functions/page/index.js +50 -4
  34. package/dist/functions/set/index.js +37 -29
  35. package/dist/functions/stack/index.js +26 -22
  36. package/dist/functions/symbol/index.d.ts +21 -0
  37. package/dist/functions/symbol/index.js +94 -0
  38. package/dist/functions/symbol/ornament.d.ts +15 -0
  39. package/dist/functions/symbol/ornament.js +73 -0
  40. package/dist/functions/symbol/shape.d.ts +22 -0
  41. package/dist/functions/symbol/shape.js +48 -0
  42. package/dist/functions/symbol/symbols/accent.d.ts +2 -0
  43. package/dist/functions/symbol/symbols/accent.js +24 -0
  44. package/dist/functions/symbol/symbols/f.d.ts +2 -0
  45. package/dist/functions/symbol/symbols/f.js +55 -0
  46. package/dist/functions/symbol/symbols/fermata.d.ts +2 -0
  47. package/dist/functions/symbol/symbols/fermata.js +24 -0
  48. package/dist/functions/symbol/symbols/mordent.d.ts +2 -0
  49. package/dist/functions/symbol/symbols/mordent.js +43 -0
  50. package/dist/functions/symbol/symbols/p.d.ts +2 -0
  51. package/dist/functions/symbol/symbols/p.js +61 -0
  52. package/dist/functions/symbol/symbols/tr.d.ts +2 -0
  53. package/dist/functions/symbol/symbols/tr.js +75 -0
  54. package/dist/functions/tempo/glyph.d.ts +12 -0
  55. package/dist/functions/tempo/glyph.js +30 -0
  56. package/dist/functions/tempo/index.js +53 -2
  57. package/dist/functions/text/index.js +76 -24
  58. package/dist/functions/tie/index.js +102 -127
  59. package/dist/functions/tuplet/index.d.ts +2 -0
  60. package/dist/functions/tuplet/index.js +211 -0
  61. package/dist/functions/up/index.d.ts +1 -0
  62. package/dist/functions/up/index.js +245 -171
  63. package/dist/functions/voice/index.js +86 -68
  64. package/dist/functions/volta/index.d.ts +2 -0
  65. package/dist/functions/volta/index.js +227 -0
  66. package/dist/index.d.ts +4 -0
  67. package/dist/index.js +4 -0
  68. package/dist/jpfun.min.js +143 -0
  69. package/dist/layout/engine.d.ts +4 -11
  70. package/dist/layout/engine.js +65 -59
  71. package/dist/layout/model.d.ts +8 -1
  72. package/dist/layout/model.js +16 -6
  73. package/dist/layout/path.d.ts +19 -0
  74. package/dist/layout/path.js +101 -0
  75. package/dist/layout/types.d.ts +51 -18
  76. package/dist/layout/types.js +3 -1
  77. package/dist/lowering/loweringContext.d.ts +18 -20
  78. package/dist/lowering/loweringContext.js +132 -94
  79. package/dist/lowering/track.d.ts +1 -1
  80. package/dist/lowering/track.js +1 -1
  81. package/dist/lowering/types.d.ts +49 -12
  82. package/dist/lowering/types.js +9 -3
  83. package/dist/parser/parse-utils/call-utils.d.ts +0 -2
  84. package/dist/parser/parse-utils/call-utils.js +0 -6
  85. package/dist/parser/parse-utils/note-utils.d.ts +8 -0
  86. package/dist/parser/parse-utils/note-utils.js +35 -13
  87. package/dist/parser/parse-utils/string-utils.d.ts +8 -0
  88. package/dist/parser/parse-utils/string-utils.js +20 -0
  89. package/dist/parser/parserContext.d.ts +8 -5
  90. package/dist/parser/parserContext.js +38 -33
  91. package/dist/parser/preprocess.js +17 -11
  92. package/dist/playback/compile.d.ts +18 -0
  93. package/dist/playback/compile.js +401 -0
  94. package/dist/playback/event.d.ts +91 -0
  95. package/dist/playback/event.js +87 -0
  96. package/dist/playback/time.d.ts +14 -0
  97. package/dist/playback/time.js +81 -0
  98. package/dist/playback/types.d.ts +128 -0
  99. package/dist/playback/types.js +3 -0
  100. package/dist/render/canvas.d.ts +4 -4
  101. package/dist/render/canvas.js +20 -5
  102. package/dist/render/index.d.ts +1 -0
  103. package/dist/render/index.js +1 -0
  104. package/dist/render/paint.d.ts +8 -0
  105. package/dist/render/paint.js +101 -0
  106. package/dist/render/svg.d.ts +3 -3
  107. package/dist/render/svg.js +10 -8
  108. package/dist/render/text.d.ts +17 -0
  109. package/dist/render/text.js +35 -0
  110. package/dist/render/types.d.ts +1 -1
  111. package/grammar.md +93 -10
  112. package/package.json +10 -6
@@ -0,0 +1,193 @@
1
+ import { ASTFunctionNode } from "../ASTtypes.js";
2
+ import { WarningDiagnostic } from "../../diagnostic.js";
3
+ import { isVisualTemporalNode } from "../../lowering/types.js";
4
+ import { isLayoutAttachment, } from "../../layout/types.js";
5
+ class AdjustFunction extends ASTFunctionNode {
6
+ static def = {
7
+ name: ["adjust", "adj"],
8
+ description: "微调目标的位置与占位",
9
+ example: `@adjust(content, dx=0px, dy=0px, dw=0px, dh=0px)
10
+ dw/dh 在排版前增减占位,最终尺寸不小于 0;dw 按原左右占位比例分配,dh 调整下方;
11
+ dx/dy 在排版完成后平移目标,邻居不会让开,因此可以故意重叠。
12
+ 括住的若是关系对象(连音线等)且其中没有对象,平移的就是这条关系对象`,
13
+ allowExtraArgs: false,
14
+ args: [
15
+ {
16
+ type: "content",
17
+ default: null,
18
+ },
19
+ {
20
+ name: "dx",
21
+ type: "length",
22
+ default: { value: 0, unit: "px" },
23
+ },
24
+ {
25
+ name: "dy",
26
+ type: "length",
27
+ default: { value: 0, unit: "px" },
28
+ },
29
+ {
30
+ name: "dw",
31
+ type: "length",
32
+ default: { value: 0, unit: "px" },
33
+ },
34
+ {
35
+ name: "dh",
36
+ type: "length",
37
+ default: { value: 0, unit: "px" },
38
+ },
39
+ ],
40
+ };
41
+ target;
42
+ dx;
43
+ dy;
44
+ dw;
45
+ dh;
46
+ get children() { return [this.target]; }
47
+ timeFlowModel() {
48
+ return {
49
+ children: [this.target],
50
+ mode: "sequence",
51
+ };
52
+ }
53
+ /** 微调不创建时间事件,只收集作用域内的对象与关系对象 */
54
+ loweringEnter(ctx) {
55
+ const targets = { temporal: 0, attachment: 0 };
56
+ const group = {
57
+ targets,
58
+ onTemporal: node => {
59
+ if (!isVisualTemporalNode(node))
60
+ return;
61
+ targets.temporal++;
62
+ offsetTemporal(node, this);
63
+ },
64
+ onAttachment: attachment => {
65
+ if (!isLayoutAttachment(attachment))
66
+ return;
67
+ targets.attachment++;
68
+ offsetAttachment(attachment, targets, this.dx, this.dy);
69
+ },
70
+ };
71
+ ctx.beginLoweringGroup(this, group);
72
+ return [];
73
+ }
74
+ loweringExit(ctx) {
75
+ const group = ctx.endLoweringGroup(this);
76
+ if (group.targets.temporal === 0 && group.targets.attachment === 0) {
77
+ ctx.diagnostics.push(new WarningDiagnostic("W_ADJUST_NO_TARGET", "@adjust 没有找到可调整的对象", this.sourceSpan));
78
+ }
79
+ return [];
80
+ }
81
+ constructor(sourceSpan, args, ctx, parent = null) {
82
+ super(sourceSpan, parent);
83
+ const [tgt, dx, dy, dw, dh] = this.getArgValue(args, ctx);
84
+ tgt.parent = this;
85
+ this.target = tgt;
86
+ this.dx = ctx.length2px(dx);
87
+ this.dy = ctx.length2px(dy);
88
+ this.dw = ctx.length2px(dw);
89
+ this.dh = ctx.length2px(dh);
90
+ }
91
+ }
92
+ export const AdjustNode = AdjustFunction;
93
+ /** 在原对象上组合布局生命周期,保持布局索引依赖的对象身份 */
94
+ function offsetTemporal(node, owner) {
95
+ const { dx, dy, dw, dh } = owner;
96
+ if (dx === 0 && dy === 0 && dw === 0 && dh === 0)
97
+ return;
98
+ let placedX;
99
+ let placedY;
100
+ const finalize = node.finalizeLayout;
101
+ const onPlaced = node.onPlaced;
102
+ node.finalizeLayout = (context) => {
103
+ finalize?.call(node, context);
104
+ const width = Math.max(0, node.box.w + dw);
105
+ node.box.anchor = node.box.w > 0 ? node.box.anchor * width / node.box.w : 0;
106
+ node.box.w = width;
107
+ node.box.h = Math.max(0, node.box.h + dh);
108
+ };
109
+ node.onPlaced = () => {
110
+ if (node.box.x !== placedX)
111
+ node.box.x += dx;
112
+ if (node.box.y !== placedY)
113
+ node.box.y += dy;
114
+ onPlaced?.call(node);
115
+ placedX = node.box.x;
116
+ placedY = node.box.y;
117
+ };
118
+ }
119
+ /**
120
+ * 平移一条关系对象
121
+ *
122
+ * 在原 Attachment 上组合 createGeometry,保留依赖查找与 instanceof 所需的对象身份
123
+ * 作用域里只要有对象被平移过,关系对象就已经跟着端点走了,这里不能再平移第二次
124
+ */
125
+ function offsetAttachment(attachment, targets, dx, dy) {
126
+ if (dx === 0 && dy === 0)
127
+ return;
128
+ const createGeometry = attachment.createGeometry;
129
+ attachment.createGeometry = (context) => {
130
+ const geometry = createGeometry.call(attachment, context);
131
+ if (targets.temporal > 0)
132
+ return geometry;
133
+ const shift = (region) => region.line === void 0
134
+ ? { x: region.x + dx, y: region.y + dy, w: region.w, h: region.h }
135
+ : { x: region.x + dx, y: region.y + dy, w: region.w, h: region.h, line: region.line, track: region.track };
136
+ return {
137
+ regions: geometry.regions.map(shift),
138
+ occupancy: geometry.occupancy?.map(shift),
139
+ paint(painter) {
140
+ // attachment 的绘制大多用闭包存储了,所以只能代理 painter
141
+ geometry.paint(new TranslatingPainter(painter, dx, dy));
142
+ },
143
+ };
144
+ };
145
+ }
146
+ /** Painter 没有变换栈,被微调的关系对象只能逐条命令平移 */
147
+ class TranslatingPainter {
148
+ target;
149
+ dx;
150
+ dy;
151
+ constructor(target, dx, dy) {
152
+ this.target = target;
153
+ this.dx = dx;
154
+ this.dy = dy;
155
+ }
156
+ drawText(text, x, y, style) {
157
+ this.target.drawText(text, x + this.dx, y + this.dy, style);
158
+ }
159
+ drawLine(x1, y1, x2, y2, style) {
160
+ this.target.drawLine(x1 + this.dx, y1 + this.dy, x2 + this.dx, y2 + this.dy, style);
161
+ }
162
+ drawRect(x, y, w, h, style) {
163
+ this.target.drawRect(x + this.dx, y + this.dy, w, h, style);
164
+ }
165
+ drawCircle(cx, cy, r, style) {
166
+ this.target.drawCircle(cx + this.dx, cy + this.dy, r, style);
167
+ }
168
+ drawPath(commands, style, transform) {
169
+ if (transform) {
170
+ const moved = { ...transform, x: transform.x + this.dx, y: transform.y + this.dy };
171
+ this.target.drawPath(commands, style, moved);
172
+ return;
173
+ }
174
+ this.target.drawPath(commands.map(command => this.translateCommand(command)), style);
175
+ }
176
+ translateCommand(command) {
177
+ switch (command.op) {
178
+ case "Z": return command;
179
+ case "Q": return {
180
+ op: "Q",
181
+ cx: command.cx + this.dx, cy: command.cy + this.dy,
182
+ x: command.x + this.dx, y: command.y + this.dy,
183
+ };
184
+ case "C": return {
185
+ op: "C",
186
+ cx1: command.cx1 + this.dx, cy1: command.cy1 + this.dy,
187
+ cx2: command.cx2 + this.dx, cy2: command.cy2 + this.dy,
188
+ x: command.x + this.dx, y: command.y + this.dy,
189
+ };
190
+ default: return { op: command.op, x: command.x + this.dx, y: command.y + this.dy };
191
+ }
192
+ }
193
+ }
@@ -1,2 +1,10 @@
1
1
  import { ASTFunctionClass } from "../ASTtypes.js";
2
+ import type { PlaybackCursor } from "../../playback/types.js";
2
3
  export declare const BarNode: ASTFunctionClass;
4
+ /**
5
+ * 某一列此刻处在所属反复段的第几遍
6
+ *
7
+ * 遍数是回跳的直接后果,所以和跳转规则一样归小节线所有;房子只消费这个数。
8
+ * 没有 `|:` 时整首曲子就是一段。
9
+ */
10
+ export declare function repeatPass(cursor: PlaybackCursor, column: number): number;
@@ -23,7 +23,7 @@ class BarFunction extends ASTFunctionNode {
23
23
  name: "length",
24
24
  type: "length",
25
25
  default: {
26
- value: 1,
26
+ value: 1.25,
27
27
  unit: "em",
28
28
  },
29
29
  },
@@ -61,20 +61,18 @@ class BarFunction extends ASTFunctionNode {
61
61
  }
62
62
  ;
63
63
  type;
64
- barLength; // 固化值
65
64
  size;
66
65
  constructor(sourceSpan, args, ctx, parent = null) {
67
66
  super(sourceSpan, parent);
68
- const [type, barlen] = this.getArgValue(args, ctx);
67
+ const [type, size] = this.getArgValue(args, ctx);
69
68
  this.type = type;
70
- this.barLength = ctx.length2px(barlen);
71
- this.size = ctx.fontSize;
69
+ this.size = ctx.length2px(size);
72
70
  }
73
71
  loweringEnter() {
74
- return [new BarTemporalNode(this)];
72
+ return [this.type >= 2 ? new RepeatBarTemporalNode(this) : new BarTemporalNode(this)];
75
73
  }
76
74
  toString() {
77
- return `@bar(${this.type}, ${this.barLength}px)`;
75
+ return `@bar(${this.type}, ${this.size}px)`;
78
76
  }
79
77
  }
80
78
  export const BarNode = BarFunction;
@@ -84,7 +82,6 @@ class BarTemporalNode extends TemporalNodeBase {
84
82
  constructor(ast) {
85
83
  super();
86
84
  this.ast = ast;
87
- this.T = 0;
88
85
  this.mergeKey = ANCHOR_KEY;
89
86
  this.initLayoutBox();
90
87
  // 由于有最小时长,因此设置alpha依然有效
@@ -124,10 +121,10 @@ class BarTemporalNode extends TemporalNodeBase {
124
121
  });
125
122
  }
126
123
  prepareLayout() {
127
- const { type, barLength, size } = this.ast;
124
+ const { type, size } = this.ast;
128
125
  this.lines.length = 0;
129
126
  this.repeatDots.length = 0;
130
- const h = Math.max(barLength, size * 0.6);
127
+ const h = size;
131
128
  const thin = Math.max(1, size * 0.065);
132
129
  const thick = thin * 2.6;
133
130
  const gap = thin * 1.8;
@@ -178,3 +175,35 @@ class BarTemporalNode extends TemporalNodeBase {
178
175
  }
179
176
  }
180
177
  }
178
+ /** 反复段起点标记:`:|` 靠它找回跳目标,遍数也按它计数 */
179
+ const REPEAT_START = "repeat.start";
180
+ /**
181
+ * 某一列此刻处在所属反复段的第几遍
182
+ *
183
+ * 遍数是回跳的直接后果,所以和跳转规则一样归小节线所有;房子只消费这个数。
184
+ * 没有 `|:` 时整首曲子就是一段。
185
+ */
186
+ export function repeatPass(cursor, column) {
187
+ return cursor.visits(cursor.seek(REPEAT_START, column + 1, -1) ?? 0);
188
+ }
189
+ /** 只有反复线参与播放顺序;普通小节线太多,进控制流扫描是纯开销 */
190
+ class RepeatBarTemporalNode extends BarTemporalNode {
191
+ /** 只在 type>=2 时创建,所以剩下的三种是:2 段首、3 段尾、4 两者都是 */
192
+ playbackMarks() {
193
+ return this.ast.type === 3 ? [] : [REPEAT_START];
194
+ }
195
+ /** 每条反复线只回跳一次,所以连写几条就是几遍 */
196
+ playbackFlow(columnOf) {
197
+ if (this.ast.type === 2)
198
+ return;
199
+ const at = columnOf(this);
200
+ if (at === undefined)
201
+ return;
202
+ return {
203
+ range: [at, at],
204
+ run: cursor => cursor.visits(at) > 1
205
+ ? undefined
206
+ : { kind: "jump", column: cursor.seek(REPEAT_START, at, -1) ?? 0 },
207
+ };
208
+ }
209
+ }
@@ -1,8 +1,7 @@
1
1
  import { ANCHOR_KEY, isVisualTemporalNode, } from "../../lowering/types.js";
2
+ import { Fraction } from "../../fraction.js";
2
3
  import { DIV_ADDON_KEY, DivNode, } from "../div/index.js";
3
4
  import { collectExplicitBeamEndpoints, createBeamLayoutAttachment, } from "./layout.js";
4
- const QUARTER_NOTE_DURATION = 1;
5
- const TIME_EPSILON = 1e-6;
6
5
  /** 只返回实际参与当前事件 div addon 的 div,先沿祖先链找,不够再按书写顺序向下补 */
7
6
  function findActiveDivs(node) {
8
7
  const result = [];
@@ -72,6 +71,22 @@ function outermostScopes(scopes) {
72
71
  return true;
73
72
  });
74
73
  }
74
+ function sourceSpanForAutoBeam(nodes) {
75
+ let start = Infinity;
76
+ let end = -Infinity;
77
+ for (const node of nodes) {
78
+ start = Math.min(start, node.ast.sourceSpan.start);
79
+ 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);
83
+ }
84
+ }
85
+ return { start, end };
86
+ }
87
+ function createAutoBeam(nodes) {
88
+ return createBeamLayoutAttachment(nodes, false, sourceSpanForAutoBeam(nodes));
89
+ }
75
90
  /** 同一个 div 内部始终按轨道连接,手工 beam 端点会截断自动片段 */
76
91
  function createScopeBeams(scopes, explicitEndpoints) {
77
92
  const attachments = [];
@@ -88,7 +103,7 @@ function createScopeBeams(scopes, explicitEndpoints) {
88
103
  let segment = [];
89
104
  const flush = () => {
90
105
  if (segment.length >= 2)
91
- attachments.push(createBeamLayoutAttachment(segment));
106
+ attachments.push(createAutoBeam(segment));
92
107
  segment = [];
93
108
  };
94
109
  for (const node of nodes) {
@@ -104,7 +119,7 @@ function createScopeBeams(scopes, explicitEndpoints) {
104
119
  return attachments;
105
120
  }
106
121
  function beatAt(time) {
107
- return Math.floor((time + TIME_EPSILON) / QUARTER_NOTE_DURATION);
122
+ return Math.floor(time.numerator / time.denominator);
108
123
  }
109
124
  /**
110
125
  * 多个独立 div 的默认连接规则
@@ -117,11 +132,12 @@ function createAdjacentBeams(result, nodeScopes, explicitEndpoints) {
117
132
  const attachments = [];
118
133
  const groups = new Map();
119
134
  const lineStarts = new Map();
120
- let measureStart = 0;
135
+ const measureStart = new Fraction();
136
+ const beatTime = new Fraction();
121
137
  for (const column of result.columns) {
122
138
  for (const node of column) {
123
139
  const current = lineStarts.get(node.layoutLine);
124
- if (current === undefined || node.t < current)
140
+ if (current === undefined || node.t.compare(current) < 0)
125
141
  lineStarts.set(node.layoutLine, node.t);
126
142
  }
127
143
  }
@@ -131,7 +147,7 @@ function createAdjacentBeams(result, nodeScopes, explicitEndpoints) {
131
147
  return;
132
148
  groups.delete(track);
133
149
  if (group.nodes.length >= 2)
134
- attachments.push(createBeamLayoutAttachment(group.nodes));
150
+ attachments.push(createAutoBeam(group.nodes));
135
151
  };
136
152
  const flushAll = () => {
137
153
  for (const track of [...groups.keys()])
@@ -141,7 +157,7 @@ function createAdjacentBeams(result, nodeScopes, explicitEndpoints) {
141
157
  const anchor = column.find(node => node.mergeKey === ANCHOR_KEY);
142
158
  if (anchor) {
143
159
  flushAll();
144
- measureStart = anchor.t;
160
+ measureStart.copyFrom(anchor.t);
145
161
  }
146
162
  for (const node of column) {
147
163
  if (node.mergeKey === ANCHOR_KEY)
@@ -152,40 +168,41 @@ function createAdjacentBeams(result, nodeScopes, explicitEndpoints) {
152
168
  const isCandidate = isVisualTemporalNode(node)
153
169
  && isIndependentDiv
154
170
  && autoBeamEnabled
155
- && node.T < QUARTER_NOTE_DURATION - TIME_EPSILON
171
+ && node.T.compare(1) < 0
156
172
  && !explicitEndpoints.has(node);
157
173
  if (!isCandidate) {
158
174
  // 同轨可见元素必须打断相邻关系,即使它本身是零时长文本
159
175
  // 不可见的 set/key/tempo 等零时长状态不会打断
160
- if (isVisualTemporalNode(node) || node.T > TIME_EPSILON)
176
+ if (isVisualTemporalNode(node) || !node.T.isZero())
161
177
  flush(node.track);
162
178
  continue;
163
179
  }
164
180
  const lineStart = lineStarts.get(node.layoutLine) ?? node.t;
165
- const beat = beatAt(node.t - Math.max(measureStart, lineStart));
181
+ const activeStart = measureStart.compare(lineStart) >= 0 ? measureStart : lineStart;
182
+ const beat = beatAt(beatTime.copyFrom(node.t).sub(activeStart));
166
183
  const current = groups.get(node.track);
167
184
  if (!current) {
168
185
  groups.set(node.track, {
169
186
  nodes: [node],
170
187
  line: node.layoutLine,
171
188
  beat,
172
- endTime: node.t + node.T,
189
+ endTime: node.t.clone().add(node.T),
173
190
  });
174
191
  continue;
175
192
  }
176
- const isContinuous = Math.abs(node.t - current.endTime) < TIME_EPSILON;
193
+ const isContinuous = node.t.equals(current.endTime);
177
194
  if (node.layoutLine !== current.line || beat !== current.beat || !isContinuous) {
178
195
  flush(node.track);
179
196
  groups.set(node.track, {
180
197
  nodes: [node],
181
198
  line: node.layoutLine,
182
199
  beat,
183
- endTime: node.t + node.T,
200
+ endTime: node.t.clone().add(node.T),
184
201
  });
185
202
  continue;
186
203
  }
187
204
  current.nodes.push(node);
188
- current.endTime = node.t + node.T;
205
+ current.endTime.copyFrom(node.t).add(node.T);
189
206
  }
190
207
  }
191
208
  flushAll();
@@ -1,5 +1,5 @@
1
1
  import { ASTFunctionNode } from "../ASTtypes.js";
2
- import { ErrorDiagnostic } from "../../diagnostic.js";
2
+ import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
3
3
  import { createAutomaticBeamAttachments } from "./auto.js";
4
4
  import { createBeamLayoutAttachment, validateExplicitBeamAttachments, } from "./layout.js";
5
5
  class BeamFunction extends ASTFunctionNode {
@@ -19,7 +19,7 @@ class BeamFunction extends ASTFunctionNode {
19
19
  for (const [, value] of args) {
20
20
  const parsed = value instanceof ASTFunctionNode
21
21
  ? value
22
- : ctx.parseArgWithType(value.start, value.end, "label", sourceSpan.start);
22
+ : ctx.parseArgWithType(value.valueSpan, "label", sourceSpan.start);
23
23
  if (parsed instanceof ASTFunctionNode)
24
24
  this.endPoints.push(parsed);
25
25
  }
@@ -27,7 +27,7 @@ class BeamFunction extends ASTFunctionNode {
27
27
  let k = ctx.labelableNodes.length - 1;
28
28
  while (this.endPoints.length < 2 && k >= 0) {
29
29
  const candidate = ctx.labelableNodes[k--];
30
- if (this.endPoints.includes(candidate))
30
+ if (!candidate || this.endPoints.includes(candidate))
31
31
  continue;
32
32
  this.endPoints.unshift(candidate);
33
33
  }
@@ -40,14 +40,18 @@ class BeamFunction extends ASTFunctionNode {
40
40
  const endPoints = [];
41
41
  for (const ast of this.endPoints) {
42
42
  // 暂时只用最后一个;理应有且仅有一个
43
- const temporal = ctx.getTemporalNodes(ast).at(-1);
43
+ let temporal = ctx.getTemporalNodes(ast).at(-1);
44
+ while (temporal?.foldedInto)
45
+ temporal = temporal.foldedInto;
44
46
  if (!temporal)
45
47
  continue;
46
48
  endPoints.push(temporal);
47
49
  }
48
- if (endPoints.length < 2)
50
+ if (endPoints.length < 2) {
51
+ ctx.diagnostics.push(Diagnostic.warning.UnresolvedEndpoint("beam", this.sourceSpan));
49
52
  return [];
50
- ctx.addLayoutAttachment(createBeamLayoutAttachment(endPoints, true, this.sourceSpan));
53
+ }
54
+ ctx.addAttachment(createBeamLayoutAttachment(endPoints, true, this.sourceSpan));
51
55
  return [];
52
56
  }
53
57
  }
@@ -1,9 +1,10 @@
1
1
  import { type LoweringResult, type TemporalNodeBase } from "../../lowering/types.js";
2
2
  import type { SourceSpan } from "../../parser/types.js";
3
3
  import type { LayoutAttachment } from "../../layout/types.js";
4
+ import type { LoweringAttachment } from "../../lowering/types.js";
4
5
  /** 显式和自动分组共享同一个几何对象 */
5
- export declare function createBeamLayoutAttachment(endPoints: TemporalNodeBase[], explicit?: boolean, sourceSpan?: SourceSpan): LayoutAttachment;
6
+ export declare function createBeamLayoutAttachment(endPoints: TemporalNodeBase[], explicit: boolean, sourceSpan: SourceSpan): LayoutAttachment;
6
7
  /** 显式 beam 必须严格连接最终同轨同谱面行中的相邻可见主体 */
7
8
  export declare function validateExplicitBeamAttachments(result: LoweringResult): void;
8
9
  /** 自动分组在 loweringAugment 当下读取已经注册的显式 beam 端点 */
9
- export declare function collectExplicitBeamEndpoints(attachments: readonly LayoutAttachment[]): Set<TemporalNodeBase>;
10
+ export declare function collectExplicitBeamEndpoints(attachments: readonly LoweringAttachment[]): Set<TemporalNodeBase>;
@@ -1,8 +1,8 @@
1
1
  import { isVisualTemporalNode, } from "../../lowering/types.js";
2
2
  import { ErrorDiagnostic } from "../../diagnostic.js";
3
- import { claimDivLine, divLinePortName, } from "../div/index.js";
3
+ import { claimDivLine, divLinePortName, divLineRuns, divLineWidth, } from "../div/index.js";
4
4
  /** 显式和自动分组共享同一个几何对象 */
5
- export function createBeamLayoutAttachment(endPoints, explicit = false, sourceSpan) {
5
+ export function createBeamLayoutAttachment(endPoints, explicit, sourceSpan) {
6
6
  return new BeamLayoutAttachment(endPoints, explicit, sourceSpan);
7
7
  }
8
8
  /** 显式 beam 必须严格连接最终同轨同谱面行中的相邻可见主体 */
@@ -50,7 +50,7 @@ export function validateExplicitBeamAttachments(result) {
50
50
  && secondPosition.index === firstPosition.index + 1;
51
51
  if (adjacent)
52
52
  continue;
53
- throw new ErrorDiagnostic("E_NON_ADJACENT_BEAM", "@beam 的端点必须按时间顺序连接同一轨道、同一谱面行中的相邻可见元素", attachment.sourceSpan ?? attachment.endPoints[i].ast.sourceSpan);
53
+ throw new ErrorDiagnostic("E_NON_ADJACENT_BEAM", "@beam 的端点必须按时间顺序连接同一轨道、同一谱面行中的相邻可见元素", attachment.sourceSpan);
54
54
  }
55
55
  }
56
56
  }
@@ -66,22 +66,19 @@ export function collectExplicitBeamEndpoints(attachments) {
66
66
  return result;
67
67
  }
68
68
  class BeamLayoutAttachment {
69
- box = {
70
- x: 0,
71
- y: 0,
72
- w: 0,
73
- h: 0,
74
- };
75
69
  layer = "foreground";
76
70
  endPoints;
77
71
  explicit;
78
72
  sourceSpan;
79
- lines = [];
80
- strokeWidth = 1;
73
+ /** 端点字号不随布局变化,装饰尺寸可以一次算定 */
74
+ fontSize;
75
+ strokeWidth;
81
76
  constructor(endPoints, explicit, sourceSpan) {
82
77
  this.endPoints = endPoints;
83
78
  this.explicit = explicit;
84
79
  this.sourceSpan = sourceSpan;
80
+ this.fontSize = endPoints.reduce((size, endpoint) => isVisualTemporalNode(endpoint) ? Math.max(size, endpoint.ast.size) : size, 0);
81
+ this.strokeWidth = divLineWidth(this.fontSize);
85
82
  }
86
83
  /** 同一 beam 组内的相邻元素使用更短的自然弹簧间距 */
87
84
  prepareHorizontal(context) {
@@ -99,76 +96,56 @@ class BeamLayoutAttachment {
99
96
  }
100
97
  }
101
98
  }
102
- layout(context) {
103
- this.updateGeometry(context);
104
- const halfStroke = this.strokeWidth / 2;
105
- return this.lines.map(line => ({
106
- x: Math.min(line.start.x, line.end.x) - halfStroke,
107
- y: Math.min(line.start.y, line.end.y) - halfStroke,
108
- w: Math.abs(line.end.x - line.start.x) + this.strokeWidth,
109
- h: Math.abs(line.end.y - line.start.y) + this.strokeWidth,
99
+ createGeometry(context) {
100
+ const lines = this.collectLines(context);
101
+ const strokeWidth = this.strokeWidth;
102
+ // 减时线永远水平,butt 端帽只在纵向占半个描边
103
+ const regions = lines.map(line => ({
104
+ x: Math.min(line.start.x, line.end.x),
105
+ y: line.start.y - strokeWidth / 2,
106
+ w: Math.abs(line.end.x - line.start.x),
107
+ h: strokeWidth,
110
108
  line: line.line,
111
109
  track: line.track,
112
110
  }));
113
- }
114
- paint(painter) {
115
- for (const line of this.lines) {
116
- painter.drawLine(line.start.x, line.start.y, line.end.x, line.end.y, { stroke: "#000", strokeWidth: this.strokeWidth });
117
- }
111
+ return {
112
+ regions,
113
+ paint(painter) {
114
+ for (const line of lines) {
115
+ painter.drawLine(line.start.x, line.start.y, line.end.x, line.end.y, { stroke: "#000", strokeWidth });
116
+ }
117
+ },
118
+ };
118
119
  }
119
120
  absolutePort(node, name) {
120
121
  const port = node.ports[name];
121
- if (!port)
122
- return null;
123
122
  return {
124
123
  x: node.box.x + port.x,
125
124
  y: node.box.y + port.y,
126
125
  };
127
126
  }
128
- updateGeometry(context) {
129
- this.lines.length = 0;
127
+ collectLines(context) {
128
+ const lines = [];
130
129
  const available = this.endPoints.filter(isVisualTemporalNode);
131
130
  if (available.length < 2)
132
- return;
133
- // 选择端点的使用最大字号作为装饰尺寸
134
- const fontSize = available.reduce((size, endpoint) => Math.max(size, endpoint.ast.size), 0);
135
- this.strokeWidth = Math.max(1, fontSize * 0.07);
136
- // 每一级只合并连续提供该级 div 端口的对象
137
- for (let level = 0;; level++) {
138
- const spanGroups = [];
139
- let spans = [];
140
- let hasPorts = false;
141
- for (const node of available) {
142
- const left = this.absolutePort(node, divLinePortName(level, "left"));
143
- const right = this.absolutePort(node, divLinePortName(level, "right"));
144
- if (left || right)
145
- hasPorts = true;
146
- if (!left || !right) {
147
- if (spans.length > 0)
148
- spanGroups.push(spans);
149
- spans = [];
150
- continue;
151
- }
131
+ return lines;
132
+ for (const { level, from, to } of divLineRuns(available)) {
133
+ const spans = [];
134
+ for (let i = from; i <= to; i++) {
135
+ const node = available[i];
152
136
  spans.push({
153
- left,
154
- right,
137
+ left: this.absolutePort(node, divLinePortName(level, "left")),
138
+ right: this.absolutePort(node, divLinePortName(level, "right")),
155
139
  line: node.layoutLine,
156
140
  track: node.track,
157
141
  node,
158
142
  });
159
143
  }
160
- if (spans.length > 0)
161
- spanGroups.push(spans);
162
- if (!hasPorts)
163
- break;
164
- for (const group of spanGroups) {
165
- if (group.length >= 2)
166
- this.addSystemLines(group, context, level);
167
- }
144
+ this.addSystemLines(spans, context, level, lines);
168
145
  }
169
146
  // 显式关系允许连接没有 div 端口的任意可见对象
170
- if (this.lines.length === 0 && this.explicit) {
171
- const gap = fontSize * 0.12;
147
+ if (lines.length === 0 && this.explicit) {
148
+ const gap = this.fontSize * 0.12;
172
149
  const spans = available.map(node => {
173
150
  const point = {
174
151
  x: node.box.x + node.box.anchor,
@@ -182,11 +159,12 @@ class BeamLayoutAttachment {
182
159
  node,
183
160
  };
184
161
  });
185
- this.addSystemLines(spans, context, null);
162
+ this.addSystemLines(spans, context, null, lines);
186
163
  }
164
+ return lines;
187
165
  }
188
166
  /** 同一级减时线按谱面行拆开,跨行时连接到对应页面边界 */
189
- addSystemLines(spans, context, connectedLevel) {
167
+ addSystemLines(spans, context, connectedLevel, lines) {
190
168
  const firstLine = Math.min(...spans.map(item => item.line));
191
169
  const lastLine = Math.max(...spans.map(item => item.line));
192
170
  const fallbackTrack = spans[0].track;
@@ -199,7 +177,7 @@ class BeamLayoutAttachment {
199
177
  if (current.length === 0) {
200
178
  const visualAxis = context.getVisualAxis(line, fallbackTrack);
201
179
  const y = visualAxis + visualAxisOffset;
202
- this.lines.push({
180
+ lines.push({
203
181
  start: { x: context.originX, y },
204
182
  end: { x: context.originX + context.width, y },
205
183
  line,
@@ -222,7 +200,7 @@ class BeamLayoutAttachment {
222
200
  for (const span of current)
223
201
  claimDivLine(span.node, connectedLevel);
224
202
  }
225
- this.lines.push({
203
+ lines.push({
226
204
  start,
227
205
  end,
228
206
  line,