jpfun 1.1.0 → 1.2.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 (54) hide show
  1. package/dist/diagnostic.d.ts +1 -0
  2. package/dist/diagnostic.js +1 -0
  3. package/dist/functions/ASTtypes.d.ts +2 -3
  4. package/dist/functions/ASTtypes.js +2 -3
  5. package/dist/functions/adjust/index.js +15 -67
  6. package/dist/functions/bar/index.js +8 -7
  7. package/dist/functions/beam/auto.js +15 -11
  8. package/dist/functions/beam/layout.js +22 -48
  9. package/dist/functions/br/index.d.ts +9 -3
  10. package/dist/functions/br/index.js +20 -16
  11. package/dist/functions/dash/index.js +13 -11
  12. package/dist/functions/div/index.d.ts +2 -2
  13. package/dist/functions/div/index.js +5 -9
  14. package/dist/functions/dot/index.js +5 -9
  15. package/dist/functions/dyn/index.js +125 -53
  16. package/dist/functions/grace/index.d.ts +2 -2
  17. package/dist/functions/grace/index.js +5 -9
  18. package/dist/functions/head/index.js +6 -7
  19. package/dist/functions/meter/index.js +7 -5
  20. package/dist/functions/note/index.js +5 -7
  21. package/dist/functions/ottava/index.js +8 -7
  22. package/dist/functions/page/index.js +8 -12
  23. package/dist/functions/pagebreak/index.js +2 -1
  24. package/dist/functions/rest/index.js +5 -5
  25. package/dist/functions/stack/index.js +1 -3
  26. package/dist/functions/symbol/symbols/dynamics.d.ts +3 -0
  27. package/dist/functions/symbol/symbols/dynamics.js +10 -1
  28. package/dist/functions/tempo/index.js +8 -3
  29. package/dist/functions/temporal.d.ts +18 -6
  30. package/dist/functions/temporal.js +1 -1
  31. package/dist/functions/text/index.js +1 -3
  32. package/dist/functions/up/index.js +29 -28
  33. package/dist/functions/voice/voice.d.ts +2 -1
  34. package/dist/functions/voice/voice.js +7 -13
  35. package/dist/functions/voice/voices.d.ts +4 -3
  36. package/dist/functions/voice/voices.js +8 -8
  37. package/dist/jpfun.min.js +48 -45
  38. package/dist/layout/engine.js +224 -211
  39. package/dist/layout/page.d.ts +2 -2
  40. package/dist/layout/page.js +8 -22
  41. package/dist/layout/types.d.ts +2 -4
  42. package/dist/lowering/loweringContext.d.ts +12 -7
  43. package/dist/lowering/loweringContext.js +50 -51
  44. package/dist/lowering/types.d.ts +2 -3
  45. package/dist/parser/grammarType.d.ts +4 -3
  46. package/dist/parser/parse-utils/brace-utils.js +4 -3
  47. package/dist/parser/parse-utils/call-utils.js +7 -7
  48. package/dist/parser/parserContext.d.ts +5 -9
  49. package/dist/parser/parserContext.js +24 -36
  50. package/dist/parser/types.d.ts +2 -1
  51. package/dist/playback/compile.js +23 -13
  52. package/dist/playback/types.d.ts +0 -1
  53. package/grammar.md +7 -6
  54. package/package.json +2 -2
