jpfun 0.2.0 → 0.3.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 (112) hide show
  1. package/README.md +69 -11
  2. package/dist/diagnostic.js +5 -2
  3. package/dist/fraction.d.ts +24 -0
  4. package/dist/fraction.js +132 -0
  5. package/dist/functions/ASTtypes.d.ts +24 -7
  6. package/dist/functions/ASTtypes.js +35 -16
  7. package/dist/functions/adjust/index.d.ts +2 -0
  8. package/dist/functions/adjust/index.js +193 -0
  9. package/dist/functions/bar/index.d.ts +8 -0
  10. package/dist/functions/bar/index.js +39 -10
  11. package/dist/functions/beam/auto.js +32 -15
  12. package/dist/functions/beam/index.js +10 -6
  13. package/dist/functions/beam/layout.d.ts +3 -2
  14. package/dist/functions/beam/layout.js +42 -64
  15. package/dist/functions/box/index.js +35 -34
  16. package/dist/functions/br/index.js +9 -7
  17. package/dist/functions/dash/index.js +33 -1
  18. package/dist/functions/default.js +14 -7
  19. package/dist/functions/div/index.d.ts +16 -0
  20. package/dist/functions/div/index.js +45 -17
  21. package/dist/functions/dot/index.js +11 -3
  22. package/dist/functions/grace/index.d.ts +8 -11
  23. package/dist/functions/grace/index.js +82 -76
  24. package/dist/functions/head/index.d.ts +2 -0
  25. package/dist/functions/head/index.js +492 -0
  26. package/dist/functions/key/index.js +97 -3
  27. package/dist/functions/meter/index.d.ts +2 -0
  28. package/dist/functions/meter/index.js +154 -0
  29. package/dist/functions/note/accidentals.d.ts +24 -3
  30. package/dist/functions/note/accidentals.js +31 -1
  31. package/dist/functions/note/index.js +45 -65
  32. package/dist/functions/page/index.d.ts +9 -2
  33. package/dist/functions/page/index.js +50 -4
  34. package/dist/functions/set/index.js +37 -29
  35. package/dist/functions/stack/index.js +26 -22
  36. package/dist/functions/symbol/index.d.ts +21 -0
  37. package/dist/functions/symbol/index.js +94 -0
  38. package/dist/functions/symbol/ornament.d.ts +15 -0
  39. package/dist/functions/symbol/ornament.js +73 -0
  40. package/dist/functions/symbol/shape.d.ts +22 -0
  41. package/dist/functions/symbol/shape.js +48 -0
  42. package/dist/functions/symbol/symbols/accent.d.ts +2 -0
  43. package/dist/functions/symbol/symbols/accent.js +24 -0
  44. package/dist/functions/symbol/symbols/f.d.ts +2 -0
  45. package/dist/functions/symbol/symbols/f.js +55 -0
  46. package/dist/functions/symbol/symbols/fermata.d.ts +2 -0
  47. package/dist/functions/symbol/symbols/fermata.js +24 -0
  48. package/dist/functions/symbol/symbols/mordent.d.ts +2 -0
  49. package/dist/functions/symbol/symbols/mordent.js +43 -0
  50. package/dist/functions/symbol/symbols/p.d.ts +2 -0
  51. package/dist/functions/symbol/symbols/p.js +61 -0
  52. package/dist/functions/symbol/symbols/tr.d.ts +2 -0
  53. package/dist/functions/symbol/symbols/tr.js +75 -0
  54. package/dist/functions/tempo/glyph.d.ts +12 -0
  55. package/dist/functions/tempo/glyph.js +30 -0
  56. package/dist/functions/tempo/index.js +53 -2
  57. package/dist/functions/text/index.js +76 -24
  58. package/dist/functions/tie/index.js +102 -127
  59. package/dist/functions/tuplet/index.d.ts +2 -0
  60. package/dist/functions/tuplet/index.js +211 -0
  61. package/dist/functions/up/index.d.ts +1 -0
  62. package/dist/functions/up/index.js +245 -171
  63. package/dist/functions/voice/index.js +86 -68
  64. package/dist/functions/volta/index.d.ts +2 -0
  65. package/dist/functions/volta/index.js +227 -0
  66. package/dist/index.d.ts +4 -0
  67. package/dist/index.js +4 -0
  68. package/dist/jpfun.min.js +143 -0
  69. package/dist/layout/engine.d.ts +4 -11
  70. package/dist/layout/engine.js +65 -59
  71. package/dist/layout/model.d.ts +8 -1
  72. package/dist/layout/model.js +16 -6
  73. package/dist/layout/path.d.ts +19 -0
  74. package/dist/layout/path.js +101 -0
  75. package/dist/layout/types.d.ts +51 -18
  76. package/dist/layout/types.js +3 -1
  77. package/dist/lowering/loweringContext.d.ts +18 -20
  78. package/dist/lowering/loweringContext.js +132 -94
  79. package/dist/lowering/track.d.ts +1 -1
  80. package/dist/lowering/track.js +1 -1
  81. package/dist/lowering/types.d.ts +49 -12
  82. package/dist/lowering/types.js +9 -3
  83. package/dist/parser/parse-utils/call-utils.d.ts +0 -2
  84. package/dist/parser/parse-utils/call-utils.js +0 -6
  85. package/dist/parser/parse-utils/note-utils.d.ts +8 -0
  86. package/dist/parser/parse-utils/note-utils.js +35 -13
  87. package/dist/parser/parse-utils/string-utils.d.ts +8 -0
  88. package/dist/parser/parse-utils/string-utils.js +20 -0
  89. package/dist/parser/parserContext.d.ts +8 -5
  90. package/dist/parser/parserContext.js +38 -33
  91. package/dist/parser/preprocess.js +17 -11
  92. package/dist/playback/compile.d.ts +18 -0
  93. package/dist/playback/compile.js +401 -0
  94. package/dist/playback/event.d.ts +91 -0
  95. package/dist/playback/event.js +87 -0
  96. package/dist/playback/time.d.ts +14 -0
  97. package/dist/playback/time.js +81 -0
  98. package/dist/playback/types.d.ts +128 -0
  99. package/dist/playback/types.js +3 -0
  100. package/dist/render/canvas.d.ts +4 -4
  101. package/dist/render/canvas.js +20 -5
  102. package/dist/render/index.d.ts +1 -0
  103. package/dist/render/index.js +1 -0
  104. package/dist/render/paint.d.ts +8 -0
  105. package/dist/render/paint.js +101 -0
  106. package/dist/render/svg.d.ts +3 -3
  107. package/dist/render/svg.js +10 -8
  108. package/dist/render/text.d.ts +17 -0
  109. package/dist/render/text.js +35 -0
  110. package/dist/render/types.d.ts +1 -1
  111. package/grammar.md +93 -10
  112. package/package.json +10 -6
