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,180 @@
1
+ import { ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
2
+ import { pathBounds } from "../../layout/path.js";
3
+ import { ASTFunctionNode, } from "../ASTtypes.js";
4
+ import { isVisualTemporalNode } from "../temporal.js";
5
+ // gliss 判断音高的准则是 resolvedMidi 属性
6
+ function pitchOf(node) {
7
+ const { resolvedMidi } = node;
8
+ return typeof resolvedMidi === "number" ? resolvedMidi : undefined;
9
+ }
10
+ class GlissFunction extends ASTFunctionNode {
11
+ static def = {
12
+ name: ["gliss"],
13
+ description: "滑音连线",
14
+ details: `\
15
+ ~~~jpfun
16
+ 1 -@a 5@b @gliss(a, b)
17
+ ~~~
18
+ 若附属对象无音高,将使用前面最近的的同轨有音高对象的音高`,
19
+ allowExtraArgs: false,
20
+ args: [
21
+ {
22
+ type: "label",
23
+ default: null,
24
+ description: "一个端点的标签,先后按谱面时间确定"
25
+ },
26
+ {
27
+ type: "label",
28
+ default: null,
29
+ description: "另一个端点的标签"
30
+ },
31
+ ],
32
+ };
33
+ from;
34
+ to;
35
+ constructor(span, args, ctx, parent = null) {
36
+ super(span, parent);
37
+ [this.from, this.to] = this.getArgValue(args, ctx);
38
+ }
39
+ loweringEnter(ctx) {
40
+ const from = ctx.getTemporalNodes(this.from).at(-1);
41
+ const to = ctx.getTemporalNodes(this.to).at(-1);
42
+ if (!from || !to || !isVisualTemporalNode(from) || !isVisualTemporalNode(to)) {
43
+ throw new ErrorDiagnostic("E_GLISS_ENDPOINT", "@gliss 的标签必须指向已生成且具有排版盒子的对象", this.sourceSpan);
44
+ }
45
+ ctx.addAttachment(new GlissAttachment(from, to, this.sourceSpan, ctx.diagnostics));
46
+ return [];
47
+ }
48
+ toString(source) {
49
+ const from = this.from instanceof ASTFunctionNode ? this.from.label : undefined;
50
+ const to = this.to instanceof ASTFunctionNode ? this.to.label : undefined;
51
+ return from && to ? `@gliss(${from}, ${to})` : source.slice(this.sourceSpan.start, this.sourceSpan.end);
52
+ }
53
+ }
54
+ export const GlissNode = GlissFunction;
55
+ function layoutHost(node, line) {
56
+ while (node.foldedInto && isVisualTemporalNode(node.foldedInto) && (!line || line.columnOf(node) < 0)) {
57
+ node = node.foldedInto;
58
+ }
59
+ return node;
60
+ }
61
+ class GlissAttachment {
62
+ from;
63
+ to;
64
+ sourceSpan;
65
+ diagnostics;
66
+ layer = "foreground";
67
+ endPoints;
68
+ direction;
69
+ warned = false;
70
+ constructor(from, to, sourceSpan, diagnostics) {
71
+ this.from = from;
72
+ this.to = to;
73
+ this.sourceSpan = sourceSpan;
74
+ this.diagnostics = diagnostics;
75
+ this.endPoints = [from, to];
76
+ }
77
+ get orderedEndpoints() {
78
+ const [a, b] = this.endPoints;
79
+ const fromHost = layoutHost(a);
80
+ const toHost = layoutHost(b);
81
+ const { sourceSpan } = this;
82
+ if (fromHost.t.equals(toHost.t))
83
+ throw new ErrorDiagnostic("E_GLISS_ORDER", "@gliss 两个端点不能位于同一时刻", sourceSpan);
84
+ if (fromHost.layoutLine !== toHost.layoutLine)
85
+ throw new ErrorDiagnostic("E_GLISS_CROSS_LINE", "@gliss 不支持跨谱面行", sourceSpan);
86
+ return fromHost.t.compare(toHost.t) > 0 ? [b, a] : [a, b];
87
+ }
88
+ /** 定位端点所在时间列,按需解析音高,并为箭头登记水平留白 */
89
+ prepareHorizontal(lines) {
90
+ const [endpoint, target] = this.orderedEndpoints;
91
+ const { sourceSpan } = this;
92
+ const index = endpoint.layoutLine;
93
+ const line = lines[index];
94
+ const from = line && layoutHost(endpoint, line);
95
+ const to = line && layoutHost(target, line);
96
+ const start = from ? line.columnOf(from) : -1;
97
+ const end = to ? line.columnOf(to) : -1;
98
+ if (!line || start < 0 || end <= start) {
99
+ throw new ErrorDiagnostic("E_GLISS_DOMAIN", "@gliss 的端点必须位于同一排版域的不同时间列", sourceSpan);
100
+ }
101
+ const resolvePitch = (node, column) => {
102
+ if ("resolvedMidi" in node)
103
+ return pitchOf(node);
104
+ const track = layoutHost(node, line).track;
105
+ // 当前行找不到时继续查找前面的谱面行,不要求时值连续
106
+ for (let i = index; i >= 0; i--) {
107
+ const columns = lines[i].columns;
108
+ // 从端点前一列倒查同轨对象;首个带音高属性的对象即终止搜索,空值也不跳过
109
+ for (let j = i === index ? column - 1 : columns.length - 1; j >= 0; j--) {
110
+ const previous = columns[j].find(item => item.track === track && "resolvedMidi" in item);
111
+ if (previous)
112
+ return pitchOf(previous);
113
+ }
114
+ }
115
+ };
116
+ const sourcePitch = resolvePitch(endpoint, start);
117
+ const targetPitch = resolvePitch(target, end);
118
+ this.direction = sourcePitch === undefined || targetPitch === undefined
119
+ ? undefined : Math.sign(targetPitch - sourcePitch);
120
+ if (this.direction === undefined && !this.warned) {
121
+ this.diagnostics.push(new WarningDiagnostic("W_GLISS_NO_PITCH", "@gliss 端点没有可用音高", sourceSpan));
122
+ this.warned = true; // prepareHorizontal 不一定只执行一次 所以要防抖
123
+ }
124
+ const right = from.box.w - from.box.anchor + this.size * 1.4;
125
+ // 只扩张求解器占位,不改变端点图形、附点位置或下一轮的 box
126
+ line.registerHorizontalLayoutHook(from, to, ({ columns }) => {
127
+ // 留白作用于起点整列;取最大值,避免多条关系重复累加占位。
128
+ for (const element of columns[start])
129
+ element.WR = Math.max(element.WR, right);
130
+ });
131
+ }
132
+ get size() {
133
+ return Math.max(this.from.ast.size, this.to.ast.size);
134
+ }
135
+ createGeometry() {
136
+ // 子域附件可能直接进入几何测量,未经过 prepareHorizontal
137
+ const [from, to] = this.orderedEndpoints;
138
+ const size = this.size;
139
+ const gap = size * 0.12;
140
+ const start = { x: from.box.x + from.box.w + gap, y: from.box.y + from.box.visualAxis };
141
+ const end = { x: to.box.x - gap, y: to.box.y + to.box.visualAxis };
142
+ if (from.track === to.track) {
143
+ if (this.direction === undefined) {
144
+ end.y = start.y;
145
+ }
146
+ else {
147
+ start.y += this.direction * size * 0.24;
148
+ end.y -= this.direction * size * 0.24;
149
+ }
150
+ }
151
+ if (end.x <= start.x) {
152
+ throw new ErrorDiagnostic("E_GLISS_SPACE", "@gliss 的端点之间没有可用的水平绘制空间", this.sourceSpan);
153
+ }
154
+ const angle = Math.atan2(end.y - start.y, end.x - start.x);
155
+ const length = Math.min(size * 0.3, Math.hypot(end.x - start.x, end.y - start.y) * 0.35);
156
+ const wing = (offset) => ({
157
+ x: end.x - length * Math.cos(angle + offset),
158
+ y: end.y - length * Math.sin(angle + offset),
159
+ });
160
+ const commands = [
161
+ { op: "M", ...start }, { op: "L", ...end },
162
+ { op: "M", ...wing(-Math.PI / 6) }, { op: "L", ...end },
163
+ { op: "L", ...wing(Math.PI / 6) },
164
+ ];
165
+ const strokeWidth = size * 0.05;
166
+ const bounds = pathBounds(commands);
167
+ const region = {
168
+ x: bounds.x - strokeWidth / 2, y: bounds.y - strokeWidth / 2,
169
+ w: bounds.w + strokeWidth, h: bounds.h + strokeWidth,
170
+ };
171
+ return {
172
+ regions: [{ ...region, line: from.layoutLine, track: from.track }],
173
+ // 跨轨连线不把整段高度算到起点轨,否则纵向求解会反复撑开两轨
174
+ occupancy: from.track === to.track ? [{ ...region, line: from.layoutLine, track: from.track }] : [],
175
+ paint: (painter) => {
176
+ painter.drawPath(commands, { fill: "none", stroke: "#000", strokeWidth });
177
+ },
178
+ };
179
+ }
180
+ }
@@ -1,6 +1,7 @@
1
- import type { LayoutBox, LayoutPrepareContext } from "../../layout/types.js";
1
+ import type { HorizontalLineView, LayoutBox, LayoutPrepareContext } from "../../layout/types.js";
2
2
  import type { LoweringContext } from "../../lowering/loweringContext.js";
3
3
  import type { LoweringAttachment } from "../../lowering/types.js";
4
+ import { Fraction } from "../../fraction.js";
4
5
  import { Track } from "../../lowering/track.js";
5
6
  import { TemporalNodeBase, type TimeState, type VisualTemporalNode } from "../temporal.js";
6
7
  import { GrammarNode, GrammarSugarNode } from "../../parser/grammarType.js";
@@ -64,7 +65,8 @@ export declare class GraceTemporal extends TemporalNodeBase {
64
65
  private hookOrigin;
65
66
  constructor(ast: GraceFunction, host: VisualTemporalNode, columns: readonly (readonly TemporalNodeBase[])[], root: Track, attachments: readonly LoweringAttachment[], side: GraceSide);
66
67
  /** 成员共享全局时间状态,按发声顺序固化 */
67
- onTimeState(state: TimeState): void;
68
+ onTimeState(state: TimeState): void | Fraction;
69
+ prepareHorizontal(line: HorizontalLineView): void;
68
70
  /**
69
71
  * 播放时倚音从宿主借走的时值(前倚音从开头、后倚音从末尾)
70
72
  *
@@ -1,8 +1,8 @@
1
1
  import { ErrorDiagnostic } from "../../diagnostic.js";
2
- import { layoutLocalSequence } from "../../layout/engine.js";
2
+ import { getLayoutBounds, layoutLocalSequence } from "../../layout/engine.js";
3
3
  import { Fraction } from "../../fraction.js";
4
4
  import { Track } from "../../lowering/track.js";
5
- import { isVisualTemporalNode, TemporalNodeBase, } from "../temporal.js";
5
+ import { transferFunctionAddons, isVisualTemporalNode, TemporalNodeBase, } from "../temporal.js";
6
6
  import { ASTBraceNode, ASTFunctionNode, ASTLabelNode, ASTTextNode, } from "../ASTtypes.js";
7
7
  import { createBeamLayoutAttachment } from "../beam/layout.js";
8
8
  import { DIV_ADDON_KEY } from "../div/index.js";
@@ -237,7 +237,7 @@ class GraceFunction extends ASTFunctionNode {
237
237
  throw new ErrorDiagnostic("E_GRACE_INVALID_HOST", "@grace 的宿主必须恰好产生一个可见 Temporal", host.sourceSpan);
238
238
  }
239
239
  const events = columns.flat();
240
- if (!events.some(isVisualTemporalNode) || events.some(event => event.breakBefore > 0)) {
240
+ if (!events.some(isVisualTemporalNode) || events.some(event => (event.addon?.breakBefore ?? 0) > 0)) {
241
241
  throw new ErrorDiagnostic("E_GRACE_INVALID_CONTENT", "@grace 的倚音至少产生一个可见对象,且不能换行", grace.sourceSpan);
242
242
  }
243
243
  const composite = new GraceTemporal(this, hostNode, columns, root, attachments, this.side);
@@ -354,11 +354,20 @@ export class GraceTemporal extends TemporalNodeBase {
354
354
  onTimeState(state) {
355
355
  // 同步时间的修改。比如tuplet修改的是GraceTemporal.T,这里要把它传给成员
356
356
  this.host.T.copyFrom(this.T);
357
+ let offset = undefined;
357
358
  for (const member of this.side === "pre" ? [...this.events, this.host] : [this.host, ...this.events]) {
358
359
  member.t.copyFrom(this.t);
359
360
  member.layoutLine = this.layoutLine;
360
- member.onTimeState?.(state);
361
+ const result = member.onTimeState?.(state);
362
+ if (member === this.host) {
363
+ this.T.copyFrom(member.T);
364
+ offset = result;
365
+ }
361
366
  }
367
+ return offset;
368
+ }
369
+ prepareHorizontal(line) {
370
+ this.host.prepareHorizontal?.(line);
362
371
  }
363
372
  /**
364
373
  * 播放时倚音从宿主借走的时值(前倚音从开头、后倚音从末尾)
@@ -399,12 +408,10 @@ export class GraceTemporal extends TemporalNodeBase {
399
408
  prepareLayout(context) {
400
409
  // lowering 期间修饰挂在复合体上(augmenter 要看到整体节奏),渲染时交给宿主:
401
410
  // 减时线要落在宿主数字与下八度点之间,而不是压在整个倚音盒下面
402
- if (this.addon) {
403
- this.host.addon = this.addon;
404
- this.addon = void 0;
405
- }
411
+ transferFunctionAddons(this, this.host);
406
412
  const block = context.layoutSubdomain(this, this.graceColumns, this.root, this.attachments);
407
413
  const hostWidth = layoutLocalSequence([this.host], context);
414
+ this.springConfig = { ...this.host.springConfig, ...this.springConfig };
408
415
  const graceEm = this.ast.size * GRACE_SCALE;
409
416
  const sideGap = graceEm * 0.2;
410
417
  const rise = graceEm * GRACE_RISE;
@@ -412,7 +419,8 @@ export class GraceTemporal extends TemporalNodeBase {
412
419
  // 肩线由它转发上来,所以两侧倚音会落在同一高度而不是层层叠高
413
420
  const shoulder = this.host.ports[SHOULDER_PORT]?.y ?? 0;
414
421
  const graceTop = shoulder - rise - block.height;
415
- const lift = Math.max(0, -graceTop);
422
+ const hostBounds = getLayoutBounds(this.host);
423
+ const lift = Math.max(0, -graceTop, -hostBounds.y);
416
424
  const graceX = this.side === "pre" ? 0 : hostWidth + sideGap;
417
425
  this.hostOffset = {
418
426
  x: this.host.box.x + (this.side === "pre" ? block.width + sideGap : 0),
@@ -423,7 +431,7 @@ export class GraceTemporal extends TemporalNodeBase {
423
431
  y: graceTop + lift + position.y,
424
432
  }));
425
433
  this.box.w = hostWidth + sideGap + block.width;
426
- this.box.h = lift + this.host.box.h;
434
+ this.box.h = lift + hostBounds.y + hostBounds.h;
427
435
  this.box.anchor = this.hostOffset.x + this.host.box.anchor;
428
436
  this.box.visualAxis = lift + this.host.box.visualAxis;
429
437
  // 端口原样上提:减时线、歌词、连音线都接到宿主上,关系函数不需要认识倚音
@@ -460,7 +468,7 @@ export class GraceTemporal extends TemporalNodeBase {
460
468
  for (const member of [this.host, ...this.graces]) {
461
469
  member.paint(painter);
462
470
  for (const decoration of member.decorations)
463
- decoration.paint(painter);
471
+ decoration.paint?.(painter);
464
472
  }
465
473
  if (!this.hookOrigin)
466
474
  return;
@@ -53,35 +53,23 @@ function layoutHeadSlot({ columns, rows, start, end, X, fixed, options }, occupi
53
53
  else
54
54
  X[end] = X[start];
55
55
  }
56
- /** 行从上到下按 gap 排列;capture 让 Head 在同一遍测量里取得整组范围 */
57
- function measureRows(members, gap, capture) {
58
- const placements = [];
59
- let top;
60
- let cursor;
61
- for (const extent of members) {
62
- if (!extent) {
63
- placements.push(null);
64
- continue;
65
- }
66
- const offset = cursor === void 0 ? 0 : cursor + gap - extent.top;
67
- placements.push({ offset, extent });
68
- top ??= offset + extent.top;
69
- cursor = offset + extent.bottom;
70
- }
71
- capture?.(top === void 0 || cursor === void 0 ? null : { top, bottom: cursor });
72
- return placements;
73
- }
74
56
  class HeadBoundaryTemporal extends TemporalNodeBase {
75
57
  members = [];
76
58
  slots = [];
77
59
  titleBottom = 0;
78
- leftExtent = null;
79
- rightExtent = null;
60
+ sideExtents = { left: null, right: null };
80
61
  constructor(ast) {
81
62
  super();
82
63
  this.ast = ast;
83
64
  this.initLayoutBox();
84
65
  }
66
+ validateDuration() {
67
+ for (const node of this.members) {
68
+ if (!node.T.isZero()) {
69
+ throw new ErrorDiagnostic("E_HEAD_NONZERO_DURATION", "@head 的内容必须全部为零时长", node.ast.sourceSpan);
70
+ }
71
+ }
72
+ }
85
73
  prepareLayout() { this.box.w = this.box.h = this.box.anchor = this.box.visualAxis = 0; }
86
74
  prepareHorizontal(line) {
87
75
  // 只由第一个边界协调一次整块 Head,避免六个边界重复改弹簧
@@ -92,31 +80,40 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
92
80
  if (this.slots.length > 0)
93
81
  this.alignHead();
94
82
  }
83
+ onTemporal(node) { this.members.push(node); }
95
84
  createTracks(slot) {
96
85
  const { name, owner } = slot;
97
86
  return {
98
87
  laneKey: `head/rows/${owner.sourceSpan.start}/${name}`,
99
88
  hostIndex: null,
100
89
  measure: members => {
101
- if (name === "center") {
102
- const placements = measureRows(members, owner.gap);
103
- const first = placements.find(placement => placement !== null);
104
- this.titleBottom = first ? first.offset + first.extent.bottom : 0;
105
- return placements;
106
- }
107
- return measureRows(members, owner.gap, extent => {
108
- if (name === "left")
109
- this.leftExtent = extent;
110
- else
111
- this.rightExtent = extent;
90
+ // 行从上到下排列,同一遍取得标题首行底边和侧栏整组范围
91
+ let top;
92
+ let bottom;
93
+ if (name === "center")
94
+ this.titleBottom = 0;
95
+ const placements = members.map(extent => {
96
+ if (!extent)
97
+ return null;
98
+ const offset = bottom === void 0 ? 0 : bottom + owner.gap - extent.top;
99
+ if (bottom === void 0 && name === "center")
100
+ this.titleBottom = extent.bottom;
101
+ top ??= offset + extent.top;
102
+ bottom = offset + extent.bottom;
103
+ return { offset, extent };
112
104
  });
105
+ if (name !== "center") {
106
+ this.sideExtents[name] = top === void 0 || bottom === void 0 ? null : { top, bottom };
107
+ }
108
+ return placements;
113
109
  },
114
110
  place: name === "center" ? undefined : () => {
115
- const extent = name === "left" ? this.leftExtent : this.rightExtent;
111
+ const extent = this.sideExtents[name];
116
112
  if (!extent)
117
113
  return this.titleBottom;
118
- const leftHeight = this.leftExtent ? this.leftExtent.bottom - this.leftExtent.top : 0;
119
- const rightHeight = this.rightExtent ? this.rightExtent.bottom - this.rightExtent.top : 0;
114
+ const { left, right } = this.sideExtents;
115
+ const leftHeight = left ? left.bottom - left.top : 0;
116
+ const rightHeight = right ? right.bottom - right.top : 0;
120
117
  // 两侧共享底边;以较高侧定总高度,使它的顶部恰好贴标题底边
121
118
  const targetBottom = this.titleBottom + Math.max(leftHeight, rightHeight);
122
119
  return targetBottom - extent.bottom;
@@ -155,8 +152,8 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
155
152
  cells.set(cell, [member]);
156
153
  }
157
154
  const [left, , right] = this.slots;
158
- this.packRows(left.ast, left.start.box.x, "left", cells);
159
- this.packRows(right.ast, right.end.box.x, "right", cells);
155
+ this.packRows(left.ast, left.start.box.x, cells);
156
+ this.packRows(right.ast, right.end.box.x, cells);
160
157
  }
161
158
  stretch(node, side) {
162
159
  const alpha = side === "L" ? "alpha_L" : "alpha_R";
@@ -165,9 +162,9 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
165
162
  node.springConfig[alpha] = node.springConfig[alpha] * HEAD_STRETCH;
166
163
  node.springConfig[beta] = node.springConfig[beta] * 3 / HEAD_STRETCH;
167
164
  }
168
- packRows(slot, target, side, cells) {
165
+ packRows(slot, target, cells) {
169
166
  const gap = this.ast.owner.size * ITEM_GAP_EM;
170
- const fromLeft = side === "left";
167
+ const fromLeft = slot.name === "left";
171
168
  const direction = fromLeft ? 1 : -1;
172
169
  for (const row of slot.rows) {
173
170
  const rowCells = row instanceof ASTBraceNode ? row.content : [row];
@@ -235,8 +232,12 @@ class HeadSlotNode extends ASTNodeBase {
235
232
  tracks: head.createTracks(this),
236
233
  };
237
234
  }
238
- loweringEnter() {
239
- return [new HeadBoundaryTemporal(this)];
235
+ loweringEnter(ctx) {
236
+ const boundary = new HeadBoundaryTemporal(this);
237
+ // 首边界收集真实全局事件,供末边界校验和放置后的对齐
238
+ if (this.name === "left")
239
+ ctx.beginLoweringGroup(this.owner, boundary);
240
+ return [boundary];
240
241
  }
241
242
  loweringExit() {
242
243
  return [new HeadBoundaryTemporal(this)];
@@ -396,7 +397,8 @@ H.tempo: 94
396
397
  ? previous
397
398
  : new HeadFunction(sugar.span, new Map(), ctx, null);
398
399
  head.createdBySugar = true;
399
- head.addSugarRow(FIELD_SLOT[field], HeadFunction.parseSugarRow(ctx, field, span, text, parsed));
400
+ head.slots.find(slot => slot.name === FIELD_SLOT[field])
401
+ .addRow(HeadFunction.parseSugarRow(ctx, field, span, text, parsed));
400
402
  head.sourceSpan.end = span.end;
401
403
  if (head !== previous)
402
404
  ctx.pushNode(head);
@@ -454,36 +456,22 @@ H.tempo: 94
454
456
  new HeadSlotNode(span, this, "right", rows("right", 2)),
455
457
  ];
456
458
  }
457
- loweringEnter(ctx) {
458
- // 收集真实全局事件:退出时校验时值,放置后按 AST 行归属做横向对齐
459
- const group = {
460
- members: [],
461
- onTemporal(node) { this.members.push(node); },
462
- };
463
- ctx.beginLoweringGroup(this, group);
464
- return [];
465
- }
466
459
  loweringExit(ctx) {
467
- const { members } = ctx.endLoweringGroup(this);
468
- const head = ctx.getTemporalNodes(this.slots[0])[0];
469
- head.members = members;
460
+ const head = ctx.endLoweringGroup(this);
470
461
  head.slots = this.slots.map(ast => {
471
462
  const [start, end] = ctx.getTemporalNodes(ast);
472
463
  return { ast, start, end };
473
464
  });
474
- for (const node of members) {
475
- if (!node.T.isZero()) {
476
- throw new ErrorDiagnostic("E_HEAD_NONZERO_DURATION", "@head 的内容必须全部为零时长", node.ast.sourceSpan);
477
- }
478
- if (node.breakBefore > 0) {
479
- throw new ErrorDiagnostic("E_HEAD_INTERNAL_BREAK", "@head 的内部不能使用 @br;第一层内容已经表示视觉行", node.ast.sourceSpan);
465
+ // right.end 是整个 Head 的末边界,按三槽的 sequence 排在所有内容之后
466
+ // 此时 rest 等延迟时值已固化,只检查当前 Head 的成员,无须再扫描全谱索引
467
+ head.slots[2].end.onTimeState = () => head.validateDuration();
468
+ for (const node of head.members) {
469
+ if ((node.addon?.breakBefore ?? 0) > 0) {
470
+ throw new ErrorDiagnostic("E_HEAD_INTERNAL_BREAK", "@head 的内部不能换行或换页;第一层内容已经表示视觉行", node.ast.sourceSpan);
480
471
  }
481
472
  }
482
473
  return [];
483
474
  }
484
- addSugarRow(name, row) {
485
- this.slots.find(slot => slot.name === name).addRow(row);
486
- }
487
475
  toString(source) {
488
476
  const slots = this.slots
489
477
  .filter(slot => slot.rows.length > 0)
@@ -1,7 +1,20 @@
1
1
  import { ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
2
2
  import { Fraction } from "../../fraction.js";
3
3
  import { ANCHOR_KEY, TemporalNodeBase } from "../temporal.js";
4
+ import { paintSymbol } from "../symbol/shape.js";
5
+ import { sanbanBounds, sanbanShapes } from "./shape.js";
4
6
  import { ASTFunctionNode, } from "../ASTtypes.js";
7
+ // 同一执行位置只关闭一次旧小节,保留最终拍号和最后源码边界。
8
+ const changesByPosition = new WeakMap();
9
+ function recordMeasureChange(state, node, meter) {
10
+ const position = state.currentEvent ?? node;
11
+ const span = node.ast.sourceSpan;
12
+ let change = changesByPosition.get(position);
13
+ if (!change)
14
+ changesByPosition.set(position, change = { start: span.start, end: span.end, meter });
15
+ change.end = span.end;
16
+ change.meter = meter;
17
+ }
5
18
  class MeterFunction extends ASTFunctionNode {
6
19
  static def = {
7
20
  name: ["meter"],
@@ -10,7 +23,8 @@ class MeterFunction extends ASTFunctionNode {
10
23
  ~~~jpfun
11
24
  @meter(6, 8)
12
25
  ~~~
13
- 设置 \`6/8\` 拍号:每小节含六个八分音符的时值`,
26
+ 设置 \`6/8\` 拍号:每小节含六个八分音符的时值。
27
+ 分子或分母为 0 时表示散板。`,
14
28
  allowExtraArgs: false,
15
29
  args: [
16
30
  {
@@ -43,9 +57,9 @@ class MeterFunction extends ASTFunctionNode {
43
57
  super(span, parent);
44
58
  let [num, den, size] = this.getArgValue(args, ctx);
45
59
  this.font = ctx.variables.numberfont;
46
- if (!Number.isSafeInteger(num) || !Number.isSafeInteger(num * 4) || num <= 0
47
- || !Number.isSafeInteger(den) || den <= 0) {
48
- const message = `@meter 的分子和分母必须是正整数`;
60
+ if (!Number.isSafeInteger(num) || !Number.isSafeInteger(num * 4) || num < 0
61
+ || !Number.isSafeInteger(den) || den < 0) {
62
+ const message = `@meter 的分子和分母必须是非负整数`;
49
63
  if (ctx.variables.strict)
50
64
  throw new ErrorDiagnostic("E_METER_INVALID", message, span);
51
65
  ctx.diagnostics.push(new WarningDiagnostic("W_METER_INVALID", `${message},已回落为 4/4`, span));
@@ -54,7 +68,8 @@ class MeterFunction extends ASTFunctionNode {
54
68
  this.numerator = num;
55
69
  this.denominator = den;
56
70
  // QN 以四分音符为 1;拍号不修改音符自身时值
57
- this.measureDuration = new Fraction(num * 4, den);
71
+ if (num !== 0 && den !== 0)
72
+ this.measureDuration = new Fraction(num * 4, den);
58
73
  this.size = ctx.length2px(size);
59
74
  this.strict = ctx.variables.strict;
60
75
  }
@@ -73,7 +88,7 @@ class MeterFunction extends ASTFunctionNode {
73
88
  // 诊断范围从上一边界之后延伸到当前关闭边界
74
89
  let sourceStart = 0;
75
90
  const closeMeasure = (end, sourceEnd) => {
76
- if (!active || end.equals(measureStart))
91
+ if (!active?.measureDuration || end.equals(measureStart))
77
92
  return;
78
93
  // Fraction 运算会原地修改接收者,不能直接对时间线字段做减法
79
94
  measureLength.copyFrom(end).sub(measureStart);
@@ -87,27 +102,16 @@ class MeterFunction extends ASTFunctionNode {
87
102
  }
88
103
  measureStart.copyFrom(end);
89
104
  };
90
- const metersByHost = new Map();
91
- for (const nodes of result.astToTemporal.values()) {
92
- for (const node of nodes) {
93
- if (!(node instanceof MeterTemporal))
94
- continue;
95
- let host = node;
96
- while (host.foldedInto)
97
- host = host.foldedInto;
98
- if (!metersByHost.has(host))
99
- metersByHost.set(host, node);
100
- }
101
- }
102
105
  for (const column of result.columns) {
103
106
  const time = column[0].t;
104
- const host = column.find(node => metersByHost.has(node));
105
- const meter = host && metersByHost.get(host);
106
- if (meter) {
107
- closeMeasure(time, meter.ast.sourceSpan.start);
108
- active = meter.ast;
107
+ for (const node of column) {
108
+ const change = changesByPosition.get(node);
109
+ if (!change)
110
+ continue;
111
+ closeMeasure(time, change.start);
112
+ active = change.meter;
109
113
  measureStart.copyFrom(time);
110
- sourceStart = meter.ast.sourceSpan.end;
114
+ sourceStart = change.end;
111
115
  }
112
116
  const anchor = column.find(node => node.mergeKey === ANCHOR_KEY);
113
117
  if (anchor) {
@@ -143,7 +147,13 @@ class MeterTemporal extends TemporalNodeBase {
143
147
  };
144
148
  this.initLayoutBox();
145
149
  }
150
+ onTimeState(state) {
151
+ state.meter = this.ast.measureDuration;
152
+ recordMeasureChange(state, this, this.ast);
153
+ }
146
154
  emitPlayback(emitter) {
155
+ if (!this.ast.measureDuration)
156
+ return;
147
157
  emitter.emit({
148
158
  kind: "time-signature",
149
159
  at: emitter.start,
@@ -152,6 +162,13 @@ class MeterTemporal extends TemporalNodeBase {
152
162
  });
153
163
  }
154
164
  prepareLayout(context) {
165
+ if (!this.ast.measureDuration) {
166
+ this.box.w = this.ast.size * sanbanBounds.w / sanbanBounds.h;
167
+ this.box.h = this.ast.size;
168
+ this.box.anchor = this.box.w / 2;
169
+ this.box.visualAxis = this.box.h / 2;
170
+ return;
171
+ }
155
172
  const num = context.textMeasurer.measureText(String(this.ast.numerator), this.style);
156
173
  const den = context.textMeasurer.measureText(String(this.ast.denominator), this.style);
157
174
  const gap = this.ast.size * 0.08;
@@ -167,6 +184,10 @@ class MeterTemporal extends TemporalNodeBase {
167
184
  this.box.visualAxis = this.lineY + this.lineHeight / 2;
168
185
  }
169
186
  paint(painter) {
187
+ if (!this.ast.measureDuration) {
188
+ paintSymbol(painter, sanbanShapes, sanbanBounds, this.box, this.ast.size / sanbanBounds.h);
189
+ return;
190
+ }
170
191
  const center = this.box.x + this.box.anchor;
171
192
  painter.drawText(String(this.ast.numerator), center, this.box.y + this.numeratorBaseline, this.style);
172
193
  painter.drawRect(this.box.x, this.box.y + this.lineY, this.box.w, this.lineHeight, { fill: "#000" });
@@ -0,0 +1,3 @@
1
+ import { type SymbolShape } from "../symbol/shape.js";
2
+ export declare const sanbanShapes: readonly SymbolShape[];
3
+ export declare const sanbanBounds: import("../../core.js").Rect;
@@ -0,0 +1,43 @@
1
+ import { symbolBounds } from "../symbol/shape.js";
2
+ export const sanbanShapes = [
3
+ {
4
+ path: [
5
+ { op: "M", x: 1, y: 34 },
6
+ { op: "C", cx1: 23, cy1: 36, cx2: 57, cy2: 28, x: 82, y: 23 },
7
+ { op: "C", cx1: 91, cy1: 21, cx2: 98, cy2: 24, x: 102, y: 29 },
8
+ { op: "Q", cx: 106, cy: 34, x: 98, y: 34 },
9
+ { op: "C", cx1: 68, cy1: 30, cx2: 37, cy2: 39, x: 13, y: 43 },
10
+ { op: "Q", cx: 7, cy: 44, x: 1, y: 39 },
11
+ { op: "Q", cx: -3, cy: 35, x: 1, y: 34 },
12
+ { op: "Z" },
13
+ ],
14
+ style: { fill: "#000" },
15
+ },
16
+ {
17
+ path: [
18
+ { op: "M", x: 29, y: 5 },
19
+ { op: "Q", cx: 27, cy: 3, x: 31, y: 4 },
20
+ { op: "Q", cx: 44, cy: 7, x: 42, y: 12 },
21
+ { op: "C", cx1: 39, cy1: 26, cx2: 43, cy2: 43, x: 42, y: 60 },
22
+ { op: "Q", cx: 41, cy: 69, x: 38, y: 62 },
23
+ { op: "C", cx1: 34, cy1: 47, cx2: 35, cy2: 20, x: 29, y: 5 },
24
+ { op: "Z" },
25
+ ],
26
+ style: { fill: "#000" },
27
+ },
28
+ {
29
+ path: [
30
+ { op: "M", x: 59, y: 1 },
31
+ { op: "Q", cx: 56, cy: -2, x: 61, y: 0 },
32
+ { op: "Q", cx: 76, cy: 4, x: 74, y: 9 },
33
+ { op: "C", cx1: 71, cy1: 17, cx2: 74, cy2: 32, x: 69, y: 48 },
34
+ { op: "C", cx1: 64, cy1: 66, cx2: 55, cy2: 77, x: 40, y: 84 },
35
+ { op: "Q", cx: 37, cy: 85, x: 40, y: 82 },
36
+ { op: "C", cx1: 57, cy1: 66, cx2: 63, cy2: 47, x: 64, y: 29 },
37
+ { op: "C", cx1: 65, cy1: 17, cx2: 63, cy2: 7, x: 59, y: 1 },
38
+ { op: "Z" },
39
+ ],
40
+ style: { fill: "#000" },
41
+ },
42
+ ];
43
+ export const sanbanBounds = symbolBounds(sanbanShapes);