jpfun 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/converter/midi/convert.d.ts +3 -1
  2. package/dist/converter/midi/convert.js +78 -66
  3. package/dist/converter/musicxml/features.d.ts +19 -5
  4. package/dist/converter/musicxml/features.js +46 -8
  5. package/dist/converter/musicxml/index.js +142 -23
  6. package/dist/converter/musicxml/model.d.ts +15 -0
  7. package/dist/diagnostic.js +1 -1
  8. package/dist/functions/arpeggio/index.js +2 -5
  9. package/dist/functions/arpeggio/shape.d.ts +1 -1
  10. package/dist/functions/arpeggio/shape.js +27 -21
  11. package/dist/functions/bar/index.js +37 -36
  12. package/dist/functions/beam/auto.js +16 -13
  13. package/dist/functions/beam/layout.js +15 -23
  14. package/dist/functions/br/index.js +3 -4
  15. package/dist/functions/default.js +8 -4
  16. package/dist/functions/gliss/index.d.ts +2 -0
  17. package/dist/functions/gliss/index.js +180 -0
  18. package/dist/functions/grace/index.js +3 -6
  19. package/dist/functions/head/index.js +40 -59
  20. package/dist/functions/meter/index.js +19 -18
  21. package/dist/functions/note/accidentals.js +10 -16
  22. package/dist/functions/note/index.js +13 -3
  23. package/dist/functions/ottava/index.d.ts +2 -0
  24. package/dist/functions/ottava/index.js +217 -0
  25. package/dist/functions/page/index.js +3 -3
  26. package/dist/functions/pagebreak/index.d.ts +2 -0
  27. package/dist/functions/pagebreak/index.js +36 -0
  28. package/dist/functions/rest/index.js +12 -14
  29. package/dist/functions/slide/index.d.ts +2 -0
  30. package/dist/functions/slide/index.js +132 -0
  31. package/dist/functions/stack/index.js +8 -15
  32. package/dist/functions/symbol/index.d.ts +9 -0
  33. package/dist/functions/symbol/index.js +41 -12
  34. package/dist/functions/symbol/ornament.js +14 -19
  35. package/dist/functions/symbol/shape.js +4 -1
  36. package/dist/functions/symbol/symbols/fine.js +1 -1
  37. package/dist/functions/symbol/symbols/tr.js +46 -1
  38. package/dist/functions/temporal.d.ts +16 -6
  39. package/dist/functions/temporal.js +16 -6
  40. package/dist/functions/tie/index.js +35 -25
  41. package/dist/functions/up/index.js +5 -7
  42. package/dist/functions/voice/connections.js +7 -5
  43. package/dist/functions/voice/index.js +2 -1
  44. package/dist/functions/volta/index.js +41 -21
  45. package/dist/jpfun.core.min.js +44 -68
  46. package/dist/jpfun.from-midi.min.js +5 -5
  47. package/dist/jpfun.from-musicxml.min.js +8 -8
  48. package/dist/jpfun.min.js +53 -77
  49. package/dist/layout/engine.d.ts +1 -0
  50. package/dist/layout/engine.js +42 -11
  51. package/dist/layout/page.d.ts +3 -2
  52. package/dist/layout/page.js +6 -5
  53. package/dist/layout/types.d.ts +4 -0
  54. package/dist/lowering/loweringContext.js +7 -167
  55. package/dist/parser/parserContext.d.ts +2 -0
  56. package/dist/parser/parserContext.js +27 -6
  57. package/dist/playback/compile.js +11 -2
  58. package/dist/playback/types.d.ts +4 -2
  59. package/dist/render/svg.js +1 -0
  60. package/dist/render/text.d.ts +1 -1
  61. package/dist/render/text.js +3 -2
  62. package/dist/render/types.d.ts +1 -0
  63. package/grammar.md +30 -9
  64. package/package.json +1 -1
@@ -46,20 +46,6 @@ const ACCIDENTALS = {
46
46
  ],
47
47
  },
48
48
  };
49
- /** size 是数字字号,升降号自己决定缩小多少 */
50
- function prepareAccidental(symbol, size) {
51
- const definition = ACCIDENTALS[symbol];
52
- if (!definition)
53
- return null;
54
- const glyphSize = size * GLYPH_SCALE;
55
- return {
56
- w: definition.w * glyphSize,
57
- h: definition.h * glyphSize,
58
- baseline: definition.baseline * glyphSize,
59
- strokeWidth: size * STROKE_RATIO,
60
- commands: definition.commands,
61
- };
62
- }
63
49
  /**
64
50
  * 把升降号串按同一基线依次排在 x 右侧
65
51
  * @param size 宿主数字的字号
@@ -69,13 +55,21 @@ function prepareAccidental(symbol, size) {
69
55
  */
