jpfun 0.9.0 → 1.0.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 (104) hide show
  1. package/README.md +10 -15
  2. package/dist/diagnostic.d.ts +29 -2
  3. package/dist/diagnostic.js +5 -4
  4. package/dist/functions/arpeggio/index.js +2 -3
  5. package/dist/functions/bar/index.d.ts +3 -0
  6. package/dist/functions/bar/index.js +18 -3
  7. package/dist/functions/beam/layout.js +3 -2
  8. package/dist/functions/box/index.js +1 -0
  9. package/dist/functions/dash/index.js +5 -2
  10. package/dist/functions/div/index.d.ts +1 -1
  11. package/dist/functions/div/index.js +4 -2
  12. package/dist/functions/dyn/index.js +1 -0
  13. package/dist/functions/gliss/index.js +4 -2
  14. package/dist/functions/grace/index.js +3 -5
  15. package/dist/functions/head/index.js +23 -30
  16. package/dist/functions/key/index.js +4 -7
  17. package/dist/functions/meter/index.d.ts +1 -0
  18. package/dist/functions/meter/index.js +3 -0
  19. package/dist/functions/meter/shape.d.ts +1 -1
  20. package/dist/functions/note/accidentals.d.ts +3 -3
  21. package/dist/functions/note/accidentals.js +29 -16
  22. package/dist/functions/note/index.js +11 -13
  23. package/dist/functions/note/source-transform.d.ts +15 -0
  24. package/dist/functions/note/source-transform.js +74 -67
  25. package/dist/functions/ottava/index.js +1 -0
  26. package/dist/functions/page/index.js +4 -3
  27. package/dist/functions/rest/index.js +8 -6
  28. package/dist/functions/slide/index.js +1 -0
  29. package/dist/functions/temporal.d.ts +9 -3
  30. package/dist/functions/temporal.js +15 -2
  31. package/dist/functions/tie/index.js +28 -4
  32. package/dist/functions/tremolo/index.js +1 -0
  33. package/dist/functions/tuplet/index.js +1 -0
  34. package/dist/functions/up/index.js +3 -5
  35. package/dist/functions/voice/connections.d.ts +1 -1
  36. package/dist/functions/voice/lyrics.d.ts +9 -5
  37. package/dist/functions/voice/lyrics.js +148 -44
  38. package/dist/functions/voice/voice.d.ts +6 -2
  39. package/dist/functions/voice/voice.js +49 -17
  40. package/dist/functions/voice/voices.js +2 -1
  41. package/dist/functions/volta/index.js +1 -0
  42. package/dist/index.d.ts +97 -3
  43. package/dist/index.js +97 -3
  44. package/dist/jpfun.min.js +47 -60
  45. package/dist/layout/engine.d.ts +4 -3
  46. package/dist/layout/engine.js +160 -6
  47. package/dist/layout/model.d.ts +12 -3
  48. package/dist/layout/model.js +15 -7
  49. package/dist/layout/page.js +2 -2
  50. package/dist/layout/path.js +1 -1
  51. package/dist/layout/types.d.ts +10 -2
  52. package/dist/parser/grammarType.d.ts +3 -3
  53. package/dist/parser/parse-utils/brace-utils.js +7 -17
  54. package/dist/parser/parse-utils/call-utils.d.ts +3 -1
  55. package/dist/parser/parse-utils/call-utils.js +17 -32
  56. package/dist/parser/parse-utils/note-utils.d.ts +4 -0
  57. package/dist/parser/parse-utils/note-utils.js +8 -12
  58. package/dist/parser/parserContext.d.ts +8 -2
  59. package/dist/parser/parserContext.js +57 -55
  60. package/dist/parser/preprocess.d.ts +7 -0
  61. package/dist/parser/preprocess.js +21 -19
  62. package/dist/pipeline.d.ts +1 -1
  63. package/dist/playback/compile.js +1 -1
  64. package/dist/render/canvas.js +50 -35
  65. package/dist/render/index.d.ts +1 -1
  66. package/dist/render/index.js +1 -1
  67. package/dist/render/paint.d.ts +7 -0
  68. package/dist/render/paint.js +70 -20
  69. package/dist/render/recording.d.ts +8 -1
  70. package/dist/render/recording.js +12 -0
  71. package/dist/render/svg.d.ts +5 -1
  72. package/dist/render/svg.js +37 -17
  73. package/dist/render/text.d.ts +2 -2
  74. package/dist/render/text.js +7 -6
  75. package/dist/render/translate.d.ts +3 -1
  76. package/dist/render/translate.js +6 -0
  77. package/dist/render/types.d.ts +9 -0
  78. package/grammar.md +6 -5
  79. package/package.json +8 -18
  80. package/dist/converter/midi/convert.d.ts +0 -42
  81. package/dist/converter/midi/convert.js +0 -682
  82. package/dist/converter/midi/index.d.ts +0 -5
  83. package/dist/converter/midi/index.js +0 -11
  84. package/dist/converter/midi/json.d.ts +0 -38
  85. package/dist/converter/midi/json.js +0 -1
  86. package/dist/converter/midi/triplet.d.ts +0 -30
  87. package/dist/converter/midi/triplet.js +0 -75
  88. package/dist/converter/musicxml/dom.d.ts +0 -25
  89. package/dist/converter/musicxml/dom.js +0 -65
  90. package/dist/converter/musicxml/features.d.ts +0 -114
  91. package/dist/converter/musicxml/features.js +0 -501
  92. package/dist/converter/musicxml/index.d.ts +0 -14
  93. package/dist/converter/musicxml/index.js +0 -1285
  94. package/dist/converter/musicxml/model.d.ts +0 -176
  95. package/dist/converter/musicxml/model.js +0 -1
  96. package/dist/converter/musicxml/resolve.d.ts +0 -10
  97. package/dist/converter/musicxml/resolve.js +0 -152
  98. package/dist/converter/source.d.ts +0 -19
  99. package/dist/converter/source.js +0 -53
  100. package/dist/core.d.ts +0 -24
  101. package/dist/core.js +0 -24
  102. package/dist/jpfun.core.min.js +0 -132
  103. package/dist/jpfun.from-midi.min.js +0 -9
  104. package/dist/jpfun.from-musicxml.min.js +0 -12
