jpfun 0.8.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 (140) 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/ASTtypes.d.ts +1 -14
  5. package/dist/functions/ASTtypes.js +5 -36
  6. package/dist/functions/adjust/index.js +45 -33
  7. package/dist/functions/arpeggio/index.js +44 -48
  8. package/dist/functions/arpeggio/shape.d.ts +2 -3
  9. package/dist/functions/arpeggio/shape.js +20 -50
  10. package/dist/functions/bar/index.d.ts +3 -0
  11. package/dist/functions/bar/index.js +21 -11
  12. package/dist/functions/beam/auto.js +54 -123
  13. package/dist/functions/beam/index.js +4 -9
  14. package/dist/functions/beam/layout.js +3 -2
  15. package/dist/functions/box/index.js +1 -6
  16. package/dist/functions/dash/index.js +6 -4
  17. package/dist/functions/div/index.d.ts +3 -5
  18. package/dist/functions/div/index.js +14 -12
  19. package/dist/functions/dot/index.js +3 -9
  20. package/dist/functions/dyn/index.js +7 -26
  21. package/dist/functions/gliss/index.js +99 -91
  22. package/dist/functions/grace/index.d.ts +2 -5
  23. package/dist/functions/grace/index.js +47 -94
  24. package/dist/functions/head/index.js +32 -36
  25. package/dist/functions/key/index.js +9 -12
  26. package/dist/functions/meter/index.d.ts +1 -0
  27. package/dist/functions/meter/index.js +6 -3
  28. package/dist/functions/meter/shape.d.ts +1 -1
  29. package/dist/functions/note/accidentals.d.ts +3 -3
  30. package/dist/functions/note/accidentals.js +29 -16
  31. package/dist/functions/note/index.js +12 -14
  32. package/dist/functions/note/source-transform.d.ts +15 -0
  33. package/dist/functions/note/source-transform.js +75 -71
  34. package/dist/functions/ottava/index.js +12 -32
  35. package/dist/functions/page/index.js +15 -17
  36. package/dist/functions/rest/index.js +10 -10
  37. package/dist/functions/slide/index.js +1 -1
  38. package/dist/functions/stack/index.js +8 -57
  39. package/dist/functions/temporal.d.ts +11 -5
  40. package/dist/functions/temporal.js +22 -2
  41. package/dist/functions/text/index.js +24 -30
  42. package/dist/functions/tie/index.js +42 -41
  43. package/dist/functions/tremolo/index.js +1 -1
  44. package/dist/functions/tuplet/index.js +1 -6
  45. package/dist/functions/up/index.js +82 -88
  46. package/dist/functions/voice/connections.d.ts +3 -2
  47. package/dist/functions/voice/connections.js +48 -10
  48. package/dist/functions/voice/index.d.ts +2 -3
  49. package/dist/functions/voice/index.js +2 -970
  50. package/dist/functions/voice/lyrics.d.ts +34 -0
  51. package/dist/functions/voice/lyrics.js +393 -0
  52. package/dist/functions/voice/voice.d.ts +67 -0
  53. package/dist/functions/voice/voice.js +405 -0
  54. package/dist/functions/voice/voices.d.ts +106 -0
  55. package/dist/functions/voice/voices.js +424 -0
  56. package/dist/functions/volta/index.js +6 -23
  57. package/dist/index.d.ts +97 -3
  58. package/dist/index.js +97 -3
  59. package/dist/jpfun.min.js +63 -67
  60. package/dist/layout/engine.d.ts +4 -3
  61. package/dist/layout/engine.js +190 -24
  62. package/dist/layout/model.d.ts +12 -4
  63. package/dist/layout/model.js +16 -11
  64. package/dist/layout/page.d.ts +2 -1
  65. package/dist/layout/page.js +15 -15
  66. package/dist/layout/path.js +1 -1
  67. package/dist/layout/range.d.ts +7 -6
  68. package/dist/layout/range.js +23 -14
  69. package/dist/layout/types.d.ts +19 -30
  70. package/dist/lowering/loweringContext.d.ts +8 -11
  71. package/dist/lowering/loweringContext.js +7 -13
  72. package/dist/lowering/track.d.ts +8 -1
  73. package/dist/lowering/types.d.ts +12 -8
  74. package/dist/parser/grammarType.d.ts +3 -3
  75. package/dist/parser/parse-utils/brace-utils.js +7 -17
  76. package/dist/parser/parse-utils/call-utils.d.ts +4 -3
  77. package/dist/parser/parse-utils/call-utils.js +23 -66
  78. package/dist/parser/parse-utils/note-utils.d.ts +7 -3
  79. package/dist/parser/parse-utils/note-utils.js +25 -40
  80. package/dist/parser/parse-utils/string-utils.d.ts +1 -1
  81. package/dist/parser/parse-utils/string-utils.js +8 -6
  82. package/dist/parser/parserContext.d.ts +17 -11
  83. package/dist/parser/parserContext.js +111 -65
  84. package/dist/parser/preprocess.d.ts +7 -0
  85. package/dist/parser/preprocess.js +21 -19
  86. package/dist/pipeline.d.ts +1 -1
  87. package/dist/pipeline.js +2 -2
  88. package/dist/playback/compile.js +14 -15
  89. package/dist/playback/event.d.ts +6 -6
  90. package/dist/playback/event.js +13 -49
  91. package/dist/render/canvas.d.ts +0 -2
  92. package/dist/render/canvas.js +50 -56
  93. package/dist/render/index.d.ts +1 -1
  94. package/dist/render/index.js +1 -1
  95. package/dist/render/paint.d.ts +7 -0
  96. package/dist/render/paint.js +70 -20
  97. package/dist/render/recording.d.ts +8 -1
  98. package/dist/render/recording.js +12 -0
  99. package/dist/render/svg.d.ts +5 -2
  100. package/dist/render/svg.js +70 -48
  101. package/dist/render/text.d.ts +37 -2
  102. package/dist/render/text.js +136 -1
  103. package/dist/render/translate.d.ts +3 -1
  104. package/dist/render/translate.js +6 -0
  105. package/dist/render/types.d.ts +9 -2
  106. package/grammar.md +18 -14
  107. package/package.json +8 -18
  108. package/dist/converter/midi/convert.d.ts +0 -42
  109. package/dist/converter/midi/convert.js +0 -729
  110. package/dist/converter/midi/index.d.ts +0 -5
  111. package/dist/converter/midi/index.js +0 -11
  112. package/dist/converter/midi/json.d.ts +0 -38
  113. package/dist/converter/midi/json.js +0 -1
  114. package/dist/converter/midi/triplet.d.ts +0 -30
  115. package/dist/converter/midi/triplet.js +0 -75
  116. package/dist/converter/musicxml/dom.d.ts +0 -25
  117. package/dist/converter/musicxml/dom.js +0 -65
  118. package/dist/converter/musicxml/features.d.ts +0 -114
  119. package/dist/converter/musicxml/features.js +0 -501
  120. package/dist/converter/musicxml/index.d.ts +0 -14
  121. package/dist/converter/musicxml/index.js +0 -1295
  122. package/dist/converter/musicxml/model.d.ts +0 -176
  123. package/dist/converter/musicxml/model.js +0 -1
  124. package/dist/converter/musicxml/resolve.d.ts +0 -10
  125. package/dist/converter/musicxml/resolve.js +0 -152
  126. package/dist/converter/source.d.ts +0 -22
  127. package/dist/converter/source.js +0 -51
  128. package/dist/core.d.ts +0 -24
  129. package/dist/core.js +0 -24
  130. package/dist/iife/core.d.ts +0 -1
  131. package/dist/iife/core.js +0 -3
  132. package/dist/iife/from-midi.d.ts +0 -1
  133. package/dist/iife/from-midi.js +0 -15
  134. package/dist/iife/from-musicxml.d.ts +0 -1
  135. package/dist/iife/from-musicxml.js +0 -3
  136. package/dist/iife/full.d.ts +0 -1
  137. package/dist/iife/full.js +0 -3
  138. package/dist/jpfun.core.min.js +0 -123
  139. package/dist/jpfun.from-midi.min.js +0 -9
  140. 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;
