jpfun 0.9.0 → 1.1.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 (125) hide show
  1. package/README.md +11 -16
  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 +21 -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/default.js +2 -1
  11. package/dist/functions/div/index.d.ts +1 -1
  12. package/dist/functions/div/index.js +4 -2
  13. package/dist/functions/dyn/index.js +1 -0
  14. package/dist/functions/gliss/index.js +85 -9
  15. package/dist/functions/grace/index.d.ts +1 -8
  16. package/dist/functions/grace/index.js +23 -53
  17. package/dist/functions/head/index.js +23 -30
  18. package/dist/functions/key/index.js +5 -7
  19. package/dist/functions/meter/index.d.ts +1 -0
  20. package/dist/functions/meter/index.js +3 -0
  21. package/dist/functions/meter/shape.d.ts +1 -1
  22. package/dist/functions/note/accidentals.d.ts +3 -3
  23. package/dist/functions/note/accidentals.js +29 -16
  24. package/dist/functions/note/index.d.ts +5 -2
  25. package/dist/functions/note/index.js +168 -25
  26. package/dist/functions/note/source-transform.d.ts +23 -2
  27. package/dist/functions/note/source-transform.js +95 -74
  28. package/dist/functions/ottava/index.js +1 -0
  29. package/dist/functions/page/index.d.ts +1 -36
  30. package/dist/functions/page/index.js +8 -7
  31. package/dist/functions/rest/index.js +8 -6
  32. package/dist/functions/set/index.js +2 -2
  33. package/dist/functions/slide/index.js +1 -0
  34. package/dist/functions/stack/index.js +6 -4
  35. package/dist/functions/temporal.d.ts +12 -3
  36. package/dist/functions/temporal.js +15 -2
  37. package/dist/functions/text/index.js +2 -2
  38. package/dist/functions/tie/index.js +28 -4
  39. package/dist/functions/tremolo/index.js +1 -0
  40. package/dist/functions/tuplet/index.js +1 -0
  41. package/dist/functions/up/index.js +12 -12
  42. package/dist/functions/voice/connections.d.ts +1 -1
  43. package/dist/functions/voice/connections.js +2 -2
  44. package/dist/functions/voice/lyrics.d.ts +11 -5
  45. package/dist/functions/voice/lyrics.js +151 -47
  46. package/dist/functions/voice/voice.d.ts +6 -2
  47. package/dist/functions/voice/voice.js +51 -19
  48. package/dist/functions/voice/voices.d.ts +2 -1
  49. package/dist/functions/voice/voices.js +4 -3
  50. package/dist/functions/volta/index.js +1 -0
  51. package/dist/index.d.ts +69 -3
  52. package/dist/index.js +69 -3
  53. package/dist/jpfun.min.js +47 -60
  54. package/dist/layout/engine.d.ts +4 -3
  55. package/dist/layout/engine.js +173 -27
  56. package/dist/layout/model.d.ts +13 -4
  57. package/dist/layout/model.js +15 -7
  58. package/dist/layout/page.js +2 -2
  59. package/dist/layout/path.js +1 -1
  60. package/dist/layout/types.d.ts +12 -3
  61. package/dist/lowering/accidentalMemory.d.ts +33 -0
  62. package/dist/lowering/accidentalMemory.js +84 -0
  63. package/dist/lowering/loweringContext.js +4 -0
  64. package/dist/parser/grammarType.d.ts +8 -3
  65. package/dist/parser/parse-utils/brace-utils.js +7 -17
  66. package/dist/parser/parse-utils/call-utils.d.ts +3 -1
  67. package/dist/parser/parse-utils/call-utils.js +17 -32
  68. package/dist/parser/parse-utils/note-utils.d.ts +4 -0
  69. package/dist/parser/parse-utils/note-utils.js +8 -12
  70. package/dist/parser/parse-utils/string-utils.d.ts +1 -1
  71. package/dist/parser/parse-utils/string-utils.js +1 -1
  72. package/dist/parser/parserContext.d.ts +32 -26
  73. package/dist/parser/parserContext.js +104 -194
  74. package/dist/parser/preprocess.d.ts +7 -0
  75. package/dist/parser/preprocess.js +31 -42
  76. package/dist/parser/syntax.d.ts +9 -0
  77. package/dist/parser/syntax.js +109 -0
  78. package/dist/pipeline.d.ts +1 -1
  79. package/dist/pipeline.js +3 -2
  80. package/dist/playback/compile.js +5 -7
  81. package/dist/playback/event.d.ts +1 -2
  82. package/dist/playback/event.js +2 -3
  83. package/dist/render/canvas.js +50 -35
  84. package/dist/render/index.d.ts +2 -1
  85. package/dist/render/index.js +2 -1
  86. package/dist/render/paint.d.ts +7 -0
  87. package/dist/render/paint.js +70 -20
  88. package/dist/render/recording.d.ts +8 -1
  89. package/dist/render/recording.js +12 -0
  90. package/dist/render/svg.d.ts +5 -1
  91. package/dist/render/svg.js +37 -17
  92. package/dist/render/text.d.ts +2 -2
  93. package/dist/render/text.js +7 -6
  94. package/dist/render/translate.d.ts +3 -1
  95. package/dist/render/translate.js +6 -0
  96. package/dist/render/types.d.ts +9 -0
  97. package/grammar.md +7 -5
  98. package/package.json +8 -18
  99. package/dist/converter/midi/convert.d.ts +0 -42
  100. package/dist/converter/midi/convert.js +0 -682
  101. package/dist/converter/midi/index.d.ts +0 -5
  102. package/dist/converter/midi/index.js +0 -11
  103. package/dist/converter/midi/json.d.ts +0 -38
  104. package/dist/converter/midi/json.js +0 -1
  105. package/dist/converter/midi/triplet.d.ts +0 -30
  106. package/dist/converter/midi/triplet.js +0 -75
  107. package/dist/converter/musicxml/dom.d.ts +0 -25
  108. package/dist/converter/musicxml/dom.js +0 -65
  109. package/dist/converter/musicxml/features.d.ts +0 -114
  110. package/dist/converter/musicxml/features.js +0 -501
  111. package/dist/converter/musicxml/index.d.ts +0 -14
  112. package/dist/converter/musicxml/index.js +0 -1285
  113. package/dist/converter/musicxml/model.d.ts +0 -176
  114. package/dist/converter/musicxml/model.js +0 -1
  115. package/dist/converter/musicxml/resolve.d.ts +0 -10
  116. package/dist/converter/musicxml/resolve.js +0 -152
  117. package/dist/converter/source.d.ts +0 -19
  118. package/dist/converter/source.js +0 -53
  119. package/dist/core.d.ts +0 -24
  120. package/dist/core.js +0 -24
  121. package/dist/functions/voice/index.d.ts +0 -2
  122. package/dist/functions/voice/index.js +0 -2
  123. package/dist/jpfun.core.min.js +0 -132
  124. package/dist/jpfun.from-midi.min.js +0 -9
  125. 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:
