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
@@ -122,6 +122,7 @@ class NoteFunction extends ASTFunctionNode {
122
122
  color;
123
123
  size;
124
124
  font;
125
+ weight;
125
126
  // JE 八度偏移量
126
127
  jeOctaveOffset;
127
128
  // 源码改写时判断是否需要覆盖默认升降号
@@ -131,6 +132,7 @@ class NoteFunction extends ASTFunctionNode {
131
132
  this.hasDefaultAcc = Boolean(ctx.variables["note.acc"]);
132
133
  [this.name, this.acc, this.octave, this.color] = this.getArgValue(args, ctx);
133
134
  this.font = ctx.variables.numberfont;
135
+ this.weight = ctx.variables.numberweight;
134
136
  this.size = ctx.variables.fontsize;
135
137
  // 创建时就固化参数值
136
138
  // 校验 note name
@@ -165,14 +167,14 @@ class NoteFunction extends ASTFunctionNode {
165
167
  }
166
168
  }
167
169
  export const NoteNode = NoteFunction;
168
- import { DEFAULT_KEY, DEFAULT_VELOCITY, TemporalNodeBase } from "../temporal.js";
170
+ import { DEFAULT_KEY, DEFAULT_TONALITY, DEFAULT_VELOCITY, TemporalNodeBase } from "../temporal.js";
169
171
  import { createDiatonicTranspose, resolveLetterNameToJianpu, resolveNoteMidi, } from "../../parser/parse-utils/note-utils.js";
170
172
  // 8 是隐形占位,9 是固定打击音的节拍记号,空串表示不绘制
171
173
  const NOTE_GLYPH = { "8": "", "9": "X" };
172
174
  class NoteTemporalNode extends TemporalNodeBase {
173
175
  // 时间固化后的参数
174
176
  resolvedMidi = null; // 按调性解析的记谱音高,不含播放偏移
175
- keySignature = "C4"; // 用于转调时记录大环境
177
+ keySignature = DEFAULT_TONALITY; // 用于转调时记录大环境
176
178
  transposeDiatonic;
177
179
  name; // 数字
178
180
  acc; // 升降号
@@ -193,7 +195,7 @@ class NoteTemporalNode extends TemporalNodeBase {
193
195
  this.numberStyle = {
194
196
  fontSize: ast.size,
195
197
  fontFamily: ast.font,
196
- fontWeight: 400,
198
+ fontWeight: ast.weight,
197
199
  textAlign: "center",
198
200
  fill: ast.color,
199
201
  };
@@ -203,10 +205,8 @@ class NoteTemporalNode extends TemporalNodeBase {
203
205
  const { size, color } = this.ast;
204
206
  const mainMetrics = context.textMeasurer.measureText("0", this.numberStyle);
205
207
  this.numberY = mainMetrics.baseline;
206
- // 升降号贴近数字左上角,按同一 baseline 排在数字左侧;
207
- // 缩小右侧间隔会在全局 anchor 不变时把升降号向右移动
208
- const accidentalGap = size * 0.01;
209
- const { placed, right: mainX } = placeAccidentals(this.acc, size, 0, this.numberY, accidentalGap);
208
+ // 升降号盒直接紧挨数字盒左缘,按同一 baseline 排在数字左侧
209
+ const { placed, right: mainX } = placeAccidentals(this.acc, size, 0, this.numberY);
210
210
  this.accidentals = placed;
211
211
  this.box.w = mainX + mainMetrics.w;
212
212
  this.box.h = mainMetrics.h;
@@ -254,12 +254,10 @@ class NoteTemporalNode extends TemporalNodeBase {
254
254
  }
255
255
  finalizeLayout() {
256
256
  this.ports["lyric"] = { x: this.box.anchor, y: this.box.h };
257
- if (this.octave > 0) { // 八度点上方留空间
258
- this.ports["tie.top"] = {
259
- x: this.box.anchor,
260
- y: getLayoutBounds(this, true).y - this.box.y - this.ast.size * 0.05,
261
- };
262
- }
257
+ this.ports["tie.top"] = {
258
+ x: this.box.anchor,
259
+ y: getLayoutBounds(this, true).y - this.box.y - this.ast.size * 0.1,
260
+ };
263
261
  }
264
262
  paint(painter) {
265
263
  const color = this.ast.color;
@@ -275,7 +273,6 @@ class NoteTemporalNode extends TemporalNodeBase {
275
273
  const keySignature = this.keySignature = state.keySignature;
276
274
  this.playbackState = { bpm: state.bpm, velocity: state.velocity, program: state.program };
277
275
  this.resolvedMidi = resolveNoteMidi(this.name, this.acc, this.octave, keySignature);
278
- this.transposeDiatonic = createDiatonicTranspose(this.name, this.acc, this.octave, keySignature);
279
276
  // 数字音名本身就是简谱显示形式,直接保留原始数字和相对八度
280
277
  if (this.name >= "0" && this.name <= "9") {
281
278
  if (this.name === "0" || this.name >= "8") {
@@ -292,6 +289,7 @@ class NoteTemporalNode extends TemporalNodeBase {
292
289
  this.octave = jianpuPitch.renderOctave;
293
290
  }
294
291
  }
292
+ this.transposeDiatonic = createDiatonicTranspose(this.name, this.octave, keySignature);
295
293
  }
296
294
  /** 发布完整音段或无声区间,实际 NoteOn/NoteOff 留到声音展开完成后生成 */
297
295
  emitPlayback(emitter) {
@@ -1,5 +1,6 @@
1
1
  import type { ASTNodeBase } from "../ASTtypes.js";
2
2
  import type { SourceSpan } from "../../parser/types.js";
3
+ import type { CallInfo } from "../../parser/grammarType.js";
3
4
  export type NoteTransform = "to-absolute" | "to-relative" | "semitone-up" | "semitone-down";
4
5
  export interface SourceEdit {
5
6
  span: SourceSpan;
@@ -16,6 +17,20 @@ interface NoteSource {
16
17
  resolvedMidi: number | null;
17
18
  keySignature: string;
18
19
  }
20
+ /**
21
+ * 仅在函数参数的顶层保护低八度逗号;已有大括号内的简写无需再包装。
22
+ * 沿 AST 父链定位最近一层显式函数调用 `@call(...)` 及目标音符所属实参,
23
+ * 统计实参起点到音符前的 `{}` 深度(跳过双引号字符串字面量)。
24
+ */
25
+ export declare function needsBraces(masked: string, ast: ASTNodeBase): boolean;
26
+ export interface NotePitch {
27
+ name: string;
28
+ acc: string;
29
+ octave: number;
30
+ absolute: boolean;
31
+ }
32
+ /** 改写显式 `@note(...)` 的音高:已有实参只改值,缺失的追加为命名参数;存在默认 acc 时显式写出 acc 以覆盖它 */
33
+ export declare function rewriteNoteCall(source: string, masked: string, call: CallInfo, pitch: NotePitch, hasDefaultAcc: boolean, edits?: SourceEdit[]): SourceEdit[];
19
34
  /** edits 始终引用原文;参数只改值,默认参数只在当前调用覆盖,避免影响其他音符 */
20
35
  export declare function rewriteNotes(source: string, notes: readonly NoteSource[], operation: NoteTransform, ranges?: readonly SourceSpan[]): SourceEdit[];
21
36
  export {};
@@ -1,19 +1,16 @@
1
1
  import { ErrorDiagnostic } from "../../diagnostic.js";
2
2
  import { preprocessSource } from "../../parser/preprocess.js";
3
- import { readCall } from "../../parser/parse-utils/call-utils.js";
3
+ import { callArgName, readCall } from "../../parser/parse-utils/call-utils.js";
4
4
  import { findClosingQuote, quote } from "../../parser/parse-utils/string-utils.js";
5
- import { NoteNameMap, SHARP_NOTE_NAMES, FLAT_NOTE_NAMES, resolveLetterNameToJianpu, tonality2Midi } from "../../parser/parse-utils/note-utils.js";
5
+ import { FLAT_NOTE_NAMES, NOTE_LETTERS, NoteNameMap, SHARP_NOTE_NAMES, normalizeAccidentalOffset, offsetToAccidental, resolveLetterNameToJianpu, tonality2Midi, wrapPitchClass, } from "../../parser/parse-utils/note-utils.js";
6
6
  import { parseNoteName } from "./noteName.js";
7
- const LETTERS = "CDEFGAB";
8
- const mod = (value, base) => ((value % base) + base) % base;
9
- const accidental = (offset) => offset < 0 ? "b".repeat(-offset) : "#".repeat(offset);
10
7
  function fail(span) {
11
8
  throw new ErrorDiagnostic("E_NOTE_TRANSFORM", "无法安全改写此音符的音高", span);
12
9
  }
13
10
  /** 音高计算只读固化事实;互转保留调内级数,半音操作采用最少升降号的拼写 */
14
11
  function targetPitch(note, operation) {
15
12
  const absolute = operation === "to-absolute"
16
- || operation !== "to-relative" && LETTERS.includes(note.ast.name);
13
+ || operation !== "to-relative" && NOTE_LETTERS.includes(note.ast.name);
17
14
  const midi = note.resolvedMidi + (operation === "semitone-up" ? 1 : operation === "semitone-down" ? -1 : 0);
18
15
  const tonic = tonality2Midi(note.keySignature);
19
16
  if (![midi, tonic, note.ast.octave, note.ast.jeOctaveOffset].every(Number.isSafeInteger))
@@ -21,47 +18,49 @@ function targetPitch(note, operation) {
21
18
  const spelling = operation === "semitone-down" ? FLAT_NOTE_NAMES : SHARP_NOTE_NAMES;
22
19
  let name, acc, octave;
23
20
  if (operation === "to-absolute") {
24
- const tonicLetter = LETTERS.indexOf(note.keySignature[0]);
25
- const base = tonicLetter < 0 ? LETTERS.indexOf(SHARP_NOTE_NAMES[mod(tonic, 12)][0]) : tonicLetter;
21
+ const base = NOTE_LETTERS.indexOf(note.keySignature[0]);
26
22
  const degree = Number(note.ast.name) - 1;
27
- name = LETTERS[(base + degree) % 7];
28
- const tonicAcc = mod(tonic - NoteNameMap[LETTERS[base]] + 6, 12) - 6;
23
+ name = NOTE_LETTERS[(base + degree) % 7];
24
+ const tonicAcc = normalizeAccidentalOffset(tonic - NoteNameMap[NOTE_LETTERS[base]]);
29
25
  octave = Math.floor((tonic - tonicAcc) / 12) - 1 + Math.floor((base + degree) / 7)
30
26
  + note.ast.octave + note.ast.jeOctaveOffset;
31
- acc = accidental(midi - ((octave + 1) * 12 + NoteNameMap[name]));
27
+ acc = offsetToAccidental(midi - ((octave + 1) * 12 + NoteNameMap[name]));
32
28
  }
33
29
  else if (operation === "to-relative") {
34
30
  const ast = note.ast;
35
- const key = LETTERS.includes(note.keySignature[0]) ? note.keySignature
36
- : SHARP_NOTE_NAMES[mod(tonic, 12)] + (Math.floor(tonic / 12) - 1);
37
- const relative = resolveLetterNameToJianpu(ast.name, ast.acc, ast.octave + ast.jeOctaveOffset, key);
31
+ const relative = resolveLetterNameToJianpu(ast.name, ast.acc, ast.octave + ast.jeOctaveOffset, note.keySignature);
38
32
  if (!relative)
39
33
  fail(ast.sourceSpan);
40
34
  ({ renderName: name, renderAcc: acc, renderOctave: octave } = relative);
41
35
  }
42
36
  else {
43
37
  const value = absolute ? midi : midi - tonic;
44
- const pitch = spelling[mod(value, 12)];
45
- name = absolute ? pitch[0] : String(LETTERS.indexOf(pitch[0]) + 1);
38
+ const pitch = spelling[wrapPitchClass(value)];
39
+ name = absolute ? pitch[0] : String(NOTE_LETTERS.indexOf(pitch[0]) + 1);
46
40
  acc = pitch.slice(1);
47
41
  octave = Math.floor(value / 12) - (absolute ? 1 : 0);
48
42
  }
49
43
  return { name, acc, octave: octave - note.ast.jeOctaveOffset, absolute };
50
44
  }
51
- /** 仅在函数参数的顶层保护低八度逗号;已有大括号内的简写无需再包装 */
52
- function needsBraces(masked, ast) {
45
+ /**
46
+ * 仅在函数参数的顶层保护低八度逗号;已有大括号内的简写无需再包装。
47
+ * 沿 AST 父链定位最近一层显式函数调用 `@call(...)` 及目标音符所属实参,
48
+ * 统计实参起点到音符前的 `{}` 深度(跳过双引号字符串字面量)。
49
+ */
50
+ export function needsBraces(masked, ast) {
53
51
  for (let parent = ast.parent; parent; parent = parent.parent) {
54
52
  const call = readCall(masked, parent.sourceSpan.start, parent.sourceSpan.end);
55
- if (!call)
56
- continue;
57
- const arg = call.args.find(item => item.valueSpan.start <= ast.sourceSpan.start
53
+ const arg = call?.args.find(item => item.valueSpan.start <= ast.sourceSpan.start
58
54
  && item.valueSpan.end >= ast.sourceSpan.end);
59
55
  if (!arg)
60
56
  continue;
61
57
  let depth = 0;
62
58
  for (let position = arg.valueSpan.start; position < ast.sourceSpan.start; position++) {
63
- if (masked[position] === '"')
64
- position = findClosingQuote(masked, position, arg.valueSpan.end);
59
+ if (masked[position] === '"') {
60
+ const close = findClosingQuote(masked, position, arg.valueSpan.end);
61
+ if (close >= 0)
62
+ position = close;
63
+ }
65
64
  else if (masked[position] === "{")
66
65
  depth++;
67
66
  else if (masked[position] === "}")
@@ -71,24 +70,62 @@ function needsBraces(masked, ast) {
71
70
  }
72
71
  return false;
73
72
  }
73
+ /** 音高简写文本;省略的部分由显式实参提供 */
74
+ function pitchToken({ name, acc, octave, absolute }, withAcc = true, withOctave = true) {
75
+ const accText = withAcc ? acc : "";
76
+ const octaveText = !withOctave ? "" : absolute ? String(octave) : octave < 0 ? ",".repeat(-octave) : "'".repeat(octave);
77
+ return absolute ? name + accText + octaveText : accText + name + octaveText;
78
+ }
79
+ /** 只记录与原文不同的改写;被掩码的片段(如注释)无法安全改写 */
80
+ function pushEdit(edits, source, masked, span, text) {
81
+ const original = source.slice(span.start, span.end);
82
+ if (original === text)
83
+ return;
84
+ if (original !== masked.slice(span.start, span.end))
85
+ fail(span);
86
+ edits.push({ span, text });
87
+ }
88
+ /** 改写显式 `@note(...)` 的音高:已有实参只改值,缺失的追加为命名参数;存在默认 acc 时显式写出 acc 以覆盖它 */
89
+ export function rewriteNoteCall(source, masked, call, pitch, hasDefaultAcc, edits = []) {
90
+ const slots = new Map();
91
+ call.args.forEach((arg, index) => {
92
+ if (arg.valueSpan.start < arg.valueSpan.end)
93
+ slots.set(callArgName(masked, arg) ?? index, arg.valueSpan);
94
+ });
95
+ const nameSlot = slots.get("name") ?? slots.get(0);
96
+ const accSlot = slots.get("acc") ?? slots.get(1);
97
+ const octaveSlot = slots.get("octave") ?? slots.get(2);
98
+ const additions = [];
99
+ const valueText = (value, slot) => !value || value.includes(",") || slot && source[slot.start] === '"' ? quote(value) : value;
100
+ const name = pitchToken(pitch, !accSlot && !hasDefaultAcc, !octaveSlot);
101
+ if (nameSlot)
102
+ pushEdit(edits, source, masked, nameSlot, valueText(name, nameSlot));
103
+ else
104
+ additions.push(`name=${valueText(name)}`);
105
+ if (accSlot)
106
+ pushEdit(edits, source, masked, accSlot, valueText(pitch.acc, accSlot));
107
+ else if (hasDefaultAcc)
108
+ additions.push(`acc=${quote(pitch.acc)}`);
109
+ if (octaveSlot)
110
+ pushEdit(edits, source, masked, octaveSlot, String(pitch.octave));
111
+ if (additions.length) {
112
+ const at = call.closeParenSpan.start;
113
+ const prefix = masked.slice(call.openParenSpan.end, at).trimEnd();
114
+ pushEdit(edits, source, masked, { start: at, end: at }, (prefix ? prefix.endsWith(",") ? " " : ", " : "") + additions.join(", "));
115
+ }
116
+ return edits;
117
+ }
74
118
  /** edits 始终引用原文;参数只改值,默认参数只在当前调用覆盖,避免影响其他音符 */
75
119
  export function rewriteNotes(source, notes, operation, ranges) {
76
120
  const { maskedSource: masked } = preprocessSource(source);
77
121
  const edits = [];
78
122
  const tokens = [];
79
- function replace(span, text) {
80
- if (source.slice(span.start, span.end) === text)
81
- return;
82
- if (source.slice(span.start, span.end) !== masked.slice(span.start, span.end))
83
- fail(span);
84
- edits.push({ span, text });
85
- }
86
123
  for (const note of notes) {
87
124
  const { ast } = note;
88
125
  const span = ast.sourceSpan;
89
126
  const call = readCall(masked, span.start, span.end);
90
127
  const explicit = call?.span.end === span.end && call.closeParenSpan;
91
- const already = operation === "to-absolute" && LETTERS.includes(ast.name)
128
+ const already = operation === "to-absolute" && NOTE_LETTERS.includes(ast.name)
92
129
  || operation === "to-relative" && /^[1-7]$/.test(ast.name);
93
130
  if (!explicit)
94
131
  tokens.push({ span, text: source.slice(span.start, span.end) });
@@ -97,47 +134,14 @@ export function rewriteNotes(source, notes, operation, ranges) {
97
134
  if (note.resolvedMidi === null || already)
98
135
  continue;
99
136
  const pitch = targetPitch(note, operation);
100
- const octaveText = pitch.absolute ? String(pitch.octave)
101
- : pitch.octave < 0 ? ",".repeat(-pitch.octave) : "'".repeat(pitch.octave);
102
- const nameText = (acc, octave) => pitch.absolute
103
- ? pitch.name + acc + octave : acc + pitch.name + octave;
104
- if (!explicit) {
105
- let text = nameText(pitch.acc, octaveText);
106
- if (text.includes(",") && needsBraces(masked, ast))
107
- text = `{${text}}`;
108
- tokens[tokens.length - 1].text = text;
137
+ if (explicit) {
138
+ rewriteNoteCall(source, masked, call, pitch, ast.hasDefaultAcc, edits);
109
139
  continue;
110
140
  }
111
- const slots = new Map();
112
- call.args.forEach((arg, index) => {
113
- if (arg.valueSpan.start === arg.valueSpan.end)
114
- return;
115
- slots.set(arg.nameSpan ? masked.slice(arg.nameSpan.start, arg.nameSpan.end).toLowerCase() : index, arg.valueSpan);
116
- });
117
- const nameSlot = slots.get("name") ?? slots.get(0);
118
- const accSlot = slots.get("acc") ?? slots.get(1);
119
- const octaveSlot = slots.get("octave") ?? slots.get(2);
120
- const additions = [];
121
- function write(slot, name, value) {
122
- const text = !value || value.includes(",")
123
- || slot && source[slot.start] === '"' ? quote(value) : value;
124
- if (slot)
125
- replace(slot, text);
126
- else
127
- additions.push(`${name}=${text}`);
128
- }
129
- write(nameSlot, "name", nameText(accSlot ? "" : pitch.acc, octaveSlot ? "" : octaveText));
130
- if (accSlot)
131
- write(accSlot, "acc", pitch.acc);
132
- else if (ast.hasDefaultAcc)
133
- additions.push('acc=""');
134
- if (octaveSlot)
135
- replace(octaveSlot, String(pitch.octave));
136
- if (additions.length) {
137
- const at = call.closeParenSpan.start;
138
- const prefix = masked.slice(call.openParenSpan.end, at).trimEnd();
139
- replace({ start: at, end: at }, (prefix ? prefix.endsWith(",") ? " " : ", " : "") + additions.join(", "));
140
- }
141
+ let text = pitchToken(pitch);
142
+ if (text.includes(",") && needsBraces(masked, ast))
143
+ text = `{${text}}`;
144
+ tokens[tokens.length - 1].text = text;
141
145
  }
142
146
  // 相邻原子改写后仍须是两个音符,例如 C4D4 -> C4 2,不能合并成 C42。
143
147
  tokens.sort((left, right) => left.span.start - right.span.start);
@@ -155,7 +159,7 @@ export function rewriteNotes(source, notes, operation, ranges) {
155
159
  }
156
160
  }
157
161
  for (const token of tokens)
158
- replace(token.span, token.text);
162
+ pushEdit(edits, source, masked, token.span, token.text);
159
163
  edits.sort((left, right) => left.span.start - right.span.start);
160
164
  for (let index = 1; index < edits.length; index++) {
161
165
  if (edits[index - 1].span.end > edits[index].span.start)
@@ -1,12 +1,8 @@
1
1
  import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
2
2
  import { unionLayoutBoxes } from "../../layout/engine.js";
3
+ import { lineEntryX, lineRightX } from "../../layout/range.js";
3
4
  import { ASTFunctionNode, } from "../ASTtypes.js";
4
5
  import { isVisualTemporalNode } from "../temporal.js";
5
- function outerHost(node) {
6
- while (node.foldedInto)
7
- node = node.foldedInto;
8
- return node;
9
- }
10
6
  class OttavaFunction extends ASTFunctionNode {
11
7
  static def = {
12
8
  name: ["ottava"],
@@ -59,7 +55,7 @@ class OttavaFunction extends ASTFunctionNode {
59
55
  for (const node of nodes) {
60
56
  if (!node.playbackState)
61
57
  continue;
62
- const host = outerHost(node);
58
+ const host = node.rootHost;
63
59
  const ottavas = ottavasByTrack.get(host.track);
64
60
  if (!ottavas)
65
61
  continue;
@@ -98,10 +94,8 @@ class OttavaFunction extends ASTFunctionNode {
98
94
  this.font = ctx.variables.numberfont;
99
95
  }
100
96
  loweringEnter(ctx) {
101
- const from = ctx.getTemporalNodes(this.from).at(0);
102
- const to = ctx.getTemporalNodes(this.to).at(-1);
103
- const head = from && outerHost(from);
104
- const tail = to && outerHost(to);
97
+ const head = ctx.getTemporalNodes(this.from).at(0)?.rootHost;
98
+ const tail = ctx.getTemporalNodes(this.to).at(-1)?.rootHost;
105
99
  if (!head || !tail || !isVisualTemporalNode(head) || !isVisualTemporalNode(tail)) {
106
100
  ctx.diagnostics.push(Diagnostic.warning.UnresolvedEndpoint("ottava", this.sourceSpan));
107
101
  return [];
@@ -121,22 +115,17 @@ class OttavaFunction extends ASTFunctionNode {
121
115
  export const OttavaNode = OttavaFunction;
122
116
  class OttavaAttachment {
123
117
  ast;
124
- from;
125
- to;
118
+ kind = "ottava";
126
119
  layer = "foreground";
120
+ endPoints;
127
121
  constructor(ast, from, to) {
128
122
  this.ast = ast;
129
- this.from = from;
130
- this.to = to;
123
+ this.endPoints = (from.t.compare(to.t) || from.order - to.order) > 0
124
+ ? [to, from] : [from, to];
131
125
  }
132
126
  get sourceSpan() { return this.ast.sourceSpan; }
133
- get endPoints() {
134
- return (this.from.t.compare(this.to.t) || this.from.order - this.to.order) > 0
135
- ? [this.to, this.from] : [this.from, this.to];
136
- }
137
127
  createGeometry(context) {
138
- const endpoints = this.endPoints;
139
- const [from, to] = endpoints;
128
+ const [from, to] = this.endPoints;
140
129
  const firstLine = from.layoutLine;
141
130
  const lastLine = to.layoutLine;
142
131
  if (context.lines[firstLine].columnOf(from) < 0 || context.lines[lastLine].columnOf(to) < 0) {
@@ -168,17 +157,8 @@ class OttavaAttachment {
168
157
  const line = firstLine + offset;
169
158
  const first = line === firstLine;
170
159
  const last = line === lastLine;
171
- const runs = context.lines[line].trackRuns;
172
- let left = first ? from.box.x + (from.ports["body.left"]?.x ?? 0)
173
- : runs.get(track)?.find(host => !host.T.isZero())?.box.x ?? context.originX;
174
- let right = to.box.x + (to.ports["body.right"]?.x ?? to.box.w);
175
- if (!last) {
176
- right = context.originX + (runs.size === 0 ? context.width : 0);
177
- for (const run of runs.values()) {
178
- for (const host of run)
179
- right = Math.max(right, host.box.x + host.box.w);
180
- }
181
- }
160
+ let left = first ? from.box.x + (from.ports["body.left"]?.x ?? 0) : lineEntryX(context, line, track);
161
+ let right = last ? to.box.x + (to.ports["body.right"]?.x ?? to.box.w) : lineRightX(context, line);
182
162
  if (left > right)
183
163
  [left, right] = [right, left];
184
164
  const lineStart = first ? left + metrics.w + labelGap : left;
@@ -201,7 +181,7 @@ class OttavaAttachment {
201
181
  }
202
182
  }
203
183
  if (!Number.isFinite(lineY)) {
204
- const extent = context.getRangeExtents(line, first || last ? endpoints : undefined, track);
184
+ const extent = context.getRangeExtents(line, first || last ? this.endPoints : undefined, track);
205
185
  const axis = context.getVisualAxis(line, track);
206
186
  lineY = above
207
187
  ? axis + (extent?.top ?? 0) - gap - (region.y + region.h)
@@ -19,6 +19,7 @@ class PageNumberAttachment {
19
19
  pattern;
20
20
  marginBottom;
21
21
  style;
22
+ kind = "page-number";
22
23
  layer = "foreground";
23
24
  constructor(sourceSpan, pattern, marginBottom, style) {
24
25
  this.sourceSpan = sourceSpan;
@@ -51,7 +52,7 @@ export class PageFunction extends ASTFunctionNode {
51
52
  ~~~jpfun
52
53
  @page(
53
54
  width=794px, height=1123px, top=48px, bottom=48px,
54
- left=40px, right=40px, gap=1em, fillRatio=0.5,
55
+ left=40px, right=40px, gap=1em, minGap=0.4em, fillRatio=0.5,
55
56
  numbering="1/1", barNumbering="(1)"
56
57
  )
57
58
  ~~~
@@ -64,9 +65,9 @@ export class PageFunction extends ASTFunctionNode {
64
65
  { name: "bottom", description: "页面下边距,启用页码时至少为 `16px`", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginBottom) },
65
66
  { name: "left", description: "页面左边距", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginLeft) },
66
67
  { name: "right", description: "页面右边距", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginRight) },
67
- { name: "gap", description: "谱面行之间的最小间距", type: "length", default: { value: 1, unit: "em" } },
68
- // 单个 1 取当前页;多个 1 中最后一个取总页数
69
- { name: "numbering", description: "页码格式,空值隐藏;`1` 显示当前页,`1/1` 显示当前页/总页数", type: "string", default: "" },
68
+ { name: "gap", description: "谱面行主旋律之间的标准间距", type: "length", default: { value: 1, unit: "em" } },
69
+ { name: "minGap", description: "行间保留的最小间距", type: "length", default: { value: 0.4, unit: "em" } },
70
+ { name: "numbering", description: "页码格式,空值隐藏;`1`:当前页,`1/1`:显示当前页/总页数", type: "string", default: "" },
70
71
  { name: "barNumbering", description: "行首小节号格式,默认空值隐藏;`1` 显示当前小节号,`(1)` 显示带括号的小节号", type: "string", default: "" },
71
72
  { name: "font", description: "页码/小节号字体,空值沿用当前字体设置", type: "string", default: "" },
72
73
  { name: "fillRatio", description: "自然宽度达到该比例后撑满", type: "number", default: DEFAULT_PAGE_CONFIG.fillRatio },
@@ -90,18 +91,15 @@ export class PageFunction extends ASTFunctionNode {
90
91
  return;
91
92
  }
92
93
  ctx.documentDeclarations["page"] = true;
93
- const values = this.getArgValue(args, ctx);
94
- const fillRatio = values.pop();
95
- this.font = values.pop() || ctx.variables.font;
96
- const barNumbering = values.pop();
97
- const numbering = values.pop();
98
- const [width, height, top, bottom, left, right, gap] = values.map(value => ctx.length2px(value));
94
+ const [w, h, t, b, l, r, g, mg, numbering, barNumbering, font, fillRatio,] = this.getArgValue(args, ctx);
95
+ this.font = font || ctx.variables.font;
96
+ const [width, height, top, bottom, left, right, gap, minGap] = [w, h, t, b, l, r, g, mg].map(value => ctx.length2px(value));
99
97
  if (!Number.isFinite(width) || width <= 0)
100
98
  throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的 width 必须是正有限长度", sourceSpan);
101
99
  if (!Number.isFinite(height))
102
100
  throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的 height 必须是有限长度;小于等于 0 表示不自动分页", sourceSpan);
103
- if ([top, bottom, left, right, gap].some(value => !Number.isFinite(value) || value < 0))
104
- throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的边距和 gap 必须是非负有限长度", sourceSpan);
101
+ if ([top, bottom, left, right, gap, minGap].some(value => !Number.isFinite(value) || value < 0))
102
+ throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的边距、gap 和 minGap 必须是非负有限长度", sourceSpan);
105
103
  if (left + right >= width)
106
104
  throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的左右边距没有留下可用内容宽度", sourceSpan);
107
105
  if (height > 0 && top + bottom >= height)
@@ -116,28 +114,28 @@ export class PageFunction extends ASTFunctionNode {
116
114
  marginLeft: left,
117
115
  marginRight: right,
118
116
  lineGap: gap,
117
+ minLineGap: minGap,
119
118
  fillRatio,
120
119
  });
121
120
  this.numbering = numbering;
122
121
  this.barNumbering = barNumbering;
123
122
  }
124
123
  loweringEnter(ctx) {
125
- if (!ctx || !this.config)
124
+ if (!this.config)
126
125
  return [];
127
126
  ctx.setPageConfig(this.config);
128
127
  if (this.numbering) {
129
128
  ctx.addAttachment(new PageNumberAttachment(this.sourceSpan, this.numbering, this.config.marginBottom, { ...PAGE_NUMBER_STYLE, fontFamily: this.font }));
130
129
  }
131
- if (this.barNumbering) {
130
+ if (this.barNumbering)
132
131
  registerBarNumbering(ctx, this.barNumbering, this.font);
133
- }
134
132
  return [];
135
133
  }
136
134
  toString() {
137
135
  if (!this.config)
138
136
  return "@page()";
139
- const { width, height, marginTop, marginBottom, marginLeft, marginRight, lineGap, fillRatio } = this.config;
140
- return `@page(width=${width}px, height=${Number.isFinite(height) ? height : 0}px, top=${marginTop}px, bottom=${marginBottom}px, left=${marginLeft}px, right=${marginRight}px, gap=${lineGap}px, numbering=${quote(this.numbering)}, barNumbering=${quote(this.barNumbering)}, font=${quote(this.font)}, fillRatio=${fillRatio})`;
137
+ const { width, height, marginTop, marginBottom, marginLeft, marginRight, lineGap, minLineGap, fillRatio } = this.config;
138
+ return `@page(width=${width}px, height=${Number.isFinite(height) ? height : 0}px, top=${marginTop}px, bottom=${marginBottom}px, left=${marginLeft}px, right=${marginRight}px, gap=${lineGap}px, minGap=${minLineGap}px, numbering=${quote(this.numbering)}, barNumbering=${quote(this.barNumbering)}, font=${quote(this.font)}, fillRatio=${fillRatio})`;
141
139
  }
142
140
  }
143
141
  export const PageNode = PageFunction;
@@ -40,6 +40,7 @@ class RestFunction extends ASTFunctionNode {
40
40
  width;
41
41
  size;
42
42
  font;
43
+ weight;
43
44
  constructor(span, args, ctx, parent = null) {
44
45
  super(span, parent);
45
46
  const [count, width, size] = this.getArgValue(args, ctx);
@@ -53,6 +54,7 @@ class RestFunction extends ASTFunctionNode {
53
54
  throw new ErrorDiagnostic("E_REST_SIZE", "@rest 的 width 必须有限且非负,size 必须有限且为正", span);
54
55
  }
55
56
  this.font = ctx.variables.numberfont;
57
+ this.weight = ctx.variables.numberweight;
56
58
  }
57
59
  // 可以被 volta 这样的标记
58
60
  labelable() { return this; }
@@ -75,10 +77,8 @@ class RestFunction extends ASTFunctionNode {
75
77
  if (!(node.ast instanceof ASTFunctionNode)
76
78
  || (node.ast.callName !== "note" && node.ast.callName !== "dash"))
77
79
  continue;
78
- let host = node;
79
80
  // 沿折叠链找到最外层宿主,将内部成员归到同一主体
80
- while (host.foldedInto)
81
- host = host.foldedInto;
81
+ const host = node.rootHost;
82
82
  // 私有倚音属于独立轨道,不代表外层宿主的休止或起音
83
83
  if (node.track !== host.track)
84
84
  continue;
@@ -141,7 +141,7 @@ class RestTemporal extends TemporalNodeBase {
141
141
  this.mergeKey = REST_KEY;
142
142
  restsByHost.set(this, this);
143
143
  this.initLayoutBox();
144
- this.textStyle = { fontSize: ast.size, fontFamily: ast.font, textAlign: "center" };
144
+ this.textStyle = { fontSize: ast.size, fontFamily: ast.font, fontWeight: ast.weight, textAlign: "center" };
145
145
  }
146
146
  onTimeState(state) {
147
147
  const measure = state.meter;
@@ -153,7 +153,7 @@ class RestTemporal extends TemporalNodeBase {
153
153
  }
154
154
  this.measureDuration.copyFrom(measure);
155
155
  this.T.copyFrom(measure).mul(this.ast.count);
156
- const host = state.currentEvent ?? this;
156
+ const host = this.rootHost;
157
157
  // 只登记全局休止宿主的同轨成员,私有倚音不接管宿主。
158
158
  if (host.mergeKey === REST_KEY && this.track === host.track) {
159
159
  const rest = restsByHost.get(host);
@@ -220,14 +220,14 @@ class RestTemporal extends TemporalNodeBase {
220
220
  paint(painter) {
221
221
  const { size, count } = this.ast;
222
222
  const left = this.box.x;
223
- const right = left + this.lineWidth;
224
223
  const axis = this.box.y + this.box.visualAxis;
225
224
  const stroke = size * 0.12;
226
225
  const barStroke = stroke * 2;
227
- const halfCap = (size * 0.65 - stroke) / 2;
228
- painter.drawLine(left + barStroke / 2, axis, right - barStroke / 2, axis, { strokeWidth: barStroke });
229
- painter.drawLine(left + stroke / 2, axis - halfCap, left + stroke / 2, axis + halfCap, { strokeWidth: stroke });
230
- painter.drawLine(right - stroke / 2, axis - halfCap, right - stroke / 2, axis + halfCap, { strokeWidth: stroke });
226
+ const capHeight = size * 0.65;
227
+ const style = { fill: "#000" };
228
+ painter.drawRect(left, axis - barStroke / 2, this.lineWidth, barStroke, style);
229
+ painter.drawRect(left, axis - capHeight / 2, stroke, capHeight, style);
230
+ painter.drawRect(left + this.lineWidth - stroke, axis - capHeight / 2, stroke, capHeight, style);
231
231
  painter.drawText(String(count), left + this.lineWidth / 2, this.box.y + this.metrics.baseline, this.textStyle);
232
232
  }
233
233
  }
@@ -22,7 +22,6 @@ class SlideFunction extends ASTFunctionNode {
22
22
  side;
23
23
  direction;
24
24
  get children() { return [this.content]; }
25
- timeFlowModel() { return { children: this.children, mode: "sequence" }; }
26
25
  labelable() { return ASTFunctionNode.findLabelable(this.content); }
27
26
  constructor(span, args, ctx, parent = null) {
28
27
  super(span, parent);
@@ -82,6 +81,7 @@ export const SlideNode = SlideFunction;
82
81
  class SlideAttachment {
83
82
  host;
84
83
  owner;
84
+ kind = "slide";
85
85
  layer = "foreground";
86
86
  endPoints;
87
87
  get sourceSpan() { return this.owner.sourceSpan; }