jpfun 0.5.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 (79) 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/ASTtypes.d.ts +4 -0
  9. package/dist/functions/ASTtypes.js +25 -14
  10. package/dist/functions/adjust/index.js +6 -2
  11. package/dist/functions/arpeggio/index.js +21 -17
  12. package/dist/functions/arpeggio/shape.d.ts +1 -1
  13. package/dist/functions/arpeggio/shape.js +27 -21
  14. package/dist/functions/bar/index.js +37 -36
  15. package/dist/functions/beam/auto.js +18 -24
  16. package/dist/functions/beam/layout.js +15 -23
  17. package/dist/functions/box/index.js +52 -1
  18. package/dist/functions/br/index.js +3 -4
  19. package/dist/functions/default.js +10 -5
  20. package/dist/functions/div/index.js +2 -3
  21. package/dist/functions/gliss/index.d.ts +2 -0
  22. package/dist/functions/gliss/index.js +180 -0
  23. package/dist/functions/grace/index.d.ts +4 -2
  24. package/dist/functions/grace/index.js +19 -11
  25. package/dist/functions/head/index.js +50 -62
  26. package/dist/functions/meter/index.js +45 -24
  27. package/dist/functions/meter/shape.d.ts +3 -0
  28. package/dist/functions/meter/shape.js +43 -0
  29. package/dist/functions/note/accidentals.js +10 -16
  30. package/dist/functions/note/index.js +38 -48
  31. package/dist/functions/ottava/index.d.ts +2 -0
  32. package/dist/functions/ottava/index.js +217 -0
  33. package/dist/functions/page/index.js +3 -3
  34. package/dist/functions/pagebreak/index.d.ts +2 -0
  35. package/dist/functions/pagebreak/index.js +36 -0
  36. package/dist/functions/rest/index.d.ts +2 -0
  37. package/dist/functions/rest/index.js +231 -0
  38. package/dist/functions/slide/index.d.ts +2 -0
  39. package/dist/functions/slide/index.js +132 -0
  40. package/dist/functions/stack/index.js +8 -15
  41. package/dist/functions/symbol/index.d.ts +9 -0
  42. package/dist/functions/symbol/index.js +41 -12
  43. package/dist/functions/symbol/ornament.js +15 -20
  44. package/dist/functions/symbol/shape.js +4 -1
  45. package/dist/functions/symbol/symbols/fine.js +1 -1
  46. package/dist/functions/symbol/symbols/tr.js +46 -1
  47. package/dist/functions/temporal.d.ts +36 -12
  48. package/dist/functions/temporal.js +29 -9
  49. package/dist/functions/tie/index.js +46 -32
  50. package/dist/functions/tuplet/index.js +1 -1
  51. package/dist/functions/up/index.js +51 -33
  52. package/dist/functions/voice/connections.d.ts +19 -0
  53. package/dist/functions/voice/connections.js +90 -0
  54. package/dist/functions/voice/index.js +245 -99
  55. package/dist/functions/volta/index.js +41 -21
  56. package/dist/jpfun.core.min.js +48 -55
  57. package/dist/jpfun.from-midi.min.js +5 -5
  58. package/dist/jpfun.from-musicxml.min.js +8 -8
  59. package/dist/jpfun.min.js +57 -64
  60. package/dist/layout/engine.d.ts +4 -1
  61. package/dist/layout/engine.js +232 -75
  62. package/dist/layout/model.js +22 -66
  63. package/dist/layout/page.d.ts +3 -2
  64. package/dist/layout/page.js +7 -6
  65. package/dist/layout/types.d.ts +34 -45
  66. package/dist/lowering/loweringContext.d.ts +1 -1
  67. package/dist/lowering/loweringContext.js +41 -171
  68. package/dist/parser/parserContext.d.ts +2 -0
  69. package/dist/parser/parserContext.js +31 -14
  70. package/dist/parser/preprocess.js +4 -6
  71. package/dist/playback/compile.js +12 -3
  72. package/dist/playback/types.d.ts +4 -2
  73. package/dist/render/paint.js +1 -1
  74. package/dist/render/svg.js +1 -0
  75. package/dist/render/text.d.ts +1 -1
  76. package/dist/render/text.js +3 -2
  77. package/dist/render/types.d.ts +1 -0
  78. package/grammar.md +221 -257
  79. package/package.json +1 -1