package/README.md CHANGED
@@ -18,18 +18,9 @@ Or load via CDN (`globalThis.jpfun`):
18
18
  <script src="https://unpkg.com/jpfun"></script>
19
19
  ```
20
20
 
21
- In production, pin all CDN bundles to the same `jpfun@x.y.z` version.
21
+ This loads `dist/jpfun.min.js` and exposes the public APIs as `globalThis.jpfun`. Pin a version in production, for example `https://unpkg.com/jpfun@1.0.0`.
22
22
 
23
- IIFE bundles under `jpfun/dist/` share the `jpfun` global:
24
-
25
- | Bundle | Capabilities |
26
- | --- | --- |
27
- | `jpfun.min.js` | Core and both converters |
28
- | `jpfun.core.min.js` | Compilation, rendering, playback, and source editing; no converters |
29
- | `jpfun.from-midi.min.js` | MIDI JSON import; automatic line breaking also requires core |
30
- | `jpfun.from-musicxml.min.js` | Standalone MusicXML import |
31
-
32
- For standalone MIDI import, set a positive `barsPerLine`.
23
+ Conversion scripts are distributed separately by `@jpfun/convert`.
33
24
 
34
25
  ## Quick Start
35
26
 
@@ -59,8 +50,12 @@ Check returned `diagnostics` for recoverable problems and catch compilation erro
59
50
 