@@ -82,17 +77,17 @@ The registry is shared across compilations. Names are case-insensitive, and late
82
77
 
83
78
  ### Note Transformations & Editor Analysis
84
79
 
85
- - `transformNotes(source, lowering, operation, ranges?)`: Returns `{ span, text }[]` edits for `"to-absolute"`, `"to-relative"`, `"semitone-up"`, or `"semitone-down"`. Use lowering from the exact same source; apply edits in one editor transaction or from right to left.
80
+ - `transformNotes(source, lowering, operation, ranges?, relower?)`: Returns `{ span, text }[]` edits for `"to-absolute"`, `"to-relative"`, `"semitone-up"`, or `"semitone-down"`. Use lowering from the exact same source; apply edits in one editor transaction or from right to left. Semitone shifts on numbered notes with `note.carry` enabled need `relower(source) => LoweringResult` to re-lower candidates and pin accidentals so other pitches stay unchanged.
86
81
  - `analyzeScoreSyntax(source, functions?)`: Fault-tolerant lexical/call analysis for real-time editor highlighting and completion.
87
82
  - `Diagnostic.format(code, message, params)`: Override to localize diagnostic messages.
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) {
@@ -191,6 +192,9 @@ class BarTemporalNode extends TemporalNodeBase {
191
192
  this.mergeKey = ANCHOR_KEY;
192
193
  this.initLayoutBox();
193
194
  }
195
+ onTimeState(state) {
196
+ state.accidentals.clear(this.track);
197
+ }
194
198
  /**
195
199
  * 给 bar 两侧的相邻元素增加 mu,避免被压缩到一起
196
200
  */
@@ -280,22 +284,36 @@ class BarTemporalNode extends TemporalNodeBase {
280
284
  }
281
285
  }