@@ -0,0 +1,231 @@
1
+ import { ErrorDiagnostic } from "../../diagnostic.js";
2
+ import { Fraction } from "../../fraction.js";
3
+ import { ASTFunctionNode, ASTNodeBase, } from "../ASTtypes.js";
4
+ import { ANCHOR_KEY, isVisualTemporalNode, TemporalNodeBase } from "../temporal.js";
5
+ // 同刻状态先固化,休止只与休止合列,普通音符随后进入
6
+ const REST_KEY = Number.MAX_VALUE;
7
+ const restsByHost = new WeakMap();
8
+ class RestFunction extends ASTFunctionNode {
9
+ static def = {
10
+ name: ["rest"],
11
+ description: "多小节休止",
12
+ details: `\
13
+ ~~~jpfun
14
+ @meter(4,4) | @rest(19) |
15
+ ~~~
16
+ 使用当前拍号产生 19 个整小节的静音(必须先声明拍号)`,
17
+ allowExtraArgs: false,
18
+ args: [
19
+ {
20
+ name: "n",
21
+ description: "休止的小节数",
22
+ type: "number",
23
+ default: 1
24
+ },
25
+ {
26
+ name: "width",
27
+ description: "横线的最小宽度",
28
+ type: "length",
29
+ default: { value: 3, unit: "em" }
30
+ },
31
+ {
32
+ name: "size",
33
+ description: "数字字号与笔画尺寸",
34
+ type: "length",
35
+ default: { value: 1, unit: "em" }
36
+ },
37
+ ],
38
+ };
39
+ count;
40
+ width;
41
+ size;
42
+ font;
43
+ constructor(span, args, ctx, parent = null) {
44
+ super(span, parent);
45
+ const [count, width, size] = this.getArgValue(args, ctx);
46
+ if (!Number.isSafeInteger(count) || count <= 0 || count > 0xffffffff) {
47
+ throw new ErrorDiagnostic("E_REST_COUNT", "@rest 的 n 必须是正安全整数,且小节线数量可由数组表示", span);
48
+ }
49
+ this.count = count;
50
+ this.width = ctx.length2px(width);
51
+ this.size = ctx.length2px(size);
52
+ if (!Number.isFinite(this.width) || this.width < 0 || !Number.isFinite(this.size) || this.size <= 0) {
53
+ throw new ErrorDiagnostic("E_REST_SIZE", "@rest 的 width 必须有限且非负,size 必须有限且为正", span);
54
+ }
55
+ this.font = ctx.variables.numberfont;
56
+ }
57
+ // 可以被 volta 这样的标记
58
+ labelable() { return this; }
59
+ loweringEnter() {
60
+ return [new RestTemporal(this)];
61
+ }
62
+ static loweringFinalize(result) {
63
+ // 没有全局休止列时,跳过索引扫描和边界补入
64
+ if (!result.columns.some(column => column.some(node => node.mergeKey === REST_KEY)))
65
+ return;
66
+ let order = 0;
67
+ const onsets = new Map();
68
+ // 扫描完整来源索引,纳入未直接出现在时间列中的折叠成员
69
+ for (const nodes of result.astToTemporal.values()) {
70
+ // 为新增边界预留唯一 order,并记录各宿主的最早音符
71
+ for (const node of nodes) {
72
+ order = Math.max(order, node.order + 1);
73
+ if (!(node.ast instanceof ASTFunctionNode)
74
+ || (node.ast.callName !== "note" && node.ast.callName !== "dash"))
75
+ continue;
76
+ let host = node;
77
+ // 沿折叠链找到最外层宿主,将内部成员归到同一主体
78
+ while (host.foldedInto)
79
+ host = host.foldedInto;
80
+ // 私有倚音属于独立轨道,不代表外层宿主的休止或起音
81
+ if (node.track !== host.track)
82
+ continue;
83
+ const onset = onsets.get(host);
84
+ if (!onset || node.order < onset.order)
85
+ onsets.set(host, node);
86
+ }
87
+ }
88
+ const columns = [];
89
+ const previous = new Map();
90
+ // 保留原时间列,并在休止列后追加其内部小节边界
91
+ for (const column of result.columns) {
92
+ columns.push(column);
93
+ let longest;
94
+ // 检查各轨是否用增时线延续休止,同时选出同列最长休止
95
+ for (const node of column) {
96
+ if (node.T.compare(0) > 0) {
97
+ const onset = onsets.get(node);
98
+ const before = previous.get(node.track);
99
+ if (before && restsByHost.has(before)
100
+ && onset?.ast instanceof ASTFunctionNode && onset.ast.callName === "dash") {
101
+ throw new ErrorDiagnostic("E_REST_SUSTAIN", "增时线不能延续整小节休止", onset.ast.sourceSpan);
102
+ }
103
+ previous.set(node.track, node);
104
+ }
105
+ const rest = restsByHost.get(node);
106
+ if (rest && (!longest || rest.T.compare(longest.T) > 0))
107
+ longest = rest;
108
+ }
109
+ if (!longest)
110
+ continue;
111
+ const time = longest.t.clone();
112
+ // 按小节时长补入 n−1 个不可见边界;时间已固化,不再参与声部归并
113
+ for (let index = 1; index < longest.ast.count; index++) {
114
+ time.add(longest.measureDuration);
115
+ const boundary = new TemporalNodeBase();
116
+ boundary.ast = new ASTNodeBase(longest.ast.sourceSpan, longest.ast);
117
+ boundary.t.copyFrom(time);
118
+ boundary.track = longest.track;
119
+ boundary.layoutLine = longest.layoutLine;
120
+ boundary.order = order++;
121
+ boundary.mergeKey = ANCHOR_KEY;
122
+ result.astToTemporal.set(boundary.ast, [boundary]);
123
+ columns.push([boundary]);
124
+ }
125
+ }
126
+ result.columns = columns;
127
+ }
128
+ toString() { return `@rest(${this.count})`; }
129
+ }
130
+ export const RestNode = RestFunction;
131
+ class RestTemporal extends TemporalNodeBase {
132
+ measureDuration = new Fraction();
133
+ metrics;
134
+ lineWidth = 0;
135
+ textStyle;
136
+ constructor(ast) {
137
+ super();
138
+ this.ast = ast;
139
+ this.mergeKey = REST_KEY;
140
+ restsByHost.set(this, this);
141
+ this.initLayoutBox();
142
+ this.textStyle = { fontSize: ast.size, fontFamily: ast.font, textAlign: "center" };
143
+ }
144
+ onTimeState(state) {
145
+ const measure = state.meter;
146
+ if (!(measure instanceof Fraction)) {
147
+ throw new ErrorDiagnostic("E_REST_METER", "整小节休止前必须有实际生效的显式拍号", this.ast.sourceSpan);
148
+ }
149
+ if (!Number.isSafeInteger(measure.numerator * this.ast.count)) {
150
+ throw new ErrorDiagnostic("E_REST_COUNT", "@rest 的总时值超出精确整数范围", this.ast.sourceSpan);
151
+ }
152
+ this.measureDuration.copyFrom(measure);
153
+ this.T.copyFrom(measure).mul(this.ast.count);
154
+ const host = state.currentEvent ?? this;
155
+ // 只登记全局休止宿主的同轨成员,私有倚音不接管宿主。
156
+ if (host.mergeKey === REST_KEY && this.track === host.track) {
157
+ const rest = restsByHost.get(host);
158
+ if (!rest || this.order < rest.order)
159
+ restsByHost.set(host, this);
160
+ }
161
+ this.playbackState = { bpm: state.bpm };
162
+ return this.T;
163
+ }
164
+ emitPlayback(emitter) {
165
+ emitter.span({ start: emitter.start, end: emitter.end });
166
+ }
167
+ prepareLayout(context) {
168
+ const size = this.ast.size;
169
+ // 抵消布局器的时长平方根缩放,左右弹簧自然长度固定为 6px
170
+ const alpha = 6 / Math.sqrt(this.T.toNumber());
171
+ this.springConfig = { alpha_L: alpha, alpha_R: alpha };
172
+ this.metrics = context.textMeasurer.measureText(String(this.ast.count), this.textStyle);
173
+ this.lineWidth = Math.max(this.ast.width, this.metrics.w + size * 0.5);
174
+ this.box.w = this.lineWidth + size * 0.25;
175
+ this.box.h = this.metrics.h + size * 0.5;
176
+ this.box.anchor = size * 0.4;
177
+ this.box.visualAxis = this.box.h - size * 0.65 / 2;
178
+ }
179
+ prepareHorizontal(line) {
180
+ let host = this;
181
+ // 向外寻找实际占据布局列的宿主,让被包装的休止也能注册横向约束
182
+ while (line.columnOf(host) < 0 && host.foldedInto && isVisualTemporalNode(host.foldedInto))
183
+ host = host.foldedInto;
184
+ const column = line.columnOf(host);
185
+ if (column < 0)
186
+ return;
187
+ const barAt = (index) => line.columns[index]?.find(node => node.track === host.track && node.mergeKey === ANCHOR_KEY) ?? host;
188
+ const first = barAt(column - 1);
189
+ const last = barAt(column + 1);
190
+ if (first === last)
191
+ return;
192
+ line.registerHorizontalLayoutHook(first, last, ({ columns, rows, start, end, X, fixed }) => {
193
+ // 锁定休止及相邻小节线之间的列间距,撑满行宽时也不拉开
194
+ for (let i = start; i < end; i++) {
195
+ if (fixed[i])
196
+ continue;
197
+ let distance = 0;
198
+ // 取所有声部所需间距的最大值,避免压紧休止时造成其他声部交叠
199
+ for (let row = 0; row < rows; row++) {
200
+ const left = columns[i][row];
201
+ const right = columns[i + 1][row];
202
+ // 右侧留隙已在休止盒内,只给左侧补同样的墨迹间距
203
+ const rest = restsByHost.get(right.time);
204
+ const gap = rest ? rest.ast.size * 0.25 : 0;
205
+ distance = Math.max(distance, left.WR + right.WL + gap);
206
+ }
207
+ const shift = X[i] + distance - X[i + 1];
208
+ // 平移右侧已锁定的块及其末列,保留连续休止先前确定的间隙
209
+ for (let j = i + 1; j < X.length; j++) {
210
+ X[j] += shift;
211
+ if (!fixed[j])
212
+ break;
213
+ }
214
+ fixed[i] = 1;
215
+ }
216
+ });
217
+ }
218
+ paint(painter) {
219
+ const { size, count } = this.ast;
220
+ const left = this.box.x;
221
+ const right = left + this.lineWidth;
222
+ const axis = this.box.y + this.box.visualAxis;
223
+ const stroke = size * 0.12;
224
+ const barStroke = stroke * 2;
225
+ const halfCap = (size * 0.65 - stroke) / 2;
226
+ painter.drawLine(left + barStroke / 2, axis, right - barStroke / 2, axis, { strokeWidth: barStroke });
227
+ painter.drawLine(left + stroke / 2, axis - halfCap, left + stroke / 2, axis + halfCap, { strokeWidth: stroke });
228
+ painter.drawLine(right - stroke / 2, axis - halfCap, right - stroke / 2, axis + halfCap, { strokeWidth: stroke });
229
+ painter.drawText(String(count), left + this.lineWidth / 2, this.box.y + this.metrics.baseline, this.textStyle);
230
+ }
231
+ }
@@ -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;
@@ -1,5 +1,6 @@
1
1
  import { type TimeState } from "../temporal.js";