60
51
  For Canvas, create and size one canvas per layout page; see the [rendering example](https://madderscientist.github.io/jpFun/docs/developer/use/#渲染结果). The default text measurer estimates widths; `CanvasTextMeasurer` measures browser font widths for both SVG and Canvas layout.
61
52
 
53
+ Node.js TypeScript consumers must include `"DOM"` in `compilerOptions.lib` (for example, `["ES2022", "DOM"]`) because the public Canvas declarations use `CanvasRenderingContext2D`. This only supplies types; it does not add browser APIs at runtime.
54
+
62
55
  ## Core APIs
63
56
 
57
+ Import public APIs directly from `jpfun`, including built-in function nodes, `ParserContext`, `LoweringContext`, parser utilities, layout helpers, playback events, painters, and symbol definitions.
58
+
64
59
  ### Custom Symbols (`symbols`)
65
60
 
66
61
  Register or override `@symbol` (`$name`) definitions for instrument-specific symbol packages:
@@ -88,11 +83,11 @@ The registry is shared across compilations. Names are case-insensitive, and late
88
83
 
89
84
  ### MIDI & MusicXML Import
90
85
 
91
- Import from dedicated subpaths (or from `"jpfun"`):
86
+ Install the optional converter package with `npm install @jpfun/convert`:
92
87
 
93
88
  ```ts
94
- import { midiJsonToJpFun } from "jpfun/converter/midi";
95
- import { musicXmlToJpFun } from "jpfun/converter/musicxml";
89
+ import { midiJsonToJpFun } from "@jpfun/convert/midi";
90
+ import { musicXmlToJpFun } from "@jpfun/convert/musicxml";
96
91
 
97
92
  const fromMidi = midiJsonToJpFun(parsedMidiJson, { pitchMode: "absolute", alignRate: 4, barsPerLine: 0 });
98
93
  const { script, diagnostics } = musicXmlToJpFun(xmlDocument.documentElement, { pitchMode: "absolute", barsPerLine: 4 });
@@ -104,4 +99,4 @@ See the [Developer Documentation](https://madderscientist.github.io/jpFun/docs/d
104
99
 
105
100
  ## License
106
101
 
107
- [Apache-2.0](LICENSE), except the `$turn` / `$iturn` / `$coda` glyphs derived from [Bravura](https://github.com/steinbergmedia/bravura), licensed under [SIL OFL 1.1](Bravura-LICENSE.txt). Include `Bravura-LICENSE.txt` when redistributing these glyphs or bundles containing them.
102
+ [Apache-2.0](https://github.com/madderscientist/jpFun/blob/main/LICENSE), except the `$turn` / `$iturn` / `$coda` glyphs derived from [Bravura](https://github.com/steinbergmedia/bravura), licensed under [SIL OFL 1.1](Bravura-LICENSE.txt). Include `Bravura-LICENSE.txt` when redistributing these glyphs or bundles containing them.
@@ -24,10 +24,37 @@ export declare abstract class Diagnostic {
24
24
  line: number;
25
25
  column: number;
26
26
  };
27
- static error: any;
28
- static warning: any;
27
+ static error: typeof errors;
28
+ static warning: typeof warnings;
29
29
  }
30
30
  export declare class ErrorDiagnostic extends Diagnostic {
31
31
  }
32
32
  export declare class WarningDiagnostic extends Diagnostic {
33
33
  }
34
+ declare const errors: {
35
+ Bug: (message: string, span: SourceSpan) => ErrorDiagnostic;
36
+ MissingArg: (functionName: string, argumentName: string | number, span: SourceSpan) => ErrorDiagnostic;
37
+ PosAfterNamedArg: (functionName: string, span: SourceSpan) => ErrorDiagnostic;
38
+ EmptyContent: (functionName: string, argumentName: string | number, span: SourceSpan) => ErrorDiagnostic;
39
+ UnterminatedCall: (functionName: string, span: SourceSpan) => ErrorDiagnostic;
40
+ UnknownFunction: (functionName: string, span: SourceSpan) => ErrorDiagnostic;
41
+ UnknownLabel: (labelName: string, span: SourceSpan) => ErrorDiagnostic;
42
+ BreakInsideEvent: (span: SourceSpan) => ErrorDiagnostic;
43
+ PageOverflow: (required: number, available: number, span: SourceSpan) => ErrorDiagnostic;
44
+ };
45
+ declare const warnings: {
46
+ InvalidUnicodeEscape: (span: SourceSpan) => WarningDiagnostic;
47
+ UnknownFunction: (functionName: string, span: SourceSpan) => WarningDiagnostic;
48
+ TooManyPosArgs: (functionName: string, expected: number, actual: number, span: SourceSpan) => WarningDiagnostic;
49
+ InvalidNumber: (value: string, span: SourceSpan) => WarningDiagnostic;
50
+ InvalidBoolean: (value: string, span: SourceSpan) => WarningDiagnostic;
51
+ InvalidLength: (value: string, span: SourceSpan) => WarningDiagnostic;
52
+ InvalidLengthUnit: (unit: string, span: SourceSpan) => WarningDiagnostic;
53
+ InvalidContent: (span: SourceSpan) => WarningDiagnostic;
54
+ UnmatchedBrace: (span: SourceSpan) => WarningDiagnostic;
55
+ LabelWithoutTarget: (labelName: string, span: SourceSpan) => WarningDiagnostic;
56
+ TargetAlreadyLabeled: (newLabel: string, oldLabel: string, span: SourceSpan) => WarningDiagnostic;
57
+ UnresolvedEndpoint: (functionName: string, span: SourceSpan) => WarningDiagnostic;
58
+ ZeroTimeTrack: (span: SourceSpan, trackOrder: number) => WarningDiagnostic;
59
+ };
60
+ export {};
@@ -37,9 +37,8 @@ export class Diagnostic {
37
37
  }
38
38
  static offsetToLineCol(offset, lineStarts) {
39
39
  const count = lineStarts.length;
40
- if (count === 0) {
40
+ if (count === 0)
41
41
  return { line: 1, column: Math.max(0, offset) + 1 };
42
- }
43
42
  let target = offset;
44
43
  if (target < 0)
45
44
  target = 0;
@@ -68,7 +67,7 @@ export class ErrorDiagnostic extends Diagnostic {
68
67
  }
69
68
  export class WarningDiagnostic extends Diagnostic {
70
69
  }
71
- Diagnostic.error = {
70
+ const errors = {
72
71
  Bug: (message, span) => new ErrorDiagnostic("E_BUG", "解析器错误: {message},请联系开发者修复这个问题", span, { message }),
73
72
  MissingArg: (functionName, argumentName, span) => new ErrorDiagnostic("E_MISSING_REQUIRED_ARG", "函数@{fn} 缺少必需的参数 {arg}", span, { fn: functionName, arg: formatArg(argumentName) }),
74
73
  PosAfterNamedArg: (functionName, span) => new ErrorDiagnostic("E_POSARG_AFTER_KWARG", "函数 @{fn} 的位置参数出现在命名参数之后,这是不允许的", span, { fn: functionName }),
@@ -79,7 +78,7 @@ Diagnostic.error = {
79
78
  BreakInsideEvent: (span) => new ErrorDiagnostic("E_BREAK_INSIDE_EVENT", "换行或换页切断了一个仍在持续的事件;请把长音写成多个事件,或调整换行、换页的位置", span),
80
79
  PageOverflow: (required, available, span) => new ErrorDiagnostic("E_PAGE_OVERFLOW", "谱面行需要 {required}px 高度,但页面内容区只有 {available}px", span, { required, available }),
81
80
  };
82
- Diagnostic.warning = {
81
+ const warnings = {
83
82
  InvalidUnicodeEscape: (span) => new WarningDiagnostic("W_STRING_INVALID_UNICODE_ESCAPE", "无效的 Unicode 转义:请使用 \\uXXXX(四位十六进制数字);将保留该字符串原文", span),
84
83
  UnknownFunction: (functionName, span) => new WarningDiagnostic("W_UNKNOWN_FUNCTION", "未知函数: @{fn},将被当作普通文本处理", span, { fn: functionName }),
85
84
  TooManyPosArgs: (functionName, expected, actual, span) => new WarningDiagnostic("W_TOO_MANY_POS_ARGS", "函数 @{fn} 接收了过多的位置参数,期望 {expected} 个但得到了 {actual} 个", span, { fn: functionName, expected, actual }),
@@ -94,3 +93,5 @@ Diagnostic.warning = {
94
93
  UnresolvedEndpoint: (functionName, span) => new WarningDiagnostic("W_UNRESOLVED_ENDPOINT", "@{fn} 有端点找不到对应的谱面对象;该关系将被忽略", span, { fn: functionName }),
95
94
  ZeroTimeTrack: (span, trackOrder) => new WarningDiagnostic("W_ZERO_TIME_TRACK", "第{track}个子轨道的时长为0", span, { track: trackOrder }),
96
95
  };
96
+ Diagnostic.error = errors;
97
+ Diagnostic.warning = warnings;
@@ -1,6 +1,7 @@
1
1
  import { ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
2
2
  import { Fraction } from "../../fraction.js";
3
3
  import { getLayoutBounds, prepareLayoutHost } from "../../layout/engine.js";
4
+ import { paintVisual } from "../../render/paint.js";
4
5
  import { ASTFunctionNode, } from "../ASTtypes.js";
5
6
  import { transferFunctionAddons, TemporalNodeBase } from "../temporal.js";
6
7
  import { prepareArpeggioShape } from "./shape.js";
@@ -184,8 +185,6 @@ class ArpeggioTemporal extends TemporalNodeBase {
184
185
  painter.drawPath(this.markCommands, { fill: "#000" }, {
185
186
  x: this.box.x, y: getLayoutBounds(this.host, true).y, scaleX: 1, scaleY: 1,
186
187
  });
187
- this.host.paint(painter);
188
- for (const decoration of this.host.decorations)
189
- decoration.paint?.(painter);
188
+ paintVisual(painter, this.host);
190
189
  }
191
190
  }
@@ -12,6 +12,9 @@ export declare const BarNode: ASTFunctionClass;
12
12
  /**
13
13
  * 某一列此刻处在所属反复段的第几遍
14
14
  *
15
+ * 每条 `:|` 只回跳一次,所以遍数是 1 加上本段已到过的 `:|` 数;
16
+ * 别处再跳回本段时它已停在最后一遍,只进最后一个房子。
17
+ * 没有 `:|` 的段只能靠别处跳回,进段几次就是第几遍。
15
18
  * 遍数是回跳的直接后果,所以和跳转规则一样归小节线所有;房子只消费这个数。
16
19
  * 没有 `|:` 时整首曲子就是一段。
17
20
  */
@@ -129,6 +129,7 @@ class BarNumberAttachment {
129
129
  items;
130
130
  pattern;
131
131
  font;
132
+ kind = "bar-number";
132
133
  layer = "foreground";
133
134
  sourceSpan = undefined;
134
135
  constructor(items, pattern, font) {
@@ -280,22 +281,36 @@ class BarTemporalNode extends TemporalNodeBase {
280
281
  }
281
282
  }
282
283
  }
283
- /** 反复段起点标记:`:|` 靠它找回跳目标,遍数也按它计数 */
284
+ /** 反复段起止标记:`:|` 靠起点找回跳目标,遍数按段内到过的终点计数 */
284
285
  const REPEAT_START = "repeat.start";
286
+ const REPEAT_END = "repeat.end";
285
287
  /**
286
288
  * 某一列此刻处在所属反复段的第几遍
287
289
  *
290
+ * 每条 `:|` 只回跳一次,所以遍数是 1 加上本段已到过的 `:|` 数;
291
+ * 别处再跳回本段时它已停在最后一遍,只进最后一个房子。
292
+ * 没有 `:|` 的段只能靠别处跳回,进段几次就是第几遍。
288
293
  * 遍数是回跳的直接后果,所以和跳转规则一样归小节线所有;房子只消费这个数。
289
294
  * 没有 `|:` 时整首曲子就是一段。
290
295
  */
291
296
  export function repeatPass(cursor, column) {
292
- return cursor.visits(cursor.seek(REPEAT_START, column + 1, -1) ?? 0);
297
+ const start = cursor.seek(REPEAT_START, column + 1, -1) ?? 0;
298
+ // `:|:` 既是下一段起点又回跳本段,所以段尾要含下一段起点
299
+ const next = cursor.seek(REPEAT_START, start, 1) ?? Infinity;
300
+ let pass = 1, ends = 0;
301
+ for (let end = cursor.seek(REPEAT_END, start, 1); end !== undefined && end <= next; end = cursor.seek(REPEAT_END, end, 1)) {
302
+ ends++;
303
+ if (cursor.visits(end) > 0)
304
+ pass++;
305
+ }
306
+ return ends ? pass : cursor.visits(start);
293
307
  }
294
308
  /** 只有反复线参与播放顺序;普通小节线太多,进控制流扫描是纯开销 */
295
309
  class RepeatBarTemporalNode extends BarTemporalNode {
296
310
  /** 只在 type 3–5 时创建,所以三种分别是:3 段首、4 段尾、5 两者都是 */
297
311
  playbackMarks() {
298
- return this.ast.type === 4 ? [] : [REPEAT_START];
312
+ const { type } = this.ast;
313
+ return type === 3 ? [REPEAT_START] : type === 4 ? [REPEAT_END] : [REPEAT_START, REPEAT_END];
299
314
  }
300
315
  /** 每条反复线只回跳一次,所以连写几条就是几遍 */
301
316
  playbackFlow(columnOf) {
@@ -59,6 +59,7 @@ export function collectExplicitBeamEndpoints(attachments) {
59
59
  return result;
60
60
  }
61
61
  class BeamLayoutAttachment {
62
+ kind = "beam";
62
63
  layer = "foreground";
63
64
  endPoints;
64
65
  explicit;
@@ -105,8 +106,8 @@ class BeamLayoutAttachment {
105
106
  return {
106
107
  regions,
107
108
  paint(painter) {
108
- for (const line of lines) {
109
- painter.drawLine(line.start.x, line.start.y, line.end.x, line.end.y, { stroke: "#000", strokeWidth });
109
+ for (const region of regions) {
110
+ painter.drawRect(region.x, region.y, region.w, region.h, { fill: "#000" });
110
111
  }
111
112
  },
112
113
  };
@@ -107,6 +107,7 @@ export const BoxNode = BoxFunction;
107
107
  class BoxLayoutAttachment {
108
108
  content;
109
109
  owner;
110
+ kind = "box";
110
111
  layer = "background";
111
112
  reservedHost;
112
113
  fixedStart = null;
@@ -62,6 +62,9 @@ class DashTemporalNode extends TemporalNodeBase {
62
62
  this.box.anchor = this.lineWidth / 2;
63
63
  this.box.visualAxis = size * 0.5;
64
64
  }
65
+ finalizeLayout() {
66
+ this.ports["lyric"] = { x: this.box.anchor, y: this.box.h };
67
+ }
65
68
  /**
66
69
  * 在结构阶段延长前方同轨、时间相接的一组区间
67
70
  * 有声与无声目标都保留原对象,后续声音变换才能使用延长后的完整时值
@@ -98,7 +101,7 @@ class DashTemporalNode extends TemporalNodeBase {
98
101
  });
99
102
  }
100
103
  paint(painter) {
101
- const y = this.box.y + this.box.visualAxis;
102
- painter.drawLine(this.box.x, y, this.box.x + this.lineWidth, y, { stroke: "#000", strokeWidth: Math.max(1, this.ast.size * 0.1) });
104
+ 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" });
103
106
  }
104
107
  }
@@ -27,10 +27,10 @@ declare class DivFunction extends ASTFunctionNode {
27
27
  details: string;
28
28
  allowExtraArgs: boolean;
29
29
  args: ({
30
- name?: undefined;
31
30
  type: "content";
32
31
  description: string;
33
32
  default: null;
33
+ name?: undefined;
34
34
  } | {
35
35
  name: string;
36
36
  description: string;
@@ -167,12 +167,14 @@ class DivFunction extends ASTFunctionNode {
167
167
  },
168
168
  paint(painter) {
169
169
  // 未被关系对象接管的级别仍由本装饰独立绘制
170
+ const x = host.box.x + lineLeft;
171
+ const w = lineRight - lineLeft;
172
+ const top = host.box.y + firstLine - strokeWidth / 2;
170
173
  for (let i = 0; i < count; i++) {
171
174
  const leftPort = host.ports[divLinePortName(i, "left")];
172
175
  if (leftPort.state.claimed)
173
176
  continue;
174
- const y = host.box.y + firstLine + i * lineGap;
175
- painter.drawLine(host.box.x + lineLeft, y, host.box.x + lineRight, y, { stroke: "#000", strokeWidth });
177
+ painter.drawRect(x, top + i * lineGap, w, strokeWidth, { fill: "#000" });
176
178
  }
177
179
  },
178
180
  };
@@ -151,6 +151,7 @@ class DynAttachment {
151
151
  end;
152
152
  fromHost;
153
153
  toHost;
154
+ kind = "dyn";
154
155
  layer = "foreground";
155
156
  constructor(ast, end, fromHost, toHost) {
156
157
  this.ast = ast;
@@ -1,4 +1,4 @@
1
- import { ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
1
+ import { Diagnostic, ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
2
2
  import { pathBounds } from "../../layout/path.js";
3
3
  import { lineEntryX, lineRightX } from "../../layout/range.js";
4
4
  import { ASTFunctionNode, } from "../ASTtypes.js";
@@ -41,7 +41,8 @@ class GlissFunction extends ASTFunctionNode {
41
41
  const from = ctx.getTemporalNodes(this.from).at(-1);
42
42
  const to = ctx.getTemporalNodes(this.to).at(-1);
43
43
  if (!from || !to || !isVisualTemporalNode(from) || !isVisualTemporalNode(to)) {
44
- throw new ErrorDiagnostic("E_GLISS_ENDPOINT", "@gliss 的标签必须指向已生成且具有排版盒子的对象", this.sourceSpan);
44
+ ctx.diagnostics.push(Diagnostic.warning.UnresolvedEndpoint("gliss", this.sourceSpan));
45
+ return [];
45
46
  }
46
47
  const attachment = new GlissAttachment(from, to, this.sourceSpan);
47
48
  ctx.addAttachment(attachment);
@@ -63,6 +64,7 @@ function layoutHost(node, line) {
63
64
  }
64
65
  class GlissAttachment {
65
66
  sourceSpan;
67
+ kind = "gliss";
66
68
  layer = "foreground";
67
69
  endPoints;
68
70
  direction;
@@ -3,6 +3,7 @@ import { getLayoutBounds, layoutLocalSequence } from "../../layout/engine.js";
3
3
  import { Fraction } from "../../fraction.js";
4
4
  import { Track } from "../../lowering/track.js";
5
5
  import { transferFunctionAddons, isVisualTemporalNode, TemporalNodeBase, } from "../temporal.js";
6
+ import { paintVisual } from "../../render/paint.js";
6
7
  import { ASTFunctionNode, } from "../ASTtypes.js";
7
8
  import { createBeamLayoutAttachment } from "../beam/layout.js";
8
9
  import { DIV_ADDON_KEY } from "../div/index.js";
@@ -415,11 +416,8 @@ export class GraceTemporal extends TemporalNodeBase {
415
416
  });
416
417
  }
417
418
  paint(painter) {
418
- for (const member of [this.host, ...this.graces]) {
419
- member.paint(painter);
420
- for (const decoration of member.decorations)
421
- decoration.paint?.(painter);
422
- }
419
+ for (const member of [this.host, ...this.graces])
420
+ paintVisual(painter, member);
423
421
  if (!this.hookOrigin)
424
422
  return;
425
423
  const graceEm = this.ast.size * GRACE_SCALE;
@@ -12,7 +12,7 @@ const FIELD_SLOT = {
12
12
  signature: "left", tempo: "left", left: "left", center: "center", right: "right",
13
13
  };
14
14
  const TEXT_PRESET = {
15
- title: [2, "center"], subtitle: [0.85, "center"], author: [0.8, "right"],
15
+ title: [2, "center"], subtitle: [1, "center"], author: [0.88, "right"],
16
16
  };
17
17
  const ITEM_GAP_EM = 0.25;
18
18
  const DEFAULT_GAP_PX = 5;
@@ -346,12 +346,17 @@ H.tempo: 94
346
346
  const explicitContent = source[contentStart] === "@" || source[contentStart] === "{";
347
347
  // 裸文本整行归 Head 所有,直接越过可避免其中的 F 等字符被识别成音符
348
348
  // 显式 DSL 仍从冒号后继续扫描,保留内部函数高亮
349
+ const last = skipSpacesBack(source, lineEnd - 1, contentStart);
350
+ const contentSpan = explicitContent ? undefined : { start: contentStart, end: Math.max(contentStart, last + 1) };
349
351
  return {
350
352
  next: explicitContent ? pos : lineEnd,
351
353
  node: {
352
354
  kind: "sugar",
353
- data: { class: HeadFunction, field },
355
+ data: { class: HeadFunction, field, contentSpan },
354
356
  span: { start, end: pos },
357
+ syntaxKind: contentSpan && field !== "signature" && field !== "tempo" && contentSpan.start < contentSpan.end
358
+ ? [{ kind: "operator", span: { start, end: pos } }, { kind: "string", span: contentSpan }]
359
+ : undefined,
355
360
  },
356
361
  };
357
362
  }
@@ -361,39 +366,26 @@ H.tempo: 94
361
366
  return null;
362
367
  const field = sugar.data.field;
363
368
  let breakAt = at;
364
- for (; breakAt < nodes.length; breakAt++) {
365
- const node = nodes[breakAt];
366
- if (typeof node === "number" && (ctx.source[node] === "\r" || ctx.source[node] === "\n"))
367
- break;
368
- if (typeof node !== "number" && node.kind === "sugar" && node.data?.class === HeadFunction)
369
- break;
370
- }
371
- const stop = nodes[breakAt];
372
- // 裸文本在第一轮被整体越过,EOF 时 nodes 中没有末尾标记,需从源码恢复边界
373
- let boundary;
374
- if (typeof stop === "number")
375
- boundary = stop;
376
- else if (stop)
377
- boundary = stop.span.start;
378
- else if (breakAt > at) {
379
- const last = nodes[breakAt - 1];
380
- boundary = typeof last === "number" ? last + 1 : last.span.end;
381
- }
382
- else
383
- boundary = findLineEnd(ctx.source, sugar.span.end);
384
- const start = skipSpaces(ctx.source, sugar.span.end, boundary);
385
- const last = skipSpacesBack(ctx.source, boundary - 1, start);
386
- const span = { start, end: Math.max(start, last + 1) };
387
- if (span.start >= span.end) {
388
- throw new ErrorDiagnostic("E_HEAD_EMPTY_DECLARATION", "H.{field}: 后必须有内容", sugar.span, { field });
389
- }
390
- const text = ctx.source.slice(span.start, span.end).trim();
369
+ let span = sugar.data.contentSpan;
391
370
  let parsed;
392
- if (text.startsWith("@") || text.startsWith("{")) {
371
+ if (!span) {
372
+ for (; breakAt < nodes.length; breakAt++) {
373
+ const node = nodes[breakAt];
374
+ if (typeof node === "number" && (ctx.source[node] === "\r" || ctx.source[node] === "\n"))
375
+ break;
376
+ if (typeof node !== "number" && node.kind === "sugar" && node.data?.class === HeadFunction)
377
+ break;
378
+ }
393
379
  const sub = new ParserContext(ctx);
394
380
  sub.makeNodes(nodes.slice(at, breakAt));
395
381
  parsed = sub.nodes;
382
+ const last = parsed.at(-1)?.sourceSpan.end ?? sugar.span.end;
383
+ span = { start: skipSpaces(ctx.source, sugar.span.end, last), end: last };
396
384
  }
385
+ if (span.start >= span.end) {
386
+ throw new ErrorDiagnostic("E_HEAD_EMPTY_DECLARATION", "H.{field}: 后必须有内容", sugar.span, { field });
387
+ }
388
+ const text = ctx.source.slice(span.start, span.end);
397
389
  const previous = ctx.nodes.at(-1);
398
390
  // 只有相邻的 H.* 声明合并;普通节点或空行都会切断组合
399
391
  const head = previous instanceof HeadFunction && previous.createdBySugar
@@ -405,6 +397,7 @@ H.tempo: 94
405
397
  head.sourceSpan.end = span.end;
406
398
  if (head !== previous)
407
399
  ctx.pushNode(head);
400
+ const stop = nodes[breakAt];
408
401
  if (typeof stop !== "number")
409
402
  return breakAt;
410
403
  let next = breakAt + 1;
@@ -2,7 +2,7 @@ import { DEFAULT_TONALITY, TemporalNodeBase } from "../temporal.js";
2
2
  import { ASTFunctionNode } from "../ASTtypes.js";
3
3
  import { ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
4
4
  import { parseNoteName } from "../note/noteName.js";
5
- import { acc2Offset, NoteNameMap } from "../../parser/parse-utils/note-utils.js";
5
+ import { acc2Offset, FLAT_NOTE_NAMES, NoteNameMap, SHARP_NOTE_NAMES, wrapPitchClass } from "../../parser/parse-utils/note-utils.js";
6
6
  import { paintAccidental, placeAccidentals } from "../note/accidentals.js";
7
7
  /**
8
8
  * 把宽松的调性写法收敛成 tonality2Midi 认得的 [音名][最多一个 #b][绝对八度]
@@ -23,9 +23,8 @@ function normalizeTonality(tonality) {
23
23
  const midi = (octave + 1) * 12 + pitchClass + offset;
24
24
  if (!Number.isSafeInteger(midi))
25
25
  return null;
26
- // NoteNameMap 里同一音高的升号拼写在前、降号在后,正好用来挑方向;数字音名不参与拼写
27
- const spellings = Object.keys(NoteNameMap).filter(name => NoteNameMap[name] === ((midi % 12) + 12) % 12 && /^[A-G]/.test(name));
28
- return (offset < 0 ? spellings.at(-1) : spellings[0]) + (Math.floor(midi / 12) - 1);
26
+ const spelling = (offset < 0 ? FLAT_NOTE_NAMES : SHARP_NOTE_NAMES)[wrapPitchClass(midi)];
27
+ return spelling + (Math.floor(midi / 12) - 1);
29
28
  }
30
29
  class KeyFunction extends ASTFunctionNode {
31
30
  static def = {
@@ -65,7 +64,6 @@ class KeyFunction extends ASTFunctionNode {
65
64
  super(sourceSpan, parent);
66
65
  const [tonality, size] = this.getArgValue(args, ctx);
67
66
  this.font = ctx.variables.numberfont;
68
- this.tonality = tonality;
69
67
  this.size = ctx.length2px(size);
70
68
  const normalized = normalizeTonality(tonality);
71
69
  this.tonality = normalized ?? DEFAULT_TONALITY;
@@ -111,8 +109,7 @@ class KeyTemporalNode extends TemporalNodeBase {
111
109
  const style = this.style;
112
110
  const prefix = context.textMeasurer.measureText(PREFIX, style);
113
111
  const name = context.textMeasurer.measureText(this.ast.displayName, style);
114
- const accidentalGap = size * 0.02;
115
- const { placed, right, top } = placeAccidentals(this.ast.displayAcc, size, prefix.w, prefix.baseline, accidentalGap);
112
+ const { placed, right, top } = placeAccidentals(this.ast.displayAcc, size, prefix.w, prefix.baseline);
116
113
  this.accidentals = placed;
117
114
  // 升降号抬高后可能高过文字,整块下移把它装回盒子里
118
115
  const shift = -top;
@@ -30,6 +30,7 @@ declare class MeterFunction extends ASTFunctionNode {
30
30
  readonly size: number;
31
31
  readonly strict: boolean;
32
32
  readonly font: string;
33
+ readonly weight: number;
33
34
  constructor(span: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent?: ASTNodeBase | null);
34
35
  loweringEnter(ctx: LoweringContext): MeterTemporal[];
35
36
  /**
@@ -56,10 +56,12 @@ class MeterFunction extends ASTFunctionNode {
56
56
  size;
57
57
  strict;
58
58
  font;
59
+ weight;
59
60
  constructor(span, args, ctx, parent = null) {
60
61
  super(span, parent);
61
62
  let [num, den, size] = this.getArgValue(args, ctx);
62
63
  this.font = ctx.variables.numberfont;
64
+ this.weight = ctx.variables.numberweight;
63
65
  if (!Number.isSafeInteger(num) || !Number.isSafeInteger(num * 4) || num < 0
64
66
  || !Number.isSafeInteger(den) || den < 0) {
65
67
  const message = `@meter 的分子和分母必须是非负整数`;
@@ -147,6 +149,7 @@ class MeterTemporal extends TemporalNodeBase {
147
149
  this.style = {
148
150
  fontSize: ast.size,
149
151
  fontFamily: ast.font,
152
+ fontWeight: ast.weight,
150
153
  textAlign: "center",
151
154
  fill: "#000",
152
155
  };
@@ -1,3 +1,3 @@
1
1
  import { type SymbolShape } from "../symbol/shape.js";
2
2
  export declare const sanbanShapes: readonly SymbolShape[];
3
- export declare const sanbanBounds: import("../../core.js").Rect;
3
+ export declare const sanbanBounds: import("../../index.js").Rect;
@@ -3,6 +3,7 @@ export interface PreparedAccidental {
3
3
  w: number;
4
4
  h: number;
5
5
  baseline: number;
6
+ fill?: boolean;
6
7
  strokeWidth: number;
7
8
  commands: readonly PathCommand[];
8
9
  }
@@ -13,13 +14,12 @@ export interface PlacedAccidental {
13
14
  y: number;
14
15
  }
15
16
  /**
16
- * 把升降号串按同一基线依次排在 x 右侧
17
+ * 把升降号串按同一基线依次紧挨着排在 x 右侧
17
18
  * @param size 宿主数字的字号
18
19
  * @param baselineY 宿主文字基线在宿主盒局部坐标中的 y
19
- * @param gap 相邻升降号之间的间隔;末尾也留一份,宿主据此得到 right
20
20
  * @returns right 是下一个字形的起点,top 是最高处(可能为负,宿主自行决定是否下移)
21
21
  */
22
- export declare function placeAccidentals(symbols: string, size: number, x: number, baselineY: number, gap: number): {
22
+ export declare function placeAccidentals(symbols: string, size: number, x: number, baselineY: number): {
23
23
  placed: PlacedAccidental[];
24
24
  right: number;
25
25
  top: number;
@@ -5,18 +5,31 @@ const STROKE_RATIO = 0.06;
5
5
  const RAISE_RATIO = 0.42;
6
6
  const ACCIDENTALS = {
7
7
  "#": {
8
- w: 0.46,
9
- h: 0.78,
10
- baseline: 0.63,
8
+ w: 0.42,
9
+ h: 0.82,
10
+ baseline: 0.67,
11
+ fill: true,
11
12
  commands: [
12
- { op: "M", x: 0.34, y: 0.05 },
13
- { op: "L", x: 0.27, y: 0.95 },
14
- { op: "M", x: 0.72, y: 0.05 },
15
- { op: "L", x: 0.65, y: 0.95 },
16
- { op: "M", x: 0.08, y: 0.38 },
17
- { op: "L", x: 0.9, y: 0.28 },
18
- { op: "M", x: 0.05, y: 0.72 },
19
- { op: "L", x: 0.87, y: 0.62 },
13
+ { op: "M", x: 0.22, y: 0.07 },
14
+ { op: "L", x: 0.35, y: 0.07 },
15
+ { op: "L", x: 0.35, y: 1 },
16
+ { op: "L", x: 0.22, y: 1 },
17
+ { op: "Z" },
18
+ { op: "M", x: 0.65, y: 0 },
19
+ { op: "L", x: 0.78, y: 0 },
20
+ { op: "L", x: 0.78, y: 0.93 },
21
+ { op: "L", x: 0.65, y: 0.93 },
22
+ { op: "Z" },
23
+ { op: "M", x: 0, y: 0.33 },
24
+ { op: "L", x: 1, y: 0.18 },
25
+ { op: "L", x: 1, y: 0.32 },
26
+ { op: "L", x: 0, y: 0.47 },
27
+ { op: "Z" },
28
+ { op: "M", x: 0, y: 0.68 },
29
+ { op: "L", x: 1, y: 0.53 },
30
+ { op: "L", x: 1, y: 0.67 },
31
+ { op: "L", x: 0, y: 0.82 },
32
+ { op: "Z" },
20
33
  ],
21
34
  },
22
35
  b: {
@@ -47,13 +60,12 @@ const ACCIDENTALS = {
47
60
  },
48
61
  };
49
62
  /**
50
- * 把升降号串按同一基线依次排在 x 右侧
63
+ * 把升降号串按同一基线依次紧挨着排在 x 右侧
51
64
  * @param size 宿主数字的字号
52
65
  * @param baselineY 宿主文字基线在宿主盒局部坐标中的 y
53
- * @param gap 相邻升降号之间的间隔;末尾也留一份,宿主据此得到 right
54
66
  * @returns right 是下一个字形的起点,top 是最高处(可能为负,宿主自行决定是否下移)
55
67
  */
56
- export function placeAccidentals(symbols, size, x, baselineY, gap) {
68
+ export function placeAccidentals(symbols, size, x, baselineY) {
57
69
  const placed = [];
58
70
  const glyphSize = size * GLYPH_SCALE;
59
71
  const raise = size * RAISE_RATIO;
@@ -67,6 +79,7 @@ export function placeAccidentals(symbols, size, x, baselineY, gap) {
67
79
  w: definition.w * glyphSize,
68
80
  h: definition.h * glyphSize,
69
81
  baseline: definition.baseline * glyphSize,
82
+ fill: definition.fill,
70
83
  strokeWidth: size * STROKE_RATIO,
71
84
  commands: definition.commands,
72
85
  };
@@ -74,11 +87,11 @@ export function placeAccidentals(symbols, size, x, baselineY, gap) {
74
87
  placed.push({ shape, x: right, y });
75
88
  if (y < top)
76
89
  top = y;
77
- right += shape.w + gap;
90
+ right += shape.w;
78
91
  }
79
92
  return { placed, right, top };
80
93
  }
81
94
  /** commands 是 0..1 归一化坐标,必须配回字形自己的 w/h 才不会画歪 */
82
95
  export function paintAccidental(painter, { shape, x, y }, origin, color) {
83
- painter.drawPath(shape.commands, { stroke: color, strokeWidth: shape.strokeWidth }, { x: origin.x + x, y: origin.y + y, scaleX: shape.w, scaleY: shape.h });
96
+ painter.drawPath(shape.commands, shape.fill ? { fill: color } : { stroke: color, strokeWidth: shape.strokeWidth }, { x: origin.x + x, y: origin.y + y, scaleX: shape.w, scaleY: shape.h });
84
97
  }