@@ -0,0 +1,128 @@
1
+ import type { Diagnostic } from "../diagnostic.js";
2
+ import type { Fraction } from "../fraction.js";
3
+ import type { LoweringAttachment, TemporalNodeBase } from "../lowering/types.js";
4
+ import type { Track } from "../lowering/track.js";
5
+ import type { PlaybackDraftEvent, PlaybackEvent, PlaybackEventInput, PlaybackNoteId } from "./event.js";
6
+ export type * from "./event.js";
7
+ /**
8
+ * 播放列游标
9
+ *
10
+ * 控制流只能通过它查询已经发生的事实,因此自身不保存状态,同一份 lowering 结果重复编译结果一致
11
+ */
12
+ export interface PlaybackCursor {
13
+ /** 正在决定去留的列 */
14
+ readonly column: number;
15
+ /** 该列到目前为止被到达的次数,含本次;被跳过的到达也算 */
16
+ visits(column: number): number;
17
+ /** 从 from 出发沿 direction 找最近一个带该标记的列,不含 from 自身 */
18
+ seek(mark: string, from: number, direction: -1 | 1): number | undefined;
19
+ }
20
+ /**
21
+ * 对游标的一次干预
22
+ * - jump: 当前列不演奏,直接跳到目标列
23
+ * - stop: 在当前列之前结束
24
+ */
25
+ export type PlaybackFlowAction = {
26
+ kind: "jump";
27
+ column: number;
28
+ } | {
29
+ kind: "stop";
30
+ };
31
+ /** 把事件映射到它在播放时间流中的列;折叠成员会映射到宿主 */
32
+ export type PlaybackColumnOf = (node: TemporalNodeBase) => number | undefined;
33
+ /** 控制流在编译开始时生成的执行声明;range 是运行的升序闭区间,缺省表示每列都运行 */
34
+ export interface PlaybackFlowHook {
35
+ readonly range?: readonly [number, number];
36
+ run(cursor: PlaybackCursor): PlaybackFlowAction | undefined;
37
+ }
38
+ /** 参与播放顺序决策的能力 */
39
+ export interface PlaybackFlow {
40
+ /** 根据本轮列索引声明生效范围和运行逻辑 */
41
+ playbackFlow(columnOf: PlaybackColumnOf): PlaybackFlowHook | undefined;
42
+ }
43
+ /**
44
+ * 记谱位置固化到 Temporal 上的基础状态
45
+ *
46
+ * 将来支持音色时,在这里增加具名的 `program?: number`,并同步扩展系统状态和最终 ProgramChange 事件
47
+ * 不要用任意键索引,否则具体 MIDI 状态会失去类型约束
48
+ */
49
+ export interface PlaybackState {
50
+ readonly bpm?: number;
51
+ readonly velocity?: number;
52
+ }
53
+ /** 按线性化时间扫描的可变系统状态 */
54
+ export interface PlaybackSystemState {
55
+ bpm: number;
56
+ bpmScale: Fraction;
57
+ }
58
+ export interface PlaybackSystemSnapshot {
59
+ readonly bpm: number;
60
+ readonly bpmScale: Fraction;
61
+ readonly effectiveBpm: number;
62
+ }
63
+ /** 在指定演奏时刻修改系统状态;所有同刻控制执行完后,core 据最终状态生成 Tempo 等事件 */
64
+ export type PlaybackControl = (state: PlaybackSystemState) => void;
65
+ /** 当前节点的局部变换完成后,检查或改写此前已发布的事件,例如 dash 延后前音的 NoteOff */
66
+ export type PlaybackHook = (context: PlaybackHookContext) => void;
67
+ /** 修饰同一 play frame 中排在声明者之后的一次具体访问,例如 accent、tr 和 mordent */
68
+ export type PlaybackTransform = (context: PlaybackHookContext, events: PlaybackDraftEvent[]) => PlaybackDraftEvent[] | void;
69
+ export interface PlaybackHookContext {
70
+ /** 完整 Tempo 表,以及当前位置此前已经发布的音符事件;relation 阶段包含完整计划 */
71
+ readonly events: PlaybackDraftEvent[];
72
+ readonly diagnostics: Diagnostic[];
73
+ nextNoteId(): PlaybackNoteId;
74
+ stateAt(time: Fraction): PlaybackSystemSnapshot;
75
+ }
76
+ /** 具体 Temporal 只发布系统原语、系统控制和延迟事件变换 */
77
+ export interface PlaybackEmitter {
78
+ /** 当前访问在演奏 QN 轴上的起点 */
79
+ readonly start: Fraction;
80
+ /**
81
+ * 当前访问在演奏 QN 轴上的终点
82
+ * 和 t+T 不一定相等,例如 up 中的折叠节点
83
+ */
84
+ readonly end: Fraction;
85
+ /** 当前节点所属的原始 Track;最终输出时转换为 PlaybackPlan.tracks 的索引 */
86
+ readonly track: Track;
87
+ /** 为一对新的 NoteOn/NoteOff 分配共享身份 */
88
+ nextNoteId(): PlaybackNoteId;
89
+ /** 发布一个系统定义的原始播放事件;core 自动补来源、轨道和稳定次序 */
90
+ emit(event: PlaybackEventInput): void;
91
+ /** 在指定时刻登记系统状态修改;同刻控制全部执行后才生成最终状态事件 */
92
+ control(at: Fraction, apply: PlaybackControl): void;
93
+ /** 修饰同一 play frame 中排在当前节点之后的音符访问 */
94
+ affectFollowing(transform: PlaybackTransform): void;
95
+ /** 当前节点的局部变换完成后,在当前位置处理此前已发布的事件 */
96
+ defer(hook: PlaybackHook): void;
97
+ /** 递归发布折叠的子节点;未指定区间时继承当前 start 和 duration */
98
+ play(child: TemporalNodeBase, start?: Fraction, duration?: Fraction): void;
99
+ }
100
+ /** 所有节点 hook 完成后,attachment 可以处理跨节点关系 */
101
+ export interface PlaybackRelation extends LoweringAttachment {
102
+ applyPlayback(context: PlaybackHookContext): void;
103
+ }
104
+ export declare function isPlaybackRelation(attachment: LoweringAttachment): attachment is PlaybackRelation;
105
+ /** 控制流展开后的演奏位置到记谱位置映射 */
106
+ export interface PlaybackScorePoint {
107
+ /** 控制流展开后的连续演奏位置;反复继续前进,跳转处也不回退,单位 QN */
108
+ readonly performance: Fraction;
109
+ /** 与该演奏位置对应的原始谱面位置;反复时会回退,跳过房子时会前跳,单位 QN */
110
+ readonly score: Fraction;
111
+ }
112
+ /**
113
+ * 完整且可查询的演奏计划
114
+ *
115
+ * 刻意不做成 generator:随机定位、总时长和 MIDI 导出都需要完整计划,
116
+ * 而 tie 这类关系对象要同时改写相距很远的两个端点。无限反复属于播放器的循环控制,
117
+ * 应表示为有限计划加循环点,不是无限序列。
118
+ */
119
+ export interface PlaybackPlan {
120
+ /** 按演奏时间升序;同刻依次为 tempo、time-signature、note-off、note-on */
121
+ readonly events: readonly PlaybackEvent[];
122
+ readonly scoreMap: readonly PlaybackScorePoint[];
123
+ /** 最终至少含一个 NoteOn 的原始 Track;事件 track 是此数组的索引 */
124
+ readonly tracks: readonly Track[];
125
+ readonly performanceDuration: Fraction;
126
+ readonly durationSeconds: number;
127
+ readonly diagnostics: readonly Diagnostic[];
128
+ }
@@ -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,23 @@
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
+ measureText(text: string, style: TextStyle): GlyphMetrics;
23
+ }
@@ -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,30 @@ 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
+ measureText(text, style) {
38
+ const font = canvasFont(style);
39
+ const key = `${font}\u0000${text}`;
40
+ let width = this.widths.get(key);
41
+ if (width === undefined) {
42
+ this.context.font = font;
43
+ width = this.context.measureText(text).width;
44
+ this.widths.set(key, width);
45
+ }
46
+ return {
47
+ w: Math.max(width, style.fontSize * 0.25),
48
+ h: style.fontSize,
49
+ baseline: style.fontSize * 0.8,
50
+ };
51
+ }
52
+ }
@@ -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;
package/grammar.md CHANGED
@@ -5,6 +5,8 @@
5
5
 