@@ -46,6 +46,7 @@ declare const warnings: {
46
46
  InvalidUnicodeEscape: (span: SourceSpan) => WarningDiagnostic;
47
47
  UnknownFunction: (functionName: string, span: SourceSpan) => WarningDiagnostic;
48
48
  TooManyPosArgs: (functionName: string, expected: number, actual: number, span: SourceSpan) => WarningDiagnostic;
49
+ UnknownArg: (functionName: string, argumentName: string, span: SourceSpan) => WarningDiagnostic;
49
50
  InvalidNumber: (value: string, span: SourceSpan) => WarningDiagnostic;
50
51
  InvalidBoolean: (value: string, span: SourceSpan) => WarningDiagnostic;
51
52
  InvalidLength: (value: string, span: SourceSpan) => WarningDiagnostic;
@@ -82,6 +82,7 @@ const warnings = {
82
82
  InvalidUnicodeEscape: (span) => new WarningDiagnostic("W_STRING_INVALID_UNICODE_ESCAPE", "无效的 Unicode 转义:请使用 \\uXXXX(四位十六进制数字);将保留该字符串原文", span),
83
83
  UnknownFunction: (functionName, span) => new WarningDiagnostic("W_UNKNOWN_FUNCTION", "未知函数: @{fn},将被当作普通文本处理", span, { fn: functionName }),
84
84
  TooManyPosArgs: (functionName, expected, actual, span) => new WarningDiagnostic("W_TOO_MANY_POS_ARGS", "函数 @{fn} 接收了过多的位置参数,期望 {expected} 个但得到了 {actual} 个", span, { fn: functionName, expected, actual }),
85
+ UnknownArg: (functionName, argumentName, span) => new WarningDiagnostic("W_UNKNOWN_ARG", "函数 @{fn} 没有名为 {arg} 的参数;该参数将被忽略", span, { fn: functionName, arg: formatArg(argumentName) }),
85
86
  InvalidNumber: (value, span) => new WarningDiagnostic("W_INVALID_NUMBER", '无效的数字: "{value}";将使用默认值(若存在)', span, { value }),
86
87
  InvalidBoolean: (value, span) => new WarningDiagnostic("W_INVALID_BOOL", '无效的布尔值: "{value}": 应为 \'true\' 或 \'false\';将使用默认值(若存在)', span, { value }),
87
88
  InvalidLength: (value, span) => new WarningDiagnostic("W_INVALID_LENGTH", '无效的长度值: "{value}";请提供有效的长度值,例如 "10px" 或 "2em";将使用默认值(若存在)', span, { value }),
@@ -1,4 +1,4 @@
1
- import type { SourceSpan, LengthValue, deSugarAtomFunction, deSugarRelationFunction } from "../parser/types.js";
1
+ import type { SourceSpan, LengthValue, deSugarAtomFunction } from "../parser/types.js";
2
2
  import type { CallArgumentInfo } from "../parser/grammarType.js";
3
3
  import type { ParserContext } from "../parser/parserContext.js";
4
4
  import type { Fraction } from "../fraction.js";
@@ -90,7 +90,6 @@ export declare class ASTFunctionNode extends ASTNodeBase {
90
90
  get def(): FunctionDef | undefined;
91
91
  get callName(): string;
92
92
  static deSugarAtom: deSugarAtomFunction;
93
- static deSugarRelation: deSugarRelationFunction;
94
93
  getArgValue(args: FunctionArgs, ctx: ParserContext): paramValue[];
95
94
  toString(source: string): string;
96
95
  /**
@@ -107,4 +106,4 @@ export declare class ASTFunctionNode extends ASTNodeBase {
107
106
  */
108
107
  static findLabelable(node: ASTNodeBase): ASTFunctionNode | null;
109
108
  }
110
- export type ASTFunctionClass = (new (sourceSpan: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent: ASTNodeBase | null) => ASTFunctionNode) & Pick<typeof ASTFunctionNode, "prototype" | "def" | "deSugarAtom" | "deSugarRelation" | "layoutDecorationHandler">;
109
+ export type ASTFunctionClass = (new (sourceSpan: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent: ASTNodeBase | null) => ASTFunctionNode) & Pick<typeof ASTFunctionNode, "prototype" | "def" | "deSugarAtom" | "layoutDecorationHandler">;
@@ -114,9 +114,8 @@ export class ASTFunctionNode extends ASTNodeBase {
114
114
  get callName() {
115
115
  return this.def ? primaryName(this.def) : "";
116
116
  }
117
- // 去糖函数 详见 ParserContext 中 deSugarAtomFns 和 deSugarRelationFns 的定义
118
- static deSugarAtom = () => null; // 默认没有去糖,子类只需要定义static deSugarAtom方法即可
119
- static deSugarRelation = () => null;
117
+ // 原子去糖,默认没有,子类只需要定义 static deSugarAtom 即可;需要关系去糖时在产出的 sugar 节点上挂 relation
118
+ static deSugarAtom = () => null;
120
119
  // 按声明顺序取值,位置编号独立于仅命名参数
121
120
  getArgValue(args, ctx) {
122
121
  const def = this.def;
@@ -2,7 +2,6 @@ import { ASTFunctionNode } from "../ASTtypes.js";
2
2
  import { WarningDiagnostic } from "../../diagnostic.js";
3
3
  import { isVisualTemporalNode } from "../temporal.js";
4
4
  import { isLayoutAttachment, } from "../../layout/types.js";
5
- import { TranslatingPainter } from "../../render/translate.js";
6
5
  class AdjustFunction extends ASTFunctionNode {
7
6
  static def = {
8
7
  name: ["adjust", "adj"],
@@ -61,7 +60,8 @@ class AdjustFunction extends ASTFunctionNode {
61
60
  if (!isVisualTemporalNode(node))
62
61
  return;
63
62
  group.temporals++;
64
- offsetTemporal(node, this);
63
+ addOffset(node, this.dx, this.dy);
64
+ resizeTemporal(node, this.dw, this.dh);
65
65
  },
66
66
  onAttachment: attachment => {
67
67
  if (isLayoutAttachment(attachment))
@@ -76,9 +76,10 @@ class AdjustFunction extends ASTFunctionNode {
76
76
  if (temporals === 0 && attachments.length === 0) {
77
77
  ctx.diagnostics.push(new WarningDiagnostic("W_ADJUST_NO_TARGET", "@adjust 没有找到可调整的对象", this.sourceSpan));
78
78
  }
79
- else if (temporals === 0 && (this.dx !== 0 || this.dy !== 0)) {
79
+ else if (temporals === 0) {
80
+ // 作用域里有时间对象时,关系对象已跟随端点移动,不能再平移本身
80
81
  for (const attachment of attachments)
81
- offsetAttachment(attachment, this.dx, this.dy);
82
+ addOffset(attachment, this.dx, this.dy);
82
83
  }
83
84
  return [];
84
85
  }
@@ -97,76 +98,23 @@ class AdjustFunction extends ASTFunctionNode {
97
98
  }
98
99
  }
99
100
  export const AdjustNode = AdjustFunction;
100
- /** 在原对象上组合布局生命周期,保持布局索引依赖的对象身份 */
101
- function offsetTemporal(node, { dx, dy, dw, dh }) {
102
- if (dx === 0 && dy === 0 && dw === 0 && dh === 0)
101
+ /** 后置平移由引擎在排版后施加,嵌套微调逐层累加 */
102
+ function addOffset(target, dx, dy) {
103
+ if (dx === 0 && dy === 0)
104
+ return;
105
+ const offset = target.placementOffset;
106
+ target.placementOffset = { x: (offset?.x ?? 0) + dx, y: (offset?.y ?? 0) + dy };
107
+ }
108
+ /** 尺寸增量在原对象上组合 finalizeLayout,保持布局索引依赖的对象身份 */
109
+ function resizeTemporal(node, dw, dh) {
110
+ if (dw === 0 && dh === 0)
103
111
  return;
104
- const firstOffset = !node.placementOffset && (dx !== 0 || dy !== 0);
105
- if (dx !== 0 || dy !== 0) {
106
- node.placementOffset = { x: (node.placementOffset?.x ?? 0) + dx, y: (node.placementOffset?.y ?? 0) + dy };
107
- }
108
- let placedX;
109
- let placedY;
110
112
  const finalize = node.finalizeLayout;
111
113
  node.finalizeLayout = (context) => {
112
114
  finalize?.call(node, context);
113
- placedX = placedY = undefined;
114
115
  const width = Math.max(0, node.box.w + dw);
115
116
  node.box.anchor = node.box.w > 0 ? node.box.anchor * width / node.box.w : 0;
116
117
  node.box.w = width;
117
118
  node.box.h = Math.max(0, node.box.h + dh);
118
119
  };
119
- if (!firstOffset)
120
- return;
121
- let { x, y } = node.box;
122
- Object.defineProperties(node.box, {
123
- x: {
124
- get: () => x,
125
- set(v) { if (v === placedX && x === placedX)
126
- placedX = undefined; x = v; }
127
- },
128
- y: {
129
- get: () => y,
130
- set(v) { if (v === placedY && y === placedY)
131
- placedY = undefined; y = v; }
132
- },
133
- });
134
- const onPlaced = node.onPlaced;
135
- node.onPlaced = () => {
136
- if (x !== placedX)
137
- x += node.placementOffset.x;
138
- if (y !== placedY)
139
- y += node.placementOffset.y;
140
- onPlaced?.call(node);
141
- placedX = x;
142
- placedY = y;
143
- };
144
- }
145
- /**
146
- * 平移一条关系对象
147
- *
148
- * 在原 Attachment 上组合 createGeometry,保留依赖查找与 instanceof 所需的对象身份
149
- * 仅在作用域里没有时间对象时调用,避免关系对象既跟端点走又被重复平移
150
- */
151
- function offsetAttachment(attachment, dx, dy) {
152
- const firstOffset = !attachment.placementOffset;
153
- attachment.placementOffset = { x: (attachment.placementOffset?.x ?? 0) + dx, y: (attachment.placementOffset?.y ?? 0) + dy };
154
- if (!firstOffset)
155
- return;
156
- const createGeometry = attachment.createGeometry;
157
- attachment.createGeometry = (context) => {
158
- const geometry = createGeometry.call(attachment, context);
159
- if (context.layoutOnly)
160
- return geometry;
161
- const { x, y } = attachment.placementOffset;
162
- const shift = (region) => ({ ...region, x: region.x + x, y: region.y + y });
163
- return {
164
- regions: geometry.regions.map(shift),
165
- occupancy: geometry.occupancy?.map(shift),
166
- paint(painter) {
167
- // attachment 的绘制大多用闭包存储了,所以只能代理 painter
168
- geometry.paint(new TranslatingPainter(painter, x, y));
169
- },
170
- };
171
- };
172
120
  }
@@ -15,17 +15,16 @@ export function registerBarNumbering(ctx, pattern, font) {
15
15
  let measureRecorded = false;
16
16
  let lastLine = -1;
17
17
  for (const column of result.columns) {
18
- const time = column[0].t;
19
- if (column.some(node => node.mergeKey === ANCHOR_KEY)) {
18
+ if (column.mergeKey === ANCHOR_KEY) {
20
19
  // 只有当前小节已走过正时值才闭合进入下一小节
21
- if (time.compare(measureStart) > 0) {
20
+ if (column.t.compare(measureStart) > 0) {
22
21
  measureNumber++;
23
- measureStart.copyFrom(time);
22
+ measureStart.copyFrom(column.t);
24
23
  measureRecorded = false;
25
24
  }
26
25
  }
27
26
  else if (column.some(node => !node.T.isZero() && isVisualTemporalNode(node))) {
28
- const line = column[0].layoutLine;
27
+ const line = column.layoutLine;
29
28
  if (line !== lastLine) {
30
29
  // 首行(lastLine < 0)与单行谱不标号;跨行未闭合的小节不重复标号
31
30
  if (lastLine >= 0 && !measureRecorded)
@@ -142,7 +141,9 @@ class BarNumberAttachment {
142
141
  const firstCol = context.lines[line].columns[0];
143
142
  // 选取行首列中视觉轴最靠上的宿主,确保小节号只挂在最顶层声部上方
144
143
  const topHost = firstCol.reduce((top, host) => context.getVisualAxis(line, host.track) < context.getVisualAxis(line, top.track) ? host : top);
145
- const fontSize = topHost.ast.size;
144
+ // 字号与高度参照该声部首个有时值的主体,避免行首零时值的文字、记号等使小节号变小或错位
145
+ const ref = context.lines[line].trackRuns.get(topHost.track)?.find(host => !host.T.isZero()) ?? topHost;
146
+ const fontSize = ref.ast.size;
146
147
  const port = topHost.ports["bar.number"];
147
148
  const style = {
148
149
  fontSize: fontSize * 0.5,
@@ -156,7 +157,7 @@ class BarNumberAttachment {
156
157
  const x = port ? topHost.box.x + port.x : context.originX - fontSize * 0.15;
157
158
  const topY = port
158
159
  ? topHost.box.y + port.y
159
- : Math.min(topHost.box.y, context.getVisualAxis(line, topHost.track) - fontSize * 0.5);
160
+ : Math.min(ref.box.y, context.getVisualAxis(line, ref.track) - fontSize * 0.5);
160
161
  const baselineY = topY - fontSize * 0.04;
161
162
  return {
162
163
  text,
@@ -1,4 +1,5 @@
1
1
  import { ANCHOR_KEY, isVisualTemporalNode, } from "../temporal.js";
2
+ import { ErrorDiagnostic } from "../../diagnostic.js";
2
3
  import { Fraction } from "../../fraction.js";
3
4
  import { getDivOwner, } from "../div/index.js";
4
5
  import { meterChangeAt } from "../meter/index.js";
@@ -32,13 +33,18 @@ function createAutoBeam(nodes) {
32
33
  }
33
34
  return createBeamLayoutAttachment(nodes, false, { start, end });
34
35
  }
35
- /** 同一个 div 内部始终按轨道连接,手工 beam 端点会截断自动片段 */
36
+ /** 同一个 div 内部始终按轨道连接,手工 beam 端点会截断自动片段;连梁不能跨谱面行 */
36
37
  function createScopeBeams(scopes, explicitEndpoints) {
37
38
  const attachments = [];
38
39
  const segments = new Map();
39
40
  const flush = (segment) => {
40
- if (segment && segment.length >= 2)
41
- attachments.push(createAutoBeam(segment));
41
+ if (!segment || segment.length < 2)
42
+ return;
43
+ const line = segment[0].layoutLine;
44
+ if (segment.some(node => node.layoutLine !== line)) {
45
+ throw new ErrorDiagnostic("E_DIV_CROSS_LINE", "@div 内连成一组的减时线不能跨越谱面行", getDivOwner(segment[0]).sourceSpan);
46
+ }
47
+ attachments.push(createAutoBeam(segment));
42
48
  };
43
49
  for (const scopeNodes of scopes) {
44
50
  if (scopeNodes.length < 2)
@@ -89,18 +95,16 @@ function createAdjacentBeams(result, scopes, explicitEndpoints) {
89
95
  flush(track);
90
96
  };
91
97
  for (const column of result.columns) {
92
- const line = column[0].layoutLine;
98
+ const line = column.layoutLine;
99
+ const isAnchor = column.mergeKey === ANCHOR_KEY;
93
100
  let meter;
94
- let hasAnchor = false;
95
101
  for (const node of column) {
96
102
  meter = meterChangeAt(node) ?? meter;
97
- if (node.mergeKey === ANCHOR_KEY)
98
- hasAnchor = true;
99
103
  }
100
- if (line !== currentLine || meter || hasAnchor) {
104
+ if (line !== currentLine || meter || isAnchor) {
101
105
  currentLine = line;
102
106
  flushAll();
103
- phaseStart.copyFrom(column[0].t);
107
+ phaseStart.copyFrom(column.t);
104
108
  }
105
109
  if (meter) {
106
110
  const { numerator, denominator } = meter;
@@ -112,9 +116,9 @@ function createAdjacentBeams(result, scopes, explicitEndpoints) {
112
116
  }
113
117
  candidateDuration = beatDuration.compare(1) < 0 ? beatDuration : 1;
114
118
  }
119
+ if (isAnchor)
120
+ continue;
115
121
  for (const node of column) {
116
- if (node.mergeKey === ANCHOR_KEY)
117
- continue;
118
122
  const owner = isVisualTemporalNode(node) ? getDivOwner(node) : undefined;
119
123
  const isCandidate = isVisualTemporalNode(node)
120
124
  && owner !== undefined
@@ -91,8 +91,8 @@ class BeamLayoutAttachment {
91
91
  left = node;
92
92
  }
93
93
  }
94
- createGeometry(context) {
95
- const lines = this.collectLines(context);
94
+ createGeometry() {
95
+ const lines = this.collectLines();
96
96
  const strokeWidth = this.strokeWidth;
97
97
  // 减时线永远水平,butt 端帽只在纵向占半个描边
98
98
  const regions = lines.map(line => ({
@@ -119,7 +119,7 @@ class BeamLayoutAttachment {
119
119
  y: node.box.y + port.y,
120
120
  };
121
121
  }
122
- collectLines(context) {
122
+ collectLines() {
123
123
  const lines = [];
124
124
  const available = this.endPoints.filter(isVisualTemporalNode);
125
125
  if (available.length < 2)
@@ -136,7 +136,7 @@ class BeamLayoutAttachment {
136
136
  node,
137
137
  });
138
138
  }
139
- this.addSystemLines(spans, context, level, lines);
139
+ this.addLine(spans, level, lines);
140
140
  }
141
141
  // 显式关系允许连接没有 div 端口的任意可见对象
142
142
  if (lines.length === 0 && this.explicit) {
@@ -154,53 +154,27 @@ class BeamLayoutAttachment {
154
154
  node,
155
155
  };
156
156
  });
157
- this.addSystemLines(spans, context, null, lines);
157
+ this.addLine(spans, null, lines);
158
158
  }
159
159
  return lines;
160
160
  }
161
- /** 同一级减时线按谱面行拆开,跨行时连接到对应页面边界 */
162
- addSystemLines(spans, context, connectedLevel, lines) {
163
- const firstLine = Math.min(...spans.map(item => item.line));
164
- const lastLine = Math.max(...spans.map(item => item.line));
165
- const fallbackTrack = spans[0].track;
166
- const firstVisualAxis = context.getVisualAxis(spans[0].line, fallbackTrack);
167
- const visualAxisOffset = spans[0].left.y - firstVisualAxis;
168
- for (let line = firstLine; line <= lastLine; line++) {
169
- const current = spans
170
- .filter(item => item.line === line)
171
- .sort((left, right) => left.left.x - right.left.x);
172
- if (current.length === 0) {
173
- const visualAxis = context.getVisualAxis(line, fallbackTrack);
174
- const y = visualAxis + visualAxisOffset;
175
- lines.push({
176
- start: { x: context.originX, y },
177
- end: { x: context.originX + context.width, y },
178
- line,
179
- track: fallbackTrack,
180
- });
181
- continue;
182
- }
183
- const first = current[0];
184
- const last = current[current.length - 1];
185
- const y = first.left.y;
186
- const start = { x: first.left.x, y };
187
- const end = { x: last.right.x, y };
188
- if (line > firstLine)
189
- start.x = context.originX;
190
- if (line < lastLine)
191
- end.x = context.originX + context.width;
192
- if (start.x === end.x && firstLine === lastLine)
193
- continue;
194
- if (connectedLevel !== null) {
195
- for (const span of current)
196
- claimDivLine(span.node, connectedLevel);
197
- }
198
- lines.push({
199
- start,
200
- end,
201
- line,
202
- track: first.track,
203
- });
161
+ /** 端点在 lowering 收尾时已保证同一谱面行,只需连接首尾端口 */
162
+ addLine(spans, connectedLevel, lines) {
163
+ spans.sort((left, right) => left.left.x - right.left.x);
164
+ const first = spans[0];
165
+ const last = spans[spans.length - 1];
166
+ const y = first.left.y;
167
+ if (first.left.x === last.right.x)
168
+ return;
169
+ if (connectedLevel !== null) {
170
+ for (const span of spans)
171
+ claimDivLine(span.node, connectedLevel);
204
172
  }
173
+ lines.push({
174
+ start: { x: first.left.x, y },
175
+ end: { x: last.right.x, y },
176
+ line: first.line,
177
+ track: first.track,
178
+ });
205
179
  }
206
180
  }
@@ -13,15 +13,21 @@ declare class BrFunction extends ASTFunctionNode {
13
13
  args: {
14
14
  name: string;
15
15
  description: string;
16
- type: "number";
17
- default: number;
16
+ type: "length";
17
+ default: {
18
+ value: number;
19
+ unit: "em";
20
+ };
18
21
  }[];
19
22
  };
20
23
  static deSugarAtom(source: string, start: number, end: number, depth: number): {
21
24
  next: number;
22
25
  node: GrammarCallNodeTyped;
23
26
  } | null;
24
- readonly offset: number;
27
+ readonly lineGap: {
28
+ gap: number;
29
+ minGap: number;
30
+ };
25
31
  loweringEnter(ctx: LoweringContext): TemporalNodeBase[];
26
32
  /**
27
33
  * 换行与换页共享校验;边界会切开全谱,不能截断持续事件
@@ -1,7 +1,7 @@
1
1
  import { ASTFunctionNode } from "../ASTtypes.js";
2
2
  import { skipSpaces, skipSpacesBack } from "../../parser/parserContext.js";
3
3
  import { TemporalNodeBase } from "../temporal.js";
4
- import { Diagnostic, WarningDiagnostic } from "../../diagnostic.js";
4
+ import { Diagnostic } from "../../diagnostic.js";
5
5
  import { Fraction } from "../../fraction.js";
6
6
  class BrFunction extends ASTFunctionNode {
7
7
  static def = {
@@ -9,19 +9,26 @@ class BrFunction extends ASTFunctionNode {
9
9
  description: "换行",
10
10
  details: `\
11
11
  ~~~jpfun
12
- 1 2 @br() 3 4
12
+ @set(br.gap=1.5em)
13
+ 1 2 @br() 3 4 @br(3em) 5 6
13
14
  ~~~
14
15
 
15
- \`@br()\` 换到下一行,\`@br(2)\` 空出一行再继续
16
+ \`@br()\` 换到下一行,连写 \`@br() @br()\` 叠加两段行距;用 \`@set(br.gap=...)\` 设置后续默认行距
16
17
 
17
18
  **简写**:仅在顶层,连续至少两个换行表示换行`,
18
19
  allowExtraArgs: false,
19
20
  args: [
20
21
  {
21
- name: "offset",
22
- description: "后续内容偏移的谱面行数,2 表示空出一行再继续",
23
- type: "number",
24
- default: 1,
22
+ name: "gap",
23
+ description: "上一行下沿到下一行主旋律上沿的标准间距;下一行顶部外扩记号优先借用这段间距",
24
+ type: "length",
25
+ default: { value: 1, unit: "em" },
26
+ },
27
+ {
28
+ name: "minGap",
29
+ description: "顶部外扩记号借用间距后,与上一行保留的最小间距",
30
+ type: "length",
31
+ default: { value: 0.4, unit: "em" },
25
32
  },
26
33
  ],
27
34
  };
@@ -45,13 +52,13 @@ class BrFunction extends ASTFunctionNode {
45
52
  };
46
53
  return { next, node };
47
54
  }
48
- offset;
55
+ lineGap;
49
56
  loweringEnter(ctx) {
50
57
  ctx.deferFinalize(BrFunction.loweringFinalize);
51
58
  const br = new TemporalNodeBase();
52
59
  br.ast = this;
53
60
  br.mergeKey = -1;
54
- br.addon = { breakBefore: this.offset };
61
+ br.addon = { breakBefore: this.lineGap };
55
62
  return [br];
56
63
  }
57
64
  /**
@@ -62,7 +69,7 @@ class BrFunction extends ASTFunctionNode {
62
69
  const candidateEnd = new Fraction();
63
70
  let latestNode = null;
64
71
  for (const column of result.columns) {
65
- if (latestNode && latestEnd.compare(column[0].t) > 0 && column.some(node => (node.addon?.breakBefore ?? 0) > 0)) {
72
+ if (latestNode && latestEnd.compare(column.t) > 0 && column.some(node => node.addon?.breakBefore)) {
66
73
  throw Diagnostic.error.BreakInsideEvent(latestNode.ast.sourceSpan);
67
74
  }
68
75
  for (const node of column) {
@@ -78,12 +85,9 @@ class BrFunction extends ASTFunctionNode {
78
85
  }
79
86
  constructor(span, args, ctx, parent = null) {
80
87
  super(span, parent);
81
- const [offset] = this.getArgValue(args, ctx);
82
- this.offset = Number.isFinite(offset) ? Math.max(1, Math.floor(offset)) : 1;
83
- if (this.offset !== offset) {
84
- ctx.diagnostics.push(new WarningDiagnostic("W_BR_OFFSET", "@br 的 offset 必须是大于等于 1 的整数,已被修正为 {offset}", this.sourceSpan, { offset: this.offset }));
85
- }
88
+ const [gap, minGap] = this.getArgValue(args, ctx).map(value => ctx.length2px(value));
89
+ this.lineGap = { gap, minGap };
86
90
  }
87
- toString() { return `@br(${this.offset})`; }
91
+ toString() { return `@br(gap=${this.lineGap.gap}px, minGap=${this.lineGap.minGap}px)`; }
88
92
  }
89
93
  export const BrNode = BrFunction;
@@ -28,9 +28,16 @@ class DashFunction extends ASTFunctionNode {
28
28
  }
29
29
  ;
30
30
  size;
31
+ /** 与数字音符相同的测量样式,盒宽由此决定 */
32
+ numberStyle;
31
33
  constructor(span, _args, ctx, parent = null) {
32
34
  super(span, parent);
33
35
  this.size = ctx.variables.fontsize;
36
+ this.numberStyle = {
37
+ fontSize: this.size,
38
+ fontFamily: ctx.variables.numberfont,
39
+ fontWeight: ctx.variables.numberweight,
40
+ };
34
41
  }
35
42
  loweringEnter() {
36
43
  return [new DashTemporalNode(this)];
@@ -40,7 +47,6 @@ class DashFunction extends ASTFunctionNode {
40
47
  }
41
48
  export const DashNode = DashFunction;
42
49
  class DashTemporalNode extends TemporalNodeBase {
43
- lineWidth = 0;
44
50
  constructor(ast) {
45
51
  super();
46
52
  this.ast = ast;
@@ -48,18 +54,13 @@ class DashTemporalNode extends TemporalNodeBase {
48
54
  this.mergeKey = DEFAULT_KEY;
49
55
  this.initLayoutBox();
50
56
  }
51
- /** 固化记谱位置的速度,控制流直接跳到增时线时也能恢复正确状态 */
52
- onTimeState(state) {
53
- this.playbackState = { bpm: state.bpm };
54
- }
55
- prepareLayout() {
57
+ prepareLayout(context) {
56
58
  const size = this.ast.size;
57
- this.lineWidth = size * 0.42;
58
- // dash 与数字音符共享视觉中心和完整字号高度
59
+ // dash 与数字音符共享盒宽、视觉中心和完整字号高度,线在盒内居中
59
60
  // 线本身位于数字视觉中心,不使用极小的 glyph 高度作为轨道高度
60
- this.box.w = this.lineWidth;
61
+ this.box.w = context.textMeasurer.measureText("0", this.ast.numberStyle).w;
61
62
  this.box.h = size;
62
- this.box.anchor = this.lineWidth / 2;
63
+ this.box.anchor = this.box.w / 2;
63
64
  this.box.visualAxis = size * 0.5;
64
65
  }
65
66
  finalizeLayout() {
@@ -101,7 +102,8 @@ class DashTemporalNode extends TemporalNodeBase {
101
102
  });
102
103
  }
103
104
  paint(painter) {
105
+ const w = this.ast.size * 0.42;
104
106
  const h = Math.max(1, this.ast.size * 0.1);
105
- painter.drawRect(this.box.x, this.box.y + this.box.visualAxis - h / 2, this.lineWidth, h, { fill: "#000" });
107
+ painter.drawRect(this.box.x + this.box.anchor - w / 2, this.box.y + this.box.visualAxis - h / 2, w, h, { fill: "#000" });
106
108
  }
107
109
  }
@@ -1,5 +1,5 @@
1
1
  import { ASTNodeBase, FunctionArgs, SourceSpan, ParserContext, ASTFunctionNode } from "../ASTtypes.js";
2
- import { GrammarNode, GrammarSugarNode } from "../../parser/grammarType.js";
2
+ import { GrammarSugarNode } from "../../parser/grammarType.js";
3
3
  import type { LayoutDecorationHandler, LayoutHost } from "../../layout/types.js";
4
4
  import type { LoweringContext } from "../../lowering/loweringContext.js";
5
5
  import type { TemporalNodeBase } from "../temporal.js";
@@ -47,7 +47,7 @@ declare class DivFunction extends ASTFunctionNode {
47
47
  next: number;
48
48
  node: GrammarSugarNode;
49
49
  } | null;
50
- static deSugarRelation(ctx: ParserContext, nodes: (GrammarNode | number)[], at: number): number | null;
50
+ private static deSugarRelation;
51
51
  /**
52
52
  * 减时线是目标对象下方的通用装饰
53
53
  * 多对象自动连线属于 beam 的关系排版,不在这里猜测相邻元素
@@ -89,35 +89,31 @@ class DivFunction extends ASTFunctionNode {
89
89
  }
90
90
  if (divCnt === 0)
91
91
  return null;
92
- // 对前一个节点的探查放到 deSugarRelation 中
92
+ // 对前一个节点的探查放到 relation 中
93
93
  const node = {
94
94
  kind: "sugar",
95
- data: {
96
- class: DivFunction,
97
- n: divCnt,
98
- },
95
+ data: divCnt,
99
96
  span: { start, end: pos },
97
+ relation: DivFunction.deSugarRelation,
100
98
  };
101
99
  return { next: pos, node };
102
100
  }
103
101
  ;
104
102
  static deSugarRelation(ctx, nodes, at) {
105
103
  const n = nodes[at++];
106
- if (n.data?.class !== DivFunction)
107
- return null;
108
104
  const prevIndex = ctx.findLastOperandIndex();
109
105
  if (prevIndex < 0)
110
106
  return at; // 没有了 直接当作无效文本跳过
111
107
  const prev = ctx.nodes[prevIndex];
112
108
  if (prev instanceof DivFunction) {
113
109
  // 已经是div了 继续加深
114
- prev.n += n.data.n;
110
+ prev.n += n.data;
115
111
  prev.sourceSpan.end = Math.max(prev.sourceSpan.end, n.span.end);
116
112
  return at;
117
113
  }
118
114
  const argMap = new Map();
119
115
  argMap.set(0, prev);
120
- argMap.set("n", n.data.n);
116
+ argMap.set("n", n.data);
121
117
  const spanPrev = prev.sourceSpan;
122
118
  ctx.nodes[prevIndex] = new DivFunction({
123
119
  start: Math.min(spanPrev.start, n.span.start),
@@ -42,36 +42,32 @@ class DotFunction extends ASTFunctionNode {
42
42
  }
43
43
  if (dotCnt === 0)
44
44
  return null;
45
- // 对前一个节点的探查放到 deSugarRelation 中
45
+ // 对前一个节点的探查放到 relation 中
46
46
  const node = {
47
47
  kind: "sugar",
48
- data: {
49
- class: DotFunction,
50
- n: dotCnt,
51
- },
48
+ data: dotCnt,
52
49
  span: { start, end: pos },
50
+ relation: DotFunction.deSugarRelation,
53
51
  };
54
52
  return { next: pos, node };
55
53
  }
56
54
  ;
57
55
  static deSugarRelation(ctx, nodes, at) {
58
56
  const n = nodes[at++];
59
- if (n.data?.class !== DotFunction)
60
- return null;
61
57
  const prevIndex = ctx.findLastOperandIndex();
62
58
  if (prevIndex < 0)
63
59
  return at; // 没有了 直接当作无效文本跳过
64
60
  const prev = ctx.nodes[prevIndex];
65
61
  if (prev instanceof DotFunction) {
66
62
  // 已经是dot了 继续加深
67
- prev.n += n.data.n;
63
+ prev.n += n.data;
68
64
  prev.sourceSpan.end = Math.max(prev.sourceSpan.end, n.span.end);
69
65
  return at;
70
66
  }
71
67
  // 参数数量不校验 在构造函数里写
72
68
  const argMap = new Map();
73
69
  argMap.set(0, prev);
74
- argMap.set("n", n.data.n);
70
+ argMap.set("n", n.data);
75
71
  const spanPrev = prev.sourceSpan;
76
72
  ctx.nodes[prevIndex] = new DotFunction({
77
73
  start: Math.min(spanPrev.start, n.span.start),