@@ -29,7 +29,7 @@ export declare class ASTNodeBase {
29
29
  * 时间求解模式
30
30
  * loweringEnter 返回的事件已规范化并加入索引后调用,决定子节点的展开方式。
31
31
  * 需要本轮事件时通过 ctx.getTemporalNodes 查询
32
- * @returns 返回 null 表示没有子元素,返回对象表示参与时间求解
32
+ * @returns 返回 null 表示不由通用递归器展开子元素;默认将 children 按 sequence 依次展开
33
33
  */
34
34
  timeFlowModel(_ctx: LoweringContext): TimeFlowModel | null;
35
35
  /**
@@ -54,12 +54,6 @@ export declare class ASTBraceNode extends ASTNodeBase {
54
54
  content: ASTNodeBase[];
55
55
  get children(): ASTNodeBase[];
56
56
  constructor(sourceSpan: SourceSpan, content: ASTNodeBase[], parent?: ASTNodeBase | null);
57
- innerSpan(): SourceSpan;
58
- static getContentSpan(content: ASTNodeBase[] | ASTNodeBase): SourceSpan;
59
- timeFlowModel(): {
60
- children: ASTNodeBase[];
61
- mode: "sequence";
62
- };
63
57
  toString(source: string): string;
64
58
  }
65
59
  export interface FunctionArgDef {
@@ -96,9 +90,7 @@ export declare class ASTFunctionNode extends ASTNodeBase {
96
90
  get def(): FunctionDef | undefined;
97
91
  get callName(): string;
98
92
  static deSugarAtom: deSugarAtomFunction;
99
- get deSugarAtom(): deSugarAtomFunction;
100
93
  static deSugarRelation: deSugarRelationFunction;
101
- get deSugarRelation(): deSugarRelationFunction;
102
94
  getArgValue(args: FunctionArgs, ctx: ParserContext): paramValue[];
103
95
  toString(source: string): string;
104
96
  /**
@@ -114,10 +106,5 @@ export declare class ASTFunctionNode extends ASTNodeBase {
114
106
  * 只有函数节点声明 labelable,别的节点读到的必是 undefined,所以无需 instanceof
115
107
  */
116
108
  static findLabelable(node: ASTNodeBase): ASTFunctionNode | null;
117
- /**
118
- * 用于语法糖向前结合
119
- * 从指定位置向前寻找最后一个可由后缀语法糖包装的节点,跳过不产生语义对象的文本
120
- */
121
- static findLastFuncContentIndex(nodes: ASTNodeBase[], i: number): number;
122
109
  }
