jpfun 0.2.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 (167) hide show
  1. package/README.md +141 -11
  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/diagnostic.js +5 -2
  23. package/dist/fraction.d.ts +24 -0
  24. package/dist/fraction.js +132 -0
  25. package/dist/functions/ASTtypes.d.ts +51 -31
  26. package/dist/functions/ASTtypes.js +59 -38
  27. package/dist/functions/adjust/index.d.ts +2 -0
  28. package/dist/functions/adjust/index.js +193 -0
  29. package/dist/functions/arpeggio/index.d.ts +2 -0
  30. package/dist/functions/arpeggio/index.js +180 -0
  31. package/dist/functions/arpeggio/shape.d.ts +7 -0
  32. package/dist/functions/arpeggio/shape.js +122 -0
  33. package/dist/functions/bar/index.d.ts +8 -0
  34. package/dist/functions/bar/index.js +62 -25
  35. package/dist/functions/beam/auto.d.ts +1 -1
  36. package/dist/functions/beam/auto.js +33 -16
  37. package/dist/functions/beam/index.js +10 -6
  38. package/dist/functions/beam/layout.d.ts +4 -3
  39. package/dist/functions/beam/layout.js +43 -65
  40. package/dist/functions/box/index.js +37 -36
  41. package/dist/functions/br/index.js +10 -8
  42. package/dist/functions/dash/index.js +40 -7
  43. package/dist/functions/default.js +19 -8
  44. package/dist/functions/div/index.d.ts +16 -0
  45. package/dist/functions/div/index.js +45 -17
  46. package/dist/functions/dot/index.js +23 -25
  47. package/dist/functions/dyn/index.d.ts +2 -0
  48. package/dist/functions/dyn/index.js +242 -0
  49. package/dist/functions/grace/index.d.ts +8 -11
  50. package/dist/functions/grace/index.js +84 -79
  51. package/dist/functions/head/index.d.ts +2 -0
  52. package/dist/functions/head/index.js +496 -0
  53. package/dist/functions/key/index.js +98 -3
  54. package/dist/functions/meter/index.d.ts +2 -0
  55. package/dist/functions/meter/index.js +155 -0
  56. package/dist/functions/note/accidentals.d.ts +24 -3
  57. package/dist/functions/note/accidentals.js +31 -1
  58. package/dist/functions/note/index.js +106 -79
  59. package/dist/functions/note/noteNameFSM.js +52 -63
  60. package/dist/functions/page/index.d.ts +11 -2
  61. package/dist/functions/page/index.js +65 -4
  62. package/dist/functions/program/index.d.ts +2 -0
  63. package/dist/functions/program/index.js +30 -0
  64. package/dist/functions/set/index.js +43 -32
  65. package/dist/functions/stack/index.js +26 -22
  66. package/dist/functions/symbol/index.d.ts +31 -0
  67. package/dist/functions/symbol/index.js +139 -0
  68. package/dist/functions/symbol/ornament.d.ts +15 -0
  69. package/dist/functions/symbol/ornament.js +73 -0
  70. package/dist/functions/symbol/shape.d.ts +24 -0
  71. package/dist/functions/symbol/shape.js +52 -0
  72. package/dist/functions/symbol/symbols/accent.d.ts +2 -0
  73. package/dist/functions/symbol/symbols/accent.js +24 -0
  74. package/dist/functions/symbol/symbols/dc.d.ts +4 -0
  75. package/dist/functions/symbol/symbols/dc.js +82 -0
  76. package/dist/functions/symbol/symbols/ds.d.ts +2 -0
  77. package/dist/functions/symbol/symbols/ds.js +93 -0
  78. package/dist/functions/symbol/symbols/dynamics.d.ts +3 -0
  79. package/dist/functions/symbol/symbols/dynamics.js +168 -0
  80. package/dist/functions/symbol/symbols/fermata.d.ts +2 -0
  81. package/dist/functions/symbol/symbols/fermata.js +24 -0
  82. package/dist/functions/symbol/symbols/fine.d.ts +2 -0
  83. package/dist/functions/symbol/symbols/fine.js +12 -0
  84. package/dist/functions/symbol/symbols/mordent.d.ts +2 -0
  85. package/dist/functions/symbol/symbols/mordent.js +56 -0
  86. package/dist/functions/symbol/symbols/prall.d.ts +2 -0
  87. package/dist/functions/symbol/symbols/prall.js +42 -0
  88. package/dist/functions/symbol/symbols/segno.d.ts +4 -0
  89. package/dist/functions/symbol/symbols/segno.js +82 -0
  90. package/dist/functions/symbol/symbols/tr.d.ts +2 -0
  91. package/dist/functions/symbol/symbols/tr.js +71 -0
  92. package/dist/functions/tempo/glyph.d.ts +12 -0
  93. package/dist/functions/tempo/glyph.js +30 -0
  94. package/dist/functions/tempo/index.js +57 -4
  95. package/dist/functions/temporal.d.ts +138 -0
  96. package/dist/functions/temporal.js +101 -0
  97. package/dist/functions/text/index.js +86 -27
  98. package/dist/functions/tie/index.js +136 -152
  99. package/dist/functions/tuplet/index.d.ts +2 -0
  100. package/dist/functions/tuplet/index.js +218 -0
  101. package/dist/functions/up/index.d.ts +1 -0
  102. package/dist/functions/up/index.js +258 -182
  103. package/dist/functions/voice/index.js +203 -109
  104. package/dist/functions/volta/index.d.ts +2 -0
  105. package/dist/functions/volta/index.js +230 -0
  106. package/dist/iife/core.d.ts +1 -0
  107. package/dist/iife/core.js +3 -0
  108. package/dist/iife/from-midi.d.ts +1 -0
  109. package/dist/iife/from-midi.js +15 -0
  110. package/dist/iife/from-musicxml.d.ts +1 -0
  111. package/dist/iife/from-musicxml.js +3 -0
  112. package/dist/iife/full.d.ts +1 -0
  113. package/dist/iife/full.js +3 -0
  114. package/dist/index.d.ts +3 -17
  115. package/dist/index.js +3 -17
  116. package/dist/jpfun.core.min.js +153 -0
  117. package/dist/jpfun.from-midi.min.js +9 -0
  118. package/dist/jpfun.from-musicxml.min.js +12 -0
  119. package/dist/jpfun.min.js +166 -0
  120. package/dist/layout/default.js +2 -3
  121. package/dist/layout/engine.d.ts +6 -12
  122. package/dist/layout/engine.js +115 -64
  123. package/dist/layout/model.d.ts +12 -5
  124. package/dist/layout/model.js +31 -18
  125. package/dist/layout/page.js +5 -4
  126. package/dist/layout/path.d.ts +19 -0
  127. package/dist/layout/path.js +101 -0
  128. package/dist/layout/types.d.ts +71 -20
  129. package/dist/layout/types.js +3 -1
  130. package/dist/lowering/loweringContext.d.ts +20 -20
  131. package/dist/lowering/loweringContext.js +153 -101
  132. package/dist/lowering/track.d.ts +5 -9
  133. package/dist/lowering/track.js +7 -2
  134. package/dist/lowering/types.d.ts +26 -112
  135. package/dist/lowering/types.js +1 -92
  136. package/dist/parser/parse-utils/call-utils.d.ts +0 -2
  137. package/dist/parser/parse-utils/call-utils.js +0 -6
  138. package/dist/parser/parse-utils/note-utils.d.ts +8 -0
  139. package/dist/parser/parse-utils/note-utils.js +35 -13
  140. package/dist/parser/parse-utils/string-utils.d.ts +10 -0
  141. package/dist/parser/parse-utils/string-utils.js +24 -0
  142. package/dist/parser/parserContext.d.ts +11 -9
  143. package/dist/parser/parserContext.js +65 -55
  144. package/dist/parser/preprocess.js +17 -11
  145. package/dist/pipeline.d.ts +6 -5
  146. package/dist/pipeline.js +4 -5
  147. package/dist/playback/compile.d.ts +18 -0
  148. package/dist/playback/compile.js +414 -0
  149. package/dist/playback/event.d.ts +105 -0
  150. package/dist/playback/event.js +105 -0
  151. package/dist/playback/time.d.ts +14 -0
  152. package/dist/playback/time.js +81 -0
  153. package/dist/playback/types.d.ts +129 -0
  154. package/dist/playback/types.js +3 -0
  155. package/dist/render/canvas.d.ts +4 -4
  156. package/dist/render/canvas.js +20 -5
  157. package/dist/render/index.d.ts +1 -0
  158. package/dist/render/index.js +1 -0
  159. package/dist/render/paint.d.ts +8 -0
  160. package/dist/render/paint.js +101 -0
  161. package/dist/render/svg.d.ts +3 -3
  162. package/dist/render/svg.js +10 -8
  163. package/dist/render/text.d.ts +22 -0
  164. package/dist/render/text.js +42 -0
  165. package/dist/render/types.d.ts +1 -1
  166. package/grammar.md +132 -13
  167. package/package.json +19 -6
