jpfun 0.6.0 → 0.8.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 (134) hide show
  1. package/Bravura-LICENSE.txt +93 -0
  2. package/README.md +49 -146
  3. package/dist/Bravura-LICENSE.txt +93 -0
  4. package/dist/converter/midi/convert.d.ts +3 -11
  5. package/dist/converter/midi/convert.js +89 -67
  6. package/dist/converter/musicxml/features.d.ts +34 -12
  7. package/dist/converter/musicxml/features.js +131 -24
  8. package/dist/converter/musicxml/index.js +221 -54
  9. package/dist/converter/musicxml/model.d.ts +24 -0
  10. package/dist/core.d.ts +1 -0
  11. package/dist/core.js +1 -0
  12. package/dist/diagnostic.d.ts +7 -1
  13. package/dist/diagnostic.js +40 -88
  14. package/dist/fraction.js +3 -2
  15. package/dist/functions/ASTtypes.d.ts +2 -18
  16. package/dist/functions/ASTtypes.js +0 -16
  17. package/dist/functions/arpeggio/index.js +17 -22
  18. package/dist/functions/arpeggio/shape.d.ts +1 -1
  19. package/dist/functions/arpeggio/shape.js +27 -21
  20. package/dist/functions/bar/index.d.ts +8 -0
  21. package/dist/functions/bar/index.js +139 -36
  22. package/dist/functions/beam/auto.d.ts +1 -2
  23. package/dist/functions/beam/auto.js +44 -27
  24. package/dist/functions/beam/index.js +2 -3
  25. package/dist/functions/beam/layout.d.ts +1 -1
  26. package/dist/functions/beam/layout.js +16 -24
  27. package/dist/functions/br/index.d.ts +34 -2
  28. package/dist/functions/br/index.js +8 -8
  29. package/dist/functions/dash/index.js +6 -6
  30. package/dist/functions/default.js +10 -5
  31. package/dist/functions/div/index.d.ts +1 -0
  32. package/dist/functions/div/index.js +8 -4
  33. package/dist/functions/dot/index.js +2 -2
  34. package/dist/functions/dyn/index.js +49 -31
  35. package/dist/functions/gliss/index.d.ts +2 -0
  36. package/dist/functions/gliss/index.js +202 -0
  37. package/dist/functions/grace/index.d.ts +1 -7
  38. package/dist/functions/grace/index.js +11 -19
  39. package/dist/functions/head/index.js +41 -60
  40. package/dist/functions/key/index.js +8 -10
  41. package/dist/functions/meter/index.d.ts +56 -1
  42. package/dist/functions/meter/index.js +30 -24
  43. package/dist/functions/note/accidentals.js +10 -16
  44. package/dist/functions/note/index.js +18 -8
  45. package/dist/functions/note/noteName.d.ts +16 -0
  46. package/dist/functions/note/noteName.js +88 -0
  47. package/dist/functions/note/source-transform.js +6 -5
  48. package/dist/functions/ottava/index.d.ts +2 -0
  49. package/dist/functions/ottava/index.js +233 -0
  50. package/dist/functions/page/index.d.ts +1 -0
  51. package/dist/functions/page/index.js +22 -13
  52. package/dist/functions/pagebreak/index.d.ts +2 -0
  53. package/dist/functions/pagebreak/index.js +36 -0
  54. package/dist/functions/rest/index.js +15 -15
  55. package/dist/functions/set/index.js +4 -4
  56. package/dist/functions/slide/index.d.ts +2 -0
  57. package/dist/functions/slide/index.js +132 -0
  58. package/dist/functions/stack/index.js +8 -15
  59. package/dist/functions/symbol/index.d.ts +30 -2
  60. package/dist/functions/symbol/index.js +93 -19
  61. package/dist/functions/symbol/ornament.d.ts +1 -2
  62. package/dist/functions/symbol/ornament.js +14 -19
  63. package/dist/functions/symbol/shape.d.ts +6 -0
  64. package/dist/functions/symbol/shape.js +20 -4
  65. package/dist/functions/symbol/symbols/coda.d.ts +4 -0
  66. package/dist/functions/symbol/symbols/coda.js +56 -0
  67. package/dist/functions/symbol/symbols/dynamics.d.ts +1 -1
  68. package/dist/functions/symbol/symbols/dynamics.js +18 -8
  69. package/dist/functions/symbol/symbols/fine.js +1 -1
  70. package/dist/functions/symbol/symbols/harmonic.d.ts +2 -0
  71. package/dist/functions/symbol/symbols/harmonic.js +11 -0
  72. package/dist/functions/symbol/symbols/marcato.d.ts +2 -0
  73. package/dist/functions/symbol/symbols/marcato.js +22 -0
  74. package/dist/functions/symbol/symbols/staccato.d.ts +2 -0
  75. package/dist/functions/symbol/symbols/staccato.js +24 -0
  76. package/dist/functions/symbol/symbols/tenuto.d.ts +2 -0
  77. package/dist/functions/symbol/symbols/tenuto.js +11 -0
  78. package/dist/functions/symbol/symbols/tocoda.d.ts +2 -0
  79. package/dist/functions/symbol/symbols/tocoda.js +16 -0
  80. package/dist/functions/symbol/symbols/tr.js +46 -1
  81. package/dist/functions/symbol/symbols/turn.d.ts +3 -0
  82. package/dist/functions/symbol/symbols/turn.js +50 -0
  83. package/dist/functions/symbol/symbols/wheel.d.ts +2 -0
  84. package/dist/functions/symbol/symbols/wheel.js +36 -0
  85. package/dist/functions/temporal.d.ts +17 -6
  86. package/dist/functions/temporal.js +17 -6
  87. package/dist/functions/text/index.js +15 -6
  88. package/dist/functions/tie/index.js +64 -30
  89. package/dist/functions/tremolo/index.d.ts +2 -0
  90. package/dist/functions/tremolo/index.js +319 -0
  91. package/dist/functions/tuplet/index.js +4 -8
  92. package/dist/functions/up/index.js +7 -9
  93. package/dist/functions/voice/connections.js +7 -5
  94. package/dist/functions/voice/index.js +19 -11
  95. package/dist/functions/volta/index.js +41 -21
  96. package/dist/jpfun.core.min.js +64 -80
  97. package/dist/jpfun.from-midi.min.js +5 -5
  98. package/dist/jpfun.from-musicxml.min.js +8 -8
  99. package/dist/jpfun.min.js +69 -85
  100. package/dist/layout/default.d.ts +0 -1
  101. package/dist/layout/default.js +0 -1
  102. package/dist/layout/engine.d.ts +1 -0
  103. package/dist/layout/engine.js +42 -11
  104. package/dist/layout/page.d.ts +3 -2
  105. package/dist/layout/page.js +6 -5
  106. package/dist/layout/types.d.ts +4 -0
  107. package/dist/lowering/loweringContext.d.ts +11 -13
  108. package/dist/lowering/loweringContext.js +30 -197
  109. package/dist/lowering/types.d.ts +1 -3
  110. package/dist/parser/parse-utils/note-utils.d.ts +1 -1
  111. package/dist/parser/parse-utils/note-utils.js +8 -9
  112. package/dist/parser/parse-utils/string-utils.d.ts +3 -2
  113. package/dist/parser/parse-utils/string-utils.js +16 -3
  114. package/dist/parser/parserContext.d.ts +2 -0
  115. package/dist/parser/parserContext.js +36 -8
  116. package/dist/pipeline.js +0 -1
  117. package/dist/playback/compile.js +131 -72
  118. package/dist/playback/event.d.ts +1 -1
  119. package/dist/playback/event.js +9 -9
  120. package/dist/playback/time.js +42 -31
  121. package/dist/playback/types.d.ts +7 -3
  122. package/dist/render/canvas.d.ts +2 -0
  123. package/dist/render/canvas.js +25 -22
  124. package/dist/render/recording.js +1 -4
  125. package/dist/render/svg.js +1 -0
  126. package/dist/render/text.d.ts +1 -1
  127. package/dist/render/text.js +3 -2
  128. package/dist/render/translate.d.ts +0 -1
  129. package/dist/render/translate.js +6 -23
  130. package/dist/render/types.d.ts +1 -0
  131. package/grammar.md +52 -25
  132. package/package.json +3 -3
  133. package/dist/functions/note/noteNameFSM.d.ts +0 -8
  134. package/dist/functions/note/noteNameFSM.js +0 -181