70
56
  export function placeAccidentals(symbols, size, x, baselineY, gap) {
71
57
  const placed = [];
58
+ const glyphSize = size * GLYPH_SCALE;
72
59
  const raise = size * RAISE_RATIO;
73
60
  let right = x;
74
61
  let top = 0;
75
62
  for (const symbol of symbols) {
76
- const shape = prepareAccidental(symbol, size);
77
- if (!shape)
63
+ const definition = ACCIDENTALS[symbol];
64
+ if (!definition)
78
65
  continue;
66
+ const shape = {
67
+ w: definition.w * glyphSize,
68
+ h: definition.h * glyphSize,
69
+ baseline: definition.baseline * glyphSize,
70
+ strokeWidth: size * STROKE_RATIO,
71
+ commands: definition.commands,
72
+ };
79
73
  const y = baselineY - shape.baseline - raise;
80
74
  placed.push({ shape, x: right, y });
81
75
  if (y < top)
@@ -1,6 +1,7 @@
1
1
  import { ASTTextNode, ASTFunctionNode } from "../ASTtypes.js";
2
2
  import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
3
3
  import { parseNoteName } from "./noteNameFSM.js";
4
+ import { getLayoutBounds } from "../../layout/engine.js";
4
5
  import { paintAccidental, placeAccidentals } from "./accidentals.js";
5
6
  import { rewriteNotes } from "./source-transform.js";
6
7
  /** 根据同一源码的 lowering 生成局部修改;传入 ranges 时只处理完整落入任一选区的音符 */
@@ -170,7 +171,7 @@ import { createDiatonicTranspose, resolveLetterNameToJianpu, resolveNoteMidi, }
170
171
  const NOTE_GLYPH = { "8": "", "9": "X" };
171
172
  class NoteTemporalNode extends TemporalNodeBase {
172
173
  // 时间固化后的参数
173
- resolvedMidi = null; // MIDI音高 name是数字则需要在onTimeState中基于当前调性偏移 播放的音高
174
+ resolvedMidi = null; // 按调性解析的记谱音高,不含播放偏移
174
175
  keySignature = "C4"; // 用于转调时记录大环境
175
176
  transposeDiatonic;
176
177
  name; // 数字
@@ -253,6 +254,12 @@ class NoteTemporalNode extends TemporalNodeBase {
253
254
  }
254
255
  finalizeLayout() {
255
256
  this.ports["lyric"] = { x: this.box.anchor, y: this.box.h };
257
+ if (this.octave > 0) { // 八度点上方留空间
258
+ this.ports["tie.top"] = {
259
+ x: this.box.anchor,
260
+ y: getLayoutBounds(this, true).y - this.box.y - this.ast.size * 0.05,
261
+ };
262
+ }
256
263
  }
257
264
  paint(painter) {
258
265
  const color = this.ast.color;
@@ -290,6 +297,8 @@ class NoteTemporalNode extends TemporalNodeBase {
290
297
  emitPlayback(emitter) {
291
298
  const percussion = this.ast.name === "9";
292
299
  const midi = percussion ? 37 : this.resolvedMidi;
300
+ const shift = percussion ? 0 : this.playbackState?.pitchShift ?? 0;
301
+ const transpose = this.transposeDiatonic;
293
302
  if (emitter.end.compare(emitter.start) <= 0)
294
303
  return;
295
304
  // 休止符和占位符也要保留结构边界,速度效果与后续延长才能覆盖这段时间。
@@ -301,9 +310,10 @@ class NoteTemporalNode extends TemporalNodeBase {
301
310
  emitter.note({
302
311
  start: emitter.start,
303
312
  end: emitter.end,
304
- midi,
313
+ midi: midi + shift,
305
314
  velocity: this.playbackState?.velocity ?? DEFAULT_VELOCITY,
306
- ...(percussion ? { percussion: true } : { transpose: this.transposeDiatonic }),
315
+ ...(percussion ? { percussion: true }
316
+ : { transpose: shift && transpose ? steps => transpose(steps) + shift : transpose }),
307
317
  });
308
318
  }
309
319
  }
@@ -0,0 +1,2 @@
1
+ import { type ASTFunctionClass } from "../ASTtypes.js";
2
+ export declare const OttavaNode: ASTFunctionClass;
@@ -0,0 +1,217 @@
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 ottavas = result.attachments.filter((attachment) => attachment instanceof OttavaAttachment).map(attachment => {
42
+ const [from, to] = attachment.endPoints;
43
+ return { from, end: to.t.clone().add(to.T), shift: attachment.ast.shift * 12 };
44
+ });
45
+ if (ottavas.length === 0)
46
+ return;
47
+ for (const nodes of result.astToTemporal.values()) {
48
+ for (const node of nodes) {
49
+ if (!node.playbackState)
50
+ continue;
51
+ const host = outerHost(node);
52
+ let shift = 0;
53
+ for (const ottava of ottavas) {
54
+ if (host.track === ottava.from.track && host.t.compare(ottava.from.t) >= 0
55
+ && host.t.compare(ottava.end) < 0) {
56
+ shift += ottava.shift;
57
+ }
58
+ }
59
+ if (shift !== 0) {
60
+ node.playbackState = {
61
+ ...node.playbackState,
62
+ pitchShift: (node.playbackState.pitchShift ?? 0) + shift,
63
+ };
64
+ }
65
+ }
66
+ }
67
+ };
68
+ from;
69
+ to;
70
+ shift;
71
+ size;
72
+ font;
73
+ constructor(span, args, ctx, parent = null) {
74
+ super(span, parent);
75
+ const [from, to, shift] = this.getArgValue(args, ctx);
76
+ if (!Number.isSafeInteger(shift) || shift === 0 || !Number.isSafeInteger(shift * 12)) {
77
+ throw new ErrorDiagnostic("E_OTTAVA_INVALID_SHIFT", "@ottava 的 shift 必须为可安全换算为半音的非零整数", span);
78
+ }
79
+ this.from = from;
80
+ this.to = to;
81
+ this.shift = shift;
82
+ this.size = ctx.variables.fontsize;
83
+ this.font = ctx.variables.numberfont;
84
+ }
85
+ loweringEnter(ctx) {
86
+ const from = ctx.getTemporalNodes(this.from).at(0);
87
+ const to = ctx.getTemporalNodes(this.to).at(-1);
88
+ const head = from && outerHost(from);
89
+ const tail = to && outerHost(to);
90
+ if (!head || !tail || !isVisualTemporalNode(head) || !isVisualTemporalNode(tail)) {
91
+ ctx.diagnostics.push(Diagnostic.warning.UnresolvedEndpoint("ottava", this.sourceSpan));
92
+ return [];
93
+ }
94
+ if (head.track !== tail.track) {
95
+ throw new ErrorDiagnostic("E_OTTAVA_CROSS_TRACK", "@ottava 的两个端点必须位于同一音轨", this.sourceSpan);
96
+ }
97
+ ctx.addAttachment(new OttavaAttachment(this, head, tail));
98
+ return [];
99
+ }
100
+ toString(source) {
101
+ const name = (node) => (node instanceof ASTFunctionNode ? node.label : undefined) ?? node.toString(source);
102
+ return `@ottava(${name(this.from)}, ${name(this.to)}, ${this.shift})`;
103
+ }
104
+ }
105
+ export const OttavaNode = OttavaFunction;
106
+ class OttavaAttachment {
107
+ ast;
108
+ from;
109
+ to;
110
+ layer = "foreground";
111
+ constructor(ast, from, to) {
112
+ this.ast = ast;
113
+ this.from = from;
114
+ this.to = to;
115
+ }
116
+ get sourceSpan() { return this.ast.sourceSpan; }
117
+ get endPoints() {
118
+ return (this.from.t.compare(this.to.t) || this.from.order - this.to.order) > 0
119
+ ? [this.to, this.from] : [this.from, this.to];
120
+ }
121
+ createGeometry(context) {
122
+ const endpoints = this.endPoints;
123
+ const [from, to] = endpoints;
124
+ const firstLine = from.layoutLine;
125
+ const lastLine = to.layoutLine;
126
+ if (context.lines[firstLine].columnOf(from) < 0 || context.lines[lastLine].columnOf(to) < 0) {
127
+ return { regions: [], paint() { } };
128
+ }
129
+ const { size, font, shift } = this.ast;
130
+ const above = shift > 0;
131
+ const track = from.track;
132
+ const strokeWidth = Math.max(0.75, size * 0.035);
133
+ const lineStyle = { stroke: "#000", strokeWidth };
134
+ const dash = size * 0.22;
135
+ const dashStep = dash + size * 0.14;
136
+ const halfStroke = strokeWidth / 2;
137
+ const hook = size * 0.45;
138
+ const gap = size * 0.2;
139
+ const labelGap = size * 0.08;
140
+ const text = String(Math.abs(shift) * 7 + 1);
141
+ const style = {
142
+ fontSize: size * 0.6,
143
+ fontFamily: font,
144
+ fontStyle: "italic",
145
+ textAlign: "left",
146
+ fill: "#000",
147
+ };
148
+ const metrics = context.textMeasurer.measureText(text, style);
149
+ const labelTop = above ? -halfStroke : halfStroke - metrics.h;
150
+ const labelY = labelTop + metrics.baseline;
151
+ const draws = Array.from({ length: lastLine - firstLine + 1 }, (_, offset) => {
152
+ const line = firstLine + offset;
153
+ const first = line === firstLine;
154
+ const last = line === lastLine;
155
+ const runs = context.lines[line].trackRuns;
156
+ let left = first ? from.box.x + (from.ports["body.left"]?.x ?? 0)
157
+ : runs.get(track)?.find(host => !host.T.isZero())?.box.x ?? context.originX;
158
+ let right = to.box.x + (to.ports["body.right"]?.x ?? to.box.w);
159
+ if (!last) {
160
+ right = context.originX + (runs.size === 0 ? context.width : 0);
161
+ for (const run of runs.values()) {
162
+ for (const host of run)
163
+ right = Math.max(right, host.box.x + host.box.w);
164
+ }
165
+ }
166
+ if (left > right)
167
+ [left, right] = [right, left];
168
+ const lineStart = first ? left + metrics.w + labelGap : left;
169
+ const part = (x, y, w, h) => ({ x, y, w, h, line, track });
170
+ const parts = lineStart < right
171
+ ? [part(lineStart - halfStroke, -halfStroke, right - lineStart + strokeWidth, strokeWidth)] : [];
172
+ if (first)
173
+ parts.push(part(left, labelTop, metrics.w, metrics.h));
174
+ if (last)
175
+ parts.push(part(right - halfStroke, above ? -halfStroke : -hook - halfStroke, strokeWidth, hook + strokeWidth));
176
+ const region = part(0, 0, 0, 0);
177
+ unionLayoutBoxes(region, parts);
178
+ let lineY = above ? Infinity : -Infinity;
179
+ for (const part of parts) {
180
+ for (const [lane, extent] of context.getHorizontalExtents(line, part.x, part.x + part.w)) {
181
+ const axis = context.getVisualAxis(line, lane);
182
+ lineY = above
183
+ ? Math.min(lineY, axis + extent.top - gap - part.y - part.h)
184
+ : Math.max(lineY, axis + extent.bottom + gap - part.y);
185
+ }
186
+ }
187
+ if (!Number.isFinite(lineY)) {
188
+ const extent = context.getRangeExtents(line, first || last ? endpoints : undefined, track);
189
+ const axis = context.getVisualAxis(line, track);
190
+ lineY = above
191
+ ? axis + (extent?.top ?? 0) - gap - (region.y + region.h)
192
+ : axis + (extent?.bottom ?? 0) + gap - region.y;
193
+ }
194
+ for (const part of parts)
195
+ part.y += lineY;
196
+ region.y += lineY;
197
+ return { left, right, lineStart, lineY, first, last, parts, region };
198
+ });
199
+ return {
200
+ regions: draws.map(draw => draw.region),
201
+ occupancy: draws.flatMap(draw => draw.parts),
202
+ paint(painter) {
203
+ for (const draw of draws) {
204
+ const { left, right, lineStart, lineY, first, last } = draw;
205
+ for (let x = lineStart; x < right; x += dashStep) {
206
+ painter.drawLine(x, lineY, Math.min(x + dash, right), lineY, lineStyle);
207
+ }
208
+ if (first)
209
+ painter.drawText(text, left, lineY + labelY, style);
210
+ if (last) {
211
+ painter.drawLine(right, lineY, right, lineY + (above ? hook : -hook), lineStyle);
212
+ }
213
+ }
214
+ },
215
+ };
216
+ }
217
+ }
@@ -57,7 +57,7 @@ export class PageFunction extends ASTFunctionNode {
57
57
  allowExtraArgs: false,
58
58
  args: [
59
59
  { name: "width", description: "页面宽度,须大于左右页边距之和", type: "length", default: px(DEFAULT_PAGE_CONFIG.width) },
60
- { name: "height", description: "页面高度,0 表示不分页、高度随内容增长;宽度为 `794px` 时,A4 对应高度约为 `1123px`", type: "length", default: px(0) },
60
+ { name: "height", description: "页面高度,小于等于 0 表示不自动分页、高度随内容增长;宽度为 `794px` 时,A4 对应高度约为 `1123px`", type: "length", default: px(0) },
61
61
  { name: "top", description: "页面上边距", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginTop) },
62
62
  { name: "bottom", description: "页面下边距,启用页码时至少为 `16px`", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginBottom) },
63
63
  { name: "left", description: "页面左边距", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginLeft) },
@@ -93,8 +93,8 @@ export class PageFunction extends ASTFunctionNode {
93
93
  const [width, height, top, bottom, left, right, gap] = values.map(value => ctx.length2px(value));
94
94
  if (!Number.isFinite(width) || width <= 0)
95
95
  throw Diagnostic.error.InvalidPageConfig("@page 的 width 必须是正有限长度", sourceSpan);
96
- if (!Number.isFinite(height) || height < 0)
97
- throw Diagnostic.error.InvalidPageConfig("@page 的 height 必须是非负有限长度;0 表示不分页", sourceSpan);
96
+ if (!Number.isFinite(height))
97
+ throw Diagnostic.error.InvalidPageConfig("@page 的 height 必须是有限长度;小于等于 0 表示不自动分页", sourceSpan);
98
98
  if ([top, bottom, left, right, gap].some(value => !Number.isFinite(value) || value < 0))
99
99
  throw Diagnostic.error.InvalidPageConfig("@page 的边距和 gap 必须是非负有限长度", sourceSpan);
100
100
  if (left + right >= width)
@@ -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
+ static loweringFinalize = BrNode.loweringFinalize;
22
+ justify;
23
+ constructor(span, args, ctx, parent = null) {
24
+ super(span, parent);
25
+ [this.justify] = this.getArgValue(args, ctx);
26
+ }
27
+ loweringEnter() {
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,7 +54,8 @@ class RestFunction extends ASTFunctionNode {
54
54
  }
55
55
  this.font = ctx.variables.numberfont;
56
56
  }
57
- labelable() { return null; }
57
+ // 可以被 volta 这样的标记
58
+ labelable() { return this; }
58
59
  loweringEnter() {
59
60
  return [new RestTemporal(this)];
60
61
  }
@@ -66,12 +67,11 @@ class RestFunction extends ASTFunctionNode {
66
67
  const onsets = new Map();
67
68
  // 扫描完整来源索引,纳入未直接出现在时间列中的折叠成员
68
69
  for (const nodes of result.astToTemporal.values()) {
69
- // 为新增边界预留唯一 order,并记录各宿主的休止代表和最早音符
70
+ // 为新增边界预留唯一 order,并记录各宿主的最早音符
70
71
  for (const node of nodes) {
71
72
  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")))
73
+ if (!(node.ast instanceof ASTFunctionNode)
74
+ || (node.ast.callName !== "note" && node.ast.callName !== "dash"))
75
75
  continue;
76
76
  let host = node;
77
77
  // 沿折叠链找到最外层宿主,将内部成员归到同一主体
@@ -80,15 +80,6 @@ class RestFunction extends ASTFunctionNode {
80
80
  // 私有倚音属于独立轨道,不代表外层宿主的休止或起音
81
81
  if (node.track !== host.track)
82
82
  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
83
  const onset = onsets.get(host);
93
84
  if (!onset || node.order < onset.order)
94
85
  onsets.set(host, node);
@@ -160,6 +151,13 @@ class RestTemporal extends TemporalNodeBase {
160
151
  }
161
152
  this.measureDuration.copyFrom(measure);
162
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
+ }
163
161
  this.playbackState = { bpm: state.bpm };
164
162
  return this.T;
165
163
  }
@@ -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
  /** 发布系统控制,或注册对同一折叠序列后续音符的局部变换 */