jpfun 0.9.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 (104) 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/arpeggio/index.js +2 -3
  5. package/dist/functions/bar/index.d.ts +3 -0
  6. package/dist/functions/bar/index.js +18 -3
  7. package/dist/functions/beam/layout.js +3 -2
  8. package/dist/functions/box/index.js +1 -0
  9. package/dist/functions/dash/index.js +5 -2
  10. package/dist/functions/div/index.d.ts +1 -1
  11. package/dist/functions/div/index.js +4 -2
  12. package/dist/functions/dyn/index.js +1 -0
  13. package/dist/functions/gliss/index.js +4 -2
  14. package/dist/functions/grace/index.js +3 -5
  15. package/dist/functions/head/index.js +23 -30
  16. package/dist/functions/key/index.js +4 -7
  17. package/dist/functions/meter/index.d.ts +1 -0
  18. package/dist/functions/meter/index.js +3 -0
  19. package/dist/functions/meter/shape.d.ts +1 -1
  20. package/dist/functions/note/accidentals.d.ts +3 -3
  21. package/dist/functions/note/accidentals.js +29 -16
  22. package/dist/functions/note/index.js +11 -13
  23. package/dist/functions/note/source-transform.d.ts +15 -0
  24. package/dist/functions/note/source-transform.js +74 -67
  25. package/dist/functions/ottava/index.js +1 -0
  26. package/dist/functions/page/index.js +4 -3
  27. package/dist/functions/rest/index.js +8 -6
  28. package/dist/functions/slide/index.js +1 -0
  29. package/dist/functions/temporal.d.ts +9 -3
  30. package/dist/functions/temporal.js +15 -2
  31. package/dist/functions/tie/index.js +28 -4
  32. package/dist/functions/tremolo/index.js +1 -0
  33. package/dist/functions/tuplet/index.js +1 -0
  34. package/dist/functions/up/index.js +3 -5
  35. package/dist/functions/voice/connections.d.ts +1 -1
  36. package/dist/functions/voice/lyrics.d.ts +9 -5
  37. package/dist/functions/voice/lyrics.js +148 -44
  38. package/dist/functions/voice/voice.d.ts +6 -2
  39. package/dist/functions/voice/voice.js +49 -17
  40. package/dist/functions/voice/voices.js +2 -1
  41. package/dist/functions/volta/index.js +1 -0
  42. package/dist/index.d.ts +97 -3
  43. package/dist/index.js +97 -3
  44. package/dist/jpfun.min.js +47 -60
  45. package/dist/layout/engine.d.ts +4 -3
  46. package/dist/layout/engine.js +160 -6
  47. package/dist/layout/model.d.ts +12 -3
  48. package/dist/layout/model.js +15 -7
  49. package/dist/layout/page.js +2 -2
  50. package/dist/layout/path.js +1 -1
  51. package/dist/layout/types.d.ts +10 -2
  52. package/dist/parser/grammarType.d.ts +3 -3
  53. package/dist/parser/parse-utils/brace-utils.js +7 -17
  54. package/dist/parser/parse-utils/call-utils.d.ts +3 -1
  55. package/dist/parser/parse-utils/call-utils.js +17 -32
  56. package/dist/parser/parse-utils/note-utils.d.ts +4 -0
  57. package/dist/parser/parse-utils/note-utils.js +8 -12
  58. package/dist/parser/parserContext.d.ts +8 -2
  59. package/dist/parser/parserContext.js +57 -55
  60. package/dist/parser/preprocess.d.ts +7 -0
  61. package/dist/parser/preprocess.js +21 -19
  62. package/dist/pipeline.d.ts +1 -1
  63. package/dist/playback/compile.js +1 -1
  64. package/dist/render/canvas.js +50 -35
  65. package/dist/render/index.d.ts +1 -1
  66. package/dist/render/index.js +1 -1
  67. package/dist/render/paint.d.ts +7 -0
  68. package/dist/render/paint.js +70 -20
  69. package/dist/render/recording.d.ts +8 -1
  70. package/dist/render/recording.js +12 -0
  71. package/dist/render/svg.d.ts +5 -1
  72. package/dist/render/svg.js +37 -17
  73. package/dist/render/text.d.ts +2 -2
  74. package/dist/render/text.js +7 -6
  75. package/dist/render/translate.d.ts +3 -1
  76. package/dist/render/translate.js +6 -0
  77. package/dist/render/types.d.ts +9 -0
  78. package/grammar.md +6 -5
  79. package/package.json +8 -18
  80. package/dist/converter/midi/convert.d.ts +0 -42
  81. package/dist/converter/midi/convert.js +0 -682
  82. package/dist/converter/midi/index.d.ts +0 -5
  83. package/dist/converter/midi/index.js +0 -11
  84. package/dist/converter/midi/json.d.ts +0 -38
  85. package/dist/converter/midi/json.js +0 -1
  86. package/dist/converter/midi/triplet.d.ts +0 -30
  87. package/dist/converter/midi/triplet.js +0 -75
  88. package/dist/converter/musicxml/dom.d.ts +0 -25
  89. package/dist/converter/musicxml/dom.js +0 -65
  90. package/dist/converter/musicxml/features.d.ts +0 -114
  91. package/dist/converter/musicxml/features.js +0 -501
  92. package/dist/converter/musicxml/index.d.ts +0 -14
  93. package/dist/converter/musicxml/index.js +0 -1285
  94. package/dist/converter/musicxml/model.d.ts +0 -176
  95. package/dist/converter/musicxml/model.js +0 -1
  96. package/dist/converter/musicxml/resolve.d.ts +0 -10
  97. package/dist/converter/musicxml/resolve.js +0 -152
  98. package/dist/converter/source.d.ts +0 -19
  99. package/dist/converter/source.js +0 -53
  100. package/dist/core.d.ts +0 -24
  101. package/dist/core.js +0 -24
  102. package/dist/jpfun.core.min.js +0 -132
  103. package/dist/jpfun.from-midi.min.js +0 -9
  104. 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;