6
6
  ## 2. 基本类型
7
7
  - 字符串,用引号包裹,只能用英文双引号`"`。如果不会引起歧义,可以不加引号。(单引号用于其他语法糖)
8
+ - 引号必须配对才算字符串,找不到闭引号时它只是普通字符;可跨行
9
+ - `\` 后的任意字符取字面量,如 `"说\"你好\""`;没有 `\n` 这类语义转义
8
10
  - bool值,只能为 `true` / `false`,
9
11
  - 数字
10
12
  - 内容,用 `{}` 包裹。如果不会引起歧义,可以不加括号
@@ -14,6 +16,8 @@
14
16
  “内容”的基本元素:
15
17
  - 函数调用:`@func(...)`,函数名后必须立即接`(`,参数使用逗号分隔,参数可以是(2)中提到的四个类型
16
18
  - 标签:`XXX@label`,不按要求的函数调用都会被理解为label,用于关系型函数的参数
19
+ - 绑定到它前面最近的可标注对象;`@div` `@box` `@text` 这类对标签透明,会被跳过继续向前找
20
+ - 目标已经有标签,或前面是不可标注的复合体(如宙主无可标注内容的 `@grace`)时,标签失效并报警告
17
21
 
18
22
  > 歧义:比如字符串为 `"123,456"`,在函数调用时,逗号是参数的分隔符,如果没有引号,则会认为传递了两个数字,引发歧义。因此必须用引号分割
19
23
 
@@ -21,15 +25,21 @@
21
25
 
22
26
  ## 3. 主要函数
23
27
  - `@1(tonality)` 修改调性 如 `1=C` 作用域为当前时间之后
28
+ - 规范写法:`[音名][最多一个 #/b][绝对八度]`,音名可用 `A`~`G` 或 `1`~`7`,八度可省(默认 4)
29
+ - 不规范但读得懂的写法会**按实际音高归一化**,并报 `W_KEY_TONALITY` 说明切换到了什么:`C##`→`D4`、`Cbb`→`Bb3`、`B#4`→`C5`、`Cn`→`C4`、小写 `f#`→`F#4`;落在黑键上时跟随原来的升降方向拼写
30
+ - 彻底读不懂时(`X`、`H4`)退回 `C4`,同样报 `W_KEY_TONALITY`
31
+ - `strict` 为真时,以上两种情况都抛 `E_KEY_TONALITY`
24
32
  - `@tempo(number)` 修改bpm 作用域为当前时间之后
25
-
33
+ - `@meter(num, den, size=0.7em)` 设置拍号 `num/den`,以分数形式显示
34
+ - 第一条小节线前允许不满拍,但不能超拍;之后由小节线、拍号变更或文档结尾关闭并校验完整时长
26
35
  - `@set(key=value, ...)` 修改函数的缺省值,作用域为当前 `{}`
27
- 几个特殊变量:
36
+ - 写法 `函数名.参数名=值`,按该参数声明的类型解析;函数名可写别名
37
+ - 找不到对应的函数或参数会报警并忽略,不会静默无效
38
+ 几个系统变量(不属于任何函数,直接写名字):
28
39
  - `fontsize`: length类型,是所有`em`的基准
29
40
  - `strict`: bool类型,开启后如果函数未定义不再忽略,一些宽容的语法糖也将被禁止
30
- - `autobeam`: bool类型,默认 `true`;设为 `false` 后,不同 `div` 函数之间不会自动连接
31
41
 
32
- - `@page(width, height, top, bottom, left, right, gap)` 设置文档页面
42
+ - `@page(width, height, top, bottom, left, right, gap, numbering)` 设置文档页面
33
43
  - 只能在文档顶层声明一次;嵌套声明或后续重复声明会产生诊断并被忽略
34
44
  - 所有参数都是长度,parse 时按当时的 `em` 固化为 px
35
45
  - 默认:`width=794px`、`height=0px`(无限高)、上下边距 `48px`、左右边距 `40px`、`gap=1em`
@@ -37,6 +47,24 @@
37
47
  - 有限高度下,如果一行连同上下边距都放不下,layout 直接报错
38
48
  - 一页放不下下一行时从下一页开始;已封口页面的行间距会平分剩余纵向空间,末页保持最小 `gap`
39
49
 
50
+ - `@head(left={}, center={}, right={})` 排版曲谱头
51
+ - 可在内容作用域中嵌套,也可与前后内容共享逻辑谱面行;需要换行时显式写 `@br()`
52
+ - 三槽第一层节点各占一行:`left={A B}` 是两行,`left={{A B}}` 是同行
53
+ - 内部内容必须全部为零时长;普通函数、stack/voices 和 attachment 仍走全局 Track、列与关系布局
54
+ - left/right 整体底部对齐;较高侧的顶部贴住 center 第一行的下侧
55
+ - left 每行从左向右、right 每行从右向左紧凑排列顶层单元,单元间隔为 `0.25em`;复合内容整体移动
56
+ - 行声明语法糖:
57
+ ```
58
+ H.title: 小星星
59
+ H.subtitle: 经典儿歌
60
+ H.author: 佚名 作词
61
+ H.author: 莫扎特 作曲
62
+ H.signature: 1=C 4/4
63
+ H.tempo: 94
64
+ ```
65
+ - 连续声明合成一个 head,空行或普通内容结束组合;一次声明固定为一行
66
+ - `H.left/center/right:` 接受任意零时长 DSL 内容;裸文本自动转成 `@text`
67
+
40
68
  - `@stack(...)` 临时伴奏/临时多声部:第一个成员留在宿主轨,其余成员按书写顺序依次向上叠放;与 `^` 的区别见下面的对照表
41
69
  - `@voices(...)` 多声部块:所有成员都有独立轨道,整块在宿主基线上局部居中(首末两条基线的中点对齐宿主轴),两个以上成员时在声部名与音符之间画多声部括线;里面只能是 `@voice`,一般用语法糖创建
42
70
  - `@voice({}, 音轨名, 名称1={}, 名称2={}, ...)`
@@ -50,9 +78,21 @@
50
78
  起始条件2: `L(xxx):`。终止条件:该层级的换行符或结束。如果上一个不是voice就报错
51
79
 
52
80
  - `@up(...)` 和弦:把同一时间位置的几个音合成一个符号。语法糖 `^`,自下而上写
53
- - 时值、对齐基准和减时线都以最下面的成员为准,连音线从最上面的成员起跳
81
+ - 时值、对齐基准和减时线都以最下面的成员为准
82
+ - up 中至少有一个可标注成员时,up 整体才能被标注
83
+ - `{1@x}^{@1(C4)}` 中 `x` 标注成员 `1`,`@tie(x,y)` 从 `1` 起跳
84
+ - `{1^@1(C4)}@x` 中 `x` 标注整个 up,`@tie(x,y)` 从最上面的成员起跳
54
85
  - 每个参数必须恰好产生一个可见对象,放不下整段旋律
55
86
 
87
+ - `@down(...)` 向下堆叠:第一个参数是宿主,其余依次叠在它下方。语法糖 `_`
88
+ - 常用于力度记号等写在音符下面的标记:`1 _ $p`
89
+ - 与 `^` 共用同一个容器,混写时**全部绑到同一个宿主**,和 LaTeX 的上下标一样,不需要括号分组
90
+ - `1^2_3^4_5` 等价于 `@down(@up(1, 2, 4), 3, 5)`:`1` 是宿主,`2 4` 在上,`3 5` 在下
91
+ - 宿主留在轨道基线上,两侧成员各自向外撑开行高;横向宽度仍只取宿主
92
+ - 播放事件按**先附属成员、最后宿主**发布,所以修饰类记号的局部变换一律作用到宿主,与它画在上方还是下方无关
93
+ - 反过来把记号写成宿主(`$accent ^ 1`)就够不到其它成员,这不是 bug 而是同一条规则
94
+ - 力度这类**持续状态**记号不受此限,写在宿主上方或下方都生效(`1 ^ $p`、`1 _ $p`);但把记号自己当宿主就轮不到其它成员了(`$p ^ 1` 里宿主本音不变,之后的音才变弱),与 `@key` 同一条规则
95
+
56
96
  ### `^` 和 `&` 的区别
57
97
  两者都是「往上叠」,但机制不同,只有在「单音符、等时长」这一种情形下看起来一样:
58
98
 
@@ -72,6 +112,15 @@
72
112
  - 倚音**默认就是八分音符**(自带一条减时线),再写一个 `/` 变成十六分音符
73
113
  - 倚音不进入时间流:整体时值等于宿主时值,小节线、拍位、自动连梁都不受影响
74
114
  - 播放时倚音从宿主借时值:`比例 = 倚音字面总时值 / 四分音符`,基准取宿主经 div 与 dot 之后的实际时值,上限 0.75
115
+ - 写在宿主或倚音成员上的标签保留在该成员:`@grace({1},{2@x})` 中 `x` 连接倚音 `2`
116
+ - 写在 grace 调用后的标签穿透到宿主的可标注节点:`@grace({1},{2})@x` 中 `x` 连接宿主 `1`
117
+
118
+ - `@tuplet(content, normal)` 多连音
119
+ - 从内容自动推导最短正时值 `shortest` 和原总时值 `writtenTotal`
120
+ - 连音数字 `actual = writtenTotal / shortest`,必须是大于等于 2 的整数
121
+ - 缩放后总时值为 `shortest * normal`,即所有成员的时间统一乘以 `normal / actual`
122
+ - `@tuplet({1/23}, 4)` 中原时值为 `1/2 + 1 + 1 = 5/2 QN`,共 5 个最短单位;缩放后总时值为 `2 QN`,上方显示数字 5
123
+ - 内容必须位于同一音轨和同一谱面行;允许嵌套,但嵌套括线目前可能重叠
75
124
 
76
125
  - `@note(...)` / `@n(...)`
77
126
  - 音名:`A B C D E F G`
@@ -79,36 +128,69 @@
79
128
  - 隐形占位:`8`
80
129
  - 只打拍不发音:`9`,显示为 `X`(不显示升降号和八度点)
81
130
  - 升降符:`#` `b` `n`(可重复,如 `bb`、`###`)
82
- - `@div(...)` / `@/(...)`
131
+ - `@div(内容, n=1, autobeam=true)` / `@/(...)`
83
132
  - 语法糖:直接在后面加`/`,可多个
84
133
  - 同一个 `div` 内容中的减时事件始终连接,与 `autobeam` 无关
85
134
  - 默认自动连接同轨、连续、同一逻辑行且位于同一四分音符拍内的独立 `div`,例如 `1/ 2// 3/`
86
135
  - 自动连接在拍边界、小节线、显式换行、时间间隙、同轨可见非候选元素、普通长事件、开关变化或手工 `@beam` 处结束
87
- - `@set(autobeam=false)` 关闭不同 `div` 之间的自动连接;局部减时线仍各自绘制
136
+ - `autobeam=false` 关闭**该 div** 与周围 div 的自动连接,内部减时线仍然连接
88
137
  - `@dot(...)` / `@.(...)`
89
138
  - 语法糖:直接在后面加`.`,可多个
90
139
  - `@dash()` / `@-()`
91
140
  - 语法糖:直接在后面加`-`,可多个
92
- - `@bar(...)` 创建一个小节线 时间线上强制对齐
141
+ - `@bar(...)` 创建一个小节线,时间线上强制对齐
142
+ - `|:` 标记反复起点,`:|` 回到此前最近的反复起点;没有起点时回到曲首
143
+ - 每条 `:|` 只回跳一次,连续写多条即可增加遍数
144
+ - 重叠反复按最近起点解释:`|: 1 |: 2 :| 3 :|` 播放为 `1 2 2 3 2 3`
145
+ - `@text(内容, size=1em, lineheight=1.25, align=left)` 文本标记
146
+ - 语法糖:`"渐强"` 等价于 `@text(渐强)`;引号内的逗号和右括号不再是参数分隔符
147
+ - 括号内可以直接换行,`lineheight` 是相对自身字号的倍数
148
+ - `align=left`(默认)各行左对齐,锚点在第一行首字符中心,单字标记因此能像音符一样对准宿主
149
+ - `align=center` 各行居中,锚点取整块中心,适合多行标题
150
+ - `align=right` 各行右对齐,锚点取第一行末字符中心,适合谱头作者栏
151
+ - 受预处理规则影响:行尾奇数个 `\` 会把换行当续行吃掉,不加引号时第二行的 `%` 会开启行注释
152
+ - `@symbol(name, size=0.5em)` 乐谱符号容器
153
+ - 语法糖:`$name`,名称必须以 ASCII 字母开头,后续可含字母、数字、`_` 和 `-`
154
+ - 名称按小写查询内置符号表;未知名称抛出 `E_UNKNOWN_SYMBOL`
155
+ - 每个符号是 `src/functions/symbol/symbols/` 下的一个对象字面量:固定图形加可选播放规则,符号之间互不依赖
156
+ - 符号高度 = `size × weight`,`weight` 由符号自己声明,用来修正宽扁字形的视觉重量
157
+ - 内置:`$tr`(颤音)、`$f`(强)、`$p`(弱)、`$fermata`(延长记号)、`$mordent`(波音)、`$accent`(重音)
158
+ - 持续类记号按**记谱位置**生效,从它所在位置一直到下一个同类记号:`$p=48`、`$f=96`;反复回跳后用的是目标位置之前的那个值
159
+ - 修饰类记号只作用于同一 `up` 中排在符号下方的成员,独立写出时只绘制:重音 velocity `+20`、`$tr` 在本音与调内上方二度间交替、`$mordent` 为本音—上方音—本音
160
+ - 延长记号把目标音覆盖区间的速度减半;NoteOn/NoteOff 的 QN 位置不变,实际秒数翻倍
161
+ - 装饰音的交替密度按发声时的速度决定(落在 8~64 Hz),默认速度下恰好是 `1/8` 四分音符
162
+ - `@volta(from, to, pass, ...)` 反复房子:一段只在指定遍数演奏的区间
163
+ - `from` `to` 是区间首末音符的标签,两者可以是同一个;写顺序不限,按时间列取 min/max
164
+ - 遍数必填(房子上的数字本来就是谱面的一部分),必须是正整数,否则抛 `E_VOLTA_INVALID_PASS`。可以再跟任意多个遍数表示**几遍共用一个房子**,如 `@volta(a, b, 1, 2)`;重复和乱序都会被规整,标签按升序写成 `1.2.`
165
+ - 不指向任何具体的反复线,属于哪个反复段完全由区间位置决定,每段的遍数各自从第一遍数起
166
+ - 同一列被两个房子标成互斥的遍数时它一遍都不会演,报 `W_PLAYBACK_COLUMN_NEVER_PLAYED`
167
+ - 按记谱惯例,括线两端会贴到相邻小节线的锚点上(相邻列不是小节线时才按内容取边)
93
168
  - `@br(offset=1)` 在后续事件前偏移指定行数
94
169
  - `offset` 是第一个位置参数,因此通常写作 `@br(2)`
95
170
  - 默认值为 1;按非负整数固化,小数向下取整,负数视为 0
96
171
  - `@br(0)` 不换行,`@br(2)` 会保留一个空行
97
172
  - 每次调用独立生效,多个 br 暂不合并
173
+ - `@adjust(内容, dx=0px, dy=0px, dw=0px, dh=0px)` 手工微调排版盒
174
+ - `dx`/`dy` 在排版完成后平移,邻居不会让开,因此可以故意重叠;关系函数读取的是平移后的盒子,连音线等会跟着走
175
+ - `dw`/`dh` 在排版之前增减占位,邻居会跟着让开或收拢,最终宽高不会小于 0;`dw` 按原左右占位比例分配,`dh` 只调整下方
176
+ - 括住多个对象时逐个施加同一增量;括住的若是关系对象且其中没有对象,平移的就是这条关系对象
177
+ - `@up`、`@grace` 的内部成员可以微调,尺寸增量按复合体原有盒模型反馈给外层;`@up` 的横向宽度仍只取最下面的成员
98
178
 
99
179
  注意:简谱中永远先减时线作用,再加上附点,无论函数作用先后
100
180
 
101
181
  ### 关系型
102
182
  参数类型为标签,如果不传,则默认取最后两个注册的节点(比如note)
103
- - `@beam(...)`:手工连接传参的减时线;不受 `autobeam` 开关影响。参数必须按时间顺序对应同轨、同谱面行中的相邻可见元素;over 只有第一参数内的元素可参与外层 beam
104
- - `@tie(...)`:按参数顺序连接同一轨道中的元素;跨轨端点报错。近距离使用普通弧线,远距离或跨行时使用带水平段的连音线
183
+ - `@beam(...)`:手工连接传参的减时线;不受 `div.autobeam` 开关影响。参数必须按时间顺序对应同轨、同谱面行中的相邻可见元素;over 只有第一参数内的元素可参与外层 beam
184
+ - `@tie(...)`:按参数顺序连接元素;跨轨端点仍绘制连音线,但播放时只有同轨、同音且连续的音符才合并。近距离使用普通弧线,远距离或跨行时使用带水平段的连音线
105
185
 
106
186
  语法糖实例:
187
+ - `"渐强"` -> `@text(渐强)`
107
188
  - `@bar(C1 C3)` -> `@bar({ C1 C3 })`
108
189
  - `{...}//` -> `@div({ ... }, 2)`
109
190
  - `{...}.` -> `@dot({ ... }, 1)`
110
191
  - `-` -> `@dash()`
111
192
  - `--` -> `@dash() @dash()`
193
+ - `$fermata` -> `@symbol(fermata)`(需要 registry 中已有 `fermata` 定义)
112
194
  - `C1 C3# |` -> `@note(C,1) @note(C,3,#) @bar()`
113
195
 
114
196
 
@@ -125,6 +207,7 @@
125
207
  以下规则由 `src/parser/preprocess.ts` 在词法预处理阶段执行。所有替换都保持等长(用空格替换),以保证 offset 稳定。
126
208
 
127
209
  - 注释规则:`%` 在非字符串上下文下表示行注释起点,作用到行尾(不含换行)。
210
+ - 字符串上下文要求双引号**配对**(`\` 转义的引号不算闭合);找不到闭引号时该 `"` 只是普通字符,不会影响后文的注释识别。字符串可以跨行。
128
211
  - `\%` 不会转义注释符:反斜杠不会阻止 `%` 开启注释。
129
212
  - 换行识别:支持 `\n`、`\r\n`,兼容 `\r`;`lineStarts` 以逻辑换行为单位记录下一行起点。
130
213
  - 行尾连续反斜杠规则: