jpfun 0.9.0 → 1.1.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 (125) hide show
  1. package/README.md +11 -16
  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 +21 -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/default.js +2 -1
  11. package/dist/functions/div/index.d.ts +1 -1
  12. package/dist/functions/div/index.js +4 -2
  13. package/dist/functions/dyn/index.js +1 -0
  14. package/dist/functions/gliss/index.js +85 -9
  15. package/dist/functions/grace/index.d.ts +1 -8
  16. package/dist/functions/grace/index.js +23 -53
  17. package/dist/functions/head/index.js +23 -30
  18. package/dist/functions/key/index.js +5 -7
  19. package/dist/functions/meter/index.d.ts +1 -0
  20. package/dist/functions/meter/index.js +3 -0
  21. package/dist/functions/meter/shape.d.ts +1 -1
  22. package/dist/functions/note/accidentals.d.ts +3 -3
  23. package/dist/functions/note/accidentals.js +29 -16
  24. package/dist/functions/note/index.d.ts +5 -2
  25. package/dist/functions/note/index.js +168 -25
  26. package/dist/functions/note/source-transform.d.ts +23 -2
  27. package/dist/functions/note/source-transform.js +95 -74
  28. package/dist/functions/ottava/index.js +1 -0
  29. package/dist/functions/page/index.d.ts +1 -36
  30. package/dist/functions/page/index.js +8 -7
  31. package/dist/functions/rest/index.js +8 -6
  32. package/dist/functions/set/index.js +2 -2
  33. package/dist/functions/slide/index.js +1 -0
  34. package/dist/functions/stack/index.js +6 -4
  35. package/dist/functions/temporal.d.ts +12 -3
  36. package/dist/functions/temporal.js +15 -2
  37. package/dist/functions/text/index.js +2 -2
  38. package/dist/functions/tie/index.js +28 -4
  39. package/dist/functions/tremolo/index.js +1 -0
  40. package/dist/functions/tuplet/index.js +1 -0
  41. package/dist/functions/up/index.js +12 -12
  42. package/dist/functions/voice/connections.d.ts +1 -1
  43. package/dist/functions/voice/connections.js +2 -2
  44. package/dist/functions/voice/lyrics.d.ts +11 -5
  45. package/dist/functions/voice/lyrics.js +151 -47
  46. package/dist/functions/voice/voice.d.ts +6 -2
  47. package/dist/functions/voice/voice.js +51 -19
  48. package/dist/functions/voice/voices.d.ts +2 -1
  49. package/dist/functions/voice/voices.js +4 -3
  50. package/dist/functions/volta/index.js +1 -0
  51. package/dist/index.d.ts +69 -3
  52. package/dist/index.js +69 -3
  53. package/dist/jpfun.min.js +47 -60
  54. package/dist/layout/engine.d.ts +4 -3
  55. package/dist/layout/engine.js +173 -27
  56. package/dist/layout/model.d.ts +13 -4
  57. package/dist/layout/model.js +15 -7
  58. package/dist/layout/page.js +2 -2
  59. package/dist/layout/path.js +1 -1
  60. package/dist/layout/types.d.ts +12 -3
  61. package/dist/lowering/accidentalMemory.d.ts +33 -0
  62. package/dist/lowering/accidentalMemory.js +84 -0
  63. package/dist/lowering/loweringContext.js +4 -0
  64. package/dist/parser/grammarType.d.ts +8 -3
  65. package/dist/parser/parse-utils/brace-utils.js +7 -17
  66. package/dist/parser/parse-utils/call-utils.d.ts +3 -1
  67. package/dist/parser/parse-utils/call-utils.js +17 -32
  68. package/dist/parser/parse-utils/note-utils.d.ts +4 -0
  69. package/dist/parser/parse-utils/note-utils.js +8 -12
  70. package/dist/parser/parse-utils/string-utils.d.ts +1 -1
  71. package/dist/parser/parse-utils/string-utils.js +1 -1
  72. package/dist/parser/parserContext.d.ts +32 -26
  73. package/dist/parser/parserContext.js +104 -194
  74. package/dist/parser/preprocess.d.ts +7 -0
  75. package/dist/parser/preprocess.js +31 -42
  76. package/dist/parser/syntax.d.ts +9 -0
  77. package/dist/parser/syntax.js +109 -0
  78. package/dist/pipeline.d.ts +1 -1
  79. package/dist/pipeline.js +3 -2
  80. package/dist/playback/compile.js +5 -7
  81. package/dist/playback/event.d.ts +1 -2
  82. package/dist/playback/event.js +2 -3
  83. package/dist/render/canvas.js +50 -35
  84. package/dist/render/index.d.ts +2 -1
  85. package/dist/render/index.js +2 -1
  86. package/dist/render/paint.d.ts +7 -0
  87. package/dist/render/paint.js +70 -20
  88. package/dist/render/recording.d.ts +8 -1
  89. package/dist/render/recording.js +12 -0
  90. package/dist/render/svg.d.ts +5 -1
  91. package/dist/render/svg.js +37 -17
  92. package/dist/render/text.d.ts +2 -2
  93. package/dist/render/text.js +7 -6
  94. package/dist/render/translate.d.ts +3 -1
  95. package/dist/render/translate.js +6 -0
  96. package/dist/render/types.d.ts +9 -0
  97. package/grammar.md +7 -5
  98. package/package.json +8 -18
  99. package/dist/converter/midi/convert.d.ts +0 -42
  100. package/dist/converter/midi/convert.js +0 -682
  101. package/dist/converter/midi/index.d.ts +0 -5
  102. package/dist/converter/midi/index.js +0 -11
  103. package/dist/converter/midi/json.d.ts +0 -38
  104. package/dist/converter/midi/json.js +0 -1
  105. package/dist/converter/midi/triplet.d.ts +0 -30
  106. package/dist/converter/midi/triplet.js +0 -75
  107. package/dist/converter/musicxml/dom.d.ts +0 -25
  108. package/dist/converter/musicxml/dom.js +0 -65
  109. package/dist/converter/musicxml/features.d.ts +0 -114
  110. package/dist/converter/musicxml/features.js +0 -501
  111. package/dist/converter/musicxml/index.d.ts +0 -14
  112. package/dist/converter/musicxml/index.js +0 -1285
  113. package/dist/converter/musicxml/model.d.ts +0 -176
  114. package/dist/converter/musicxml/model.js +0 -1
  115. package/dist/converter/musicxml/resolve.d.ts +0 -10
  116. package/dist/converter/musicxml/resolve.js +0 -152
  117. package/dist/converter/source.d.ts +0 -19
  118. package/dist/converter/source.js +0 -53
  119. package/dist/core.d.ts +0 -24
  120. package/dist/core.js +0 -24
  121. package/dist/functions/voice/index.d.ts +0 -2
  122. package/dist/functions/voice/index.js +0 -2
  123. package/dist/jpfun.core.min.js +0 -132
  124. package/dist/jpfun.from-midi.min.js +0 -9
  125. package/dist/jpfun.from-musicxml.min.js +0 -12
@@ -1,19 +1,20 @@
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";
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";
3
+ import { callArgName, readCall } from "../../parser/parse-utils/call-utils.js";
4
+ import { findClosingQuote, quoteSourceString } from "../../parser/parse-utils/string-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
  }
10
+ /** 未传 ranges 视为全选;否则音符须完整落入任一选区 */
11
+ export function selects(ranges, span) {
12
+ return !ranges || ranges.some(range => range.start <= span.start && range.end >= span.end);
13
+ }
13
14
  /** 音高计算只读固化事实;互转保留调内级数,半音操作采用最少升降号的拼写 */
14
15
  function targetPitch(note, operation) {
15
16
  const absolute = operation === "to-absolute"
16
- || operation !== "to-relative" && LETTERS.includes(note.ast.name);
17
+ || operation !== "to-relative" && NOTE_LETTERS.includes(note.ast.name);
17
18
  const midi = note.resolvedMidi + (operation === "semitone-up" ? 1 : operation === "semitone-down" ? -1 : 0);
18
19
  const tonic = tonality2Midi(note.keySignature);
19
20
  if (![midi, tonic, note.ast.octave, note.ast.jeOctaveOffset].every(Number.isSafeInteger))
@@ -21,13 +22,13 @@ function targetPitch(note, operation) {
21
22
  const spelling = operation === "semitone-down" ? FLAT_NOTE_NAMES : SHARP_NOTE_NAMES;
22
23
  let name, acc, octave;
23
24
  if (operation === "to-absolute") {
24
- const base = LETTERS.indexOf(note.keySignature[0]);
25
+ const base = NOTE_LETTERS.indexOf(note.keySignature[0]);
25
26
  const degree = Number(note.ast.name) - 1;
26
- name = LETTERS[(base + degree) % 7];
27
- const tonicAcc = mod(tonic - NoteNameMap[LETTERS[base]] + 6, 12) - 6;
27
+ name = NOTE_LETTERS[(base + degree) % 7];
28
+ const tonicAcc = normalizeAccidentalOffset(tonic - NoteNameMap[NOTE_LETTERS[base]]);
28
29
  octave = Math.floor((tonic - tonicAcc) / 12) - 1 + Math.floor((base + degree) / 7)
29
30
  + note.ast.octave + note.ast.jeOctaveOffset;
30
- acc = accidental(midi - ((octave + 1) * 12 + NoteNameMap[name]));
31
+ acc = offsetToAccidental(midi - ((octave + 1) * 12 + NoteNameMap[name]));
31
32
  }
32
33
  else if (operation === "to-relative") {
33
34
  const ast = note.ast;
@@ -35,30 +36,37 @@ function targetPitch(note, operation) {
35
36
  if (!relative)
36
37
  fail(ast.sourceSpan);
37
38
  ({ renderName: name, renderAcc: acc, renderOctave: octave } = relative);
39
+ // carry 下按显示的记号写出,数字音名读回来音高不变
40
+ acc = note.displayAcc ?? acc;
38
41
  }
39
42
  else {
40
43
  const value = absolute ? midi : midi - tonic;
41
- const pitch = spelling[mod(value, 12)];
42
- name = absolute ? pitch[0] : String(LETTERS.indexOf(pitch[0]) + 1);
44
+ const pitch = spelling[wrapPitchClass(value)];
45
+ name = absolute ? pitch[0] : String(NOTE_LETTERS.indexOf(pitch[0]) + 1);
43
46
  acc = pitch.slice(1);
44
47
  octave = Math.floor(value / 12) - (absolute ? 1 : 0);
45
48
  }
46
49
  return { name, acc, octave: octave - note.ast.jeOctaveOffset, absolute };
47
50
  }
48
- /** 仅在函数参数的顶层保护低八度逗号;已有大括号内的简写无需再包装 */
49
- function needsBraces(masked, ast) {
51
+ /**
52
+ * 仅在函数参数的顶层保护低八度逗号;已有大括号内的简写无需再包装。
53
+ * 沿 AST 父链定位最近一层显式函数调用 `@call(...)` 及目标音符所属实参,
54
+ * 统计实参起点到音符前的 `{}` 深度(跳过双引号字符串字面量)。
55
+ */
56
+ export function needsBraces(masked, ast) {
50
57
  for (let parent = ast.parent; parent; parent = parent.parent) {
51
58
  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
59
+ const arg = call?.args.find(item => item.valueSpan.start <= ast.sourceSpan.start
55
60
  && item.valueSpan.end >= ast.sourceSpan.end);
56
61
  if (!arg)
57
62
  continue;
58
63
  let depth = 0;
59
64
  for (let position = arg.valueSpan.start; position < ast.sourceSpan.start; position++) {
60
- if (masked[position] === '"')
61
- position = findClosingQuote(masked, position, arg.valueSpan.end);
65
+ if (masked[position] === '"') {
66
+ const close = findClosingQuote(masked, position, arg.valueSpan.end);
67
+ if (close >= 0)
68
+ position = close;
69
+ }
62
70
  else if (masked[position] === "{")
63
71
  depth++;
64
72
  else if (masked[position] === "}")
@@ -68,73 +76,86 @@ function needsBraces(masked, ast) {
68
76
  }
69
77
  return false;
70
78
  }
71
- /** edits 始终引用原文;参数只改值,默认参数只在当前调用覆盖,避免影响其他音符 */
72
- export function rewriteNotes(source, notes, operation, ranges) {
79
+ /** 音高简写文本;省略的部分由显式实参提供 */
80
+ function pitchToken({ name, acc, octave, absolute }, withAcc = true, withOctave = true) {
81
+ const accText = withAcc ? acc : "";
82
+ const octaveText = !withOctave ? "" : absolute ? String(octave) : octave < 0 ? ",".repeat(-octave) : "'".repeat(octave);
83
+ return absolute ? name + accText + octaveText : accText + name + octaveText;
84
+ }
85
+ /** 只记录与原文不同的改写;被掩码的片段(如注释)无法安全改写 */
86
+ function pushEdit(edits, source, masked, span, text) {
87
+ const original = source.slice(span.start, span.end);
88
+ if (original === text)
89
+ return;
90
+ if (original !== masked.slice(span.start, span.end))
91
+ fail(span);
92
+ edits.push({ span, text });
93
+ }
94
+ /** 改写显式 `@note(...)` 的音高:已有实参只改值,缺失的追加为命名参数;存在默认 acc 时显式写出 acc 以覆盖它 */
95
+ export function rewriteNoteCall(source, masked, call, pitch, hasDefaultAcc, edits = []) {
96
+ const slots = new Map();
97
+ call.args.forEach((arg, index) => {
98
+ if (arg.valueSpan.start < arg.valueSpan.end)
99
+ slots.set(callArgName(masked, arg) ?? index, arg.valueSpan);
100
+ });
101
+ const nameSlot = slots.get("name") ?? slots.get(0);
102
+ const accSlot = slots.get("acc") ?? slots.get(1);
103
+ const octaveSlot = slots.get("octave") ?? slots.get(2);
104
+ const additions = [];
105
+ const valueText = (value, slot) => !value || value.includes(",") || slot && source[slot.start] === '"' ? quoteSourceString(value) : value;
106
+ // name 末尾的 `!`(force)不属于音高,原样保留
107
+ const bang = nameSlot && /!"?$/.test(source.slice(nameSlot.start, nameSlot.end)) ? "!" : "";
108
+ const name = pitchToken(pitch, !accSlot && !hasDefaultAcc, !octaveSlot) + bang;
109
+ if (nameSlot)
110
+ pushEdit(edits, source, masked, nameSlot, valueText(name, nameSlot));
111
+ else
112
+ additions.push(`name=${valueText(name)}`);
113
+ if (accSlot)
114
+ pushEdit(edits, source, masked, accSlot, valueText(pitch.acc, accSlot));
115
+ else if (hasDefaultAcc)
116
+ additions.push(`acc=${quoteSourceString(pitch.acc)}`);
117
+ if (octaveSlot)
118
+ pushEdit(edits, source, masked, octaveSlot, String(pitch.octave));
119
+ if (additions.length) {
120
+ const at = call.closeParenSpan.start;
121
+ const prefix = masked.slice(call.openParenSpan.end, at).trimEnd();
122
+ pushEdit(edits, source, masked, { start: at, end: at }, (prefix ? prefix.endsWith(",") ? " " : ", " : "") + additions.join(", "));
123
+ }
124
+ return edits;
125
+ }
126
+ /**
127
+ * edits 始终引用原文;参数只改值,默认参数只在当前调用覆盖,避免影响其他音符。
128
+ * pins 给指定音符强制写出升降号(升降半音后为保持 carry 下其他音高不变而补记)
129
+ */
130
+ export function rewriteNotes(source, notes, operation, ranges, pins) {
73
131
  const { maskedSource: masked } = preprocessSource(source);
74
132
  const edits = [];
75
133
  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
134
  for (const note of notes) {
84
135
  const { ast } = note;
85
136
  const span = ast.sourceSpan;
86
137
  const call = readCall(masked, span.start, span.end);
87
138
  const explicit = call?.span.end === span.end && call.closeParenSpan;
88
- const already = operation === "to-absolute" && LETTERS.includes(ast.name)
139
+ const already = operation === "to-absolute" && NOTE_LETTERS.includes(ast.name)
89
140
  || operation === "to-relative" && /^[1-7]$/.test(ast.name);
90
141
  if (!explicit)
91
142
  tokens.push({ span, text: source.slice(span.start, span.end) });
92
- if (ranges && !ranges.some(range => range.start <= span.start && range.end >= span.end))
93
- continue;
94
- if (note.resolvedMidi === null || already)
143
+ const pin = pins?.get(ast);
144
+ const selected = selects(ranges, span) && note.resolvedMidi !== null && !already;
145
+ if (!selected && pin === undefined)
95
146
  continue;
96
- 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;
147
+ const pitch = selected ? targetPitch(note, operation) : { name: ast.name, acc: ast.acc, octave: ast.octave, absolute: false };
148
+ if (pin !== undefined)
149
+ pitch.acc = pin;
150
+ if (explicit) {
151
+ rewriteNoteCall(source, masked, call, pitch, ast.hasDefaultAcc, edits);
106
152
  continue;
107
153
  }
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
- }
154
+ // 简写末尾的 `!`(force)不属于音高,原样保留
155
+ let text = pitchToken(pitch) + (source[span.end - 1] === "!" ? "!" : "");
156
+ if (text.includes(",") && needsBraces(masked, ast))
157
+ text = `{${text}}`;
158
+ tokens[tokens.length - 1].text = text;
138
159
  }
139
160
  // 相邻原子改写后仍须是两个音符,例如 C4D4 -> C4 2,不能合并成 C42。
140
161
  tokens.sort((left, right) => left.span.start - right.span.start);
@@ -152,7 +173,7 @@ export function rewriteNotes(source, notes, operation, ranges) {
152
173
  }
153
174
  }
154
175
  for (const token of tokens)
155
- replace(token.span, token.text);
176
+ pushEdit(edits, source, masked, token.span, token.text);
156
177
  edits.sort((left, right) => left.span.start - right.span.start);
157
178
  for (let index = 1; index < edits.length; index++) {
158
179
  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) {
@@ -1,37 +1,2 @@
1
- import type { LoweringContext } from "../../lowering/loweringContext.js";
2
- import type { PageConfig } from "../../layout/types.js";
3
- import { ASTFunctionNode, type ASTFunctionClass, type ASTNodeBase, type FunctionArgs, type LengthValue, type ParserContext, type SourceSpan } from "../ASTtypes.js";
4
- /** 页码字号,同时也是放得下页码所需的最小下边距 */
5
- export declare const PAGE_NUMBER_FONT_SIZE = 16;
6
- export declare class PageFunction extends ASTFunctionNode {
7
- static def: {
8
- name: string[];
9
- description: string;
10
- details: string;
11
- allowExtraArgs: boolean;
12
- args: ({
13
- name: string;
14
- description: string;
15
- type: "length";
16
- default: LengthValue;
17
- } | {
18
- name: string;
19
- description: string;
20
- type: "string";
21
- default: string;
22
- } | {
23
- name: string;
24
- description: string;
25
- type: "number";
26
- default: number;
27
- })[];
28
- };
29
- readonly config: PageConfig | null;
30
- private readonly numbering;
31
- private readonly barNumbering;
32
- readonly font: string;
33
- constructor(sourceSpan: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent?: ASTNodeBase | null);
34
- loweringEnter(ctx: LoweringContext): never[];
35
- toString(): string;
36
- }
1
+ import { type ASTFunctionClass } from "../ASTtypes.js";
37
2
  export declare const PageNode: ASTFunctionClass;
@@ -1,11 +1,11 @@
1
1
  import { DEFAULT_PAGE_CONFIG, normalizePageConfig, } from "../../layout/page.js";
2
2
  import { ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
3
- import { quote } from "../../parser/parse-utils/string-utils.js";
3
+ import { quoteSourceString } from "../../parser/parse-utils/string-utils.js";
4
4
  import { registerBarNumbering } from "../bar/index.js";
5
5
  import { ASTFunctionNode, } from "../ASTtypes.js";
6
6
  const px = (value) => ({ value, unit: "px" });
7
7
  /** 页码字号,同时也是放得下页码所需的最小下边距 */
8
- export const PAGE_NUMBER_FONT_SIZE = 16;
8
+ const PAGE_NUMBER_FONT_SIZE = 16;
9
9
  const PAGE_NUMBER_STYLE = { fontSize: PAGE_NUMBER_FONT_SIZE, textAlign: "center", fill: "#606060" };
10
10
  /** 单个 1 取当前页;多个 1 中最后一个取总页数,其余取当前页 */
11
11
  function formatPageNumber(pattern, current, total) {
@@ -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;
@@ -43,7 +44,7 @@ class PageNumberAttachment {
43
44
  };
44
45
  }
45
46
  }
46
- export class PageFunction extends ASTFunctionNode {
47
+ class PageFunction extends ASTFunctionNode {
47
48
  static def = {
48
49
  name: ["page"],
49
50
  description: "设置文档页面",
@@ -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) {
@@ -134,7 +135,7 @@ export class PageFunction extends ASTFunctionNode {
134
135
  if (!this.config)
135
136
  return "@page()";
136
137
  const { width, height, marginTop, marginBottom, marginLeft, marginRight, lineGap, minLineGap, fillRatio } = this.config;
137
- 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})`;
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=${quoteSourceString(this.numbering)}, barNumbering=${quoteSourceString(this.barNumbering)}, font=${quoteSourceString(this.font)}, fillRatio=${fillRatio})`;
138
139
  }
139
140
  }
140
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; }
@@ -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
  }
@@ -1,6 +1,6 @@
1
1
  import { ASTFunctionNode, primaryName, resolveArgType } from "../ASTtypes.js";
2
2
  import { WarningDiagnostic } from "../../diagnostic.js";
3
- import { quote } from "../../parser/parse-utils/string-utils.js";
3
+ import { quoteSourceString } from "../../parser/parse-utils/string-utils.js";
4
4
  import { ParserContext } from "../../parser/parserContext.js";
5
5
  class SetFunction extends ASTFunctionNode {
6
6
  static def = {
@@ -63,7 +63,7 @@ class SetFunction extends ASTFunctionNode {
63
63
  }
64
64
  toString() {
65
65
  return `@set(${Array.from(this.args, ([key, value]) => {
66
- const text = typeof value === "string" ? quote(value)
66
+ const text = typeof value === "string" ? quoteSourceString(value)
67
67
  : value && typeof value === "object" && "unit" in value ? `${value.value}${value.unit}` : value;
68
68
  return `${key}=${text}`;
69
69
  }).join(", ")})`;
@@ -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; }
@@ -72,10 +72,12 @@ class StackFunction extends ASTFunctionNode {
72
72
  const host = leftNode instanceof StackFunction
73
73
  ? leftNode
74
74
  : new StackFunction(n.span, new Map(), ctx).addContent(leftNode);
75
- const next = ctx.consumeRightOperand(nodes, at, right => host.addContent(right));
76
- if (next !== null)
77
- return next;
78
- throw new ErrorDiagnostic("E_STACK_NO_TARGET", "@stack语法糖错误: 右边没有找到可叠加的目标", n.span);
75
+ ctx.deferRightOperand(right => {
76
+ if (!right)
77
+ throw new ErrorDiagnostic("E_STACK_NO_TARGET", "@stack语法糖错误: 右边没有找到可叠加的目标", n.span);
78
+ return host.addContent(right);
79
+ });
80
+ return at;
79
81
  }
80
82
  contents = [];
81
83
  get children() { return this.contents; }
@@ -2,10 +2,11 @@
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";
9
+ import type { AccidentalMemory } from "../lowering/accidentalMemory.js";
9
10
  import type { PlaybackEmitter, PlaybackState } from "../playback/types.js";
10
11
  import type { Painter } from "../render/types.js";
11
12
  /**
@@ -21,6 +22,8 @@ export interface TimeState {
21
22
  velocity: number;
22
23
  keySignature: string;
23
24
  program: number;
25
+ /** 小节内变音记忆。系统字段,由 solidifyColumns 创建,任何时刻都能直接读写 */
26
+ accidentals: AccidentalMemory;
24
27
  /** 当前小节时长(QN);尚无显式拍号或散板时为 undefined */
25
28
  meter?: Fraction;
26
29
  [key: string]: any;
@@ -75,6 +78,12 @@ export declare class TemporalNodeBase implements TimeLineEvent {
75
78
  foldedInto?: TemporalNodeBase;
76
79
  /** 沿 foldedInto 上溯到最外层宿主(未折叠时返回自身) */
77
80
  get rootHost(): TemporalNodeBase;
81
+ /**
82
+ * 绘制分组的语义类型,渲染器据此输出 `<g data-kind>`;空串表示不开组。
83
+ *
84
+ * 缺省取来源函数的主名,同一函数生成的对象画法不同时由子类覆盖。
85
+ */
86
+ get kind(): string;
78
87
  /** 由 LoweringContext 在列归并后固化的谱面行号 */
79
88
  layoutLine: number;
80
89
  /** 不可见状态事件保持 undefined */
@@ -96,7 +105,7 @@ export declare class TemporalNodeBase implements TimeLineEvent {
96
105
  * - tie.top:连音线端点;缺省为 anchor 与内容上沿,up 提供最上层成员的端点。
97
106
  * - div.{level}.left / div.{level}.right:从 0 编号的减时线端点,由 div.place 发布,供 beam 接管。
98
107
  * - dot:附点起点;缺省为盒右边界与 visualAxis,音符覆盖为字形附近的位置。
99
- * - lyric:歌词对齐点(voice 只读 x);未提供则不作为歌词目标,note 在 finalizeLayout 发布。
108
+ * - lyric:歌词对齐点(voice 只读 x);未提供则不作为歌词目标,note 与 dash 在 finalizeLayout 发布。
100
109
  * - bar.number:多声部连谱号顶部的行首小节号锚点。
101
110
  *
102
111
  * up、grace、arpeggio 转发宿主端口并换算局部坐标;端口不表达装饰是否存在。
@@ -113,7 +122,7 @@ export declare class TemporalNodeBase implements TimeLineEvent {
113
122
  * 2. Temporal.prepareLayout 可先加入节点自身的装饰,例如下八度点;
114
123
  * 3. 引擎再通过 addon 对应的 layoutDecorationHandler 加入函数装饰;
115
124
  * 4. 引擎分别按 above/below.order 分配空间并调用 place
116
- * 5. 最终 paintLayout 在主体 paint 后调用可选的 decoration.paint
125
+ * 5. 最终 paintVisual 在主体 paint 后调用可选的 decoration.paint
117
126
  *
118
127
  * 数组必须保留到绘制结束,因为 decoration 通常以闭包保存本次测量得到的几何。它只属于当前 layout pass,不能跨 pass 复用。
119
128
  * 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 后失效
@@ -1,6 +1,6 @@
1
1
  import { ASTFunctionNode } from "../ASTtypes.js";
2
2
  import { ErrorDiagnostic } from "../../diagnostic.js";
3
- import { findClosingQuote, quote } from "../../parser/parse-utils/string-utils.js";
3
+ import { findClosingQuote, quoteSourceString } from "../../parser/parse-utils/string-utils.js";
4
4
  import { DEFAULT_KEY, TemporalNodeBase } from "../temporal.js";
5
5
  import { paintRichLine, parseRichText, prepareRichLine } from "../../render/text.js";
6
6
  class TextFunction extends ASTFunctionNode {
@@ -92,7 +92,7 @@ class TextFunction extends ASTFunctionNode {
92
92
  }
93
93
  loweringEnter() { return [new TextTemporalNode(this)]; }
94
94
  toString() {
95
- return `@text(${quote(this.text)}, size=${this.size}px, lineheight=${this.lineHeight}, align=${this.align}, font=${quote(this.font)})`;
95
+ return `@text(${quoteSourceString(this.text)}, size=${this.size}px, lineheight=${this.lineHeight}, align=${this.align}, font=${quoteSourceString(this.font)})`;
96
96
  }
97
97
  }
98
98
  export const TextNode = TextFunction;
@@ -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;