@@ -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,13 +18,13 @@ 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 base = LETTERS.indexOf(note.keySignature[0]);
21
+ const base = NOTE_LETTERS.indexOf(note.keySignature[0]);
25
22
  const degree = Number(note.ast.name) - 1;
26
- name = LETTERS[(base + degree) % 7];
27
- 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]]);
28
25
  octave = Math.floor((tonic - tonicAcc) / 12) - 1 + Math.floor((base + degree) / 7)
29
26
  + note.ast.octave + note.ast.jeOctaveOffset;
30
- acc = accidental(midi - ((octave + 1) * 12 + NoteNameMap[name]));
27
+ acc = offsetToAccidental(midi - ((octave + 1) * 12 + NoteNameMap[name]));
31
28
  }
32
29
  else if (operation === "to-relative") {
33
30
  const ast = note.ast;
@@ -38,27 +35,32 @@ function targetPitch(note, operation) {
38
35
  }
39
36
  else {
40
37
  const value = absolute ? midi : midi - tonic;
41
- const pitch = spelling[mod(value, 12)];
42
- 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);
43
40
  acc = pitch.slice(1);
44
41
  octave = Math.floor(value / 12) - (absolute ? 1 : 0);
45
42
  }
46
43
  return { name, acc, octave: octave - note.ast.jeOctaveOffset, absolute };
47
44
  }
