jpfun 0.3.0 → 0.4.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 +73 -1
  2. package/dist/converter/midi/convert.d.ts +50 -0
  3. package/dist/converter/midi/convert.js +700 -0
  4. package/dist/converter/midi/index.d.ts +5 -0
  5. package/dist/converter/midi/index.js +11 -0
  6. package/dist/converter/midi/json.d.ts +38 -0
  7. package/dist/converter/midi/json.js +1 -0
  8. package/dist/converter/midi/triplet.d.ts +30 -0
  9. package/dist/converter/midi/triplet.js +75 -0
  10. package/dist/converter/musicxml/dom.d.ts +25 -0
  11. package/dist/converter/musicxml/dom.js +65 -0
  12. package/dist/converter/musicxml/features.d.ts +51 -0
  13. package/dist/converter/musicxml/features.js +232 -0
  14. package/dist/converter/musicxml/index.d.ts +9 -0
  15. package/dist/converter/musicxml/index.js +1140 -0
  16. package/dist/converter/musicxml/model.d.ts +123 -0
  17. package/dist/converter/musicxml/model.js +1 -0
  18. package/dist/converter/source.d.ts +22 -0
  19. package/dist/converter/source.js +51 -0
  20. package/dist/core.d.ts +22 -0
  21. package/dist/core.js +22 -0
  22. package/dist/functions/ASTtypes.d.ts +28 -25
  23. package/dist/functions/ASTtypes.js +25 -23
  24. package/dist/functions/adjust/index.js +1 -1
  25. package/dist/functions/arpeggio/index.d.ts +2 -0
  26. package/dist/functions/arpeggio/index.js +180 -0
  27. package/dist/functions/arpeggio/shape.d.ts +7 -0
  28. package/dist/functions/arpeggio/shape.js +122 -0
  29. package/dist/functions/bar/index.js +23 -15
  30. package/dist/functions/beam/auto.d.ts +1 -1
  31. package/dist/functions/beam/auto.js +1 -1
  32. package/dist/functions/beam/layout.d.ts +2 -2
  33. package/dist/functions/beam/layout.js +1 -1
  34. package/dist/functions/box/index.js +2 -2
  35. package/dist/functions/br/index.js +1 -1
  36. package/dist/functions/dash/index.js +7 -6
  37. package/dist/functions/default.js +6 -2
  38. package/dist/functions/dot/index.js +12 -22
  39. package/dist/functions/dyn/index.d.ts +2 -0
  40. package/dist/functions/dyn/index.js +242 -0
  41. package/dist/functions/grace/index.d.ts +1 -1
  42. package/dist/functions/grace/index.js +2 -3
  43. package/dist/functions/head/index.js +149 -145
  44. package/dist/functions/key/index.js +5 -4
  45. package/dist/functions/meter/index.js +6 -5
  46. package/dist/functions/note/index.js +68 -21
  47. package/dist/functions/note/noteNameFSM.js +52 -63
  48. package/dist/functions/page/index.d.ts +2 -0
  49. package/dist/functions/page/index.js +22 -7
  50. package/dist/functions/program/index.d.ts +2 -0
  51. package/dist/functions/program/index.js +30 -0
  52. package/dist/functions/set/index.js +8 -5
  53. package/dist/functions/symbol/index.d.ts +13 -3
  54. package/dist/functions/symbol/index.js +61 -16
  55. package/dist/functions/symbol/shape.d.ts +2 -0
  56. package/dist/functions/symbol/shape.js +14 -10
  57. package/dist/functions/symbol/symbols/dc.d.ts +4 -0
  58. package/dist/functions/symbol/symbols/dc.js +82 -0
  59. package/dist/functions/symbol/symbols/{f.d.ts → ds.d.ts} +1 -1
  60. package/dist/functions/symbol/symbols/ds.js +93 -0
  61. package/dist/functions/symbol/symbols/dynamics.d.ts +3 -0
  62. package/dist/functions/symbol/symbols/dynamics.js +168 -0
  63. package/dist/functions/symbol/symbols/{p.d.ts → fine.d.ts} +1 -1
  64. package/dist/functions/symbol/symbols/fine.js +12 -0
  65. package/dist/functions/symbol/symbols/mordent.js +44 -31
  66. package/dist/functions/symbol/symbols/prall.d.ts +2 -0
  67. package/dist/functions/symbol/symbols/prall.js +42 -0
  68. package/dist/functions/symbol/symbols/segno.d.ts +4 -0
  69. package/dist/functions/symbol/symbols/segno.js +82 -0
  70. package/dist/functions/symbol/symbols/tr.js +0 -4
  71. package/dist/functions/tempo/index.js +5 -3
  72. package/dist/functions/temporal.d.ts +138 -0
  73. package/dist/functions/temporal.js +101 -0
  74. package/dist/functions/text/index.js +14 -7
  75. package/dist/functions/tie/index.js +37 -28
  76. package/dist/functions/tuplet/index.js +14 -7
  77. package/dist/functions/up/index.js +23 -21
  78. package/dist/functions/voice/index.js +121 -45
  79. package/dist/functions/volta/index.js +51 -48
  80. package/dist/iife/core.d.ts +1 -0
  81. package/dist/iife/core.js +3 -0
  82. package/dist/iife/from-midi.d.ts +1 -0
  83. package/dist/iife/from-midi.js +15 -0
  84. package/dist/iife/from-musicxml.d.ts +1 -0
  85. package/dist/iife/from-musicxml.js +3 -0
  86. package/dist/iife/full.d.ts +1 -0
  87. package/dist/iife/full.js +3 -0
  88. package/dist/index.d.ts +3 -21
  89. package/dist/index.js +3 -21
  90. package/dist/jpfun.core.min.js +153 -0
  91. package/dist/jpfun.from-midi.min.js +9 -0
  92. package/dist/jpfun.from-musicxml.min.js +12 -0
  93. package/dist/jpfun.min.js +71 -48
  94. package/dist/layout/default.js +2 -3
  95. package/dist/layout/engine.d.ts +2 -1
  96. package/dist/layout/engine.js +71 -26
  97. package/dist/layout/model.d.ts +4 -4
  98. package/dist/layout/model.js +15 -12
  99. package/dist/layout/page.js +5 -4
  100. package/dist/layout/path.js +3 -3
  101. package/dist/layout/types.d.ts +20 -2
  102. package/dist/lowering/loweringContext.d.ts +3 -1
  103. package/dist/lowering/loweringContext.js +28 -14
  104. package/dist/lowering/track.d.ts +4 -8
  105. package/dist/lowering/track.js +6 -1
  106. package/dist/lowering/types.d.ts +5 -128
  107. package/dist/lowering/types.js +1 -98
  108. package/dist/parser/parse-utils/string-utils.d.ts +2 -0
  109. package/dist/parser/parse-utils/string-utils.js +4 -0
  110. package/dist/parser/parserContext.d.ts +7 -8
  111. package/dist/parser/parserContext.js +41 -36
  112. package/dist/pipeline.d.ts +6 -5
  113. package/dist/pipeline.js +4 -5
  114. package/dist/playback/compile.d.ts +1 -1
  115. package/dist/playback/compile.js +15 -2
  116. package/dist/playback/event.d.ts +17 -3
  117. package/dist/playback/event.js +30 -12
  118. package/dist/playback/time.js +1 -1
  119. package/dist/playback/types.d.ts +5 -4
  120. package/dist/render/text.d.ts +6 -1
  121. package/dist/render/text.js +8 -1
  122. package/grammar.md +44 -8
  123. package/package.json +11 -2
  124. package/dist/functions/symbol/symbols/f.js +0 -55
  125. package/dist/functions/symbol/symbols/p.js +0 -61