123
110
  export type ASTFunctionClass = (new (sourceSpan: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent: ASTNodeBase | null) => ASTFunctionNode) & Pick<typeof ASTFunctionNode, "prototype" | "def" | "deSugarAtom" | "deSugarRelation" | "layoutDecorationHandler">;
@@ -26,9 +26,12 @@ export class ASTNodeBase {
26
26
  * 时间求解模式
27
27
  * loweringEnter 返回的事件已规范化并加入索引后调用,决定子节点的展开方式。
28
28
  * 需要本轮事件时通过 ctx.getTemporalNodes 查询
29
- * @returns 返回 null 表示没有子元素,返回对象表示参与时间求解
29
+ * @returns 返回 null 表示不由通用递归器展开子元素;默认将 children 按 sequence 依次展开
30
30
  */
31
- timeFlowModel(_ctx) { return null; }
31
+ timeFlowModel(_ctx) {
32
+ const children = this.children;
33
+ return children ? { mode: "sequence", children } : null;
34
+ }
32
35
  /**
33
36
  * 离开当前层级的回调 同 loweringEnter
34
37
  *
@@ -72,27 +75,6 @@ export class ASTBraceNode extends ASTNodeBase {
72
75
  this.content = content;
73
76
  this.content.forEach(item => item.parent = this);
74
77
  }
75
- innerSpan() {
76
- return ASTBraceNode.getContentSpan(this.content);
77
- }
78
- // 是复制的
79
- static getContentSpan(content) {
80
- if (Array.isArray(content)) {
81
- if (content.length === 0)
82
- return { start: 0, end: 0 };
83
- const firstSpan = ASTBraceNode.getContentSpan(content[0]);
84
- const lastSpan = ASTBraceNode.getContentSpan(content[content.length - 1]);
85
- return { start: firstSpan.start, end: lastSpan.end };
86
- }
87
- else
88
- return { start: content.sourceSpan.start, end: content.sourceSpan.end };
89
- }
90
- timeFlowModel() {
91
- return {
92
- children: this.content,
93
- mode: "sequence",
94
- };
95
- }
96
78
  toString(source) {
97
79
  return `{${this.content.map(item => item.toString(source)).join("")}}`;
98
80
  }
@@ -134,9 +116,7 @@ export class ASTFunctionNode extends ASTNodeBase {
134
116
  }
135
117
  // 去糖函数 详见 ParserContext 中 deSugarAtomFns 和 deSugarRelationFns 的定义
136
118
  static deSugarAtom = () => null; // 默认没有去糖,子类只需要定义static deSugarAtom方法即可
137
- get deSugarAtom() { return this.constructor.deSugarAtom; }
138
119
  static deSugarRelation = () => null;
139
- get deSugarRelation() { return this.constructor.deSugarRelation; }
140
120
  // 按声明顺序取值,位置编号独立于仅命名参数
141
121
  getArgValue(args, ctx) {
142
122
  const def = this.def;
@@ -185,15 +165,4 @@ export class ASTFunctionNode extends ASTNodeBase {
185
165
  }
186
166
  return null;
187
167
  }
188
- /**
189
- * 用于语法糖向前结合
190
- * 从指定位置向前寻找最后一个可由后缀语法糖包装的节点,跳过不产生语义对象的文本
191
- */
192
- static findLastFuncContentIndex(nodes, i) {
193
- for (; i >= 0; i--) {
194
- if (nodes[i] instanceof ASTFunctionNode || nodes[i] instanceof ASTBraceNode)
195
- return i;
196
- }
197
- return -1;
198
- }
199
168
  }