2
2
  import type { PlaybackCursor, PlaybackEmitter, PlaybackFlowAction } from "../../playback/types.js";
3
+ import type { TextStyle } from "../../render/types.js";
3
4
  import { type ASTFunctionClass } from "../ASTtypes.js";
4
5
  import { type SymbolShape } from "./shape.js";
5
6
  /**
@@ -10,17 +11,25 @@ import { type SymbolShape } from "./shape.js";
10
11
  export interface SymbolDefinition {
11
12
  readonly name: string;
12
13
  readonly description: string;
14
+ /** 查表未命中时使用;忽略大小写,从名称开头匹配,不允许 g/y */
15
+ readonly pattern?: {
16
+ readonly regex: RegExp;
17
+ readonly resolve: (match: RegExpExecArray) => SymbolDefinition;
18
+ };
13
19
  /** 固定图形;文字记号改用 text */
14
20
  readonly shapes?: readonly SymbolShape[];
15
21
  /** 交给宿主字体绘制的文字记号,与 shapes 二选一 */
16
22
  readonly text?: {
17
23
  readonly content: string;
18
24
  readonly fontFamily: string;
25
+ readonly fontStyle?: TextStyle["fontStyle"];
19
26
  };
20
27
  /** 符号高度 = size × weight,用来修正宽扁字形的视觉重量;默认 1 */