@@ -0,0 +1,123 @@
1
+ import type { Fraction } from "../../fraction.js";
2
+ export type MusicXmlArpeggio = "none" | "up" | "down";
3
+ /** 单个书面音高,tie 标记保留在音高上以支持和弦成员独立连音 */
4
+ export interface MusicXmlPitch {
5
+ step: string;
6
+ alter: number;
7
+ octave: number;
8
+ tieStart: boolean;
9
+ tieStop: boolean;
10
+ }
11
+ /** 一个 lane 上的原子事件,同起止音高已合并为一个和弦事件 */
12
+ export interface MusicXmlEvent {
13
+ start: Fraction;
14
+ duration: Fraction;
15
+ pitches: MusicXmlPitch[];
16
+ rest: boolean;
17
+ order: number;
18
+ modifiers: {
19
+ name: string;
20
+ placement: "above" | "below";
21
+ }[];
22
+ annotations: {
23
+ text: string;
24
+ placement: "above" | "below";
25
+ boxed?: boolean;
26
+ }[];
27
+ preGraces: MusicXmlPitch[][];
28
+ postGraces: MusicXmlPitch[][];
29
+ lyrics: Map<string, string>;
30
+ arpeggio?: MusicXmlArpeggio;
31
+ program?: number;
32
+ timeModification?: {
33
+ actual: number;
34
+ normal: number;
35
+ start: boolean;
36
+ stop: boolean;
37
+ };
38
+ }
39
+ /** MusicXML 的 part + staff + voice 对应一条 jpFun lane */
40
+ export interface MusicXmlLane {
41
+ partId: string;
42
+ partName: string;
43
+ staff: string;
44
+ voice: string;
45
+ events: MusicXmlEvent[];
46
+ }
47
+ /** 全谱时间流上的拍号状态点 */
48
+ export interface MusicXmlMeterPoint {
49
+ at: Fraction;
50
+ numerator: number;
51
+ denominator: number;
52
+ }
53
+ /** 全谱时间流上的调号状态点 */
54
+ export interface MusicXmlKeyPoint {
55
+ at: Fraction;
56
+ fifths: number;
57
+ mode: string;
58
+ }
59
+ /** 尚未附着到事件的力度或文字方向 */
60
+ export interface MusicXmlDirectionPoint {
61
+ at: Fraction;
62
+ partId: string;
63
+ staff: string;
64
+ voice: string;
65
+ placement: "above" | "below";
66
+ dynamic?: string;
67
+ texts: {
68
+ text: string;
69
+ boxed: boolean;
70
+ }[];
71
+ }
72
+ /** 参与楔形线配对的原始起止点 */
73
+ export interface MusicXmlWedgePoint {
74
+ at: Fraction;
75
+ partId: string;
76
+ staff: string;
77
+ voice: string;
78
+ number: string;
79
+ type: "crescendo" | "diminuendo" | "stop";
80
+ }
81
+ /** 已配对的渐强或渐弱区间 */
82
+ export interface MusicXmlWedgeSpan {
83
+ from: MusicXmlWedgePoint;
84
+ end: Fraction;
85
+ }
86
+ /** 参与房子配对的原始起止点 */
87
+ export interface MusicXmlEndingPoint {
88
+ at: Fraction;
89
+ type: "start" | "stop" | "discontinue";
90
+ passes: number[];
91
+ }
92
+ /** 已配对的房子区间,遍数语义由起点持有 */
93
+ export interface MusicXmlEndingSpan {
94
+ from: MusicXmlEndingPoint;
95
+ end: Fraction;
96
+ }
97
+ /** XML 解析完成后的格式无关乐谱模型,渲染阶段不再读取 DOM */
98
+ export interface ParsedMusicXmlScore {
99
+ title: string;
100
+ subtitle: string;
101
+ creator: string;
102
+ page?: {
103
+ width: number;
104
+ height: number;
105
+ top: number;
106
+ bottom: number;
107
+ left: number;
108
+ right: number;
109
+ };
110
+ lanes: MusicXmlLane[];
111
+ meters: MusicXmlMeterPoint[];
112
+ keys: MusicXmlKeyPoint[];
113
+ tempos: {
114
+ at: Fraction;
115
+ bpm: number;
116
+ }[];
117
+ wedges: MusicXmlWedgeSpan[];
118
+ endings: MusicXmlEndingSpan[];
119
+ bars: Map<string, string>;
120
+ measureBoundaries: Set<string>;
121
+ lineBreaks: Set<string>;
122
+ end: Fraction;
123
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,22 @@
1
+ export { quote } from "../parser/parse-utils/string-utils.js";
2
+ export type PitchMode = "relative" | "absolute";
3
+ export interface SourcePitch {
4
+ name: string;
5
+ accidental: string;
6
+ octave: number;
7
+ }
8
+ interface HeadOptions {
9
+ title?: string;
10
+ subtitle?: string;
11
+ author?: string;
12
+ key: string;
13
+ meter: readonly [numerator: number, denominator: number];
14
+ tempo: number;
15
+ }
16
+ /** 按书写顺序把多个零时长标记叠到主体上方。 */
17
+ export declare function attachAbove(source: string, additions: readonly string[]): string;
18
+ /** 把已解释为目标记谱方式的音高写成 jpFun token。 */
19
+ export declare function renderPitch(pitch: SourcePitch, mode: PitchMode, suffix?: string): string;
20
+ export declare function renderHead(options: HeadOptions): string;
21
+ /** 把“每个声部的各系统”转置成“每个系统的完整声部组” */
22
+ export declare function renderSystems(groups: readonly (readonly string[])[]): string;
@@ -0,0 +1,51 @@
1
+ /** MIDI 与 MusicXML 共享的 jpFun 源码片段生成工具 */
2
+ import { quote } from "../parser/parse-utils/string-utils.js";
3
+ export { quote } from "../parser/parse-utils/string-utils.js";
4
+ const HEAD_TEXT_PRESET = {
5
+ title: "size=2em, align=center",
6
+ subtitle: "size=0.85em, align=center",
7
+ author: "size=0.8em, align=right",
8
+ };
9
+ /** 按书写顺序把多个零时长标记叠到主体上方。 */
10
+ export function attachAbove(source, additions) {
11
+ for (let index = additions.length - 1; index >= 0; index--) {
12
+ source = `{${source} ^ ${additions[index]}}`;
13
+ }
14
+ return source;
15
+ }
16
+ /** 把已解释为目标记谱方式的音高写成 jpFun token。 */
17
+ export function renderPitch(pitch, mode, suffix = "") {
18
+ if (mode === "absolute") {
19
+ return pitch.octave === 0
20
+ ? `@note(${pitch.name}, ${pitch.accidental}, 0)${suffix}`
21
+ : `${pitch.name}${pitch.accidental}${pitch.octave}${suffix}`;
22
+ }
23
+ const octaveMarks = pitch.octave > 0 ? "'".repeat(pitch.octave) : ",".repeat(-pitch.octave);
24
+ return `${pitch.accidental}${pitch.name}${octaveMarks}${suffix}`;
25
+ }
26
+ function renderHeadText(field, value) {
27
+ // 会被注释、续行或 DSL 语法误读的文本改用显式 @text,其余保留简洁的 H.* 裸文本
28
+ const needsExplicitText = value.trim() !== value
29
+ || /[\r\n%]/.test(value) || /^\s*[@{]/.test(value) || value.endsWith("\\");
30
+ return needsExplicitText
31
+ ? `H.${field}: @text(${quote(value)}, ${HEAD_TEXT_PRESET[field]})`
32
+ : `H.${field}: ${value}`;
33
+ }
34
+ export function renderHead(options) {
35
+ const [numerator, denominator] = options.meter;
36
+ const lines = [];
37
+ if (options.title)
38
+ lines.push(renderHeadText("title", options.title));
39
+ if (options.subtitle)
40
+ lines.push(renderHeadText("subtitle", options.subtitle));
41
+ if (options.author)
42
+ lines.push(renderHeadText("author", options.author));
43
+ lines.push(`H.signature: 1=${options.key} ${numerator}/${denominator}`);
44
+ lines.push(`H.tempo: ${options.tempo}`);
45
+ return lines.join("\n");
46
+ }
47
+ /** 把“每个声部的各系统”转置成“每个系统的完整声部组” */
48
+ export function renderSystems(groups) {
49
+ const systemCount = Math.max(0, ...groups.map(lines => lines.length));
50
+ return Array.from({ length: systemCount }, (_, index) => groups.map(lines => lines[index]).filter(Boolean).join("\n")).join("\n\n");
51
+ }
package/dist/core.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ export * from "./pipeline.js";
2
+ export * from "./functions/ASTtypes.js";
3
+ export * from "./functions/temporal.js";
4
+ export * from "./functions/default.js";
5
+ export * from "./diagnostic.js";
6
+ export * from "./fraction.js";
7
+ export * from "./parser/types.js";
8
+ export * from "./parser/grammarType.js";
9
+ export * from "./parser/parserContext.js";
10
+ export * from "./parser/preprocess.js";
11
+ export * from "./lowering/types.js";
12
+ export * from "./lowering/loweringContext.js";
13
+ export * from "./lowering/track.js";
14
+ export * from "./playback/types.js";
15
+ export * from "./playback/time.js";
16
+ export * from "./playback/compile.js";
17
+ export * from "./layout/types.js";
18
+ export * from "./layout/model.js";
19
+ export * from "./layout/default.js";
20
+ export * from "./layout/page.js";
21
+ export * from "./layout/engine.js";
22
+ export * from "./render/index.js";
package/dist/core.js ADDED
@@ -0,0 +1,22 @@
1
+ export * from "./pipeline.js";
2
+ export * from "./functions/ASTtypes.js";
3
+ export * from "./functions/temporal.js";
4
+ export * from "./functions/default.js";
5
+ export * from "./diagnostic.js";
6
+ export * from "./fraction.js";
7
+ export * from "./parser/types.js";
8
+ export * from "./parser/grammarType.js";
9
+ export * from "./parser/parserContext.js";
10
+ export * from "./parser/preprocess.js";
11
+ export * from "./lowering/types.js";
12
+ export * from "./lowering/loweringContext.js";
13
+ export * from "./lowering/track.js";
14
+ export * from "./playback/types.js";
15
+ export * from "./playback/time.js";
16
+ export * from "./playback/compile.js";
17
+ export * from "./layout/types.js";
18
+ export * from "./layout/model.js";
19
+ export * from "./layout/default.js";
20
+ export * from "./layout/page.js";
21
+ export * from "./layout/engine.js";
22
+ export * from "./render/index.js";
@@ -2,7 +2,8 @@ import type { SourceSpan, LengthValue, deSugarAtomFunction, deSugarRelationFunct
2
2
  import type { CallArgumentInfo } from "../parser/grammarType.js";
3
3
  import type { ParserContext } from "../parser/parserContext.js";
4
4
  import type { Fraction } from "../fraction.js";
5
- import type { LoweringAugmenter, LoweringFinalizer, TemporalNodeBase, TimeFlowModel } from "../lowering/types.js";
5
+ import type { LoweringAugmenter, LoweringFinalizer, TimeFlowModel } from "../lowering/types.js";
6
+ import type { TemporalNodeBase } from "./temporal.js";
6
7
  import type { LoweringContext } from "../lowering/loweringContext.js";
7
8
  import type { Track } from "../lowering/track.js";
8
9
  import type { LayoutDecorationHandler } from "../layout/types.js";
@@ -17,27 +18,6 @@ export declare class ASTNodeBase {
17
18
  get children(): ASTNodeBase[] | null;
18
19
  constructor(sourceSpan: SourceSpan, // 源码区间
19
20
  parent?: ASTNodeBase | null);
20
- /**
21
- * lowering 固化后的 attachment 生成钩子
22
- *
23
- * 普通 loweringEnter/loweringExit 在递归遍历 AST 时执行,
24
- * 此时尚未完成锚点归并,事件的 t、track 和 layoutLine 不可用,因此需要观察完整事件流的功能不能在普通 hook 中可靠决定分组。
25
- * 该 hook 读取 LoweringResult 并返回新建的 LoweringAttachment,LoweringContext 将返回值追加到当前文档或 fragment 的 attachments,不会把它们放入时间列或推进时间。
26
- *
27
- * 例:autobeam 扫描最终列,按轨道、谱面行、拍点和显式 beam 端点决定分组,再生成 BeamLayoutAttachment
28
- */
29
- static loweringAugment?: LoweringAugmenter;
30
- /**
31
- * 所有 loweringAugment 结果追加完成后的最终处理;此时已经得到了完整的 lowering 语义
32
- * 可以进行校验(如 beam 和 tie)或者修改某些值
33
- */
34
- static loweringFinalize?: LoweringFinalizer;
35
- /**
36
- * 装饰函数可选的排版声明
37
- * layout 引擎按 key 收集,不需要识别具体函数类
38
- * addon 中的 `@key` 标志会使用该装饰
39
- */
40
- static layoutDecorationHandler?: LayoutDecorationHandler;
41
21
  /**
42
22
  * 进入当前层级的回调
43
23
  * @param ctx 当前的 lowering 上下文
@@ -47,10 +27,11 @@ export declare class ASTNodeBase {
47
27
  loweringEnter(_ctx: LoweringContext, _track: Track): Iterable<TemporalNodeBase>;
48
28
  /**
49
29
  * 时间求解模式
50
- * 由 loweringContext 调用,决定当前节点在时间求解阶段的展开方式
30
+ * loweringEnter 返回的事件已规范化并加入索引后调用,决定子节点的展开方式。
31
+ * 需要本轮事件时通过 ctx.getTemporalNodes 查询
51
32
  * @returns 返回 null 表示没有子元素,返回对象表示参与时间求解
52
33
  */
53
- timeFlowModel(): TimeFlowModel | null;
34
+ timeFlowModel(_ctx: LoweringContext): TimeFlowModel | null;
54
35
  /**
55
36
  * 离开当前层级的回调 同 loweringEnter
56
37
  *
@@ -115,6 +96,28 @@ export declare class ASTFunctionNode extends ASTNodeBase {
115
96
  get deSugarRelation(): deSugarRelationFunction;
116
97
  getArgValue(args: FunctionArgs, ctx: ParserContext): paramValue[];
117
98
  toString(source: string): string;
99
+ /**
100
+ * lowering 固化后的 attachment 生成钩子
101
+ *
102
+ * 普通 loweringEnter/loweringExit 在递归遍历 AST 时执行,
103
+ * 此时尚未完成锚点归并,事件的 t、track 和 layoutLine 不可用,因此需要观察完整事件流的功能不能在普通 hook 中可靠决定分组。
104
+ * 该 hook 读取 LoweringResult 并返回新建的 LoweringAttachment,LoweringContext 将返回值追加到当前文档或 fragment 的 attachments,不会把它们放入时间列或推进时间。
105
+ *
106
+ * 例:autobeam 扫描最终列,按轨道、谱面行、拍点和显式 beam 端点决定分组,再生成 BeamLayoutAttachment
107
+ */
108
+ static loweringAugment?: LoweringAugmenter;
109
+ /**
110
+ * 所有 loweringAugment 结果追加完成后的最终处理;此时已经得到了完整的 lowering 语义
111
+ * 所有派生 attachment 追加完成后,按函数注册顺序处理完整结果
112
+ * 可以进行校验(如 beam 和 tie)或者修改某些值
113
+ */
114
+ static loweringFinalize?: LoweringFinalizer;
115
+ /**
116
+ * 装饰函数可选的排版声明
117
+ * layout 引擎按 key 收集,不需要识别具体函数类
118
+ * addon 中的 `@key` 标志会使用该装饰
119
+ */
120
+ static layoutDecorationHandler?: LayoutDecorationHandler;
118
121
  /**
119
122
  * 在子树里找标签承载者
120
123
  * 未实现 labelable = 透明,继续下潜;实现了就采信它的返回值,null 即拒绝,不再往里找。
@@ -129,4 +132,4 @@ export declare class ASTFunctionNode extends ASTNodeBase {
129
132
  */
130
133
  static findLastFuncContentNode(nodes: ASTNodeBase[], i: number): ASTNodeBase | null;
131
134
  }
132
- export type ASTFunctionClass = new (sourceSpan: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent: ASTNodeBase | null) => ASTFunctionNode;
135
+ export type ASTFunctionClass = (new (sourceSpan: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent: ASTNodeBase | null) => ASTFunctionNode) & Pick<typeof ASTFunctionNode, "prototype" | "def" | "deSugarAtom" | "deSugarRelation" | "loweringAugment" | "loweringFinalize" | "layoutDecorationHandler">;
@@ -13,27 +13,6 @@ export class ASTNodeBase {
13
13
  this.sourceSpan = sourceSpan;
14
14
  this.parent = parent;
15
15
  }
16
- /**
17
- * lowering 固化后的 attachment 生成钩子
18
- *
19
- * 普通 loweringEnter/loweringExit 在递归遍历 AST 时执行,
20
- * 此时尚未完成锚点归并,事件的 t、track 和 layoutLine 不可用,因此需要观察完整事件流的功能不能在普通 hook 中可靠决定分组。
21
- * 该 hook 读取 LoweringResult 并返回新建的 LoweringAttachment,LoweringContext 将返回值追加到当前文档或 fragment 的 attachments,不会把它们放入时间列或推进时间。
22
- *
23
- * 例:autobeam 扫描最终列,按轨道、谱面行、拍点和显式 beam 端点决定分组,再生成 BeamLayoutAttachment
24
- */
25
- static loweringAugment;
26
- /**
27
- * 所有 loweringAugment 结果追加完成后的最终处理;此时已经得到了完整的 lowering 语义
28
- * 可以进行校验(如 beam 和 tie)或者修改某些值
29
- */
30
- static loweringFinalize;
31
- /**
32
- * 装饰函数可选的排版声明
33
- * layout 引擎按 key 收集,不需要识别具体函数类
34
- * addon 中的 `@key` 标志会使用该装饰
35
- */
36
- static layoutDecorationHandler;
37
16
  /**
38
17
  * 进入当前层级的回调
39
18
  * @param ctx 当前的 lowering 上下文
@@ -45,10 +24,11 @@ export class ASTNodeBase {
45
24
  }
46
25
  /**
47
26
  * 时间求解模式
48
- * 由 loweringContext 调用,决定当前节点在时间求解阶段的展开方式
27
+ * loweringEnter 返回的事件已规范化并加入索引后调用,决定子节点的展开方式。
28
+ * 需要本轮事件时通过 ctx.getTemporalNodes 查询
49
29
  * @returns 返回 null 表示没有子元素,返回对象表示参与时间求解
50
30
  */
51
- timeFlowModel() { return null; }
31
+ timeFlowModel(_ctx) { return null; }
52
32
  /**
53
33
  * 离开当前层级的回调 同 loweringEnter
54
34
  *
@@ -171,6 +151,28 @@ export class ASTFunctionNode extends ASTNodeBase {
171
151
  return super.toString(source);
172
152
  return `@${name} `;
173
153
  }
154
+ /**
155
+ * lowering 固化后的 attachment 生成钩子
156
+ *
157
+ * 普通 loweringEnter/loweringExit 在递归遍历 AST 时执行,
158
+ * 此时尚未完成锚点归并,事件的 t、track 和 layoutLine 不可用,因此需要观察完整事件流的功能不能在普通 hook 中可靠决定分组。
159
+ * 该 hook 读取 LoweringResult 并返回新建的 LoweringAttachment,LoweringContext 将返回值追加到当前文档或 fragment 的 attachments,不会把它们放入时间列或推进时间。
160
+ *
161
+ * 例:autobeam 扫描最终列,按轨道、谱面行、拍点和显式 beam 端点决定分组,再生成 BeamLayoutAttachment
162
+ */
163
+ static loweringAugment;
164
+ /**
165
+ * 所有 loweringAugment 结果追加完成后的最终处理;此时已经得到了完整的 lowering 语义
166
+ * 所有派生 attachment 追加完成后,按函数注册顺序处理完整结果
167
+ * 可以进行校验(如 beam 和 tie)或者修改某些值
168
+ */
169
+ static loweringFinalize;
170
+ /**
171
+ * 装饰函数可选的排版声明
172
+ * layout 引擎按 key 收集,不需要识别具体函数类
173
+ * addon 中的 `@key` 标志会使用该装饰
174
+ */
175
+ static layoutDecorationHandler;
174
176
  /**
175
177
  * 在子树里找标签承载者
176
178
  * 未实现 labelable = 透明,继续下潜;实现了就采信它的返回值,null 即拒绝,不再往里找。
@@ -1,6 +1,6 @@
1
1
  import { ASTFunctionNode } from "../ASTtypes.js";
2
2
  import { WarningDiagnostic } from "../../diagnostic.js";
3
- import { isVisualTemporalNode } from "../../lowering/types.js";
3
+ import { isVisualTemporalNode } from "../temporal.js";
4
4
  import { isLayoutAttachment, } from "../../layout/types.js";
5
5
  class AdjustFunction extends ASTFunctionNode {
6
6
  static def = {
@@ -0,0 +1,2 @@
1
+ import { type ASTFunctionClass } from "../ASTtypes.js";
2
+ export declare const ArpeggioNode: ASTFunctionClass;
@@ -0,0 +1,180 @@
1
+ import { ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
2
+ import { Fraction } from "../../fraction.js";
3
+ import { prepareLayoutHost } from "../../layout/engine.js";
4
+ import { ASTFunctionNode, } from "../ASTtypes.js";
5
+ import { TemporalNodeBase } from "../temporal.js";
6
+ import { prepareArpeggioShape } from "./shape.js";
7
+ /** Fold 保持模块私有;琶音只在自己的边界读取它已经公开在实例上的结构。 */
8
+ function readFold(node) {
9
+ const candidate = node;
10
+ const ast = node.ast;
11
+ return (ast.callName === "up" || ast.callName === "down")
12
+ && Array.isArray(candidate.members)
13
+ && Array.isArray(ast.contents)
14
+ ? candidate
15
+ : null;
16
+ }
17
+ class ArpeggioFunction extends ASTFunctionNode {
18
+ static def = {
19
+ name: ["arp", "arpeggio"],
20
+ description: "琶音",
21
+ example: `@arp({1 ^ 3 ^ 5}) 默认从低到高,无箭头
22
+ @arp({1 ^ 3 ^ 5}, direction=up) 从低到高,顶端带箭头
23
+ @arp({1 ^ 3 ^ 5}, direction=down) 从高到低,底端带箭头`,
24
+ allowExtraArgs: false,
25
+ args: [
26
+ {
27
+ name: "content",
28
+ type: "content",
29
+ default: null
30
+ },
31
+ {
32
+ name: "direction",
33
+ type: "string",
34
+ default: ""
35
+ },
36
+ ],
37
+ };
38
+ content;
39
+ direction;
40
+ size;
41
+ get children() { return [this.content]; }
42
+ constructor(span, args, ctx, parent = null) {
43
+ super(span, parent);
44
+ const [content, direction] = this.getArgValue(args, ctx);
45
+ let normalized = "";
46
+ if (direction !== "" && direction !== "up" && direction !== "down") {
47
+ ctx.diagnostics.push(new WarningDiagnostic("W_ARPEGGIO_INVALID_DIRECTION", "@arp 的 direction 只能是 up 或 down,已回退到无箭头上行琶音", span));
48
+ }
49
+ else
50
+ normalized = direction;
51
+ this.content = content;
52
+ this.direction = normalized;
53
+ this.size = ctx.variables.fontsize;
54
+ content.parent = this;
55
+ }
56
+ loweringEnter(ctx, track) {
57
+ let host = null;
58
+ ctx.isolateFromLoweringGroups(() => {
59
+ const events = ctx.trackedEvents(this.content, new Fraction(), track).flat();
60
+ if (events.length !== 1 || !events[0].box) {
61
+ throw new ErrorDiagnostic("E_ARPEGGIO_INVALID_CONTENT", "@arp 的内容必须恰好产生一个同轨和弦", this.content.sourceSpan);
62
+ }
63
+ host = events[0];
64
+ });
65
+ const fold = readFold(host);
66
+ if (!fold || fold.members.length < 2 || fold.members.some(member => member.track !== track)) {
67
+ throw new ErrorDiagnostic("E_ARPEGGIO_INVALID_CONTENT", "@arp 只接受至少包含两个成员的同轨 @up/@down 折叠体", this.content.sourceSpan);
68
+ }
69
+ return [new ArpeggioTemporal(this, fold)];
70
+ }
71
+ toString(source) {
72
+ const direction = this.direction ? `, direction=${this.direction}` : "";
73
+ return `@arp(${this.content.toString(source)}${direction})`;
74
+ }
75
+ }
76
+ export const ArpeggioNode = ArpeggioFunction;
77
+ class ArpeggioTemporal extends TemporalNodeBase {
78
+ host;
79
+ playbackMembers;
80
+ hostX = 0;
81
+ markX = 0;
82
+ markCommands = [];
83
+ constructor(ast, host) {
84
+ super();
85
+ this.ast = ast;
86
+ this.host = host;
87
+ const aboveCount = host.ast.contents.length;
88
+ const bottomToTop = [
89
+ ...host.members.slice(aboveCount).reverse(),
90
+ host.members[0],
91
+ ...host.members.slice(1, aboveCount),
92
+ ];
93
+ this.playbackMembers = ast.direction === "down" ? bottomToTop.reverse() : bottomToTop;
94
+ this.T.copyFrom(host.T);
95
+ this.mergeKey = host.mergeKey;
96
+ this.initLayoutBox();
97
+ if (host.addon)
98
+ this.addon = { ...host.addon };
99
+ host.addon = void 0;
100
+ host.foldedInto = this;
101
+ }
102
+ onTimeState(state) {
103
+ this.host.t.copyFrom(this.t);
104
+ this.host.T.copyFrom(this.T);
105
+ this.host.track = this.track;
106
+ this.host.layoutLine = this.layoutLine;
107
+ this.host.onTimeState?.(state);
108
+ }
109
+ prepareLayout(context) {
110
+ if (this.addon) {
111
+ this.host.addon = this.addon;
112
+ this.addon = void 0;
113
+ }
114
+ prepareLayoutHost(this.host, context);
115
+ const em = this.ast.size;
116
+ const gap = em * 0.16;
117
+ const { commands, bounds: markBounds } = prepareArpeggioShape(this.host.box.h, em, this.ast.direction);
118
+ this.markCommands = commands;
119
+ this.markX = -markBounds.x;
120
+ this.hostX = markBounds.w + gap;
121
+ this.box.w = this.hostX + this.host.box.w;
122
+ this.box.h = this.host.box.h;
123
+ this.box.anchor = this.hostX + this.host.box.anchor;
124
+ this.box.visualAxis = this.host.box.visualAxis;
125
+ for (const name in this.host.ports) {
126
+ const port = this.host.ports[name];
127
+ this.ports[name] = { x: this.hostX + port.x, y: port.y };
128
+ }
129
+ }
130
+ onPlaced() {
131
+ this.host.box.x = this.box.x + this.hostX;
132
+ this.host.box.y = this.box.y;
133
+ this.host.onPlaced?.();
134
+ }
135
+ emitPlayback(emitter) {
136
+ emitter.play(this.host);
137
+ const total = emitter.end.clone().sub(emitter.start);
138
+ const step = new Fraction(1, 8);
139
+ const maxStep = total.clone().div(2).div(this.playbackMembers.length - 1);
140
+ if (step.compare(maxStep) > 0)
141
+ step.copyFrom(maxStep);
142
+ const slots = new Map(this.playbackMembers.map((member, index) => [member, index]));
143
+ const owner = this;
144
+ emitter.defer(context => {
145
+ let rootOrigin;
146
+ for (let index = context.events.length - 1; index >= 0; index--) {
147
+ const event = context.events[index];
148
+ if (!event.origins.some(origin => origin.node === owner))
149
+ continue;
150
+ rootOrigin = event.origins[0];
151
+ break;
152
+ }
153
+ if (!rootOrigin)
154
+ return;
155
+ for (const event of context.events) {
156
+ if ((event.kind !== "note-on" && event.kind !== "note-off")
157
+ || event.origins[0] !== rootOrigin)
158
+ continue;
159
+ const member = event.origins.find(origin => slots.has(origin.node))?.node;
160
+ const slot = member ? slots.get(member) : undefined;
161
+ if (!slot)
162
+ continue;
163
+ event.at.add(step.clone().mul(slot));
164
+ if (event.kind === "note-off" && event.at.compare(emitter.end) > 0) {
165
+ event.at.copyFrom(emitter.end);
166
+ }
167
+ }
168
+ });
169
+ }
170
+ paint(painter) {
171
+ const originX = this.box.x;
172
+ const originY = this.box.y;
173
+ painter.drawPath(this.markCommands, { fill: "#000" }, {
174
+ x: originX + this.markX, y: originY, scaleX: 1, scaleY: 1,
175
+ });
176
+ this.host.paint(painter);
177
+ for (const decoration of this.host.decorations)
178
+ decoration.paint(painter);
179
+ }
180
+ }
@@ -0,0 +1,7 @@
1
+ import type { Rect } from "../../layout/types.js";
2
+ import type { PathCommand } from "../../render/types.js";
3
+ /** 按 MuseScore 的原始重叠比例铺满指定高度,并一次性返回最终边界。 */
4
+ export declare function prepareArpeggioShape(height: number, em: number, direction: "" | "up" | "down"): {
5
+ commands: PathCommand[];
6
+ bounds: Rect;
7
+ };