@@ -0,0 +1,81 @@
1
+ import { DEFAULT_BPM } from "../functions/temporal.js";
2
+ /** 演奏时间(QN)按分段速度积分为秒 */
3
+ export function performanceTimeToSeconds(events, performanceTime) {
4
+ const target = Math.max(0, performanceTime);
5
+ let seconds = 0;
6
+ let position = 0;
7
+ let bpm = DEFAULT_BPM;
8
+ for (const event of events) {
9
+ if (event.kind !== "tempo")
10
+ continue;
11
+ const next = event.at.toNumber();
12
+ if (next > target)
13
+ break;
14
+ if (next > position)
15
+ seconds += (next - position) * 60 / bpm;
16
+ position = next;
17
+ bpm = event.bpm;
18
+ }
19
+ return seconds + (target - position) * 60 / bpm;
20
+ }
21
+ export function secondsToPerformanceTime(events, seconds) {
22
+ let remaining = Math.max(0, seconds);
23
+ let position = 0;
24
+ let bpm = DEFAULT_BPM;
25
+ for (const event of events) {
26
+ if (event.kind !== "tempo")
27
+ continue;
28
+ const next = event.at.toNumber();
29
+ const segmentSeconds = (next - position) * 60 / bpm;
30
+ if (remaining < segmentSeconds)
31
+ return position + remaining * bpm / 60;
32
+ remaining -= segmentSeconds;
33
+ position = next;
34
+ bpm = event.bpm;
35
+ }
36
+ return position + remaining * bpm / 60;
37
+ }
38
+ /** 演奏进度换算为谱面进度 */
39
+ export function performanceTimeToScoreTime(scoreMap, performanceTime) {
40
+ const target = Math.max(0, performanceTime);
41
+ let result = target;
42
+ for (const point of scoreMap) {
43
+ const performance = point.performance.toNumber();
44
+ if (performance > target)
45
+ break;
46
+ result = point.score.toNumber() + target - performance;
47
+ }
48
+ return result;
49
+ }
50
+ /**
51
+ * 谱面位置换算为演奏时间,供“点击谱面从这里播放”使用
52
+ *
53
+ * 反复让同一个谱面位置对应多段演奏时间,这里取最早的一遍。
54
+ */
55
+ export function scoreTimeToPerformanceTime(scoreMap, scoreTime) {
56
+ const target = Math.max(0, scoreTime);
57
+ let nextReachable;
58
+ for (let i = 0; i < scoreMap.length; i++) {
59
+ const point = scoreMap[i];
60
+ const score = point.score.toNumber();
61
+ if (score > target) {
62
+ if (!nextReachable || score < nextReachable.score.toNumber())
63
+ nextReachable = point;
64
+ continue;
65
+ }
66
+ const next = scoreMap[i + 1];
67
+ const span = next ? next.performance.toNumber() - point.performance.toNumber() : Infinity;
68
+ if (target - score >= span)
69
+ continue;
70
+ return point.performance.toNumber() + (target - score);
71
+ }
72
+ return nextReachable?.performance.toNumber() ?? target;
73
+ }
74
+ export function secondsToScoreTime(plan, seconds) {
75
+ const performance = Math.min(secondsToPerformanceTime(plan.events, seconds), plan.performanceDuration.toNumber());
76
+ return performanceTimeToScoreTime(plan.scoreMap, performance);
77
+ }
78
+ export function scoreTimeToSeconds(plan, scoreTime) {
79
+ const performance = Math.min(scoreTimeToPerformanceTime(plan.scoreMap, scoreTime), plan.performanceDuration.toNumber());
80
+ return performanceTimeToSeconds(plan.events, performance);
81
+ }
@@ -0,0 +1,129 @@
1
+ import type { Diagnostic } from "../diagnostic.js";
2
+ import type { Fraction } from "../fraction.js";
3
+ import type { LoweringAttachment } from "../lowering/types.js";
4
+ import type { TemporalNodeBase } from "../functions/temporal.js";
5
+ import type { Track } from "../lowering/track.js";
6
+ import type { PlaybackDraftEvent, PlaybackEvent, PlaybackEventInput, PlaybackNoteId } from "./event.js";
7
+ export type * from "./event.js";
8
+ /**
9
+ * 播放列游标
10
+ *
11
+ * 控制流只能通过它查询已经发生的事实,因此自身不保存状态,同一份 lowering 结果重复编译结果一致
12
+ */
13
+ export interface PlaybackCursor {
14
+ /** 正在决定去留的列 */
15
+ readonly column: number;
16
+ /** 该列到目前为止被到达的次数,含本次;被跳过的到达也算 */
17
+ visits(column: number): number;
18
+ /** 从 from 出发沿 direction 找最近一个带该标记的列,不含 from 自身 */
19
+ seek(mark: string, from: number, direction: -1 | 1): number | undefined;
20
+ }
21
+ /**
22
+ * 对游标的一次干预
23
+ * - jump: 当前列不演奏,直接跳到目标列
24
+ * - stop: 在当前列之前结束
25
+ */
26
+ export type PlaybackFlowAction = {
27
+ kind: "jump";
28
+ column: number;
29
+ } | {
30
+ kind: "stop";
31
+ };
32
+ /** 把事件映射到它在播放时间流中的列;折叠成员会映射到宿主 */
33
+ export type PlaybackColumnOf = (node: TemporalNodeBase) => number | undefined;
34
+ /** 控制流在编译开始时生成的执行声明;range 是运行的升序闭区间,缺省表示每列都运行 */
35
+ export interface PlaybackFlowHook {
36
+ readonly range?: readonly [number, number];
37
+ run(cursor: PlaybackCursor): PlaybackFlowAction | undefined;
38
+ }
39
+ /** 参与播放顺序决策的能力 */
40
+ export interface PlaybackFlow {
41
+ /** 根据本轮列索引声明生效范围和运行逻辑 */
42
+ playbackFlow(columnOf: PlaybackColumnOf): PlaybackFlowHook | undefined;
43
+ }
44
+ /**
45
+ * 记谱位置固化到 Temporal 上的基础状态
46
+ *
47
+ * 不要用任意键索引,否则具体 MIDI 状态会失去类型约束
48
+ */
49
+ export interface PlaybackState {
50
+ readonly bpm?: number;
51
+ readonly velocity?: number;
52
+ readonly program?: number;
53
+ }
54
+ /** 按线性化时间扫描的可变系统状态 */
55
+ export interface PlaybackSystemState {
56
+ bpm: number;
57
+ bpmScale: Fraction;
58
+ }
59
+ export interface PlaybackSystemSnapshot {
60
+ readonly bpm: number;
61
+ readonly bpmScale: Fraction;
62
+ readonly effectiveBpm: number;
63
+ }
64
+ /** 在指定演奏时刻修改系统状态;所有同刻控制执行完后,core 据最终状态生成 Tempo 等事件 */
65
+ export type PlaybackControl = (state: PlaybackSystemState) => void;
66
+ /** 当前节点的局部变换完成后,检查或改写此前已发布的事件,例如 dash 延后前音的 NoteOff */
67
+ export type PlaybackHook = (context: PlaybackHookContext) => void;
68
+ /** 修饰同一 play frame 中排在声明者之后的一次具体访问,例如 accent、tr 和波音 */
69
+ export type PlaybackTransform = (context: PlaybackHookContext, events: PlaybackDraftEvent[]) => PlaybackDraftEvent[] | void;
70
+ export interface PlaybackHookContext {
71
+ /** 完整 Tempo 表,以及当前位置此前已经发布的音符事件;relation 阶段包含完整计划 */
72
+ readonly events: PlaybackDraftEvent[];
73
+ readonly diagnostics: Diagnostic[];
74
+ nextNoteId(): PlaybackNoteId;
75
+ stateAt(time: Fraction): PlaybackSystemSnapshot;
76
+ }
77
+ /** 具体 Temporal 只发布系统原语、系统控制和延迟事件变换 */
78
+ export interface PlaybackEmitter {
79
+ /** 当前访问在演奏 QN 轴上的起点 */
80
+ readonly start: Fraction;
81
+ /**
82
+ * 当前访问在演奏 QN 轴上的终点
83
+ * 和 t+T 不一定相等,例如 up 中的折叠节点
84
+ */
85
+ readonly end: Fraction;
86
+ /** 当前节点所属的原始 Track;最终输出时转换为 PlaybackPlan.tracks 的索引 */
87
+ readonly track: Track;
88
+ /** 为一对新的 NoteOn/NoteOff 分配共享身份 */
89
+ nextNoteId(): PlaybackNoteId;
90
+ /** 发布一个系统定义的原始播放事件;core 自动补来源、轨道和稳定次序 */
91
+ emit(event: PlaybackEventInput): void;
92
+ /** 在指定时刻登记系统状态修改;同刻控制全部执行后才生成最终状态事件 */
93
+ control(at: Fraction, apply: PlaybackControl): void;
94
+ /** 修饰同一 play frame 中排在当前节点之后的音符访问 */
95
+ affectFollowing(transform: PlaybackTransform): void;
96
+ /** 当前节点的局部变换完成后,在当前位置处理此前已发布的事件 */
97
+ defer(hook: PlaybackHook): void;
98
+ /** 递归发布折叠的子节点;未指定区间时继承当前 start 和 duration */
99
+ play(child: TemporalNodeBase, start?: Fraction, duration?: Fraction): void;
100
+ }
101
+ /** 所有节点 hook 完成后,attachment 可以处理跨节点关系 */
102
+ export interface PlaybackRelation extends LoweringAttachment {
103
+ applyPlayback(context: PlaybackHookContext): void;
104
+ }
105
+ export declare function isPlaybackRelation(attachment: LoweringAttachment): attachment is PlaybackRelation;
106
+ /** 控制流展开后的演奏位置到记谱位置映射 */
107
+ export interface PlaybackScorePoint {
108
+ /** 控制流展开后的连续演奏位置;反复继续前进,跳转处也不回退,单位 QN */
109
+ readonly performance: Fraction;
110
+ /** 与该演奏位置对应的原始谱面位置;反复时会回退,跳过房子时会前跳,单位 QN */
111
+ readonly score: Fraction;
112
+ }
113
+ /**
114
+ * 完整且可查询的演奏计划
115
+ *
116
+ * 刻意不做成 generator:随机定位、总时长和 MIDI 导出都需要完整计划,
117
+ * 而 tie 这类关系对象要同时改写相距很远的两个端点。无限反复属于播放器的循环控制,
118
+ * 应表示为有限计划加循环点,不是无限序列。
119
+ */
120
+ export interface PlaybackPlan {
121
+ /** 按演奏时间升序;同刻依次为 tempo、time-signature、program-change、note-off、note-on */
122
+ readonly events: readonly PlaybackEvent[];
123
+ readonly scoreMap: readonly PlaybackScorePoint[];
124
+ /** 最终至少含一个 NoteOn 的原始 Track;事件 track 是此数组的索引 */
125
+ readonly tracks: readonly Track[];
126
+ readonly performanceDuration: Fraction;
127
+ readonly durationSeconds: number;
128
+ readonly diagnostics: readonly Diagnostic[];
129
+ }
@@ -0,0 +1,3 @@
1
+ export function isPlaybackRelation(attachment) {
2
+ return typeof attachment.applyPlayback === "function";
3
+ }
@@ -1,4 +1,4 @@
1
- import { type DocumentLayoutResult } from "../layout/engine.js";
1
+ import type { DocumentLayoutResult } from "../layout/engine.js";
2
2
  import type { PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from "./types.js";
3
3
  /**
4
4
  * CanvasRenderingContext2D 的 Painter 适配器
@@ -7,7 +7,7 @@ import type { PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from
7
7
  * 调用方可以在构造前配置 context,再使用同一个布局结果绘制
8
8
  */
9
9
  export declare class CanvasPainter implements Painter {
10
- private context;
10
+ private readonly context;
11
11
  constructor(context: CanvasRenderingContext2D);
12
12
  drawText(text: string, x: number, y: number, style: TextStyle): void;
13
13
  drawLine(x1: number, y1: number, x2: number, y2: number, style?: PaintStyle): void;
@@ -15,5 +15,5 @@ export declare class CanvasPainter implements Painter {
15
15
  drawCircle(cx: number, cy: number, r: number, style?: PaintStyle): void;
16
16
  drawPath(commands: readonly PathCommand[], style?: PaintStyle, transform?: PathTransform): void;
17
17
  }
18
- /** 使用 Canvas 后端绘制一个已经完成布局的文档 */
19
- export declare function renderLayoutToCanvas(result: DocumentLayoutResult, context: CanvasRenderingContext2D): void;
18
+ /** 使用 Canvas 后端把一个布局结果一次绘制到独立页面 context */
19
+ export declare function renderLayoutPagesToCanvas(result: DocumentLayoutResult, contexts: readonly CanvasRenderingContext2D[]): void;
@@ -1,4 +1,5 @@
1
- import { paintLayout } from "../layout/engine.js";
1
+ import { layoutPageBounds, paintLayoutPages } from "./paint.js";
2
+ import { canvasFont } from "./text.js";
2
3
  function tracePath(context, commands, x = 0, y = 0, scaleX = 1, scaleY = 1) {
3
4
  context.beginPath();
4
5
  for (const command of commands) {
@@ -43,7 +44,7 @@ export class CanvasPainter {
43
44
  this.context.save();
44
45
  applyOpacity(this.context, style);
45
46
  this.context.fillStyle = style.fill ?? "#000";
46
- this.context.font = `${style.fontWeight ?? "normal"} ${style.fontSize}px ${style.fontFamily ?? "sans-serif"}`;
47
+ this.context.font = canvasFont(style);
47
48
  this.context.textAlign = style.textAlign ?? "left";
48
49
  this.context.textBaseline = "alphabetic";
49
50
  this.context.fillText(text, x, y);
@@ -115,7 +116,21 @@ export class CanvasPainter {
115
116
  this.context.restore();
116
117
  }
117
118
  }
118
- /** 使用 Canvas 后端绘制一个已经完成布局的文档 */
119
- export function renderLayoutToCanvas(result, context) {
120
- paintLayout(result, new CanvasPainter(context));
119
+ /** 使用 Canvas 后端把一个布局结果一次绘制到独立页面 context */
120
+ export function renderLayoutPagesToCanvas(result, contexts) {
121
+ const pages = layoutPageBounds(result);
122
+ if (contexts.length !== pages.length) {
123
+ throw new Error(`Expected ${pages.length} page contexts, got ${contexts.length}`);
124
+ }
125
+ for (const [index, context] of contexts.entries()) {
126
+ context.save();
127
+ context.translate(-pages[index].x, -pages[index].y);
128
+ }
129
+ try {
130
+ paintLayoutPages(result, contexts.map(context => new CanvasPainter(context)));
131
+ }
132
+ finally {
133
+ for (const context of contexts)
134
+ context.restore();
135
+ }
121
136
  }
@@ -1,4 +1,5 @@
1
1
  export * from "./types.js";
2
+ export { layoutPageBounds, paintLayout } from "./paint.js";
2
3
  export * from "./text.js";
3
4
  export * from "./recording.js";
4
5
  export * from "./svg.js";
@@ -1,4 +1,5 @@
1
1
  export * from "./types.js";
2
+ export { layoutPageBounds, paintLayout } from "./paint.js";
2
3
  export * from "./text.js";
3
4
  export * from "./recording.js";
4
5
  export * from "./svg.js";
@@ -0,0 +1,8 @@
1
+ import type { DocumentLayoutResult } from "../layout/engine.js";
2
+ import type { Rect } from "../layout/types.js";
3
+ import type { Painter } from "./types.js";
4
+ export declare function layoutPageBounds(result: DocumentLayoutResult): readonly Rect[];
5
+ /** 按固定层级把布局结果绘制到一个 Painter */
6
+ export declare function paintLayout(result: DocumentLayoutResult, painter: Painter): void;
7
+ /** 用一个代理 Painter 把一次完整绘制分发到多个页面 Painter */
8
+ export declare function paintLayoutPages(result: DocumentLayoutResult, painters: readonly Painter[]): void;
@@ -0,0 +1,101 @@
1
+ export function layoutPageBounds(result) {
2
+ return result.pages.length > 0
3
+ ? result.pages.map(page => page.bounds)
4
+ : [result.bounds];
5
+ }
6
+ /** 按固定层级把布局结果绘制到一个 Painter */
7
+ export function paintLayout(result, painter) {
8
+ for (const attachment of result.attachments) {
9
+ if (attachment.layer === "background")
10
+ attachment.paint(painter);
11
+ }
12
+ for (const node of result.objects) {
13
+ node.paint(painter);
14
+ for (const decoration of node.decorations)
15
+ decoration.paint(painter);
16
+ }
17
+ for (const attachment of result.attachments) {
18
+ if (attachment.layer === "foreground")
19
+ attachment.paint(painter);
20
+ }
21
+ }
22
+ class PagePainter {
23
+ pages;
24
+ painters;
25
+ constructor(pages, painters) {
26
+ this.pages = pages;
27
+ this.painters = painters;
28
+ }
29
+ route(top, bottom, paint) {
30
+ let low = 0;
31
+ let high = this.pages.length;
32
+ while (low < high) {
33
+ const middle = (low + high) >>> 1;
34
+ const page = this.pages[middle];
35
+ if (page.y + page.h < top)
36
+ low = middle + 1;
37
+ else
38
+ high = middle;
39
+ }
40
+ for (let index = low; index < this.pages.length && this.pages[index].y <= bottom; index++) {
41
+ paint(this.painters[index]);
42
+ }
43
+ }
44
+ drawText(text, x, y, style) {
45
+ this.route(y, y, painter => painter.drawText(text, x, y, style));
46
+ }
47
+ drawLine(x1, y1, x2, y2, style) {
48
+ const halfStroke = (style?.strokeWidth ?? 1) / 2;
49
+ this.route(Math.min(y1, y2) - halfStroke, Math.max(y1, y2) + halfStroke, painter => painter.drawLine(x1, y1, x2, y2, style));
50
+ }
51
+ drawRect(x, y, w, h, style) {
52
+ const halfStroke = style?.stroke ? (style.strokeWidth ?? 1) / 2 : 0;
53
+ this.route(y - halfStroke, y + Math.max(0, h) + halfStroke, painter => {
54
+ painter.drawRect(x, y, w, h, style);
55
+ });
56
+ }
57
+ drawCircle(cx, cy, r, style) {
58
+ const halfStroke = style?.stroke ? (style.strokeWidth ?? 1) / 2 : 0;
59
+ const radius = Math.max(0, r) + halfStroke;
60
+ this.route(cy - radius, cy + radius, painter => painter.drawCircle(cx, cy, r, style));
61
+ }
62
+ drawPath(commands, style, transform) {
63
+ if (commands.length === 0)
64
+ return;
65
+ const y = transform
66
+ ? (value) => transform.y + value * transform.scaleY
67
+ : (value) => value;
68
+ let top = Infinity;
69
+ let bottom = -Infinity;
70
+ const include = (value) => {
71
+ const transformed = y(value);
72
+ top = Math.min(top, transformed);
73
+ bottom = Math.max(bottom, transformed);
74
+ };
75
+ for (const command of commands) {
76
+ if (command.op === "Z")
77
+ continue;
78
+ if (command.op === "Q")
79
+ include(command.cy);
80
+ if (command.op === "C") {
81
+ include(command.cy1);
82
+ include(command.cy2);
83
+ }
84
+ include(command.y);
85
+ }
86
+ if (!Number.isFinite(top))
87
+ return;
88
+ const halfStroke = style?.stroke ? (style.strokeWidth ?? 1) / 2 : 0;
89
+ this.route(top - halfStroke, bottom + halfStroke, painter => {
90
+ painter.drawPath(commands, style, transform);
91
+ });
92
+ }
93
+ }
94
+ /** 用一个代理 Painter 把一次完整绘制分发到多个页面 Painter */
95
+ export function paintLayoutPages(result, painters) {
96
+ const pages = layoutPageBounds(result);
97
+ if (painters.length !== pages.length) {
98
+ throw new Error(`Expected ${pages.length} page painters, got ${painters.length}`);
99
+ }
100
+ paintLayout(result, new PagePainter(pages, painters));
101
+ }
@@ -1,4 +1,4 @@
1
- import { type DocumentLayoutResult } from "../layout/engine.js";
1
+ import type { DocumentLayoutResult } from "../layout/engine.js";
2
2
  import type { PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from "./types.js";
3
3
  export interface SvgRenderOptions {
4
4
  padding?: number;
@@ -14,5 +14,5 @@ export declare class SvgPainter implements Painter {
14
14
  drawPath(commands: readonly PathCommand[], style?: PaintStyle, transform?: PathTransform): void;
15
15
  toSvg(bounds: DocumentLayoutResult["bounds"], options?: SvgRenderOptions): string;
16
16
  }
17
- /** 使用 SVG 后端绘制一个已经完成布局的文档 */
18
- export declare function renderLayoutToSvg(result: DocumentLayoutResult, options?: SvgRenderOptions): string;
17
+ /** 使用 SVG 后端把一个布局结果绘制成独立页面 */
18
+ export declare function renderLayoutPagesToSvg(result: DocumentLayoutResult, options?: SvgRenderOptions): string[];
@@ -1,4 +1,5 @@
1
- import { paintLayout } from "../layout/engine.js";
1
+ import { layoutPageBounds, paintLayoutPages } from "./paint.js";
2
+ import { DEFAULT_TEXT_FONT } from "./text.js";
2
3
  function number(value) {
3
4
  if (!Number.isFinite(value))
4
5
  return "0";
@@ -55,7 +56,7 @@ function opacityAttribute(style) {
55
56
  export class SvgPainter {
56
57
  body = [];
57
58
  drawText(text, x, y, style) {
58
- const family = style.fontFamily ?? "sans-serif";
59
+ const family = style.fontFamily ?? DEFAULT_TEXT_FONT;
59
60
  const weight = style.fontWeight ?? "normal";
60
61
  const fill = style.fill ?? "#000";
61
62
  const textAnchor = style.textAlign === "center"
@@ -64,7 +65,7 @@ export class SvgPainter {
64
65
  this.body.push(`<text x="${number(x)}" y="${number(y)}" `
65
66
  + `font-family="${escapeXml(family)}" font-size="${number(style.fontSize)}" `
66
67
  + `font-weight="${escapeXml(String(weight))}" text-anchor="${textAnchor}" `
67
- + `fill="${escapeXml(fill)}"`
68
+ + `fill="${escapeXml(fill)}" xml:space="preserve"`
68
69
  + `${opacityAttribute(style)}>${escapeXml(text)}</text>`);
69
70
  }
70
71
  drawLine(x1, y1, x2, y2, style) {
@@ -118,9 +119,10 @@ export class SvgPainter {
118
119
  + `${background}${this.body.join("")}</svg>`;
119
120
  }
120
121
  }
121
- /** 使用 SVG 后端绘制一个已经完成布局的文档 */
122
- export function renderLayoutToSvg(result, options = {}) {
123
- const painter = new SvgPainter();
124
- paintLayout(result, painter);
125
- return painter.toSvg(result.bounds, options);
122
+ /** 使用 SVG 后端把一个布局结果绘制成独立页面 */
123
+ export function renderLayoutPagesToSvg(result, options = {}) {
124
+ const bounds = layoutPageBounds(result);
125
+ const painters = bounds.map(() => new SvgPainter());
126
+ paintLayoutPages(result, painters);
127
+ return painters.map((painter, index) => painter.toSvg(bounds[index], options));
126
128
  }
@@ -1,6 +1,28 @@
1
1
  import type { GlyphMetrics, TextMeasurer, TextStyle } from "./types.js";
2
+ /** 未指定字体族时,普通文本使用的字体栈 */
3
+ export declare const DEFAULT_TEXT_FONT = "sans-serif";
4
+ /** 简谱数字及同类谱面数字使用的字体栈 */
5
+ export declare const JIANPU_NUMBER_FONT = "'Cascadia Mono', Consolas, 'Liberation Mono', 'Noto Sans Mono', monospace";
6
+ /** Canvas 的 font 简写;测量与绘制必须用同一份,否则量到的不是将要画出的字形 */
7
+ export declare function canvasFont(style: TextStyle): string;
2
8
  /** 默认文本测量保持确定性,不依赖浏览器和操作系统字体。 */
3
9
  export declare class DefaultTextMeasurer implements TextMeasurer {
4
10
  measureText(text: string, style: TextStyle): GlyphMetrics;
5
11
  }
6
12
  export declare const defaultTextMeasurer: DefaultTextMeasurer;
13
+ /**
14
+ * 用宿主的 Canvas 字体度量文本,使排版盒与实际绘制的字形一致。
15
+ *
16
+ * 只有宽度取真实值:h/baseline 保持 em 盒约定,换成真实字体盒会让行距和分页依赖平台字体。
17
+ */
18
+ export declare class CanvasTextMeasurer implements TextMeasurer {
19
+ private readonly context;
20
+ private readonly widths;
21
+ constructor(context: CanvasRenderingContext2D);
22
+ /**
23
+ * 字体名称不变但实际资源变化时调用,例如 Web 字体加载完成后,旧缓存仍是回退字体的宽度。
24
+ * 清理后宿主需重新编译、布局和绘制;仅切换字体族、字号或字重无需清理,它们已包含在缓存键中。
25
+ */
26
+ clearCache(): void;
27
+ measureText(text: string, style: TextStyle): GlyphMetrics;
28
+ }
@@ -1,3 +1,11 @@
1
+ /** 未指定字体族时,普通文本使用的字体栈 */
2
+ export const DEFAULT_TEXT_FONT = "sans-serif";
3
+ /** 简谱数字及同类谱面数字使用的字体栈 */
4
+ export const JIANPU_NUMBER_FONT = "'Cascadia Mono', Consolas, 'Liberation Mono', 'Noto Sans Mono', monospace";
5
+ /** Canvas 的 font 简写;测量与绘制必须用同一份,否则量到的不是将要画出的字形 */
6
+ export function canvasFont(style) {
7
+ return `${style.fontWeight ?? "normal"} ${style.fontSize}px ${style.fontFamily ?? DEFAULT_TEXT_FONT}`;
8
+ }
1
9
  /** 默认文本测量保持确定性,不依赖浏览器和操作系统字体。 */
2
10
  export class DefaultTextMeasurer {
3
11
  measureText(text, style) {
@@ -15,3 +23,37 @@ export class DefaultTextMeasurer {
15
23
  }
16
24
  }
17
25
  export const defaultTextMeasurer = new DefaultTextMeasurer();
26
+ /**
27
+ * 用宿主的 Canvas 字体度量文本,使排版盒与实际绘制的字形一致。
28
+ *
29
+ * 只有宽度取真实值:h/baseline 保持 em 盒约定,换成真实字体盒会让行距和分页依赖平台字体。
30
+ */
31
+ export class CanvasTextMeasurer {
32
+ context;
33
+ widths = new Map();
34
+ constructor(context) {
35
+ this.context = context;
36
+ }
37
+ /**
38
+ * 字体名称不变但实际资源变化时调用,例如 Web 字体加载完成后,旧缓存仍是回退字体的宽度。
39
+ * 清理后宿主需重新编译、布局和绘制;仅切换字体族、字号或字重无需清理,它们已包含在缓存键中。
40
+ */
41
+ clearCache() {
42
+ this.widths.clear();
43
+ }
44
+ measureText(text, style) {
45
+ const font = canvasFont(style);
46
+ const key = `${font}\u0000${text}`;
47
+ let width = this.widths.get(key);
48
+ if (width === undefined) {
49
+ this.context.font = font;
50
+ width = this.context.measureText(text).width;
51
+ this.widths.set(key, width);
52
+ }
53
+ return {
54
+ w: Math.max(width, style.fontSize * 0.25),
55
+ h: style.fontSize,
56
+ baseline: style.fontSize * 0.8,
57
+ };
58
+ }
59
+ }
@@ -2,7 +2,7 @@
2
2
  * 字形的排版度量
3
3
  *
4
4
  * 这里的坐标都位于字形自己的局部坐标系中
5
- * 不依赖 SVG text 或 Canvas 字体测量结果
5
+ * 数值来源由具体的 TextMeasurer 决定
6
6
  */
7
7
  export interface GlyphMetrics {
8
8
  w: number;