282
286
  }
283
- /** 反复段起点标记:`:|` 靠它找回跳目标,遍数也按它计数 */
287
+ /** 反复段起止标记:`:|` 靠起点找回跳目标,遍数按段内到过的终点计数 */
284
288
  const REPEAT_START = "repeat.start";
289
+ const REPEAT_END = "repeat.end";
285
290
  /**
286
291
  * 某一列此刻处在所属反复段的第几遍
287
292
  *
293
+ * 每条 `:|` 只回跳一次,所以遍数是 1 加上本段已到过的 `:|` 数;
294
+ * 别处再跳回本段时它已停在最后一遍,只进最后一个房子。
295
+ * 没有 `:|` 的段只能靠别处跳回,进段几次就是第几遍。
288
296
  * 遍数是回跳的直接后果,所以和跳转规则一样归小节线所有;房子只消费这个数。
289
297
  * 没有 `|:` 时整首曲子就是一段。
290
298
  */
291
299
  export function repeatPass(cursor, column) {
292
- return cursor.visits(cursor.seek(REPEAT_START, column + 1, -1) ?? 0);
300
+ const start = cursor.seek(REPEAT_START, column + 1, -1) ?? 0;
301
+ // `:|:` 既是下一段起点又回跳本段,所以段尾要含下一段起点
302
+ const next = cursor.seek(REPEAT_START, start, 1) ?? Infinity;
303
+ let pass = 1, ends = 0;
304
+ for (let end = cursor.seek(REPEAT_END, start, 1); end !== undefined && end <= next; end = cursor.seek(REPEAT_END, end, 1)) {
305
+ ends++;
306
+ if (cursor.visits(end) > 0)
307
+ pass++;
308
+ }
309
+ return ends ? pass : cursor.visits(start);
293
310
  }
294
311
  /** 只有反复线参与播放顺序;普通小节线太多,进控制流扫描是纯开销 */
295
312
  class RepeatBarTemporalNode extends BarTemporalNode {
296
313
  /** 只在 type 3–5 时创建,所以三种分别是:3 段首、4 段尾、5 两者都是 */
297
314
  playbackMarks() {
298
- return this.ast.type === 4 ? [] : [REPEAT_START];
315
+ const { type } = this.ast;
316
+ return type === 3 ? [REPEAT_START] : type === 4 ? [REPEAT_END] : [REPEAT_START, REPEAT_END];
299
317
  }
300
318
  /** 每条反复线只回跳一次,所以连写几条就是几遍 */
301
319
  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
  }
@@ -30,7 +30,8 @@ import { TremoloNode } from "./tremolo/index.js";
30
30
  import { VoltaNode } from "./volta/index.js";
31
31
  import { TieNode } from "./tie/index.js";
32
32
  import { TupletNode } from "./tuplet/index.js";
33
- import { VoiceNode, VoicesNode } from "./voice/index.js";
33
+ import { VoiceNode } from "./voice/voice.js";
34
+ import { VoicesNode } from "./voice/voices.js";
34
35
  export const defaultFunctions = [
35
36
  NoteNode, DashNode, RestNode, BarNode,
36
37
  DivNode, DotNode, TupletNode, TremoloNode, // 装饰性
@@ -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);
@@ -61,8 +62,69 @@ function layoutHost(node, line) {
61
62
  }
62
63
  return node;
63
64
  }