48
- /** 仅在函数参数的顶层保护低八度逗号;已有大括号内的简写无需再包装 */
49
- function needsBraces(masked, ast) {
45
+ /**
46
+ * 仅在函数参数的顶层保护低八度逗号;已有大括号内的简写无需再包装。
47
+ * 沿 AST 父链定位最近一层显式函数调用 `@call(...)` 及目标音符所属实参,
48
+ * 统计实参起点到音符前的 `{}` 深度(跳过双引号字符串字面量)。
49
+ */
50
+ export function needsBraces(masked, ast) {
50
51
  for (let parent = ast.parent; parent; parent = parent.parent) {
51
52
  const call = readCall(masked, parent.sourceSpan.start, parent.sourceSpan.end);
52
- if (!call)
53
- continue;
54
- 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
55
54
  && item.valueSpan.end >= ast.sourceSpan.end);
56
55
  if (!arg)
57
56
  continue;
58
57
  let depth = 0;
59
58
  for (let position = arg.valueSpan.start; position < ast.sourceSpan.start; position++) {
60
- if (masked[position] === '"')
61
- 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
+ }
62
64
  else if (masked[position] === "{")
63
65
  depth++;
64
66
  else if (masked[position] === "}")
@@ -68,24 +70,62 @@ function needsBraces(masked, ast) {
68
70
  }
69
71
  return false;
70
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
+ }
71
118
  /** edits 始终引用原文;参数只改值,默认参数只在当前调用覆盖,避免影响其他音符 */
72
119
  export function rewriteNotes(source, notes, operation, ranges) {
73
120
  const { maskedSource: masked } = preprocessSource(source);
74
121
  const edits = [];
75
122
  const tokens = [];
76
- function replace(span, text) {
77
- if (source.slice(span.start, span.end) === text)
78
- return;
79
- if (source.slice(span.start, span.end) !== masked.slice(span.start, span.end))
80
- fail(span);
81
- edits.push({ span, text });
82
- }
83
123
  for (const note of notes) {
84
124
  const { ast } = note;
85
125
  const span = ast.sourceSpan;
86
126
  const call = readCall(masked, span.start, span.end);
87
127
  const explicit = call?.span.end === span.end && call.closeParenSpan;
88
- const already = operation === "to-absolute" && LETTERS.includes(ast.name)
128
+ const already = operation === "to-absolute" && NOTE_LETTERS.includes(ast.name)
89
129
  || operation === "to-relative" && /^[1-7]$/.test(ast.name);
90
130
  if (!explicit)
91
131
  tokens.push({ span, text: source.slice(span.start, span.end) });
@@ -94,47 +134,14 @@ export function rewriteNotes(source, notes, operation, ranges) {
94
134
  if (note.resolvedMidi === null || already)
95
135
  continue;
96
136
  const pitch = targetPitch(note, operation);
97
- const octaveText = pitch.absolute ? String(pitch.octave)
98
- : pitch.octave < 0 ? ",".repeat(-pitch.octave) : "'".repeat(pitch.octave);
99
- const nameText = (acc, octave) => pitch.absolute
100
- ? pitch.name + acc + octave : acc + pitch.name + octave;
101
- if (!explicit) {
102
- let text = nameText(pitch.acc, octaveText);
103
- if (text.includes(",") && needsBraces(masked, ast))
104
- text = `{${text}}`;
105
- tokens[tokens.length - 1].text = text;
137
+ if (explicit) {
138
+ rewriteNoteCall(source, masked, call, pitch, ast.hasDefaultAcc, edits);
106
139
  continue;
107
140
  }
108
- const slots = new Map();
109
- call.args.forEach((arg, index) => {
110
- if (arg.valueSpan.start === arg.valueSpan.end)
111
- return;
112
- slots.set(arg.nameSpan ? masked.slice(arg.nameSpan.start, arg.nameSpan.end).toLowerCase() : index, arg.valueSpan);
113
- });
114
- const nameSlot = slots.get("name") ?? slots.get(0);
115
- const accSlot = slots.get("acc") ?? slots.get(1);
116
- const octaveSlot = slots.get("octave") ?? slots.get(2);
117
- const additions = [];
118
- function write(slot, name, value) {
119
- const text = !value || value.includes(",")
120
- || slot && source[slot.start] === '"' ? quote(value) : value;
121
- if (slot)
122
- replace(slot, text);
123
- else
124
- additions.push(`${name}=${text}`);
125
- }
126
- write(nameSlot, "name", nameText(accSlot ? "" : pitch.acc, octaveSlot ? "" : octaveText));
127
- if (accSlot)
128
- write(accSlot, "acc", pitch.acc);
129
- else if (ast.hasDefaultAcc)
130
- additions.push('acc=""');
131
- if (octaveSlot)
132
- replace(octaveSlot, String(pitch.octave));
133
- if (additions.length) {
134
- const at = call.closeParenSpan.start;
135
- const prefix = masked.slice(call.openParenSpan.end, at).trimEnd();
136
- replace({ start: at, end: at }, (prefix ? prefix.endsWith(",") ? " " : ", " : "") + additions.join(", "));
137
- }
141
+ let text = pitchToken(pitch);
142
+ if (text.includes(",") && needsBraces(masked, ast))
143
+ text = `{${text}}`;
144
+ tokens[tokens.length - 1].text = text;
138
145
  }
139
146
  // 相邻原子改写后仍须是两个音符,例如 C4D4 -> C4 2,不能合并成 C42。
140
147
  tokens.sort((left, right) => left.span.start - right.span.start);
@@ -152,7 +159,7 @@ export function rewriteNotes(source, notes, operation, ranges) {
152
159
  }
153
160
  }
154
161
  for (const token of tokens)
155
- replace(token.span, token.text);
162
+ pushEdit(edits, source, masked, token.span, token.text);
156
163
  edits.sort((left, right) => left.span.start - right.span.start);
157
164
  for (let index = 1; index < edits.length; index++) {
158
165
  if (edits[index - 1].span.end > edits[index].span.start)
@@ -115,6 +115,7 @@ class OttavaFunction extends ASTFunctionNode {
115
115
  export const OttavaNode = OttavaFunction;
116
116
  class OttavaAttachment {
117
117
  ast;
118
+ kind = "ottava";
118
119
  layer = "foreground";
119
120
  endPoints;
120
121
  constructor(ast, from, to) {
@@ -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, minGap=0.5em, 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
  ~~~
@@ -65,7 +66,7 @@ export class PageFunction extends ASTFunctionNode {
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
68
  { name: "gap", description: "谱面行主旋律之间的标准间距", type: "length", default: { value: 1, unit: "em" } },
68
- { name: "minGap", description: "行间保留的最小间距", type: "length", default: { value: 0.5, unit: "em" } },
69
+ { name: "minGap", description: "行间保留的最小间距", type: "length", default: { value: 0.4, unit: "em" } },
69
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: "" },
@@ -120,7 +121,7 @@ export class PageFunction extends ASTFunctionNode {
120
121
  this.barNumbering = barNumbering;
121
122
  }
122
123
  loweringEnter(ctx) {
123
- if (!ctx || !this.config)
124
+ if (!this.config)
124
125
  return [];
125
126
  ctx.setPageConfig(this.config);
126
127
  if (this.numbering) {
@@ -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; }
@@ -139,7 +141,7 @@ class RestTemporal extends TemporalNodeBase {
139
141
  this.mergeKey = REST_KEY;
140
142
  restsByHost.set(this, this);
141
143
  this.initLayoutBox();
142
- this.textStyle = { fontSize: ast.size, fontFamily: ast.font, textAlign: "center" };
144
+ this.textStyle = { fontSize: ast.size, fontFamily: ast.font, fontWeight: ast.weight, textAlign: "center" };
143
145
  }
144
146
  onTimeState(state) {
145
147
  const measure = state.meter;
@@ -218,14 +220,14 @@ class RestTemporal extends TemporalNodeBase {
218
220
  paint(painter) {
219
221
  const { size, count } = this.ast;
220
222
  const left = this.box.x;
221
- const right = left + this.lineWidth;
222
223
  const axis = this.box.y + this.box.visualAxis;
223
224
  const stroke = size * 0.12;
224
225
  const barStroke = stroke * 2;
225
- const halfCap = (size * 0.65 - stroke) / 2;
226
- painter.drawLine(left + barStroke / 2, axis, right - barStroke / 2, axis, { strokeWidth: barStroke });
227
- painter.drawLine(left + stroke / 2, axis - halfCap, left + stroke / 2, axis + halfCap, { strokeWidth: stroke });
228
- 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);
229
231
  painter.drawText(String(count), left + this.lineWidth / 2, this.box.y + this.metrics.baseline, this.textStyle);
230
232
  }
231
233
  }
@@ -81,6 +81,7 @@ export const SlideNode = SlideFunction;
81
81
  class SlideAttachment {
82
82
  host;
83
83
  owner;
84
+ kind = "slide";
84
85
  layer = "foreground";
85
86
  endPoints;
86
87
  get sourceSpan() { return this.owner.sourceSpan; }
@@ -2,7 +2,7 @@
2
2
  * 时间线事件的基类
3
3
  * 由 AST 产生,跨越 lowering / layout / playback 三个阶段
4
4
  */
5
- import type { ASTNodeBase } from "./ASTtypes.js";
5
+ import { type ASTNodeBase } from "./ASTtypes.js";
6
6
  import { Fraction } from "../fraction.js";
7
7
  import type { HorizontalSpringConfig, LayoutBox, LayoutDecoration, LayoutHost, LayoutPoint, LayoutPrepareContext, HorizontalLineView, TimeLineEvent } from "../layout/types.js";
8
8
  import type { Track } from "../lowering/track.js";
@@ -75,6 +75,12 @@ export declare class TemporalNodeBase implements TimeLineEvent {
75
75
  foldedInto?: TemporalNodeBase;
76
76
  /** 沿 foldedInto 上溯到最外层宿主(未折叠时返回自身) */
77
77
  get rootHost(): TemporalNodeBase;
78
+ /**
79
+ * 绘制分组的语义类型,渲染器据此输出 `<g data-kind>`;空串表示不开组。
80
+ *
81
+ * 缺省取来源函数的主名,同一函数生成的对象画法不同时由子类覆盖。
82
+ */
83
+ get kind(): string;
78
84
  /** 由 LoweringContext 在列归并后固化的谱面行号 */
79
85
  layoutLine: number;
80
86
  /** 不可见状态事件保持 undefined */
@@ -96,7 +102,7 @@ export declare class TemporalNodeBase implements TimeLineEvent {
96
102
  * - tie.top:连音线端点;缺省为 anchor 与内容上沿,up 提供最上层成员的端点。
97
103
  * - div.{level}.left / div.{level}.right:从 0 编号的减时线端点,由 div.place 发布,供 beam 接管。
98
104
  * - dot:附点起点;缺省为盒右边界与 visualAxis,音符覆盖为字形附近的位置。
99
- * - lyric:歌词对齐点(voice 只读 x);未提供则不作为歌词目标,note 在 finalizeLayout 发布。
105
+ * - lyric:歌词对齐点(voice 只读 x);未提供则不作为歌词目标,note 与 dash 在 finalizeLayout 发布。
100
106
  * - bar.number:多声部连谱号顶部的行首小节号锚点。
101
107
  *
102
108
  * up、grace、arpeggio 转发宿主端口并换算局部坐标;端口不表达装饰是否存在。
@@ -113,7 +119,7 @@ export declare class TemporalNodeBase implements TimeLineEvent {
113
119
  * 2. Temporal.prepareLayout 可先加入节点自身的装饰,例如下八度点;
114
120
  * 3. 引擎再通过 addon 对应的 layoutDecorationHandler 加入函数装饰;
115
121
  * 4. 引擎分别按 above/below.order 分配空间并调用 place
116
- * 5. 最终 paintLayout 在主体 paint 后调用可选的 decoration.paint
122
+ * 5. 最终 paintVisual 在主体 paint 后调用可选的 decoration.paint
117
123
  *
118
124
  * 数组必须保留到绘制结束,因为 decoration 通常以闭包保存本次测量得到的几何。它只属于当前 layout pass,不能跨 pass 复用。
119
125
  * prepare 阶段生成、place 后冻结、paint 后失效
@@ -1,3 +1,8 @@
1
+ /**
2
+ * 时间线事件的基类
3
+ * 由 AST 产生,跨越 lowering / layout / playback 三个阶段
4
+ */
5
+ import { ASTFunctionNode } from "./ASTtypes.js";
1
6
  import { Fraction } from "../fraction.js";
2
7
  export const DEFAULT_BPM = 120;
3
8
  export const DEFAULT_VELOCITY = 80;
@@ -48,6 +53,14 @@ export class TemporalNodeBase {
48
53
  host = host.foldedInto;
49
54
  return host;
50
55
  }
56
+ /**
57
+ * 绘制分组的语义类型,渲染器据此输出 `<g data-kind>`;空串表示不开组。
58
+ *
59
+ * 缺省取来源函数的主名,同一函数生成的对象画法不同时由子类覆盖。
60
+ */
61
+ get kind() {
62
+ return this.ast instanceof ASTFunctionNode ? this.ast.callName : "";
63
+ }
51
64
  /** 由 LoweringContext 在列归并后固化的谱面行号 */
52
65
  layoutLine = 0;
53
66
  /** 不可见状态事件保持 undefined */
@@ -67,7 +80,7 @@ export class TemporalNodeBase {
67
80
  * - tie.top:连音线端点;缺省为 anchor 与内容上沿,up 提供最上层成员的端点。
68
81
  * - div.{level}.left / div.{level}.right:从 0 编号的减时线端点,由 div.place 发布,供 beam 接管。
69
82
  * - dot:附点起点;缺省为盒右边界与 visualAxis,音符覆盖为字形附近的位置。
70
- * - lyric:歌词对齐点(voice 只读 x);未提供则不作为歌词目标,note 在 finalizeLayout 发布。
83
+ * - lyric:歌词对齐点(voice 只读 x);未提供则不作为歌词目标,note 与 dash 在 finalizeLayout 发布。
71
84
  * - bar.number:多声部连谱号顶部的行首小节号锚点。
72
85
  *
73
86
  * up、grace、arpeggio 转发宿主端口并换算局部坐标;端口不表达装饰是否存在。
@@ -84,7 +97,7 @@ export class TemporalNodeBase {
84
97
  * 2. Temporal.prepareLayout 可先加入节点自身的装饰,例如下八度点;
85
98
  * 3. 引擎再通过 addon 对应的 layoutDecorationHandler 加入函数装饰;
86
99
  * 4. 引擎分别按 above/below.order 分配空间并调用 place
87
- * 5. 最终 paintLayout 在主体 paint 后调用可选的 decoration.paint
100
+ * 5. 最终 paintVisual 在主体 paint 后调用可选的 decoration.paint
88
101
  *
89
102
  * 数组必须保留到绘制结束,因为 decoration 通常以闭包保存本次测量得到的几何。它只属于当前 layout pass,不能跨 pass 复用。
90
103
  * prepare 阶段生成、place 后冻结、paint 后失效
@@ -4,8 +4,8 @@ import { isVisualTemporalNode, } from "../temporal.js";
4
4
  import { pathBounds } from "../../layout/path.js";
5
5
  import { getLayoutBounds } from "../../layout/engine.js";
6
6
  import { lineEntryX, lineRightX } from "../../layout/range.js";
7
- /** 仅索引被 @tie 引用过的端点,避免为全谱无关音符分配数组与 Map 节点 */
8
- const tieEndpoints = new WeakSet();
7
+ /** 被 @tie 引用过的端点 → 其上各连音线的最大弧高;播放也只索引这些端点,避免为全谱无关音符分配数组与 Map 节点 */
8
+ const tieEndpoints = new WeakMap();
9
9
  const notesByOriginNode = new WeakMap();
10
10
  function endpointNotes(notes, endpoint) {
11
11
  let index = notesByOriginNode.get(notes);
@@ -107,6 +107,7 @@ class TieFunction extends ASTFunctionNode {
107
107
  }
108
108
  export const TieNode = TieFunction;
109
109
  class TieLayoutAttachment {
110
+ kind = "tie";
110
111
  layer = "foreground";
111
112
  sourceSpan;
112
113
  endPoints;
@@ -116,8 +117,31 @@ class TieLayoutAttachment {
116
117
  thickness;
117
118
  constructor(endPoints, height, sourceSpan) {
118
119
  this.endPoints = endPoints;
119
- for (const endpoint of endPoints)
120
- tieEndpoints.add(endpoint);
120
+ // 跨轨弧线必然穿过两轨之间,加高端点留空只会撑开轨距,因此只有同轨连音线按显式弧高留空
121
+ const fixed = endPoints.every(endpoint => endpoint.track === endPoints[0].track) ? height : 0;
122
+ for (const endpoint of endPoints) {
123
+ const peak = tieEndpoints.get(endpoint);
124
+ tieEndpoints.set(endpoint, Math.max(peak ?? 0, fixed || endpoint.ast.size * AUTO_HEIGHT_RATIO));
125
+ if (peak !== undefined)
126
+ continue;
127
+ const prepareLayout = endpoint.prepareLayout;
128
+ endpoint.prepareLayout = context => {
129
+ prepareLayout.call(endpoint, context);
130
+ const size = endpoint.ast.size;
131
+ const left = endpoint.ports["body.left"]?.x ?? 0;
132
+ const right = endpoint.ports["body.right"]?.x ?? endpoint.box.w;
133
+ const halfWidth = Math.max(0, endpoint.box.anchor - left, right - endpoint.box.anchor);
134
+ const u = Math.min(0.5, halfWidth / (size * AUTO_SPAN_RATIO));
135
+ let t = Math.min(0.5, u / 0.75);
136
+ t = u / (0.75 * (1 + 2 * t * (1 - t)));
137
+ t = Math.min(0.5, u / (0.75 * (1 + 2 * t * (1 - t))));
138
+ // 上方留空使用没有 paint 的纯留白 decoration,以实现 tie 的避让效果,且 box 会忽略纯留白
139
+ // 横排前跨度未知,按参考跨度估算弧线经过主体边缘时的高度,弧高取该端点上各连音线的最大值
140
+ endpoint.decorations.push({
141
+ above: { order: 200, height: size * 0.1 + 4 * t * (1 - t) * tieEndpoints.get(endpoint) },
142
+ });
143
+ };
144
+ }
121
145
  this.height = height;
122
146
  this.sourceSpan = sourceSpan;
123
147
  this.size = endPoints.reduce((current, endpoint) => Math.max(current, endpoint.ast.size), 0);
@@ -145,6 +145,7 @@ export const TremoloNode = TremoloFunction;
145
145
  class TremoloAttachment {
146
146
  nodes;
147
147
  owner;
148
+ kind = "tremolo";
148
149
  layer = "foreground";
149
150
  endPoints;
150
151
  get sourceSpan() { return this.owner.sourceSpan; }
@@ -120,6 +120,7 @@ export const TupletNode = TupletFunction;
120
120
  */
121
121
  class TupletLayoutAttachment {
122
122
  content;
123
+ kind = "tuplet";
123
124
  layer = "foreground";
124
125
  /** lowering 固化的连音语义;重复 layout 时保持不变 */
125
126
  endPoints;
@@ -3,6 +3,7 @@ import { ErrorDiagnostic } from "../../diagnostic.js";
3
3
  import { ANCHOR_KEY, DEFAULT_KEY, transferFunctionAddons, isVisualTemporalNode, TemporalNodeBase, } from "../temporal.js";
4
4
  import { Fraction } from "../../fraction.js";
5
5
  import { getLayoutBounds, layoutLocalSequence } from "../../layout/engine.js";
6
+ import { paintVisual } from "../../render/paint.js";
6
7
  const FOLD_ARGS = [{
7
8
  name: "gap",
8
9
  namedOnly: true,
@@ -380,10 +381,7 @@ class FoldTemporal extends TemporalNodeBase {
380
381
  }
381
382
  }
382
383
  paint(painter) {
383
- for (const member of this.members) {
384
- member.paint(painter);
385
- for (const decoration of member.decorations)
386
- decoration.paint?.(painter);
387
- }
384
+ for (const member of this.members)
385
+ paintVisual(painter, member);
388
386
  }
389
387
  }
@@ -1,7 +1,7 @@
1
1
  import type { SourceSpan } from "../ASTtypes.js";
2
2
  import type { PathCommand } from "../../render/types.js";
3
3
  export declare const CURVED_BRACE_COMMANDS: readonly PathCommand[];
4
- export declare const CURVED_BRACE_BOUNDS: import("../../core.js").Rect;
4
+ export declare const CURVED_BRACE_BOUNDS: import("../../index.js").Rect;
5
5
  /** 方括线端钩,以粗竖线宽度为单位,绘制时上下镜像 */
6
6
  export declare const BRACKET_HOOK_REACH = 2.33;
7
7
  export declare const BRACKET_HOOK_DROP = 1.17;
@@ -1,25 +1,29 @@
1
1
  import type { AttachmentLayoutContext, HorizontalLineView, LayoutAttachment, LayoutPrepareContext, LayoutRegion } from "../../layout/types.js";
2
+ import type { SourceSpan } from "../../parser/types.js";
2
3
  import { type PreparedRichLine, type RichTextRun } from "../../render/text.js";
3
4
  import type { Painter, TextStyle } from "../../render/types.js";
4
5
  import type { VisualTemporalNode } from "../temporal.js";
5
6
  import type { VoiceNameTemporal } from "./voice.js";
6
7
  /** 歌词与歌词行名称相对声部字号的字号 */
7
- export declare const LYRIC_SIZE_RATIO = 0.82;
8
+ export declare const LYRIC_SIZE_RATIO = 0.88;
8
9
  /** 歌词行名称与歌词正文共用同一个基础样式 */
9
10
  export declare function lyricNameStyle(size: number, fontFamily: string): TextStyle;
11
+ export type LyricSlot = RichTextRun[] | null;
10
12
  /**
11
13
  * 把歌词拆成与音符一一对应的富文本槽位,同时支持跨槽或槽内的 Markdown 样式(`**`、`*`、`_`、`^`)。
12
14
  * 例如 `hello world` 拆成 `hello`、`world`,`hel-lo` 拆成 `hel-`、`lo`;
13
- * `你好吗` 默认逐字拆分,`你 @ 好` 中的 `@` 留出一个空槽,`{你好} 啊` 则把 `你好` 放在同一个槽位。
15
+ * `你好吗` 默认逐字拆分,`你 @ 好` 中的 `@` 留出一个空槽,
16
+ * `{你好} 啊` 把 `你好` 放在同一个槽位,`{a@@}` 则左对齐并覆盖三个槽位(后续槽记为 `null`)。
14
17
  */
15
- export declare function parseLyric(value: string): RichTextRun[][];
16
- export declare function serializeLyric(tokens: readonly (readonly RichTextRun[])[]): string;
18
+ export declare function parseLyric(value: string, offsets?: readonly number[], tokenSpans?: (SourceSpan | undefined)[]): LyricSlot[];
19
+ export declare function serializeLyric(tokens: readonly (readonly RichTextRun[] | null)[]): string;
17
20
  export declare class VoiceLyricsAttachment implements LayoutAttachment {
18
21
  private readonly nodes;
19
22
  private readonly nameHost;
20
23
  private readonly frames;
24
+ readonly kind = "lyrics";
21
25
  layer: "foreground";
22
- get sourceSpan(): import("../ASTtypes.js").SourceSpan;
26
+ get sourceSpan(): SourceSpan;
23
27
  constructor(nodes: readonly VisualTemporalNode[], nameHost: VoiceNameTemporal, frames: readonly LayoutAttachment[]);
24
28
  prepareHorizontal(lines: HorizontalLineView[], context: LayoutPrepareContext): void;
25
29
  createGeometry(context: AttachmentLayoutContext): {