21
28
  readonly weight?: number;
22
29
  /** 图形下方留白,使用符号自身坐标并随 scale 缩放;默认 0 */
23
30
  readonly paddingBottom?: number;
31
+ /** 横向对齐点,使用符号自身坐标;默认采用完整图形的中心 */
32
+ readonly anchor?: number;
24
33
  /** 写入本位置之后持续生效的状态,例如力度记号的 velocity */
25
34
  readonly onTimeState?: (state: TimeState) => void;
26
35
  /** 发布系统控制,或注册对同一折叠序列后续音符的局部变换 */
@@ -12,9 +12,23 @@ import { mordentSymbol } from "./symbols/mordent.js";
12
12
  import { prallSymbol } from "./symbols/prall.js";
13
13
  import { segnoSymbol } from "./symbols/segno.js";
14
14
  import { trSymbol } from "./symbols/tr.js";
15
- const symbolTable = new Map([trSymbol, fermataSymbol, prallSymbol, mordentSymbol, accentSymbol, ...dynamicSymbols,
16
- dcSymbol, dsSymbol, segnoSymbol, fineSymbol]
17
- .map(definition => [definition.name.toLowerCase(), definition]));
15
+ const symbolTable = new Map();
16
+ const symbolPatterns = [];
17
+ for (const definition of [trSymbol, fermataSymbol, prallSymbol, mordentSymbol, accentSymbol,
18
+ ...dynamicSymbols, dcSymbol, dsSymbol, segnoSymbol, fineSymbol]) {
19
+ const name = definition.name.toLowerCase();
20
+ if (symbolTable.has(name))
21
+ throw new Error(`Duplicate symbol name: ${definition.name}`);
22
+ symbolTable.set(name, definition);
23
+ const pattern = definition.pattern;
24
+ if (!pattern)
25
+ continue;
26
+ const { regex } = pattern;
27
+ if (regex.global || regex.sticky)
28
+ throw new Error(`Symbol pattern must not use g or y flags: ${name}`);
29
+ symbolPatterns.push(regex.ignoreCase ? pattern
30
+ : { ...pattern, regex: new RegExp(regex.source, `${regex.flags}i`) });
31
+ }
18
32
  class SymbolFunction extends ASTFunctionNode {
19
33
  static def = {
20
34
  name: ["symbol", "$"],
@@ -23,7 +37,7 @@ class SymbolFunction extends ASTFunctionNode {
23
37
  ~~~jpfun
24
38
  1 ^ @symbol(p, size=0.5em)
25
39
  ~~~
26
- **简写**:\`$name\`,如 \`1 ^ $p\`
40
+ **简写**:\`$name\`,如 \`1 ^ $p\`。名称读取到下一个空白或当前内容区间末尾,连续的标点也属于名称。
27
41
 
28
42
  **内置记号**
29
43
  ${[...symbolTable.values()].map(item => `- \`$${item.name}\`:${item.description}`).join("\n")}`,
@@ -44,12 +58,12 @@ ${[...symbolTable.values()].map(item => `- \`$${item.name}\`:${item.descriptio
44
58
  ],
45
59
  };
46
60
  static deSugarAtom(source, start, end) {
47
- if (source[start] !== "$" || !/[A-Za-z]/.test(source[start + 1] ?? ""))
61
+ if (source[start] !== "$")
62
+ return null;
63
+ const name = /^\S+/.exec(source.slice(start + 1, end))?.[0];
64
+ if (!name)
48
65
  return null;
49
- let next = start + 2;
50
- while (next < end && /[A-Za-z0-9_-]/.test(source[next]))
51
- next++;
52
- const name = source.slice(start + 1, next);
66
+ const next = start + 1 + name.length;
53
67
  const node = {
54
68
  kind: "call",
55
69
  typed: true,
@@ -66,7 +80,20 @@ ${[...symbolTable.values()].map(item => `- \`$${item.name}\`:${item.descriptio
66
80
  super(sourceSpan, parent);
67
81
  const [name, size] = this.getArgValue(args, ctx);
68
82
  this.size = ctx.length2px(size);
69
- const definition = symbolTable.get(name.toLowerCase());
83
+ const normalized = name.toLowerCase();
84
+ let definition = symbolTable.get(normalized);
85
+ if (!definition) {
86
+ let matched;
87
+ for (const pattern of symbolPatterns) {
88
+ const match = pattern.regex.exec(normalized);
89
+ if (!match || match.index !== 0 || match[0] !== normalized)
90
+ continue;
91
+ if (matched)
92
+ throw new Error(`Ambiguous symbol patterns: ${normalized}`);
93
+ matched = { pattern, match };
94
+ }
95
+ definition = matched?.pattern.resolve(matched.match);
96
+ }
70
97
  if (!definition) {
71
98
  const message = `@symbol: 未知符号: $${name}`;
72
99
  if (ctx.variables.strict)
@@ -107,7 +134,7 @@ class SymbolTemporal extends TemporalNodeBase {
107
134
  // 文字记号的字号也是 size × weight,所以与图形记号视觉等高
108
135
  this.label = text && {
109
136
  content: text.content,
110
- style: { fontSize: this.height, fontFamily: text.fontFamily },
137
+ style: { fontSize: this.height, fontFamily: text.fontFamily, fontStyle: text.fontStyle },
111
138
  };
112
139
  this.initLayoutBox();
113
140
  }
@@ -123,7 +150,9 @@ class SymbolTemporal extends TemporalNodeBase {
123
150
  this.box.w = this.bounds.w * this.scale;
124
151
  this.box.h = this.height + (this.ast.definition.paddingBottom ?? 0) * this.scale;
125
152
  }
126
- this.box.anchor = this.box.w / 2;
153
+ this.box.anchor = !this.label && this.ast.definition.anchor !== undefined
154
+ ? (this.ast.definition.anchor - this.bounds.x) * this.scale
155
+ : this.box.w / 2;
127
156
  this.box.visualAxis = this.box.h / 2;
128
157
  }
129
158
  paint(painter) {
@@ -22,14 +22,22 @@ export function ornament(pattern) {
22
22
  continue;
23
23
  }
24
24
  const duration = note.end.clone().sub(note.start);
25
- // 此处读取最终速度,结构延长和其他声部的速度效果都已计入。
26
- const bpm = context.stateAt(note.start).effectiveBpm;
27
- const steps = pattern.repeat ? repeatToFill(pattern.body, duration.toNumber(), bpm) : pattern.body;
28
- const step = duration.div(steps.length);
25
+ let count = pattern.body.length;
26
+ if (pattern.repeat) {
27
+ // 此处读取最终速度,结构延长和其他声部的速度效果都已计入。
28
+ const bpm = context.stateAt(note.start).effectiveBpm;
29
+ // 名义密度与速度无关(秒数里的 bpm 与频率里的 bpm 恰好抵消),只在 bpm 越界时按比例修正
30
+ const ratio = Math.min(MAX_BPM, Math.max(MIN_BPM, bpm)) / bpm;
31
+ // 预算按完整音型计算,避免在达到子音上限时留下半个音型。
32
+ const limit = Math.floor(MAX_SUBNOTES / pattern.body.length);
33
+ const cycles = Math.min(limit, Math.max(1, Math.round(duration.toNumber() * NOMINAL_RATE * ratio / pattern.body.length)));
34
+ count *= cycles;
35
+ }
36
+ const step = duration.div(count);
29
37
  // 用 Fraction 等分最终区间,保证首尾边界准确且不会积累浮点时间误差。
30
- for (let index = 0; index < steps.length; index++) {
31
- const offset = steps[index];
32
- const start = note.start.clone().add(step.clone().mul(index));
38
+ for (let index = 0; index < count; index++) {
39
+ const offset = pattern.body[index % pattern.body.length];
40
+ const start = step.clone().mul(index).add(note.start);
33
41
  result.push({
34
42
  ...note,
35
43
  start,
@@ -44,16 +52,3 @@ export function ornament(pattern) {
44
52
  return result;
45
53
  };
46
54
  }
47
- /** 按最终速度计算完整音型的重复次数,并限制总子音数 */
48
- function repeatToFill(body, duration, bpm) {
49
- // 名义密度与速度无关(秒数里的 bpm 与频率里的 bpm 恰好抵消),只在 bpm 越界时按比例修正
50
- const ratio = Math.min(MAX_BPM, Math.max(MIN_BPM, bpm)) / bpm;
51
- // 预算按完整音型计算,避免在达到子音上限时留下半个音型。
52
- const limit = Math.floor(MAX_SUBNOTES / body.length);
53
- const cycles = Math.min(limit, Math.max(1, Math.round(duration * NOMINAL_RATE * ratio / body.length)));
54
- const result = [];
55
- // 先得到完整音级序列,调用方再按实际子音总数统一分配宿主时值。
56
- for (let i = 0; i < cycles; i++)
57
- result.push(...body);
58
- return result;
59
- }
@@ -6,6 +6,8 @@
6
6
  * 否则墨迹会偏出框——符号原点不一定落在墨迹左上角。
7
7
  */
8
8
  import { pathBounds } from "../../layout/path.js";
9
+ // 固定字形路径不可原地修改;共享路径的重复片段只求一次曲线极值
10
+ const pathBoundsCache = new WeakMap();
9
11
  /** 全体图元的并集;宽高钳到正数,否则纯横线或纯竖线的符号会让缩放比例除零 */
10
12
  export function symbolBounds(shapes) {
11
13
  let left = Infinity;
@@ -25,7 +27,8 @@ export function symbolBounds(shapes) {
25
27
  merge(cx + dx - r, cy - r, 2 * r, 2 * r);
26
28
  }
27
29
  if (shape.path?.length) {
28
- const rect = pathBounds(shape.path);
30
+ const rect = pathBoundsCache.get(shape.path) ?? pathBounds(shape.path);
31
+ pathBoundsCache.set(shape.path, rect);
29
32
  merge(rect.x + dx, rect.y, rect.w, rect.h);
30
33
  }
31
34
  }
@@ -3,7 +3,7 @@ export const fineSymbol = {
3
3
  name: "fine",
4
4
  description: "终止记号:回跳之后经过这里就结束乐曲",
5
5
  weight: 1.4,
6
- text: { content: "Fine.", fontFamily: '"Times New Roman", serif' },
6
+ text: { content: "Fine.", fontFamily: '"Times New Roman", serif', fontStyle: "italic" },
7
7
  // 判据是回跳已经发生,不是“第二次经过”;否则写在 |: :| 里会被反复线提前触发
8
8
  onVisit: (cursor, at) => {
9
9
  const jump = cursor.seek(JUMP_MARK, at, 1);
@@ -1,7 +1,18 @@
1
+ import { symbolBounds } from "../shape.js";
1
2
  import { ornament } from "../ornament.js";
2
3
  export const trSymbol = {
3
4
  name: "tr",
4
- description: "颤音:本音与调内上方二度交替",
5
+ description: '颤音:本音与调内上方二度交替。可写为 `$tr++`,每个紧接的 `+` 添加一截波浪尾巴',
6
+ pattern: {
7
+ regex: /^tr(\++)/,
8
+ resolve: match => {
9
+ const shapes = [...trSymbol.shapes];
10
+ for (let i = 0; i < match[1].length; i++) {
11
+ shapes.push({ ...tailShape, dx: 14.11212 + i * 5.95219 });
12
+ }
13
+ return { ...trSymbol, name: match[0], anchor: trAnchor, shapes };
14
+ },
15
+ },
5
16
  shapes: [
6
17
  {
7
18
  path: [
@@ -69,3 +80,37 @@ export const trSymbol = {
69
80
  ],
70
81
  emitPlayback: emitter => emitter.affectFollowing(ornament({ body: [0, 1], repeat: true })),
71
82
  };
83
+ const trBounds = symbolBounds(trSymbol.shapes);
84
+ const trAnchor = trBounds.x + trBounds.w / 2;
85
+ // MuseScore 导出的 TrillSegment,按 tr 字形高度归一化,保留片段之间的重叠。
86
+ const tailShape = {
87
+ path: [
88
+ { op: "M", x: 7.03619, y: 4.89762 },
89
+ { op: "C", cx1: 7.03619, cy1: 4.89762, cx2: 6.87351, cy2: 4.70878, x: 6.65687, y: 4.5183 },
90
+ { op: "C", cx1: 6.57594, cy1: 4.43737, cx2: 6.46721, cy2: 4.41039, x: 6.38546, y: 4.41039 },
91
+ { op: "C", cx1: 6.30535, cy1: 4.41039, cx2: 6.25058, cy2: 4.43737, x: 6.19662, y: 4.49132 },
92
+ { op: "L", x: 5.89905, y: 4.78889 },
93
+ { op: "C", cx1: 5.8451, cy1: 4.84367, cx2: 5.79033, cy2: 4.87064, x: 5.73719, y: 4.87064 },
94
+ { op: "C", cx1: 5.62846, cy1: 4.87064, cx2: 5.57451, cy2: 4.78889, x: 5.57451, y: 4.78889 },
95
+ { op: "C", cx1: 5.57451, cy1: 4.78889, cx2: 3.84223, cy2: 3.30105, x: 3.57164, y: 3.05662 },
96
+ { op: "C", cx1: 3.27407, cy1: 2.8408, cx2: 2.9765, cy2: 2.75905, x: 2.70591, y: 2.75905 },
97
+ { op: "C", cx1: 2.13857, cy1: 2.75905, cx2: 1.62355, cy2: 3.08523, x: 1.40773, y: 3.32721 },
98
+ { op: "L", x: 0.10873, y: 4.62703 },
99
+ { op: "C", cx1: 0.02698, cy1: 4.70878, cx2: 0, cy2: 4.76192, x: 0, y: 4.84367 },
100
+ { op: "C", cx1: 0, cy1: 4.97773, cx2: 0.10873, cy2: 5.08646, x: 0.10873, y: 5.08646 },
101
+ { op: "C", cx1: 0.10873, cy1: 5.08646, cx2: 0.27141, cy2: 5.2753, x: 0.48723, y: 5.46578 },
102
+ { op: "C", cx1: 0.56898, cy1: 5.54671, cx2: 0.64909, cy2: 5.57451, x: 0.73084, y: 5.57451 },
103
+ { op: "C", cx1: 0.81259, cy1: 5.57451, cx2: 0.86655, cy2: 5.54671, x: 0.91968, y: 5.49276 },
104
+ { op: "L", x: 1.21725, y: 5.19519 },
105
+ { op: "C", cx1: 1.27284, cy1: 5.14123, cx2: 1.32598, cy2: 5.11344, x: 1.37993, y: 5.11344 },
106
+ { op: "C", cx1: 1.48866, cy1: 5.11344, cx2: 1.57041, cy2: 5.19519, x: 1.57041, y: 5.19519 },
107
+ { op: "C", cx1: 1.57041, cy1: 5.19519, cx2: 3.30105, cy2: 6.65605, x: 3.57164, y: 6.89885 },
108
+ { op: "C", cx1: 3.86921, cy1: 7.1163, cx2: 4.16678, cy2: 7.19805, x: 4.43819, y: 7.19805 },
109
+ { op: "C", cx1: 5.00635, cy1: 7.19805, cx2: 5.51973, cy2: 6.87187, x: 5.73719, y: 6.62989 },
110
+ { op: "L", x: 7.03619, y: 5.33008 },
111
+ { op: "C", cx1: 7.1163, cy1: 5.24833, cx2: 7.1441, cy2: 5.16821, x: 7.1441, y: 5.11344 },
112
+ { op: "C", cx1: 7.1441, cy1: 4.97773, cx2: 7.03619, cy2: 4.89762, x: 7.03619, y: 4.89762 },
113
+ { op: "Z" },
114
+ ],
115
+ style: { fill: "#000" },
116
+ };