65
+ /** 将刚性半宽提升至 min,并从同侧弹簧 margin 中等量扣减 */
66
+ function reserveSide(el, side, min) {
67
+ const w = side === "L" ? "WL" : "WR";
68
+ const m = side === "L" ? "margin_L" : "margin_R";
69
+ if (min > el[w]) {
70
+ el[m] = Math.max(0, el[w] + el[m] - min);
71
+ el[w] = min;
72
+ }
73
+ }
74
+ /** 在指定音轨行上按各列实际跨度比例预留 start..end 的最小锚点间距 */
75
+ function reserveSpan(line, track, from, to, minSpan) {
76
+ if (minSpan <= 0)
77
+ return;
78
+ line.registerHorizontalLayoutHook(from, to, ({ columns, rows, start, end, X, fixed }) => {
79
+ let row = 0;
80
+ while (row < rows && columns[start][row].time.track !== track)
81
+ row++;
82
+ if (row >= rows)
83
+ return;
84
+ let needed = minSpan;
85
+ let total = 0;
86
+ const gaps = new Float64Array(end - start);
87
+ for (let c = start; c < end; c++) {
88
+ if (fixed[c]) {
89
+ needed -= X[c + 1] - X[c];
90
+ continue;
91
+ }
92
+ let gap = 0;
93
+ for (let r = 0; r < rows; r++) {
94
+ const a = columns[c][r], b = columns[c + 1][r];
95
+ gap = Math.max(gap, a.WR + a.margin_R + b.WL + b.margin_L);
96
+ }
97
+ gaps[c - start] = gap;
98
+ total += gap;
99
+ }
100
+ if (needed <= 0)
101
+ return;
102
+ if (total <= 0) {
103
+ for (let c = start; c < end; c++) {
104
+ if (!fixed[c]) {
105
+ reserveSide(columns[c][row], "R", needed);
106
+ break;
107
+ }
108
+ }
109
+ return;
110
+ }
111
+ const scale = needed / total;
112
+ for (let c = start; c < end; c++) {
113
+ if (fixed[c])
114
+ continue;
115
+ const a = columns[c][row], b = columns[c + 1][row];
116
+ const target = gaps[c - start] * scale;
117
+ const wA = a.WR + a.margin_R;
118
+ const pair = wA + b.WL + b.margin_L;
119
+ const rightTarget = pair > 0 ? target * (wA / pair) : target / 2;
120
+ reserveSide(a, "R", rightTarget);
121
+ reserveSide(b, "L", target - rightTarget);
122
+ }
123
+ });
124
+ }
64
125
  class GlissAttachment {
65
126
  sourceSpan;
127
+ kind = "gliss";
66
128
  layer = "foreground";
67
129
  endPoints;
68
130
  direction;
@@ -139,13 +201,27 @@ class GlissAttachment {
139
201
  const span = Math.max(endpoint.ast.size, target.ast.size) * 1.4;
140
202
  const right = from.box.w - from.box.anchor + span;
141
203
  // 只扩张求解器占位,不改变端点图形、附点位置或下一轮的 box
142
- fromLine.registerHorizontalLayoutHook(from, from, ({ columns }) => {
143
- // 留白作用于起点整列;取最大值,避免多条关系重复累加占位。
144
- for (const element of columns[start])
145
- element.WR = Math.max(element.WR, right);
146
- });
147
- if (fromLine !== toLine) {
148
- const left = to.box.anchor + span;
204
+ if (fromLine === toLine) {
205
+ reserveSpan(fromLine, from.track, from, to, right + to.box.anchor);
206
+ return;
207
+ }
208
+ const lastCol = fromLine.columns.length - 1;
209
+ if (start < lastCol) {
210
+ const lastRight = Math.max(...fromLine.columns[lastCol].map(h => h.box.w - h.box.anchor));
211
+ reserveSpan(fromLine, from.track, from, fromLine.columns[lastCol][0], right - lastRight);
212
+ }
213
+ else {
214
+ fromLine.registerHorizontalLayoutHook(from, from, ({ columns }) => {
215
+ for (const element of columns[start])
216
+ element.WR = Math.max(element.WR, right);
217
+ });
218
+ }
219
+ const left = to.box.anchor + span;
220
+ const entry = toLine.trackRuns.get(target.track)?.find(item => !item.T.isZero());
221
+ if (entry && toLine.columnOf(entry) < end) {
222
+ reserveSpan(toLine, to.track, entry, to, left - entry.box.anchor);
223
+ }
224
+ else {
149
225
  toLine.registerHorizontalLayoutHook(to, to, ({ columns }) => {
150
226
  for (const element of columns[end])
151
227
  element.WL = Math.max(element.WL, left);
@@ -22,16 +22,9 @@ declare class GraceFunction extends ASTFunctionNode {
22
22
  grace: ASTNodeBase;
23
23
  side: GraceSide;
24
24
  size: number;
25
- /**
26
- * `A > B`:前倚音必须左结合,而右操作数是把后续全部解析完才取的,
27
- * 所以 `1>2>3` 到这里已经成了 `1>(2>3)`。把 A 插回链条最深处就能恢复为 `(1>2)>3`
28
- */
29
- private static attachPre;
30
- private static create;
31
25
  get children(): ASTNodeBase[];
32
26
  timeFlowModel(): null;
33
- constructor(span: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent?: ASTNodeBase | null, scale?: number);
34
- setGrace(node: ASTNodeBase, factor?: number): void;
27
+ constructor(span: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent?: ASTNodeBase | null);
35
28
  private adopt;
36
29
  /** 宿主收敛成一个可见 Temporal,倚音展开成局部时间列,然后整体折叠进一个复合节点 */
37
30
  loweringEnter(ctx: LoweringContext, track: Track): GraceTemporal[];
@@ -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";
@@ -22,8 +23,6 @@ const SHOULDER_PORT = "shoulder";
22
23
  * 所以只能在此刻回头改。这发生在 parse 进行中,不违反「AST parse 后只读」。
23
24
  */
24
25
  function scaleFontSize(node, factor) {
25
- if (factor === 1)
26
- return;
27
26
  const sized = node;
28
27
  if (typeof sized.size === "number")
29
28
  sized.size *= factor;
@@ -105,56 +104,31 @@ class GraceFunction extends ASTFunctionNode {
105
104
  if (n.kind !== "sugar" || n.data?.class !== GraceFunction)
106
105
  return null;
107
106
  const side = n.data.side;
108
- const leftNode = ctx.takeLeftOperand();
107
+ // 箭头指向宿主:`1>2>3` 是 `{1>2}>3`,所以 `>` 登记 chain 左结合;`1<2<3` 是 `1<{2<3}`,`<` 保持右结合
108
+ const chain = side === "pre" ? GraceFunction : undefined;
109
+ const leftNode = ctx.takeLeftOperand(chain);
109
110
  if (!leftNode) {
110
111
  throw new ErrorDiagnostic("E_GRACE_NO_TARGET", "@grace语法糖错误: 左边没有找到目标", n.span);
111
112
  }
112
- const next = ctx.consumeRightOperand(nodes, at, right =>
113
- // '<' 的倚音在右侧,右结合的解析结果本来就是嵌套语义,不必像 '>' 那样重排
114
- side === "pre"
115
- ? GraceFunction.attachPre(leftNode, right, n.span, ctx)
116
- : GraceFunction.create(ctx, n.span, "post", leftNode, right));
117
- if (next !== null)
118
- return next;
119
- throw new ErrorDiagnostic("E_GRACE_NO_TARGET", "@grace语法糖错误: 右边没有找到目标", n.span);
113
+ const size = ctx.variables.fontsize; // 字号取算符所在处,不受右侧之后的 @set 影响
114
+ ctx.deferRightOperand(right => {
115
+ if (!right)
116
+ throw new ErrorDiagnostic("E_GRACE_NO_TARGET", "@grace语法糖错误: 右边没有找到目标", n.span);
117
+ const [host, grace] = side === "pre" ? [right, leftNode] : [leftNode, right];
118
+ const args = new Map([[0, host], [1, grace], ["side", side]]);
119
+ return Object.assign(new GraceFunction(n.span, args, ctx), { size });
120
+ }, chain);
121
+ return at;
120
122
  }
121
123
  host;
122
124
  grace;
123
125
  side = "pre";
124
126
  size;
125
- /**
126
- * `A > B`:前倚音必须左结合,而右操作数是把后续全部解析完才取的,
127
- * 所以 `1>2>3` 到这里已经成了 `1>(2>3)`。把 A 插回链条最深处就能恢复为 `(1>2)>3`
128
- */
129
- static attachPre(left, right, span, ctx) {
130
- if (right instanceof GraceFunction && right.side === "pre") {
131
- // 找到最深层的 pre
132
- let deepest = right;
133
- let depth = 1;
134
- while (deepest.grace instanceof GraceFunction && deepest.grace.side === "pre") {
135
- deepest = deepest.grace;
136
- depth++;
137
- }
138
- const scale = GRACE_SCALE ** depth;
139
- const inner = GraceFunction.create(ctx, span, "pre", deepest.grace, left, GRACE_SCALE * scale);
140
- inner.size *= scale;
141
- deepest.setGrace(inner, 1); // inner 内部已按深度缩放,不能再缩
142
- return right;
143
- }
144
- return GraceFunction.create(ctx, span, "pre", right, left);
145
- }
146
- static create(ctx, span, side, host, grace, scale = GRACE_SCALE) {
147
- const argMap = new Map();
148
- argMap.set(0, host);
149
- argMap.set(1, grace);
150
- argMap.set("side", side);
151
- return new GraceFunction(span, argMap, ctx, null, scale);
152
- }
153
127
  get children() {
154
128
  return [this.host, this.grace];
155
129
  }
156
130
  timeFlowModel() { return null; }
157
- constructor(span, args, ctx, parent = null, scale = GRACE_SCALE) {
131
+ constructor(span, args, ctx, parent = null) {
158
132
  super(span, parent);
159
133
  this.size = ctx.variables.fontsize;
160
134
  [this.host, this.grace, this.side] = this.getArgValue(args, ctx);
@@ -162,12 +136,8 @@ class GraceFunction extends ASTFunctionNode {
162
136
  throw new ErrorDiagnostic("E_GRACE_INVALID_SIDE", "@grace 的 side 参数必须是 'pre' 或 'post'", span);
163
137
  }
164
138
  this.adopt(this.host);
165
- this.setGrace(this.grace, scale);
166
- }
167
- setGrace(node, factor = GRACE_SCALE) {
168
- scaleFontSize(node, factor);
169
- this.grace = node;
170
- this.adopt(node);
139
+ this.adopt(this.grace);
140
+ scaleFontSize(this.grace, GRACE_SCALE);
171
141
  }
172
142
  adopt(node) {
173
143
  node.parent = this;
@@ -306,10 +276,13 @@ export class GraceTemporal extends TemporalNodeBase {
306
276
  // 同步时间的修改。比如tuplet修改的是GraceTemporal.T,这里要把它传给成员
307
277
  this.host.T.copyFrom(this.T);
308
278
  let offset = undefined;
309
- for (const member of this.ast.side === "pre" ? [...this.events, this.host] : [this.host, ...this.events]) {
279
+ const members = this.ast.side === "pre" ? [...this.events, this.host] : [this.host, ...this.events];
280
+ const hostAt = members.indexOf(this.host);
281
+ for (const [index, member] of members.entries()) {
310
282
  member.t.copyFrom(this.t);
311
283
  member.layoutLine = this.layoutLine;
312
- const result = member.onTimeState?.(state);
284
+ // 宿主与同列其他音同时,前倚音依次在它之前,后倚音依次在它之后
285
+ const result = state.accidentals.at(index - hostAt, () => member.onTimeState?.(state));
313
286
  if (member === this.host) {
314
287
  this.T.copyFrom(member.T);
315
288
  offset = result;
@@ -415,11 +388,8 @@ export class GraceTemporal extends TemporalNodeBase {
415
388
  });
416
389
  }
417
390
  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
- }
391
+ for (const member of [this.host, ...this.graces])
392
+ paintVisual(painter, member);
423
393
  if (!this.hookOrigin)
424
394
  return;
425
395
  const graceEm = this.ast.size * GRACE_SCALE;