@@ -52,38 +52,34 @@ class AdjustFunction extends ASTFunctionNode {
52
52
  dw;
53
53
  dh;
54
54
  get children() { return [this.target]; }
55
- timeFlowModel() {
56
- return {
57
- children: [this.target],
58
- mode: "sequence",
59
- };
60
- }
61
55
  /** 微调不创建时间事件,只收集作用域内的对象与关系对象 */
62
56
  loweringEnter(ctx) {
63
- const targets = { temporal: 0, attachment: 0 };
64
57
  const group = {
65
- targets,
58
+ temporals: 0,
59
+ attachments: [],
66
60
  onTemporal: node => {
67
61
  if (!isVisualTemporalNode(node))
68
62
  return;
69
- targets.temporal++;
63
+ group.temporals++;
70
64
  offsetTemporal(node, this);
71
65
  },
72
66
  onAttachment: attachment => {
73
- if (!isLayoutAttachment(attachment))
74
- return;
75
- targets.attachment++;
76
- offsetAttachment(attachment, targets, this.dx, this.dy);
67
+ if (isLayoutAttachment(attachment))
68
+ group.attachments.push(attachment);
77
69
  },
78
70
  };
79
71
  ctx.beginLoweringGroup(this, group);
80
72
  return [];
81
73
  }
82
74
  loweringExit(ctx) {
83
- const group = ctx.endLoweringGroup(this);
84
- if (group.targets.temporal === 0 && group.targets.attachment === 0) {
75
+ const { temporals, attachments } = ctx.endLoweringGroup(this);
76
+ if (temporals === 0 && attachments.length === 0) {
85
77
  ctx.diagnostics.push(new WarningDiagnostic("W_ADJUST_NO_TARGET", "@adjust 没有找到可调整的对象", this.sourceSpan));
86
78
  }
79
+ else if (temporals === 0 && (this.dx !== 0 || this.dy !== 0)) {
80
+ for (const attachment of attachments)
81
+ offsetAttachment(attachment, this.dx, this.dy);
82
+ }
87
83
  return [];
88
84
  }
89
85
  constructor(sourceSpan, args, ctx, parent = null) {
@@ -102,58 +98,74 @@ class AdjustFunction extends ASTFunctionNode {
102
98
  }
103
99
  export const AdjustNode = AdjustFunction;
104
100
  /** 在原对象上组合布局生命周期,保持布局索引依赖的对象身份 */
105
- function offsetTemporal(node, owner) {
106
- const { dx, dy, dw, dh } = owner;
101
+ function offsetTemporal(node, { dx, dy, dw, dh }) {
107
102
  if (dx === 0 && dy === 0 && dw === 0 && dh === 0)
108
103
  return;
104
+ const firstOffset = !node.placementOffset && (dx !== 0 || dy !== 0);
109
105
  if (dx !== 0 || dy !== 0) {
110
106
  node.placementOffset = { x: (node.placementOffset?.x ?? 0) + dx, y: (node.placementOffset?.y ?? 0) + dy };
111
107
  }
112
108
  let placedX;
113
109
  let placedY;
114
110
  const finalize = node.finalizeLayout;
115
- const onPlaced = node.onPlaced;
116
111
  node.finalizeLayout = (context) => {
117
112
  finalize?.call(node, context);
113
+ placedX = placedY = undefined;
118
114
  const width = Math.max(0, node.box.w + dw);
119
115
  node.box.anchor = node.box.w > 0 ? node.box.anchor * width / node.box.w : 0;
120
116
  node.box.w = width;
121
117
  node.box.h = Math.max(0, node.box.h + dh);
122
118
  };
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;
123
135
  node.onPlaced = () => {
124
- if (node.box.x !== placedX)
125
- node.box.x += dx;
126
- if (node.box.y !== placedY)
127
- node.box.y += dy;
136
+ if (x !== placedX)
137
+ x += node.placementOffset.x;
138
+ if (y !== placedY)
139
+ y += node.placementOffset.y;
128
140
  onPlaced?.call(node);
129
- placedX = node.box.x;
130
- placedY = node.box.y;
141
+ placedX = x;
142
+ placedY = y;
131
143
  };
132
144
  }
133
145
  /**
134
146
  * 平移一条关系对象
135
147
  *
136
148
  * 在原 Attachment 上组合 createGeometry,保留依赖查找与 instanceof 所需的对象身份
137
- * 作用域里只要有对象被平移过,关系对象就已经跟着端点走了,这里不能再平移第二次
149
+ * 仅在作用域里没有时间对象时调用,避免关系对象既跟端点走又被重复平移
138
150
  */
139
- function offsetAttachment(attachment, targets, dx, dy) {
140
- if (targets.temporal > 0 || (dx === 0 && dy === 0))
141
- return;
151
+ function offsetAttachment(attachment, dx, dy) {
152
+ const firstOffset = !attachment.placementOffset;
142
153
  attachment.placementOffset = { x: (attachment.placementOffset?.x ?? 0) + dx, y: (attachment.placementOffset?.y ?? 0) + dy };
154
+ if (!firstOffset)
155
+ return;
143
156
  const createGeometry = attachment.createGeometry;
144
157
  attachment.createGeometry = (context) => {
145
158
  const geometry = createGeometry.call(attachment, context);
146
- if (targets.temporal > 0 || context.layoutOnly)
159
+ if (context.layoutOnly)
147
160
  return geometry;
148
- const shift = (region) => region.line === void 0
149
- ? { x: region.x + dx, y: region.y + dy, w: region.w, h: region.h }
150
- : { x: region.x + dx, y: region.y + dy, w: region.w, h: region.h, line: region.line, track: region.track };
161
+ const { x, y } = attachment.placementOffset;
162
+ const shift = (region) => ({ ...region, x: region.x + x, y: region.y + y });
151
163
  return {
152
164
  regions: geometry.regions.map(shift),
153
165
  occupancy: geometry.occupancy?.map(shift),
154
166
  paint(painter) {
155
167
  // attachment 的绘制大多用闭包存储了,所以只能代理 painter
156
- geometry.paint(new TranslatingPainter(painter, dx, dy));
168
+ geometry.paint(new TranslatingPainter(painter, x, y));
157
169
  },
158
170
  };
159
171
  };
@@ -1,19 +1,29 @@
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";
7
8
  /** Fold 保持模块私有;琶音只在自己的边界读取它已经公开在实例上的结构。 */
8
9
  function readFold(node) {
9
10
  const candidate = node;
10
- const ast = node.ast;
11
- return (ast.callName === "up" || ast.callName === "down")
12
- && Array.isArray(candidate.members)
11
+ const ast = candidate?.ast;
12
+ return (ast?.callName === "up" || ast?.callName === "down")
13
+ && Array.isArray(candidate?.members)
13
14
  && Array.isArray(ast.contents)
14
15
  ? candidate
15
16
  : null;
16
17
  }
18
+ /** 折叠成员共享同一对齐锚点,取最宽左半宽才能避免升降号等越过宿主左界压住琶音线 */
19
+ function foldAnchor(fold) {
20
+ let anchor = fold.box.anchor;
21
+ for (const member of fold.members) {
22
+ const nested = readFold(member);
23
+ anchor = Math.max(anchor, nested ? foldAnchor(nested) : member.box.anchor);
24
+ }
25
+ return anchor;
26
+ }
17
27
  class ArpeggioFunction extends ASTFunctionNode {
18
28
  static def = {
19
29
  name: ["arp", "arpeggio"],
@@ -43,6 +53,7 @@ class ArpeggioFunction extends ASTFunctionNode {
43
53
  direction;
44
54
  size;
45
55
  get children() { return [this.content]; }
56
+ timeFlowModel() { return null; }
46
57
  constructor(span, args, ctx, parent = null) {
47
58
  super(span, parent);
48
59
  const [content, direction] = this.getArgValue(args, ctx);
@@ -58,15 +69,9 @@ class ArpeggioFunction extends ASTFunctionNode {
58
69
  content.parent = this;
59
70
  }
60
71
  loweringEnter(ctx, track) {
61
- const host = ctx.isolateFromLoweringGroups(() => {
62
- const events = ctx.trackedEvents(this.content, new Fraction(), track).flat();
63
- if (events.length !== 1 || !events[0].box) {
64
- throw new ErrorDiagnostic("E_ARPEGGIO_INVALID_CONTENT", "@arp 的内容必须恰好产生一个同轨和弦", this.content.sourceSpan);
65
- }
66
- return events[0];
67
- });
68
- const fold = readFold(host);
69
- if (!fold || fold.members.length < 2 || fold.members.some(member => member.track !== track)) {
72
+ const events = ctx.isolateFromLoweringGroups(() => ctx.trackedEvents(this.content, new Fraction(), track).flat());
73
+ const fold = events.length === 1 ? readFold(events[0]) : null;
74
+ if (!fold || fold.members.length < 2) {
70
75
  throw new ErrorDiagnostic("E_ARPEGGIO_INVALID_CONTENT", "@arp 只接受至少包含两个成员的同轨 @up/@down 折叠体", this.content.sourceSpan);
71
76
  }
72
77
  return [new ArpeggioTemporal(this, fold)];
@@ -82,7 +87,6 @@ class ArpeggioTemporal extends TemporalNodeBase {
82
87
  /** 槽位取自成员顺序;无声成员也占槽,不能按实际发声音符重新编号 */
83
88
  slots;
84
89
  hostX = 0;
85
- markX = 0;
86
90
  markCommands = [];
87
91
  constructor(ast, host) {
88
92
  super();
@@ -91,8 +95,7 @@ class ArpeggioTemporal extends TemporalNodeBase {
91
95
  const aboveCount = host.ast.contents.length;
92
96
  const bottomToTop = [
93
97
  ...host.members.slice(aboveCount).reverse(),
94
- host.members[0],
95
- ...host.members.slice(1, aboveCount),
98
+ ...host.members.slice(0, aboveCount),
96
99
  ];
97
100
  const members = ast.direction === "down" ? bottomToTop.reverse() : bottomToTop;
98
101
  this.slots = new Map(members.map((member, index) => [member, index]));
@@ -117,24 +120,23 @@ class ArpeggioTemporal extends TemporalNodeBase {
117
120
  this.host.prepareHorizontal?.(line);
118
121
  }
119
122
  prepareLayout(context) {
120
- transferFunctionAddons(this, this.host);
121
- prepareLayoutHost(this.host, context);
122
- this.springConfig = { ...this.host.springConfig, ...this.springConfig };
123
+ const { host } = this;
124
+ transferFunctionAddons(this, host);
125
+ prepareLayoutHost(host, context);
126
+ this.springConfig = { ...host.springConfig };
123
127
  const em = this.ast.size;
124
- const gap = em * 0.16;
125
- const contentBounds = getLayoutBounds(this.host, true);
126
- const bounds = getLayoutBounds(this.host);
127
- const { commands, bounds: markBounds } = prepareArpeggioShape(contentBounds.h, em, this.ast.direction);
128
+ const contentBounds = getLayoutBounds(host, true);
129
+ const bounds = getLayoutBounds(host);
130
+ const { commands, width } = prepareArpeggioShape(contentBounds.h, em, this.ast.direction);
128
131
  this.markCommands = commands;
129
- this.markX = -markBounds.x;
130
- this.hostX = markBounds.w + gap;
131
- this.box.w = this.hostX + this.host.box.w;
132
+ this.hostX = width + em * 0.16 + foldAnchor(host) - host.box.anchor;
133
+ this.box.w = this.hostX + host.box.w;
132
134
  this.box.h = bounds.h;
133
- this.box.anchor = this.hostX + this.host.box.anchor;
134
- this.box.visualAxis = this.host.box.visualAxis - bounds.y;
135
- for (const name in this.host.ports) {
136
- const port = this.host.ports[name];
137
- this.ports[name] = { x: this.hostX + port.x, y: port.y - bounds.y };
135
+ this.box.anchor = this.hostX + host.box.anchor;
136
+ this.box.visualAxis = host.box.visualAxis - bounds.y;
137
+ for (const name in host.ports) {
138
+ const port = host.ports[name];
139
+ this.ports[name] = { ...port, x: this.hostX + port.x, y: port.y - bounds.y };
138
140
  }
139
141
  }
140
142
  onPlaced() {
@@ -149,6 +151,8 @@ class ArpeggioTemporal extends TemporalNodeBase {
149
151
  emitPlayback(emitter) {
150
152
  emitter.play(this.host);
151
153
  const total = emitter.end.clone().sub(emitter.start);
154
+ if (total.compare(0) <= 0)
155
+ return;
152
156
  const step = new Fraction(1, 8);
153
157
  // 短音段限制总延迟,让最后一个成员仍保留至少一半的宿主窗口。
154
158
  const maxStep = total.clone().div(2).div(this.slots.size - 1);
@@ -161,34 +165,26 @@ class ArpeggioTemporal extends TemporalNodeBase {
161
165
  // 宿主刚在上面发布,其全部子区间连续排在 spans 末尾;命中后处理完同组即停。
162
166
  for (let index = context.spans.length - 1; index >= 0; index--) {
163
167
  const note = context.spans[index];
164
- if (!rootOrigin) {
165
- if (!note.origins.some(origin => origin.node === owner))
166
- continue;
167
- rootOrigin = note.origins[0];
168
- }
169
- else if (note.origins[0] !== rootOrigin) {
168
+ const origin = note.origins.find(item => item.node === owner);
169
+ if (!origin || (rootOrigin && origin !== rootOrigin))
170
170
  break;
171
- }
172
- const member = note.origins.find(origin => slots.has(origin.node))?.node;
171
+ rootOrigin = origin;
172
+ const member = note.origins.find(item => slots.has(item.node))?.node;
173
173
  const slot = member ? slots.get(member) : undefined;
174
174
  if (!slot)
175
175
  continue;
176
176
  // 起止一起缩放再平移,保留宿主终点及成员内部节奏,避免只钳制尾部造成负时值。
177
- const delay = step.clone().mul(slot);
178
- const scale = total.clone().sub(delay).div(total);
179
- note.start.sub(emitter.start).mul(scale).add(emitter.start).add(delay);
180
- note.end.sub(emitter.start).mul(scale).add(emitter.start).add(delay);
177
+ const offset = step.clone().mul(slot).add(emitter.start);
178
+ const scale = emitter.end.clone().sub(offset).div(total);
179
+ note.start.sub(emitter.start).mul(scale).add(offset);
180
+ note.end.sub(emitter.start).mul(scale).add(offset);
181
181
  }
182
182
  });
183
183
  }
184
184
  paint(painter) {
185
- const originX = this.box.x;
186
- const originY = getLayoutBounds(this.host, true).y;
187
185
  painter.drawPath(this.markCommands, { fill: "#000" }, {
188
- x: originX + this.markX, y: originY, scaleX: 1, scaleY: 1,
186
+ x: this.box.x, y: getLayoutBounds(this.host, true).y, scaleX: 1, scaleY: 1,
189
187
  });
190
- this.host.paint(painter);
191
- for (const decoration of this.host.decorations)
192
- decoration.paint?.(painter);
188
+ paintVisual(painter, this.host);
193
189
  }
194
190
  }
@@ -1,7 +1,6 @@
1
- import type { Rect } from "../../layout/types.js";
2
1
  import type { PathCommand } from "../../render/types.js";
3
- /** 按 MuseScore 的原始重叠比例铺满指定高度,并一次性返回最终边界 */
2
+ /** 按 MuseScore 的原始重叠比例铺满指定高度,直接生成左上角对齐原点的局部路径 */
4
3
  export declare function prepareArpeggioShape(height: number, em: number, direction: "" | "up" | "down"): {
5
4
  commands: PathCommand[];
6
- bounds: Rect;
5
+ width: number;
7
6
  };