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
@@ -8,7 +8,7 @@ import { isPlaybackRelation } from "./types.js";
8
8
  * 按控制流声明展开出实际访问的列顺序
9
9
  *
10
10
  * 核心只维护游标、到达次数和标记表,跳转规则全部由函数在自己的 `playbackFlow` 里写:
11
- * 反复线找最近的段起点标记,房子按段起点被访问过几次决定本遍演不演。
11
+ * 反复线找最近的段起点标记,房子按本段已回跳过几次决定本遍演不演。
12
12
  * 本阶段只产生列索引;游标计数和标记索引每次编译重新建立,不会回写 lowering。
13
13
  */
14
14
  function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
@@ -228,8 +228,7 @@ export function compilePlayback(lowering, options) {
228
228
  const program = node.playbackState?.program;
229
229
  if (program !== undefined && activePrograms.get(track) !== program) {
230
230
  activePrograms.set(track, program);
231
- events.push({ kind: "program-change", at: start.clone(), order: nextEventOrder++,
232
- origins: lineage, track, program });
231
+ events.push({ kind: "program-change", at: start.clone(), order: nextEventOrder++, track, program });
233
232
  }
234
233
  const bpm = node.playbackState?.bpm;
235
234
  if (bpm !== undefined)
@@ -268,8 +267,7 @@ export function compilePlayback(lowering, options) {
268
267
  spanScales.set(span, scales);
269
268
  span.end.add(duration);
270
269
  },
271
- emit: event => events.push({ ...event, at: event.at.clone(),
272
- order: nextEventOrder++, origins: lineage }),
270
+ emit: event => events.push({ ...event, at: event.at.clone(), order: nextEventOrder++ }),
273
271
  control: (at, apply) => scheduleControl(at, lineage, apply),
274
272
  /** 只登记效果身份和比例,范围等结构与连接确定后再计算 */
275
273
  scaleFollowingBpm(key, numerator, denominator = 1, options) {
@@ -401,12 +399,11 @@ export function compilePlayback(lowering, options) {
401
399
  // 结构与连接全部确定后,只扫描一次状态;后续声音变换统一读取这份最终结果
402
400
  while (changeIndex < changes.length) {
403
401
  const at = changes[changeIndex].at;
404
- const origins = new Set();
402
+ let lastOrigin;
405
403
  // 同刻控制和效果边界全部应用后才生成快照,避免输出由扫描顺序造成的瞬时速度
406
404
  while (changeIndex < changes.length && changes[changeIndex].at.equals(at)) {
407
405
  const change = changes[changeIndex++];
408
- for (const origin of change.origins)
409
- origins.add(origin);
406
+ lastOrigin = change.origins.at(-1) ?? lastOrigin;
410
407
  if (change.kind === "control")
411
408
  change.apply(system);
412
409
  else if (change.kind === "scale") {
@@ -428,7 +425,7 @@ export function compilePlayback(lowering, options) {
428
425
  effectiveBpm: system.bpm * bpmScale.toNumber(),
429
426
  };
430
427
  if (!Number.isFinite(snapshot.effectiveBpm) || snapshot.effectiveBpm <= 0) {
431
- throw new ErrorDiagnostic("E_PLAYBACK_BPM", "系统控制产生了无效速度", [...origins].at(-1)?.node.ast.sourceSpan ?? { start: 0, end: 0 });
428
+ throw new ErrorDiagnostic("E_PLAYBACK_BPM", "系统控制产生了无效速度", lastOrigin?.node.ast.sourceSpan ?? { start: 0, end: 0 });
432
429
  }
433
430
  const previous = statePoints.at(-1)?.state;
434
431
  if (!previous || previous.bpm !== snapshot.bpm || !previous.bpmScale.equals(bpmScale)) {
@@ -441,7 +438,6 @@ export function compilePlayback(lowering, options) {
441
438
  at: at.clone(),
442
439
  bpm: snapshot.effectiveBpm,
443
440
  order: nextEventOrder++,
444
- origins: [...origins],
445
441
  });
446
442
  }
447
443
  }
@@ -465,6 +461,7 @@ export function compilePlayback(lowering, options) {
465
461
  };
466
462
  const canAbsorb = (from, to) => !transforms.has(to)
467
463
  && from.track === to.track && from.midi === to.midi && from.percussion === to.percussion;
464
+ const audible = new Set();
468
465
  const realized = new Map();
469
466
  // 后继无独立变换时直接并入前驱音段,使首段装饰与奏法覆盖连续连音;有新变换时从该处分段并在交界处合并同音
470
467
  for (const note of notes) {
@@ -519,16 +516,18 @@ export function compilePlayback(lowering, options) {
519
516
  ? []
520
517
  : undefined;
521
518
  for (const sound of owned) {
522
- const { start, end, track, midi, velocity, percussion, origins, sourceSpans } = sound;
519
+ const { start, end, track, midi, velocity, percussion, sourceSpans } = sound;
523
520
  const noteId = nextNoteId++;
524
521
  const on = {
525
522
  kind: "note-on", at: start.clone(), noteId, order: nextEventOrder++,
526
523
  track, midi, velocity, percussion,
527
- origins, sourceSpans: [...sourceSpans],
524
+ sourceSpans: [...sourceSpans],
528
525
  };
529
526
  const off = {
530
- kind: "note-off", at: end.clone(), noteId, order: nextEventOrder++, origins,
527
+ kind: "note-off", at: end.clone(), noteId, order: nextEventOrder++,
528
+ track, midi,
531
529
  };
530
+ audible.add(track);
532
531
  events.push(on, off);
533
532
  pairs?.push({ on, off });
534
533
  }
@@ -566,9 +565,9 @@ export function compilePlayback(lowering, options) {
566
565
  on.sourceSpans.push(...next.sourceSpans);
567
566
  }
568
567
  }
569
- // 稳定排序后,由统一出口检查配对、压实轨道编号并剥离编译期字段
568
+ // 稳定排序后,由统一出口压实轨道编号并剥离编译期字段
570
569
  const finalEvents = (removed.size ? events.filter(event => !removed.has(event)) : events).sort(comparePlaybackDraftEvents);
571
- const output = finalizePlaybackEvents(finalEvents, lowering.tracks);
570
+ const output = finalizePlaybackEvents(finalEvents, lowering.tracks, audible);
572
571
  const eventEnd = finalEvents.at(-1)?.at;
573
572
  if (eventEnd && eventEnd.compare(performanceEnd) > 0)
574
573
  performanceEnd.copyFrom(eventEnd);
@@ -46,9 +46,8 @@ export interface PlaybackOrigin {
46
46
  interface PlaybackDraftEventBase {
47
47
  at: Fraction;
48
48
  order: number;
49
- origins: readonly PlaybackOrigin[];
50
49
  }
51
- /** 声音展开后生成的点事件;最终输出前会校验并剥离内部字段 */
50
+ /** 声音展开后生成的点事件;最终输出前压实轨道编号并剥离编译期字段 */
52
51
  export interface PlaybackDraftNoteOnEvent extends PlaybackDraftEventBase {
53
52
  kind: "note-on";
54
53
  noteId: PlaybackNoteId;
@@ -56,12 +55,13 @@ export interface PlaybackDraftNoteOnEvent extends PlaybackDraftEventBase {
56
55
  midi: number;
57
56
  velocity: number;
58
57
  percussion?: true;
59
- transpose?: (steps: number) => number;
60
58
  sourceSpans: SourceSpan[];
61
59
  }
62
60
  export interface PlaybackDraftNoteOffEvent extends PlaybackDraftEventBase {
63
61
  kind: "note-off";
64
62
  noteId: PlaybackNoteId;
63
+ track: Track;
64
+ midi: number;
65
65
  }
66
66
  export interface PlaybackDraftTempoEvent extends PlaybackDraftEventBase {
67
67
  kind: "tempo";
@@ -87,10 +87,10 @@ export interface PlaybackEventInput {
87
87
  /** 同刻先处理系统状态,再关音和开音;相同类别保持原发布次序 */
88
88
  export declare function comparePlaybackDraftEvents(left: PlaybackDraftEvent, right: PlaybackDraftEvent): number;
89
89
  /**
90
- * 校验配对、压实发声 Track 编号并剥掉编译期字段,得到稳定、可序列化的公开事件
91
- * 输入已经稳定排序;这里保留次序,将编译期的 Track 对象和音符配对转换为公开字段
90
+ * 压实发声 Track 编号并剥掉编译期字段,得到稳定、可序列化的公开事件
91
+ * 输入已经稳定排序;这里保留次序,将编译期的 Track 对象转换为公开通道编号
92
92
  */
93
- export declare function finalizePlaybackEvents(events: readonly PlaybackDraftEvent[], trackOrder: readonly Track[]): {
93
+ export declare function finalizePlaybackEvents(events: readonly PlaybackDraftEvent[], trackOrder: readonly Track[], audible: ReadonlySet<Track>): {
94
94
  events: PlaybackEvent[];
95
95
  tracks: Track[];
96
96
  };
@@ -11,44 +11,10 @@ export function comparePlaybackDraftEvents(left, right) {
11
11
  return byTime || EVENT_PRIORITY[left.kind] - EVENT_PRIORITY[right.kind] || left.order - right.order;
12
12
  }
13
13
  /**
14
- * 校验配对、压实发声 Track 编号并剥掉编译期字段,得到稳定、可序列化的公开事件
15
- * 输入已经稳定排序;这里保留次序,将编译期的 Track 对象和音符配对转换为公开字段
14
+ * 压实发声 Track 编号并剥掉编译期字段,得到稳定、可序列化的公开事件
15
+ * 输入已经稳定排序;这里保留次序,将编译期的 Track 对象转换为公开通道编号
16
16
  */
17
- export function finalizePlaybackEvents(events, trackOrder) {
18
- const noteOns = new Map();
19
- const noteOffs = new Map();
20
- // 同一音符的两端不一定相邻,先按 noteId 建立索引并拒绝重复的开音或关音
21
- for (const event of events) {
22
- if (event.kind === "note-on") {
23
- if (noteOns.has(event.noteId))
24
- throw new Error(`Duplicate NoteOn ${event.noteId}`);
25
- noteOns.set(event.noteId, event);
26
- }
27
- else if (event.kind === "note-off") {
28
- if (noteOffs.has(event.noteId))
29
- throw new Error(`Duplicate NoteOff ${event.noteId}`);
30
- noteOffs.set(event.noteId, event);
31
- }
32
- }
33
- const audible = new Set();
34
- // 物理合并完成后仍必须一一配对,并保留正时值和可追溯的来源;同时收集实际发声轨道
35
- for (const [noteId, on] of noteOns) {
36
- const off = noteOffs.get(noteId);
37
- if (!off)
38
- throw new Error(`Note ${noteId} has no NoteOff`);
39
- if (off.at.compare(on.at) <= 0)
40
- throw new Error(`Note ${noteId} has a non-positive duration`);
41
- if (on.origins.length === 0 || off.origins.length === 0)
42
- throw new Error(`Note ${noteId} has no origin`);
43
- audible.add(on.track);
44
- }
45
- // 仅当关音数量多于开音时反查孤立的 NoteOff
46
- if (noteOffs.size !== noteOns.size) {
47
- for (const noteId of noteOffs.keys()) {
48
- if (!noteOns.has(noteId))
49
- throw new Error(`NoteOff ${noteId} has no NoteOn`);
50
- }
51
- }
17
+ export function finalizePlaybackEvents(events, trackOrder, audible) {
52
18
  // 保留 lowering 的稳定轨道顺序,只过滤未实际发声的轨道
53
19
  const trackIds = new Map();
54
20
  for (const track of trackOrder) {
@@ -76,20 +42,18 @@ export function finalizePlaybackEvents(events, trackOrder) {
76
42
  });
77
43
  continue;
78
44
  }
45
+ const track = trackIds.get(event.track);
46
+ if (track === undefined)
47
+ continue;
79
48
  if (event.kind === "program-change") {
80
- const track = trackIds.get(event.track);
81
- if (track !== undefined)
82
- output.push({
83
- kind: "program-change",
84
- at: event.at,
85
- track,
86
- program: event.program,
87
- });
49
+ output.push({
50
+ kind: "program-change",
51
+ at: event.at,
52
+ track,
53
+ program: event.program,
54
+ });
88
55
  continue;
89
56
  }
90
- // NoteOff 从配对的 NoteOn 取得轨道和键号,保证两端始终使用相同的最终身份
91
- const on = event.kind === "note-on" ? event : noteOns.get(event.noteId);
92
- const track = trackIds.get(on.track);
93
57
  if (event.kind === "note-on") {
94
58
  output.push({
95
59
  kind: "note-on",
@@ -108,7 +72,7 @@ export function finalizePlaybackEvents(events, trackOrder) {
108
72
  at: event.at,
109
73
  noteId: event.noteId,
110
74
  track,
111
- midi: on.midi,
75
+ midi: event.midi,
112
76
  });
113
77
  }
114
78
  return { events: output, tracks: [...trackIds.keys()] };
@@ -9,8 +9,6 @@ import type { PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from
9
9
  export declare class CanvasPainter implements Painter {
10
10
  private readonly context;
11
11
  constructor(context: CanvasRenderingContext2D);
12
- private beginOpacity;
13
- private endOpacity;
14
12
  drawText(text: string, x: number, y: number, style: TextStyle): void;
15
13
  drawLine(x1: number, y1: number, x2: number, y2: number, style?: PaintStyle): void;
16
14
  drawRect(x: number, y: number, w: number, h: number, style?: PaintStyle): void;
@@ -3,27 +3,31 @@ import { canvasFont } from "./text.js";
3
3
  function tracePath(context, commands, x = 0, y = 0, scaleX = 1, scaleY = 1) {
4
4
  context.beginPath();
5
5
  for (const command of commands) {
6
- if (command.op === "Z") {
7
- context.closePath();
8
- continue;
6
+ switch (command.op) {
7
+ case "M":
8
+ context.moveTo(x + command.x * scaleX, y + command.y * scaleY);
9
+ break;
10
+ case "L":
11
+ context.lineTo(x + command.x * scaleX, y + command.y * scaleY);
12
+ break;
13
+ case "Q":
14
+ context.quadraticCurveTo(x + command.cx * scaleX, y + command.cy * scaleY, x + command.x * scaleX, y + command.y * scaleY);
15
+ break;
16
+ case "C":
17
+ context.bezierCurveTo(x + command.cx1 * scaleX, y + command.cy1 * scaleY, x + command.cx2 * scaleX, y + command.cy2 * scaleY, x + command.x * scaleX, y + command.y * scaleY);
18
+ break;
19
+ case "Z":
20
+ context.closePath();
21
+ break;
22
+ default:
23
+ command;
9
24
  }
10
- if (command.op === "M") {
11
- context.moveTo(x + command.x * scaleX, y + command.y * scaleY);
12
- continue;
13
- }
14
- if (command.op === "L") {
15
- context.lineTo(x + command.x * scaleX, y + command.y * scaleY);
16
- continue;
17
- }
18
- if (command.op === "Q") {
19
- context.quadraticCurveTo(x + command.cx * scaleX, y + command.cy * scaleY, x + command.x * scaleX, y + command.y * scaleY);
20
- continue;
21
- }
22
- if (!("cx1" in command))
23
- continue;
24
- context.bezierCurveTo(x + command.cx1 * scaleX, y + command.cy1 * scaleY, x + command.cx2 * scaleX, y + command.cy2 * scaleY, x + command.x * scaleX, y + command.y * scaleY);
25
25
  }
26
26
  }
27
+ /** Canvas 会忽略 "none" 这类非法颜色并沿用上一次的样式,因此按“不绘制”处理 */
28
+ function paint(color) {
29
+ return color === "none" ? undefined : color;
30
+ }
27
31
  /**
28
32
  * CanvasRenderingContext2D 的 Painter 适配器
29
33
  *
@@ -35,88 +39,78 @@ export class CanvasPainter {
35
39
  constructor(context) {
36
40
  this.context = context;
37
41
  }
38
- beginOpacity(style) {
39
- if (style?.opacity === void 0)
40
- return void 0;
41
- const previous = this.context.globalAlpha;
42
- this.context.globalAlpha = previous * style.opacity;
43
- return previous;
44
- }
45
- endOpacity(previous) {
46
- if (previous !== void 0)
47
- this.context.globalAlpha = previous;
48
- }
49
42
  drawText(text, x, y, style) {
50
- const previousAlpha = this.beginOpacity(style);
51
- this.context.fillStyle = style.fill ?? "#000";
43
+ const fill = paint(style.fill ?? "#000");
44
+ if (!fill)
45
+ return;
46
+ this.context.fillStyle = fill;
52
47
  this.context.font = canvasFont(style);
53
48
  this.context.textAlign = style.textAlign ?? "left";
54
49
  this.context.textBaseline = "alphabetic";
55
50
  this.context.fillText(text, x, y);
56
- this.endOpacity(previousAlpha);
57
51
  }
58
52
  drawLine(x1, y1, x2, y2, style) {
59
- const previousAlpha = this.beginOpacity(style);
53
+ const stroke = paint(style?.stroke ?? style?.fill ?? "#000");
54
+ if (!stroke)
55
+ return;
60
56
  this.context.beginPath();
61
57
  this.context.moveTo(x1, y1);
62
58
  this.context.lineTo(x2, y2);
63
- this.context.strokeStyle = style?.stroke ?? style?.fill ?? "#000";
59
+ this.context.strokeStyle = stroke;
64
60
  this.context.lineWidth = style?.strokeWidth ?? 1;
65
61
  this.context.lineCap = "round";
66
62
  this.context.stroke();
67
- this.endOpacity(previousAlpha);
68
63
  }
69
64
  drawRect(x, y, w, h, style) {
70
65
  if (w < 0 || h < 0)
71
66
  return;
72
- const previousAlpha = this.beginOpacity(style);
73
- if (style?.fill) {
74
- this.context.fillStyle = style.fill;
67
+ const fill = paint(style?.fill);
68
+ if (fill) {
69
+ this.context.fillStyle = fill;
75
70
  this.context.fillRect(x, y, w, h);
76
71
  }
77
- if (style?.stroke) {
78
- this.context.strokeStyle = style.stroke;
79
- this.context.lineWidth = style.strokeWidth ?? 1;
72
+ const stroke = paint(style?.stroke);
73
+ if (stroke) {
74
+ this.context.strokeStyle = stroke;
75
+ this.context.lineWidth = style?.strokeWidth ?? 1;
80
76
  this.context.lineJoin = "miter";
81
77
  this.context.strokeRect(x, y, w, h);
82
78
  }
83
- this.endOpacity(previousAlpha);
84
79
  }
85
80
  drawCircle(cx, cy, r, style) {
86
81
  if (r < 0)
87
82
  return;
88
- const previousAlpha = this.beginOpacity(style);
89
83
  this.context.beginPath();
90
84
  this.context.arc(cx, cy, r, 0, Math.PI * 2);
91
- const fill = style?.fill ?? "#000";
92
- if (fill && fill !== "none") {
85
+ const fill = paint(style?.fill ?? "#000");
86
+ if (fill) {
93
87
  this.context.fillStyle = fill;
94
88
  this.context.fill();
95
89
  }
96
- if (style?.stroke) {
97
- this.context.strokeStyle = style.stroke;
98
- this.context.lineWidth = style.strokeWidth ?? 1;
90
+ const stroke = paint(style?.stroke);
91
+ if (stroke) {
92
+ this.context.strokeStyle = stroke;
93
+ this.context.lineWidth = style?.strokeWidth ?? 1;
99
94
  this.context.stroke();
100
95
  }
101
- this.endOpacity(previousAlpha);
102
96
  }
103
97
  drawPath(commands, style, transform) {
104
98
  if (commands.length === 0)
105
99
  return;
106
- const previousAlpha = this.beginOpacity(style);
107
100
  tracePath(this.context, commands, transform?.x, transform?.y, transform?.scaleX, transform?.scaleY);
108
- if (style?.fill) {
109
- this.context.fillStyle = style.fill;
101
+ const fill = paint(style?.fill);
102
+ if (fill) {
103
+ this.context.fillStyle = fill;
110
104
  this.context.fill();
111
105
  }
112
- if (style?.stroke) {
113
- this.context.strokeStyle = style.stroke;
114
- this.context.lineWidth = style.strokeWidth ?? 1;
106
+ const stroke = paint(style?.stroke);
107
+ if (stroke) {
108
+ this.context.strokeStyle = stroke;
109
+ this.context.lineWidth = style?.strokeWidth ?? 1;
115
110
  this.context.lineCap = "round";
116
111
  this.context.lineJoin = "round";
117
112
  this.context.stroke();
118
113
  }
119
- this.endOpacity(previousAlpha);
120
114
  }
121
115
  }
122
116
  /** 使用 Canvas 后端把一个布局结果一次绘制到独立页面 context */
@@ -1,5 +1,5 @@
1
1
  export * from "./types.js";
2
- export { layoutPageBounds, paintLayout, paintLayoutPages } from "./paint.js";
2
+ export { layoutPageBounds, paintLayout, paintLayoutPages, paintVisual } from "./paint.js";
3
3
  export * from "./text.js";
4
4
  export * from "./recording.js";
5
5
  export * from "./svg.js";
@@ -1,5 +1,5 @@
1
1
  export * from "./types.js";
2
- export { layoutPageBounds, paintLayout, paintLayoutPages } from "./paint.js";
2
+ export { layoutPageBounds, paintLayout, paintLayoutPages, paintVisual } from "./paint.js";
3
3
  export * from "./text.js";
4
4
  export * from "./recording.js";
5
5
  export * from "./svg.js";
@@ -1,7 +1,14 @@
1
1
  import type { DocumentLayoutResult } from "../layout/engine.js";
2
2
  import type { Rect } from "../layout/types.js";
3
+ import type { VisualTemporalNode } from "../functions/temporal.js";
3
4
  import type { Painter } from "./types.js";
4
5
  export declare function layoutPageBounds(result: DocumentLayoutResult): readonly Rect[];
6
+ /**
7
+ * 绘制一个可见时值对象:主体后接装饰,整体放进 node.kind 分组
8
+ *
9
+ * up、grace、arpeggio 等容器绘制成员时也应调用它,成员的组因此嵌套在容器组内
10
+ */
11
+ export declare function paintVisual(painter: Painter, node: VisualTemporalNode): void;
5
12
  /** 按固定层级把布局结果绘制到一个 Painter */
6
13
  export declare function paintLayout(result: DocumentLayoutResult, painter: Painter): void;
7
14
  /** 用一个代理 Painter 把一次完整绘制分发到多个页面 Painter */
@@ -3,29 +3,68 @@ export function layoutPageBounds(result) {
3
3
  ? result.pages.map(page => page.bounds)
4
4
  : [result.bounds];
5
5
  }
6
+ /**
7
+ * 绘制一个可见时值对象:主体后接装饰,整体放进 node.kind 分组
8
+ *
9
+ * up、grace、arpeggio 等容器绘制成员时也应调用它,成员的组因此嵌套在容器组内
10
+ */
11
+ export function paintVisual(painter, node) {
12
+ const kind = node.kind;
13
+ if (kind)
14
+ painter.beginGroup?.({ kind });
15
+ node.paint(painter);
16
+ for (const decoration of node.decorations)
17
+ decoration.paint?.(painter);
18
+ if (kind)
19
+ painter.endGroup?.();
20
+ }
21
+ function paintAttachments(painter, attachments, layer) {
22
+ for (const attachment of attachments) {
23
+ if (attachment.layer !== layer)
24
+ continue;
25
+ const kind = attachment.kind;
26
+ if (kind)
27
+ painter.beginGroup?.({ kind });
28
+ attachment.paint(painter);
29
+ if (kind)
30
+ painter.endGroup?.();
31
+ }
32
+ }
6
33
  /** 按固定层级把布局结果绘制到一个 Painter */
7
34
  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
- }
35
+ paintAttachments(painter, result.attachments, "background");
36
+ for (const node of result.objects)
37
+ paintVisual(painter, node);
38
+ paintAttachments(painter, result.attachments, "foreground");
21
39
  }
22
40
  class PagePainter {
23
41
  pages;
24
42
  painters;
43
+ /** 当前打开的分组,由外到内 */
44
+ groups = [];
45
+ /** 页下标 → 该页已补开的层数;只记录有未结束分组的页,没有图元的页不开组 */
46
+ opened = new Map();
25
47
  constructor(pages, painters) {
26
48
  this.pages = pages;
27
49
  this.painters = painters;
28
50
  }
51
+ beginGroup(group) {
52
+ this.groups.push(group);
53
+ }
54
+ endGroup() {
55
+ const depth = this.groups.length;
56
+ this.groups.pop();
57
+ // 各页层数不超过 depth,等于 depth 的页才打开过这一组
58
+ for (const [index, opened] of this.opened) {
59
+ if (opened < depth)
60
+ continue;
61
+ this.painters[index].endGroup?.();
62
+ if (depth > 1)
63
+ this.opened.set(index, depth - 1);
64
+ else
65
+ this.opened.delete(index);
66
+ }
67
+ }
29
68
  route(top, bottom, paint) {
30
69
  let low = 0;
31
70
  let high = this.pages.length;
@@ -37,8 +76,16 @@ class PagePainter {
37
76
  else
38
77
  high = middle;
39
78
  }
79
+ const depth = this.groups.length;
40
80
  for (let index = low; index < this.pages.length && this.pages[index].y <= bottom; index++) {
41
- paint(this.painters[index]);
81
+ const painter = this.painters[index];
82
+ const opened = this.opened.get(index) ?? 0;
83
+ if (opened < depth) {
84
+ for (let level = opened; level < depth; level++)
85
+ painter.beginGroup?.(this.groups[level]);
86
+ this.opened.set(index, depth);
87
+ }
88
+ paint(painter);
42
89
  }
43
90
  }
44
91
  drawText(text, x, y, style) {
@@ -62,15 +109,11 @@ class PagePainter {
62
109
  drawPath(commands, style, transform) {
63
110
  if (commands.length === 0)
64
111
  return;
65
- const y = transform
66
- ? (value) => transform.y + value * transform.scaleY
67
- : (value) => value;
68
112
  let top = Infinity;
69
113
  let bottom = -Infinity;
70
114
  const include = (value) => {
71
- const transformed = y(value);
72
- top = Math.min(top, transformed);
73
- bottom = Math.max(bottom, transformed);
115
+ top = Math.min(top, value);
116
+ bottom = Math.max(bottom, value);
74
117
  };
75
118
  for (const command of commands) {
76
119
  if (command.op === "Z")
@@ -83,6 +126,13 @@ class PagePainter {
83
126
  }
84
127
  include(command.y);
85
128
  }
129
+ if (transform) {
130
+ // 仿射变换单调,变换端点即可;scaleY 为负时上下互换
131
+ const a = transform.y + top * transform.scaleY;
132
+ const b = transform.y + bottom * transform.scaleY;
133
+ top = Math.min(a, b);
134
+ bottom = Math.max(a, b);
135
+ }
86
136
  if (!Number.isFinite(top))
87
137
  return;
88
138
  const halfStroke = style?.stroke ? (style.strokeWidth ?? 1) / 2 : 0;
@@ -1,4 +1,4 @@
1
- import type { PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from "./types.js";
1
+ import type { PaintGroup, PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from "./types.js";
2
2
  export type RecordedPaintCommand = {
3
3
  kind: "text";
4
4
  text: string;
@@ -29,6 +29,11 @@ export type RecordedPaintCommand = {
29
29
  kind: "path";
30
30
  commands: PathCommand[];
31
31
  style?: PaintStyle;
32
+ } | {
33
+ kind: "begin-group";
34
+ group: PaintGroup;
35
+ } | {
36
+ kind: "end-group";
32
37
  };
33
38
  /**
34
39
  * 记录通用绘制命令而不产生图像
@@ -39,6 +44,8 @@ export type RecordedPaintCommand = {
39
44
  export declare class RecordingPainter implements Painter {
40
45
  commands: RecordedPaintCommand[];
41
46
  replay(painter: Painter): void;
47
+ beginGroup(group: PaintGroup): void;
48
+ endGroup(): void;
42
49
  drawText(text: string, x: number, y: number, style: TextStyle): void;
43
50
  drawLine(x1: number, y1: number, x2: number, y2: number, style?: PaintStyle): void;
44
51
  drawRect(x: number, y: number, w: number, h: number, style?: PaintStyle): void;
@@ -24,9 +24,21 @@ export class RecordingPainter {
24
24
  case "path":
25
25
  painter.drawPath(command.commands, command.style);
26
26
  break;
27
+ case "begin-group":
28
+ painter.beginGroup?.(command.group);
29
+ break;
30
+ case "end-group":
31
+ painter.endGroup?.();
32
+ break;
27
33
  }
28
34
  }
29
35
  }
36
+ beginGroup(group) {
37
+ this.commands.push({ kind: "begin-group", group });
38
+ }
39
+ endGroup() {
40
+ this.commands.push({ kind: "end-group" });
41
+ }
30
42
  drawText(text, x, y, style) {
31
43
  this.commands.push({
32
44
  kind: "text",
@@ -1,12 +1,15 @@
1
1
  import type { DocumentLayoutResult } from "../layout/engine.js";
2
- import type { PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from "./types.js";
2
+ import type { PaintGroup, PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from "./types.js";
3
3
  export interface SvgRenderOptions {
4
- padding?: number;
5
4
  background?: string;
6
5
  }
7
6
  /** 生成独立 SVG 字符串的 Painter;路径直接输出最终坐标 */
8
7
  export declare class SvgPainter implements Painter {
9
8
  private body;
9
+ /** 未结束分组的开标签在 body 中的下标 */
10
+ private groupStarts;
11
+ beginGroup(group: PaintGroup): void;
12
+ endGroup(): void;
10
13
  drawText(text: string, x: number, y: number, style: TextStyle): void;
11
14
  drawLine(x1: number, y1: number, x2: number, y2: number, style?: PaintStyle): void;
12
15
  drawRect(x: number, y: number, w: number, h: number, style?: PaintStyle): void;