@@ -0,0 +1,233 @@
1
+ import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
2
+ import { unionLayoutBoxes } from "../../layout/engine.js";
3
+ import { ASTFunctionNode, } from "../ASTtypes.js";
4
+ import { isVisualTemporalNode } from "../temporal.js";
5
+ function outerHost(node) {
6
+ while (node.foldedInto)
7
+ node = node.foldedInto;
8
+ return node;
9
+ }
10
+ class OttavaFunction extends ASTFunctionNode {
11
+ static def = {
12
+ name: ["ottava"],
13
+ description: "八度号",
14
+ details: `\
15
+ ~~~jpfun
16
+ 1@a 2 3 -@b | 4
17
+ @ottava(a, b, 1)
18
+ ~~~
19
+ \`shift\` 为非零整数八度数,正数在上方标高八度号,负数在下方标低八度号,默认 \`1\`。标签使用谱面数字字体的斜体。`,
20
+ allowExtraArgs: false,
21
+ args: [
22
+ {
23
+ description: "起点标签",
24
+ type: "label",
25
+ default: null
26
+ },
27
+ {
28
+ description: "终点标签",
29
+ type: "label",
30
+ default: null
31
+ },
32
+ {
33
+ name: "shift",
34
+ description: "非零整数八度数,正数为高,负数为低",
35
+ type: "number",
36
+ default: 1
37
+ },
38
+ ],
39
+ };
40
+ static loweringFinalize(result) {
41
+ const ottavasByTrack = new Map();
42
+ for (const attachment of result.attachments) {
43
+ if (!(attachment instanceof OttavaAttachment))
44
+ continue;
45
+ const [from, to] = attachment.endPoints;
46
+ const entry = { start: from.t, end: to.t.clone().add(to.T), shift: attachment.ast.shift * 12 };
47
+ const list = ottavasByTrack.get(from.track);
48
+ if (list)
49
+ list.push(entry);
50
+ else
51
+ ottavasByTrack.set(from.track, [entry]);
52
+ }
53
+ if (ottavasByTrack.size === 0)
54
+ return;
55
+ for (const list of ottavasByTrack.values()) {
56
+ list.sort((left, right) => left.start.compare(right.start));
57
+ }
58
+ for (const nodes of result.astToTemporal.values()) {
59
+ for (const node of nodes) {
60
+ if (!node.playbackState)
61
+ continue;
62
+ const host = outerHost(node);
63
+ const ottavas = ottavasByTrack.get(host.track);
64
+ if (!ottavas)
65
+ continue;
66
+ let shift = 0;
67
+ for (const ottava of ottavas) {
68
+ if (host.t.compare(ottava.start) < 0)
69
+ break;
70
+ if (host.t.compare(ottava.end) < 0) {
71
+ shift += ottava.shift;
72
+ }
73
+ }
74
+ if (shift !== 0) {
75
+ node.playbackState = {
76
+ ...node.playbackState,
77
+ pitchShift: (node.playbackState.pitchShift ?? 0) + shift,
78
+ };
79
+ }
80
+ }
81
+ }
82
+ }
83
+ from;
84
+ to;
85
+ shift;
86
+ size;
87
+ font;
88
+ constructor(span, args, ctx, parent = null) {
89
+ super(span, parent);
90
+ const [from, to, shift] = this.getArgValue(args, ctx);
91
+ if (!Number.isSafeInteger(shift) || shift === 0 || !Number.isSafeInteger(shift * 12)) {
92
+ throw new ErrorDiagnostic("E_OTTAVA_INVALID_SHIFT", "@ottava 的 shift 必须为可安全换算为半音的非零整数", span);
93
+ }
94
+ this.from = from;
95
+ this.to = to;
96
+ this.shift = shift;
97
+ this.size = ctx.variables.fontsize;
98
+ this.font = ctx.variables.numberfont;
99
+ }
100
+ loweringEnter(ctx) {
101
+ const from = ctx.getTemporalNodes(this.from).at(0);
102
+ const to = ctx.getTemporalNodes(this.to).at(-1);
103
+ const head = from && outerHost(from);
104
+ const tail = to && outerHost(to);
105
+ if (!head || !tail || !isVisualTemporalNode(head) || !isVisualTemporalNode(tail)) {
106
+ ctx.diagnostics.push(Diagnostic.warning.UnresolvedEndpoint("ottava", this.sourceSpan));
107
+ return [];
108
+ }
109
+ if (head.track !== tail.track) {
110
+ throw new ErrorDiagnostic("E_OTTAVA_CROSS_TRACK", "@ottava 的两个端点必须位于同一音轨", this.sourceSpan);
111
+ }
112
+ ctx.addAttachment(new OttavaAttachment(this, head, tail));
113
+ ctx.deferFinalize(OttavaFunction.loweringFinalize);
114
+ return [];
115
+ }
116
+ toString(source) {
117
+ const name = (node) => (node instanceof ASTFunctionNode ? node.label : undefined) ?? node.toString(source);
118
+ return `@ottava(${name(this.from)}, ${name(this.to)}, ${this.shift})`;
119
+ }
120
+ }
121
+ export const OttavaNode = OttavaFunction;
122
+ class OttavaAttachment {
123
+ ast;
124
+ from;
125
+ to;
126
+ layer = "foreground";
127
+ constructor(ast, from, to) {
128
+ this.ast = ast;
129
+ this.from = from;
130
+ this.to = to;
131
+ }
132
+ get sourceSpan() { return this.ast.sourceSpan; }
133
+ get endPoints() {
134
+ return (this.from.t.compare(this.to.t) || this.from.order - this.to.order) > 0
135
+ ? [this.to, this.from] : [this.from, this.to];
136
+ }
137
+ createGeometry(context) {
138
+ const endpoints = this.endPoints;
139
+ const [from, to] = endpoints;
140
+ const firstLine = from.layoutLine;
141
+ const lastLine = to.layoutLine;
142
+ if (context.lines[firstLine].columnOf(from) < 0 || context.lines[lastLine].columnOf(to) < 0) {
143
+ return { regions: [], paint() { } };
144
+ }
145
+ const { size, font, shift } = this.ast;
146
+ const above = shift > 0;
147
+ const track = from.track;
148
+ const strokeWidth = Math.max(0.75, size * 0.035);
149
+ const lineStyle = { stroke: "#000", strokeWidth };
150
+ const dash = size * 0.22;
151
+ const dashStep = dash + size * 0.14;
152
+ const halfStroke = strokeWidth / 2;
153
+ const hook = size * 0.45;
154
+ const gap = size * 0.2;
155
+ const labelGap = size * 0.08;
156
+ const text = String(Math.abs(shift) * 7 + 1);
157
+ const style = {
158
+ fontSize: size * 0.6,
159
+ fontFamily: font,
160
+ fontStyle: "italic",
161
+ textAlign: "left",
162
+ fill: "#000",
163
+ };
164
+ const metrics = context.textMeasurer.measureText(text, style);
165
+ const labelTop = above ? -halfStroke : halfStroke - metrics.h;
166
+ const labelY = labelTop + metrics.baseline;
167
+ const draws = Array.from({ length: lastLine - firstLine + 1 }, (_, offset) => {
168
+ const line = firstLine + offset;
169
+ const first = line === firstLine;
170
+ const last = line === lastLine;
171
+ const runs = context.lines[line].trackRuns;
172
+ let left = first ? from.box.x + (from.ports["body.left"]?.x ?? 0)
173
+ : runs.get(track)?.find(host => !host.T.isZero())?.box.x ?? context.originX;
174
+ let right = to.box.x + (to.ports["body.right"]?.x ?? to.box.w);
175
+ if (!last) {
176
+ right = context.originX + (runs.size === 0 ? context.width : 0);
177
+ for (const run of runs.values()) {
178
+ for (const host of run)
179
+ right = Math.max(right, host.box.x + host.box.w);
180
+ }
181
+ }
182
+ if (left > right)
183
+ [left, right] = [right, left];
184
+ const lineStart = first ? left + metrics.w + labelGap : left;
185
+ const part = (x, y, w, h) => ({ x, y, w, h, line, track });
186
+ const parts = lineStart < right
187
+ ? [part(lineStart - halfStroke, -halfStroke, right - lineStart + strokeWidth, strokeWidth)] : [];
188
+ if (first)
189
+ parts.push(part(left, labelTop, metrics.w, metrics.h));
190
+ if (last)
191
+ parts.push(part(right - halfStroke, above ? -halfStroke : -hook - halfStroke, strokeWidth, hook + strokeWidth));
192
+ const region = part(0, 0, 0, 0);
193
+ unionLayoutBoxes(region, parts);
194
+ let lineY = above ? Infinity : -Infinity;
195
+ for (const part of parts) {
196
+ for (const [lane, extent] of context.getHorizontalExtents(line, part.x, part.x + part.w)) {
197
+ const axis = context.getVisualAxis(line, lane);
198
+ lineY = above
199
+ ? Math.min(lineY, axis + extent.top - gap - part.y - part.h)
200
+ : Math.max(lineY, axis + extent.bottom + gap - part.y);
201
+ }
202
+ }
203
+ if (!Number.isFinite(lineY)) {
204
+ const extent = context.getRangeExtents(line, first || last ? endpoints : undefined, track);
205
+ const axis = context.getVisualAxis(line, track);
206
+ lineY = above
207
+ ? axis + (extent?.top ?? 0) - gap - (region.y + region.h)
208
+ : axis + (extent?.bottom ?? 0) + gap - region.y;
209
+ }
210
+ for (const part of parts)
211
+ part.y += lineY;
212
+ region.y += lineY;
213
+ return { left, right, lineStart, lineY, first, last, parts, region };
214
+ });
215
+ return {
216
+ regions: draws.map(draw => draw.region),
217
+ occupancy: draws.flatMap(draw => draw.parts),
218
+ paint(painter) {
219
+ for (const draw of draws) {
220
+ const { left, right, lineStart, lineY, first, last } = draw;
221
+ for (let x = lineStart; x < right; x += dashStep) {
222
+ painter.drawLine(x, lineY, Math.min(x + dash, right), lineY, lineStyle);
223
+ }
224
+ if (first)
225
+ painter.drawText(text, left, lineY + labelY, style);
226
+ if (last) {
227
+ painter.drawLine(right, lineY, right, lineY + (above ? hook : -hook), lineStyle);
228
+ }
229
+ }
230
+ },
231
+ };
232
+ }
233
+ }
@@ -28,6 +28,7 @@ export declare class PageFunction extends ASTFunctionNode {
28
28
  };
29
29
  readonly config: PageConfig | null;
30
30
  private readonly numbering;
31
+ private readonly barNumbering;
31
32
  readonly font: string;
32
33
  constructor(sourceSpan: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent?: ASTNodeBase | null);
33
34
  loweringEnter(ctx: LoweringContext): never[];
@@ -1,6 +1,7 @@
1
1
  import { DEFAULT_PAGE_CONFIG, normalizePageConfig, } from "../../layout/page.js";
2
- import { Diagnostic, WarningDiagnostic } from "../../diagnostic.js";
2
+ import { ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
3
3
  import { quote } from "../../parser/parse-utils/string-utils.js";
4
+ import { registerBarNumbering } from "../bar/index.js";
4
5
  import { ASTFunctionNode, } from "../ASTtypes.js";
5
6
  const px = (value) => ({ value, unit: "px" });
6
7
  /** 页码字号,同时也是放得下页码所需的最小下边距 */
@@ -50,14 +51,15 @@ export class PageFunction extends ASTFunctionNode {
50
51
  ~~~jpfun
51
52
  @page(
52
53
  width=794px, height=1123px, top=48px, bottom=48px,
53
- left=40px, right=40px, gap=1em, numbering="1/1", fillRatio=0.5
54
+ left=40px, right=40px, gap=1em, fillRatio=0.5,
55
+ numbering="1/1", barNumbering="(1)"
54
56
  )
55
57
  ~~~
56
- 尺寸接受 \`px\` 或 \`em\`。页边距和行距须非负;左右边距之和须小于页宽,固定页高时上下边距之和须小于页高。`,
58
+ 页边距和行距须非负;左右边距之和须小于页宽,固定页高时上下边距之和须小于页高。`,
57
59
  allowExtraArgs: false,
58
60
  args: [
59
61
  { name: "width", description: "页面宽度,须大于左右页边距之和", type: "length", default: px(DEFAULT_PAGE_CONFIG.width) },
60
- { name: "height", description: "页面高度,0 表示不分页、高度随内容增长;宽度为 `794px` 时,A4 对应高度约为 `1123px`", type: "length", default: px(0) },
62
+ { name: "height", description: "页面高度,小于等于 0 表示不自动分页、高度随内容增长;宽度为 `794px` 时,A4 对应高度约为 `1123px`", type: "length", default: px(0) },
61
63
  { name: "top", description: "页面上边距", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginTop) },
62
64
  { name: "bottom", description: "页面下边距,启用页码时至少为 `16px`", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginBottom) },
63
65
  { name: "left", description: "页面左边距", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginLeft) },
@@ -65,12 +67,14 @@ export class PageFunction extends ASTFunctionNode {
65
67
  { name: "gap", description: "谱面行之间的最小间距", type: "length", default: { value: 1, unit: "em" } },
66
68
  // 单个 1 取当前页;多个 1 中最后一个取总页数
67
69
  { name: "numbering", description: "页码格式,空值隐藏;`1` 显示当前页,`1/1` 显示当前页/总页数", type: "string", default: "" },
68
- { name: "font", description: "页码字体,空值沿用当前字体设置", type: "string", default: "" },
70
+ { name: "barNumbering", description: "行首小节号格式,默认空值隐藏;`1` 显示当前小节号,`(1)` 显示带括号的小节号", type: "string", default: "" },
71
+ { name: "font", description: "页码/小节号字体,空值沿用当前字体设置", type: "string", default: "" },
69
72
  { name: "fillRatio", description: "自然宽度达到该比例后撑满", type: "number", default: DEFAULT_PAGE_CONFIG.fillRatio },
70
73
  ],
71
74
  };
72
75
  config;
73
76
  numbering = "";
77
+ barNumbering = "";
74
78
  font;
75
79
  constructor(sourceSpan, args, ctx, parent = null) {
76
80
  super(sourceSpan, parent);
@@ -89,20 +93,21 @@ export class PageFunction extends ASTFunctionNode {
89
93
  const values = this.getArgValue(args, ctx);
90
94
  const fillRatio = values.pop();
91
95
  this.font = values.pop() || ctx.variables.font;
96
+ const barNumbering = values.pop();
92
97
  const numbering = values.pop();
93
98
  const [width, height, top, bottom, left, right, gap] = values.map(value => ctx.length2px(value));
94
99
  if (!Number.isFinite(width) || width <= 0)
95
- throw Diagnostic.error.InvalidPageConfig("@page 的 width 必须是正有限长度", sourceSpan);
96
- if (!Number.isFinite(height) || height < 0)
97
- throw Diagnostic.error.InvalidPageConfig("@page 的 height 必须是非负有限长度;0 表示不分页", sourceSpan);
100
+ throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的 width 必须是正有限长度", sourceSpan);
101
+ if (!Number.isFinite(height))
102
+ throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的 height 必须是有限长度;小于等于 0 表示不自动分页", sourceSpan);
98
103
  if ([top, bottom, left, right, gap].some(value => !Number.isFinite(value) || value < 0))
99
- throw Diagnostic.error.InvalidPageConfig("@page 的边距和 gap 必须是非负有限长度", sourceSpan);
104
+ throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的边距和 gap 必须是非负有限长度", sourceSpan);
100
105
  if (left + right >= width)
101
- throw Diagnostic.error.InvalidPageConfig("@page 的左右边距没有留下可用内容宽度", sourceSpan);
106
+ throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的左右边距没有留下可用内容宽度", sourceSpan);
102
107
  if (height > 0 && top + bottom >= height)
103
- throw Diagnostic.error.InvalidPageConfig("@page 的上下边距没有留下可用内容高度", sourceSpan);
108
+ throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的上下边距没有留下可用内容高度", sourceSpan);
104
109
  if (numbering && bottom < PAGE_NUMBER_FONT_SIZE)
105
- throw Diagnostic.error.InvalidPageConfig(`@page 的 bottom 至少需要 ${PAGE_NUMBER_FONT_SIZE}px 才能放下页码`, sourceSpan);
110
+ throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的 bottom 至少需要 {minBottom}px 才能放下页码", sourceSpan, { minBottom: PAGE_NUMBER_FONT_SIZE });
106
111
  this.config = normalizePageConfig({
107
112
  width,
108
113
  height,
@@ -114,6 +119,7 @@ export class PageFunction extends ASTFunctionNode {
114
119
  fillRatio,
115
120
  });
116
121
  this.numbering = numbering;
122
+ this.barNumbering = barNumbering;
117
123
  }
118
124
  loweringEnter(ctx) {
119
125
  if (!ctx || !this.config)
@@ -122,13 +128,16 @@ export class PageFunction extends ASTFunctionNode {
122
128
  if (this.numbering) {
123
129
  ctx.addAttachment(new PageNumberAttachment(this.sourceSpan, this.numbering, this.config.marginBottom, { ...PAGE_NUMBER_STYLE, fontFamily: this.font }));
124
130
  }
131
+ if (this.barNumbering) {
132
+ registerBarNumbering(ctx, this.barNumbering, this.font);
133
+ }
125
134
  return [];
126
135
  }
127
136
  toString() {
128
137
  if (!this.config)
129
138
  return "@page()";
130
139
  const { width, height, marginTop, marginBottom, marginLeft, marginRight, lineGap, fillRatio } = this.config;
131
- 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, numbering=${quote(this.numbering)}, font=${quote(this.font)}, fillRatio=${fillRatio})`;
140
+ 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, numbering=${quote(this.numbering)}, barNumbering=${quote(this.barNumbering)}, font=${quote(this.font)}, fillRatio=${fillRatio})`;
132
141
  }
133
142
  }
134
143
  export const PageNode = PageFunction;
@@ -0,0 +1,2 @@
1
+ import { type ASTFunctionClass } from "../ASTtypes.js";
2
+ export declare const PageBreakNode: ASTFunctionClass;
@@ -0,0 +1,36 @@
1
+ import { TemporalNodeBase } from "../temporal.js";
2
+ import { BrNode } from "../br/index.js";
3
+ import { ASTFunctionNode, } from "../ASTtypes.js";
4
+ class PageBreakFunction extends ASTFunctionNode {
5
+ static def = {
6
+ name: ["pagebreak", "pb"],
7
+ description: "强制换页",
8
+ details: `\
9
+ ~~~jpfun
10
+ 1 2 @br() 3 4 @pagebreak() 5 6
11
+ ~~~
12
+ 同时换行并开启新页,不占音乐时值。同一时刻的并行调用只换一次页,\`justify=false\` 优先。`,
13
+ allowExtraArgs: false,
14
+ args: [{
15
+ name: "justify",
16
+ description: "是否分配当前页的剩余空间;无限页高时不拉伸",
17
+ type: "boolean",
18
+ default: true,
19
+ }],
20
+ };
21
+ justify;
22
+ constructor(span, args, ctx, parent = null) {
23
+ super(span, parent);
24
+ [this.justify] = this.getArgValue(args, ctx);
25
+ }
26
+ loweringEnter(ctx) {
27
+ ctx.deferFinalize(BrNode.loweringFinalize);
28
+ const node = new TemporalNodeBase();
29
+ node.ast = this;
30
+ node.mergeKey = -1;
31
+ node.addon = { breakBefore: 1, pageBreakBefore: this.justify };
32
+ return [node];
33
+ }
34
+ toString() { return `@pagebreak(justify=${this.justify})`; }
35
+ }
36
+ export const PageBreakNode = PageBreakFunction;
@@ -54,8 +54,11 @@ class RestFunction extends ASTFunctionNode {
54
54
  }
55
55
  this.font = ctx.variables.numberfont;
56
56
  }
57
- labelable() { return null; }
58
- loweringEnter() {
57
+ // 可以被 volta 这样的标记
58
+ labelable() { return this; }
59
+ loweringEnter(ctx) {
60
+ // 先于拍号校验(默认 order=0)补入多小节休止内部的虚拟小节边界
61
+ ctx.deferFinalize(RestFunction.loweringFinalize, -10);
59
62
  return [new RestTemporal(this)];
60
63
  }
61
64
  static loweringFinalize(result) {
@@ -66,12 +69,11 @@ class RestFunction extends ASTFunctionNode {
66
69
  const onsets = new Map();
67
70
  // 扫描完整来源索引,纳入未直接出现在时间列中的折叠成员
68
71
  for (const nodes of result.astToTemporal.values()) {
69
- // 为新增边界预留唯一 order,并记录各宿主的休止代表和最早音符
72
+ // 为新增边界预留唯一 order,并记录各宿主的最早音符
70
73
  for (const node of nodes) {
71
74
  order = Math.max(order, node.order + 1);
72
- if (!(node instanceof RestTemporal)
73
- && (!(node.ast instanceof ASTFunctionNode)
74
- || (node.ast.callName !== "note" && node.ast.callName !== "dash")))
75
+ if (!(node.ast instanceof ASTFunctionNode)
76
+ || (node.ast.callName !== "note" && node.ast.callName !== "dash"))
75
77
  continue;
76
78
  let host = node;
77
79
  // 沿折叠链找到最外层宿主,将内部成员归到同一主体
@@ -80,15 +82,6 @@ class RestFunction extends ASTFunctionNode {
80
82
  // 私有倚音属于独立轨道,不代表外层宿主的休止或起音
81
83
  if (node.track !== host.track)
82
84
  continue;
83
- if (node instanceof RestTemporal) {
84
- // 非宿主休止不接管外层时间列,同轨最早休止代表宿主
85
- if (host.mergeKey !== REST_KEY)
86
- continue;
87
- const rest = restsByHost.get(host);
88
- if (!rest || node.order < rest.order)
89
- restsByHost.set(host, node);
90
- continue;
91
- }
92
85
  const onset = onsets.get(host);
93
86
  if (!onset || node.order < onset.order)
94
87
  onsets.set(host, node);
@@ -160,6 +153,13 @@ class RestTemporal extends TemporalNodeBase {
160
153
  }
161
154
  this.measureDuration.copyFrom(measure);
162
155
  this.T.copyFrom(measure).mul(this.ast.count);
156
+ const host = state.currentEvent ?? this;
157
+ // 只登记全局休止宿主的同轨成员,私有倚音不接管宿主。
158
+ if (host.mergeKey === REST_KEY && this.track === host.track) {
159
+ const rest = restsByHost.get(host);
160
+ if (!rest || this.order < rest.order)
161
+ restsByHost.set(host, this);
162
+ }
163
163
  this.playbackState = { bpm: state.bpm };
164
164
  return this.T;
165
165
  }
@@ -28,11 +28,11 @@ class SetFunction extends ASTFunctionNode {
28
28
  const def = ctx.functions.get(key.slice(0, dot))?.prototype.def;
29
29
  const type = def && resolveArgType(def, argName, -1);
30
30
  if (!def || !type) {
31
- ctx.diagnostics.push(new WarningDiagnostic("W_SET_UNKNOWN_TARGET", `@set 的参数 [${key}] 没有对应的函数或其参数,将被忽略`, nameSpan));
31
+ ctx.diagnostics.push(new WarningDiagnostic("W_SET_UNKNOWN_TARGET", "@set 的参数 [{key}] 没有对应的函数或其参数,将被忽略", nameSpan, { key }));
32
32
  return null;
33
33
  }
34
34
  if (type === "content" || type === "label") {
35
- ctx.diagnostics.push(new WarningDiagnostic("W_SET_INVALID_VALUE_TYPE", `@set 的参数 [${key}] 内容和标签不能作为默认值,将被忽略`, nameSpan));
35
+ ctx.diagnostics.push(new WarningDiagnostic("W_SET_INVALID_VALUE_TYPE", "@set 的参数 [{key}] 内容和标签不能作为默认值,将被忽略", nameSpan, { key }));
36
36
  return null;
37
37
  }
38
38
  // 别名统一成主名,否则 getArgValue 按主名查不到
@@ -44,7 +44,7 @@ class SetFunction extends ASTFunctionNode {
44
44
  for (const [key, value] of args) {
45
45
  const arg = value;
46
46
  if (typeof key !== "string") {
47
- ctx.diagnostics.push(new WarningDiagnostic("W_SET_POSITIONAL_ARG", `函数 @set 不接收位置参数, 位置参数[${key}]将被忽略`, arg.span));
47
+ ctx.diagnostics.push(new WarningDiagnostic("W_SET_POSITIONAL_ARG", "函数 @set 不接收位置参数, 位置参数[{key}]将被忽略", arg.span, { key }));
48
48
  continue;
49
49
  }
50
50
  const target = SetFunction.resolveTarget(ctx, key.toLowerCase(), arg.nameSpan ?? arg.span);
@@ -54,7 +54,7 @@ class SetFunction extends ASTFunctionNode {
54
54
  // 按目标参数的声明类型固化,否则消费者只能拿到 raw text 各自再解析一遍
55
55
  const v = ctx.parseArgWithType(arg.valueSpan, type, sourceSpan.start);
56
56
  if (v === null) {
57
- ctx.diagnostics.push(new WarningDiagnostic("W_SET_INVALID_VALUE", `函数 @set 的参数值解析失败, 参数[${key}]将被忽略`, arg.valueSpan));
57
+ ctx.diagnostics.push(new WarningDiagnostic("W_SET_INVALID_VALUE", "函数 @set 的参数值解析失败, 参数[{key}]将被忽略", arg.valueSpan, { key }));
58
58
  continue;
59
59
  }
60
60
  ctx.setVariable(k, v);
@@ -0,0 +1,2 @@
1
+ import { type ASTFunctionClass } from "../ASTtypes.js";
2
+ export declare const SlideNode: ASTFunctionClass;
@@ -0,0 +1,132 @@
1
+ import { ErrorDiagnostic } from "../../diagnostic.js";
2
+ import { pathBounds } from "../../layout/path.js";
3
+ import { ASTFunctionNode, } from "../ASTtypes.js";
4
+ import { isVisualTemporalNode } from "../temporal.js";
5
+ class SlideFunction extends ASTFunctionNode {
6
+ static def = {
7
+ name: ["slide"],
8
+ description: "滑入或滑出记号",
9
+ details: `\
10
+ ~~~jpfun
11
+ @slide(5, side=pre, direction=up)
12
+ ~~~
13
+ 仅绘制,不改变时值和播放。pre 修饰内容首端,post 修饰末端;up/down 表示随时间上行/下行。`,
14
+ allowExtraArgs: false,
15
+ args: [
16
+ { type: "content", default: null, description: "被修饰的内容" },
17
+ { name: "side", type: "string", default: "pre", description: "pre 滑入,post 滑出" },
18
+ { name: "direction", type: "string", default: "up", description: "up 上行,down 下行" },
19
+ ],
20
+ };
21
+ content;
22
+ side;
23
+ direction;
24
+ get children() { return [this.content]; }
25
+ timeFlowModel() { return { children: this.children, mode: "sequence" }; }
26
+ labelable() { return ASTFunctionNode.findLabelable(this.content); }
27
+ constructor(span, args, ctx, parent = null) {
28
+ super(span, parent);
29
+ const [content, side, direction] = this.getArgValue(args, ctx);
30
+ if (side !== "pre" && side !== "post")
31
+ throw new ErrorDiagnostic("E_SLIDE_SIDE", "@slide 的 side 必须是 pre 或 post", span);
32
+ if (direction !== "up" && direction !== "down")
33
+ throw new ErrorDiagnostic("E_SLIDE_DIRECTION", "@slide 的 direction 必须是 up 或 down", span);
34
+ this.content = content;
35
+ this.side = side;
36
+ this.direction = direction;
37
+ content.parent = this;
38
+ }
39
+ loweringEnter(ctx) {
40
+ const pre = this.side === "pre";
41
+ const group = {
42
+ // 只保留首端或末端,不收集整段内容
43
+ onTemporal(node) {
44
+ if (isVisualTemporalNode(node) && (!pre || !group.host))
45
+ group.host = node;
46
+ },
47
+ };
48
+ ctx.beginLoweringGroup(this, group);
49
+ return [];
50
+ }
51
+ loweringExit(ctx) {
52
+ const { host } = ctx.endLoweringGroup(this);
53
+ if (!host)
54
+ throw new ErrorDiagnostic("E_SLIDE_CONTENT", "@slide 的内容必须包含可绘制对象", this.sourceSpan);
55
+ const attachment = new SlideAttachment(host, this);
56
+ ctx.addAttachment(attachment);
57
+ const prepare = host.prepareHorizontal;
58
+ host.prepareHorizontal = line => {
59
+ prepare?.call(host, line);
60
+ if (line.columnOf(host) < 0)
61
+ return;
62
+ line.registerHorizontalLayoutHook(host, host, ({ columns, start }) => {
63
+ const pre = this.side === "pre";
64
+ const edge = pre ? "WL" : "WR";
65
+ const inset = pre ? host.box.anchor : host.box.w - host.box.anchor;
66
+ const space = inset + attachment.length + host.ast.size * 0.22;
67
+ // 只扩大宿主的求解占位,重复记号不累加,原始盒子保持不变
68
+ for (const element of columns[start]) {
69
+ if (element.box !== host.box)
70
+ continue;
71
+ element[edge] = Math.max(element[edge], space);
72
+ }
73
+ });
74
+ };
75
+ return [];
76
+ }
77
+ toString(source) {
78
+ return `@slide(${this.content.toString(source)}, side=${this.side}, direction=${this.direction})`;
79
+ }
80
+ }
81
+ export const SlideNode = SlideFunction;
82
+ class SlideAttachment {
83
+ host;
84
+ owner;
85
+ layer = "foreground";
86
+ endPoints;
87
+ get sourceSpan() { return this.owner.sourceSpan; }
88
+ constructor(host, owner) {
89
+ this.host = host;
90
+ this.owner = owner;
91
+ this.endPoints = [host];
92
+ }
93
+ get length() {
94
+ const { host } = this;
95
+ return host.box.visualAxis - (host.ports["shoulder"]?.y ?? 0) + host.ast.size * 0.1;
96
+ }
97
+ createGeometry() {
98
+ const { host, owner } = this;
99
+ const size = host.ast.size;
100
+ const pre = owner.side === "pre";
101
+ const length = this.length;
102
+ const up = owner.direction === "up";
103
+ const bottom = host.box.y + host.box.visualAxis;
104
+ const left = pre ? host.box.x - size * 0.12 - length : host.box.x + host.box.w + size * 0.12;
105
+ // 下端在中心线,上端略高于数字顶端,45°
106
+ const start = { x: left, y: up ? bottom : bottom - length };
107
+ const end = { x: left + length, y: up ? bottom - length : bottom };
108
+ const angle = up ? -Math.PI / 4 : Math.PI / 4;
109
+ const wing = (offset) => ({
110
+ x: end.x - size * 0.25 * Math.cos(angle + offset),
111
+ y: end.y - size * 0.25 * Math.sin(angle + offset),
112
+ });
113
+ const commands = [
114
+ { op: "M", ...start }, { op: "L", ...end },
115
+ { op: "M", ...wing(-Math.PI / 6) }, { op: "L", ...end },
116
+ { op: "L", ...wing(Math.PI / 6) },
117
+ ];
118
+ const strokeWidth = size * 0.05;
119
+ const bounds = pathBounds(commands);
120
+ const region = {
121
+ x: bounds.x - strokeWidth / 2, y: bounds.y - strokeWidth / 2,
122
+ w: bounds.w + strokeWidth, h: bounds.h + strokeWidth,
123
+ line: host.layoutLine, track: host.track,
124
+ };
125
+ return {
126
+ regions: [region],
127
+ paint(painter) {
128
+ painter.drawPath(commands, { fill: "none", stroke: "#000", strokeWidth });
129
+ },
130
+ };
131
+ }
132
+ }
@@ -142,30 +142,23 @@ class StackFunction extends ASTFunctionNode {
142
142
  }
143
143
  }
144
144
  }
145
- /** 遇到另一个 stack 就展平;返回存活的那个,调用者必须改用返回值 */
145
+ /** 遇到另一个 stack 就展平;接收者存活,被吞并的成员列表最后清空 */
146
146
  addContent(node) {
147
- if (node instanceof StackFunction)
148
- return this.combine(node);
149
- this.contents.push(node);
150
- node.parent = this;
147
+ const contents = node instanceof StackFunction ? node.contents : [node];
151
148
  const s = node.sourceSpan;
152
149
  this.sourceSpan.start = Math.min(this.sourceSpan.start, s.start);
153
150
  this.sourceSpan.end = Math.max(this.sourceSpan.end, s.end);
151
+ for (const c of contents)
152
+ c.parent = this;
153
+ this.contents.push(...contents);
154
+ // stack 不实现 labelable、不进候选表,所以被吞并的空壳不会被 @tie() 取到,无需像 up 那样撤销登记
155
+ if (node instanceof StackFunction)
156
+ node.contents.length = 0;
154
157
  return this;
155
158
  }
156
159
  toString(source) {
157
160
  const contentStrs = this.contents.map(c => c.toString(source)).join(',\n');
158
161
  return `@stack(\n ${contentStrs.split('\n').join('\n ')}\n)`;
159
162
  }
160
- // stack 不实现 labelable、不进候选表,所以被吞并的空壳不会被 @tie() 取到,无需像 up 那样撤销登记
161
- combine(ano) {
162
- this.sourceSpan.start = Math.min(this.sourceSpan.start, ano.sourceSpan.start);
163
- this.sourceSpan.end = Math.max(this.sourceSpan.end, ano.sourceSpan.end);
164
- for (const c of ano.contents)
165
- c.parent = this;
166
- this.contents.push(...ano.contents);
167
- ano.contents.length = 0;
168
- return this;
169
- }
170
163
  }
171
164
  export const StackNode = StackFunction;