jpfun 1.0.0 → 1.2.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 (83) hide show
  1. package/README.md +1 -1
  2. package/dist/diagnostic.d.ts +1 -0
  3. package/dist/diagnostic.js +1 -0
  4. package/dist/functions/ASTtypes.d.ts +2 -3
  5. package/dist/functions/ASTtypes.js +2 -3
  6. package/dist/functions/adjust/index.js +15 -67
  7. package/dist/functions/bar/index.js +11 -7
  8. package/dist/functions/beam/auto.js +15 -11
  9. package/dist/functions/beam/layout.js +22 -48
  10. package/dist/functions/br/index.d.ts +9 -3
  11. package/dist/functions/br/index.js +20 -16
  12. package/dist/functions/dash/index.js +13 -11
  13. package/dist/functions/default.js +2 -1
  14. package/dist/functions/div/index.d.ts +2 -2
  15. package/dist/functions/div/index.js +5 -9
  16. package/dist/functions/dot/index.js +5 -9
  17. package/dist/functions/dyn/index.js +125 -53
  18. package/dist/functions/gliss/index.js +81 -7
  19. package/dist/functions/grace/index.d.ts +3 -10
  20. package/dist/functions/grace/index.js +25 -57
  21. package/dist/functions/head/index.js +6 -7
  22. package/dist/functions/key/index.js +1 -0
  23. package/dist/functions/meter/index.js +7 -5
  24. package/dist/functions/note/index.d.ts +5 -2
  25. package/dist/functions/note/index.js +162 -19
  26. package/dist/functions/note/source-transform.d.ts +8 -2
  27. package/dist/functions/note/source-transform.js +25 -11
  28. package/dist/functions/ottava/index.js +8 -7
  29. package/dist/functions/page/index.d.ts +1 -36
  30. package/dist/functions/page/index.js +11 -15
  31. package/dist/functions/pagebreak/index.js +2 -1
  32. package/dist/functions/rest/index.js +5 -5
  33. package/dist/functions/set/index.js +2 -2
  34. package/dist/functions/stack/index.js +7 -7
  35. package/dist/functions/symbol/symbols/dynamics.d.ts +3 -0
  36. package/dist/functions/symbol/symbols/dynamics.js +10 -1
  37. package/dist/functions/tempo/index.js +8 -3
  38. package/dist/functions/temporal.d.ts +21 -6
  39. package/dist/functions/temporal.js +1 -1
  40. package/dist/functions/text/index.js +3 -5
  41. package/dist/functions/up/index.js +37 -34
  42. package/dist/functions/voice/connections.js +2 -2
  43. package/dist/functions/voice/lyrics.d.ts +2 -0
  44. package/dist/functions/voice/lyrics.js +4 -4
  45. package/dist/functions/voice/voice.d.ts +2 -1
  46. package/dist/functions/voice/voice.js +9 -15
  47. package/dist/functions/voice/voices.d.ts +6 -4
  48. package/dist/functions/voice/voices.js +10 -10
  49. package/dist/index.d.ts +6 -34
  50. package/dist/index.js +6 -34
  51. package/dist/jpfun.min.js +49 -46
  52. package/dist/layout/engine.js +237 -232
  53. package/dist/layout/model.d.ts +1 -1
  54. package/dist/layout/page.d.ts +2 -2
  55. package/dist/layout/page.js +8 -22
  56. package/dist/layout/types.d.ts +4 -5
  57. package/dist/lowering/accidentalMemory.d.ts +33 -0
  58. package/dist/lowering/accidentalMemory.js +84 -0
  59. package/dist/lowering/loweringContext.d.ts +12 -7
  60. package/dist/lowering/loweringContext.js +54 -51
  61. package/dist/lowering/types.d.ts +2 -3
  62. package/dist/parser/grammarType.d.ts +10 -4
  63. package/dist/parser/parse-utils/brace-utils.js +4 -3
  64. package/dist/parser/parse-utils/call-utils.js +7 -7
  65. package/dist/parser/parse-utils/string-utils.d.ts +1 -1
  66. package/dist/parser/parse-utils/string-utils.js +1 -1
  67. package/dist/parser/parserContext.d.ts +30 -34
  68. package/dist/parser/parserContext.js +77 -181
  69. package/dist/parser/preprocess.js +10 -23
  70. package/dist/parser/syntax.d.ts +9 -0
  71. package/dist/parser/syntax.js +109 -0
  72. package/dist/parser/types.d.ts +2 -1
  73. package/dist/pipeline.js +3 -2
  74. package/dist/playback/compile.js +26 -18
  75. package/dist/playback/event.d.ts +1 -2
  76. package/dist/playback/event.js +2 -3
  77. package/dist/playback/types.d.ts +0 -1
  78. package/dist/render/index.d.ts +1 -0
  79. package/dist/render/index.js +1 -0
  80. package/grammar.md +8 -6
  81. package/package.json +2 -2
  82. package/dist/functions/voice/index.d.ts +0 -2
  83. package/dist/functions/voice/index.js +0 -2
@@ -2,6 +2,9 @@ import { SourceSpan, ASTFunctionClass } from "../ASTtypes.js";
2
2
  import type { LoweringResult } from "../../lowering/types.js";
3
3
  import { type NoteTransform, type SourceEdit } from "./source-transform.js";
4
4
  export type { NoteTransform, SourceEdit } from "./source-transform.js";
5
- /** 根据同一源码的 lowering 生成局部修改;传入 ranges 时只处理完整落入任一选区的音符 */
6
- export declare function transformNotes(source: string, lowering: LoweringResult, operation: NoteTransform, ranges?: readonly SourceSpan[]): SourceEdit[];
5
+ /**
6
+ * 根据同一源码的 lowering 生成局部修改;传入 ranges 时只处理完整落入任一选区的音符。
7
+ * 乐谱中有开启 carry 的数字音名时,升降半音需要 relower 重新降级比对并补记
8
+ */
9
+ export declare function transformNotes(source: string, lowering: LoweringResult, operation: NoteTransform, ranges?: readonly SourceSpan[], relower?: (source: string) => LoweringResult): SourceEdit[];
7
10
  export declare const NoteNode: ASTFunctionClass;
@@ -3,9 +3,21 @@ import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
3
3
  import { parseNoteName } from "./noteName.js";
4
4
  import { getLayoutBounds } from "../../layout/engine.js";
5
5
  import { paintAccidental, placeAccidentals } from "./accidentals.js";
6
- import { rewriteNotes } from "./source-transform.js";
7
- /** 根据同一源码的 lowering 生成局部修改;传入 ranges 时只处理完整落入任一选区的音符 */
8
- export function transformNotes(source, lowering, operation, ranges) {
6
+ import { rewriteNotes, selects } from "./source-transform.js";
7
+ /**
8
+ * 根据同一源码的 lowering 生成局部修改;传入 ranges 时只处理完整落入任一选区的音符。
9
+ * 乐谱中有开启 carry 的数字音名时,升降半音需要 relower 重新降级比对并补记
10
+ */
11
+ export function transformNotes(source, lowering, operation, ranges, relower) {
12
+ const notes = transformableNotes(lowering);
13
+ const carried = notes.find(note => note.ast.carry && /^[1-7]$/.test(note.ast.name));
14
+ if (!operation.startsWith("semitone") || !carried)
15
+ return rewriteNotes(source, notes, operation, ranges);
16
+ if (!relower)
17
+ throw new ErrorDiagnostic("E_NOTE_TRANSFORM", "乐谱开启了 carry,升降半音需要重新降级", carried.ast.sourceSpan);
18
+ return pinnedSemitone(source, notes, operation, ranges, relower);
19
+ }
20
+ function transformableNotes(lowering) {
9
21
  const error = lowering.diagnostics.find(item => item instanceof ErrorDiagnostic);
10
22
  if (error)
11
23
  throw error;
@@ -14,7 +26,77 @@ export function transformNotes(source, lowering, operation, ranges) {
14
26
  const invalid = lowering.diagnostics.find(item => notes.some(note => item.span.start < note.ast.sourceSpan.end && item.span.end > note.ast.sourceSpan.start));
15
27
  if (invalid)
16
28
  throw invalid;
17
- return rewriteNotes(source, notes, operation, ranges);
29
+ return notes;
30
+ }
31
+ /** 按 AST 分组并按源码位置排序;同一 AST 的多个实例保持降级顺序 */
32
+ function byAst(notes) {
33
+ const groups = new Map();
34
+ for (const note of notes)
35
+ groups.set(note.ast, [...groups.get(note.ast) ?? [], note]);
36
+ return [...groups.values()].sort((a, b) => a[0].ast.sourceSpan.start - b[0].ast.sourceSpan.start);
37
+ }
38
+ /**
39
+ * 升降半音后重新降级,给读法变了的音补写显式记号,直到除选中音 ±1 之外所有音高不变。
40
+ * 每轮只补每个 (小节, 键) 中读谱顺序第一个不一致的音,后面的音可能因此恢复,所以补记最少。
41
+ * 补记的音只读自己的记号,每轮至少新增一个固定点,最多 音符数 + 1 轮。
42
+ */
43
+ function pinnedSemitone(source, notes, operation, ranges, relower) {
44
+ const delta = operation === "semitone-up" ? 1 : -1;
45
+ const old = byAst(notes);
46
+ const want = old.map(group => group.map(note => note.resolvedMidi === null ? null : note.resolvedMidi + (selects(ranges, note.ast.sourceSpan) ? delta : 0)));
47
+ function fail(span = old[0][0].ast.sourceSpan) {
48
+ throw new ErrorDiagnostic("E_NOTE_TRANSFORM", "无法在保持其他音高不变的前提下升降半音", span);
49
+ }
50
+ const pins = new Map();
51
+ for (let round = 0; round <= old.length; round++) {
52
+ const edits = rewriteNotes(source, notes, operation, ranges, pins);
53
+ let fresh;
54
+ try {
55
+ fresh = byAst(transformableNotes(relower(applyEdits(source, edits))));
56
+ }
57
+ catch {
58
+ return fail();
59
+ }
60
+ if (fresh.length !== old.length)
61
+ fail();
62
+ const misses = [];
63
+ for (const [index, group] of fresh.entries()) {
64
+ const ast = old[index][0].ast;
65
+ if (group.length !== want[index].length)
66
+ fail(ast.sourceSpan);
67
+ for (const [instance, node] of group.entries()) {
68
+ const target = want[index][instance];
69
+ if (node.resolvedMidi === target)
70
+ continue;
71
+ // 已补记的音只读自己的记号,仍不一致就无解
72
+ if (target === null || !node.carrySlot || !/^[1-7]$/.test(node.ast.name) || pins.has(ast))
73
+ fail(ast.sourceSpan);
74
+ misses.push([ast, node, target, node.carrySlot]);
75
+ }
76
+ }
77
+ if (!misses.length)
78
+ return edits;
79
+ // 按读谱顺序:显式 @grace(1, {1 1}, side=pre) 的宿主写在前、读在后
80
+ const firsts = new Map();
81
+ for (const [ast, node, target, { bar, key }] of misses.sort((a, b) => a[3].seq - b[3].seq)) {
82
+ const keys = firsts.get(bar) ?? new Set();
83
+ if (keys.has(key))
84
+ continue;
85
+ firsts.set(bar, keys.add(key));
86
+ const offset = target - resolveNoteMidi(node.name, "", node.octave, node.keySignature);
87
+ const acc = offsetToAccidental(offset) || "n";
88
+ // 同一 AST 的多个实例要求不同记号时无解
89
+ if ((pins.get(ast) ?? acc) !== acc)
90
+ fail(ast.sourceSpan);
91
+ pins.set(ast, acc);
92
+ }
93
+ }
94
+ return fail();
95
+ }
96
+ function applyEdits(source, edits) {
97
+ for (const edit of [...edits].reverse())
98
+ source = source.slice(0, edit.span.start) + edit.text + source.slice(edit.span.end);
99
+ return source;
18
100
  }
19
101
  const JE_OCTAVE_OFFSET = "note.jeOctaveOffset";
20
102
  class NoteFunction extends ASTFunctionNode {
@@ -30,12 +112,13 @@ class NoteFunction extends ASTFunctionNode {
30
112
  - \`A#3\` 等价于 \`@note(A, #, 3)\`,默认 \`acc\` 为空时也等价于 \`@note(A#3)\`
31
113
  - \`#1'\` 等价于 \`@note(1, #, 1)\`,默认 \`acc\` 为空时也等价于 \`@note("#1'")\`
32
114
  - 支持组合升降号,如 \`A##bn99\`;无歧义时也接受后置写法,如 \`A3#\`、\`6#,,\`
33
- - 升降号后紧跟数字时归入下一音符:\`6#3\` 解析为 \`6\` 和 \`#3\``,
115
+ - 升降号后紧跟数字时归入下一音符:\`6#3\` 解析为 \`6\` 和 \`#3\`
116
+ - 末尾加 \`!\` 等价于 \`force=true\`:\`C4!\` 等价于 \`@note(C, "", 4, force=true)\``,
34
117
  allowExtraArgs: false,
35
118
  args: [
36
119
  {
37
120
  name: "name",
38
- description: "数字音名或大写字母音名,可自带升降号与八度;`0` / `Z` 为休止符,`8` 为隐形占位,`9` / `X` 为节拍记号,后三类不显示升降号和八度点",
121
+ description: "数字音名或大写字母音名,可自带升降号与八度,末尾的 `!` 等价于 `force=true`;`0` / `Z` 为休止符,`8` 为隐形占位,`9` / `X` 为节拍记号,后三类不显示升降号和八度点",
39
122
  type: "string",
40
123
  default: null,
41
124
  },
@@ -56,7 +139,20 @@ class NoteFunction extends ASTFunctionNode {
56
139
  description: "音符颜色,使用 CSS 颜色值",
57
140
  type: "string",
58
141
  default: "#000",
59
- }
142
+ },
143
+ {
144
+ name: "carry",
145
+ namedOnly: true,
146
+ description: "小节内变音延续:数字音名按本小节前文读谱,字母音名自动省略或补记变音号",
147
+ type: "boolean",
148
+ default: false,
149
+ },
150
+ {
151
+ name: "force",
152
+ description: "强制显示实际生效的变音号,不改变音高,没有变音时显示还原号;简写为音名末尾的 `!`",
153
+ type: "boolean",
154
+ default: false,
155
+ },
60
156
  ]
61
157
  };
62
158
  static deSugarAtom(source, start, end) {
@@ -77,36 +173,39 @@ class NoteFunction extends ASTFunctionNode {
77
173
  next: start + 1,
78
174
  node: {
79
175
  kind: "sugar",
80
- data: { jeOffset },
176
+ data: jeOffset,
81
177
  span: { start, end: start + 1 },
82
178
  syntaxKind: "punctuation",
179
+ relation: NoteFunction.deSugarRelation,
83
180
  },
84
181
  };
85
182
  // 解析音符名
86
183
  const parseResult = parseNoteName(source, start, end, false);
87
184
  if (!parseResult)
88
185
  return null;
186
+ // 末尾的 `!` 是 force=true 的简写;没写时继承 @set(note.force=...)
187
+ const force = parseResult.next < end && source[parseResult.next] === "!";
188
+ const next = parseResult.next + (force ? 1 : 0);
89
189
  const argMap = new Map();
90
190
  argMap.set("name", parseResult.name);
91
191
  if (parseResult.octave !== null)
92
192
  argMap.set("octave", parseResult.octave);
93
193
  argMap.set("acc", parseResult.acc ?? ""); // 必须覆盖不然会用到 set 的默认值
194
+ if (force)
195
+ argMap.set("force", true);
94
196
  const node = {
95
197
  kind: "call",
96
198
  typed: true,
97
199
  name: "note",
98
200
  args: argMap,
99
- span: { start, end: parseResult.next },
201
+ span: { start, end: next },
100
202
  syntaxKind: "atom",
101
203
  };
102
- return { next: parseResult.next, node };
204
+ return { next, node };
103
205
  }
104
206
  static deSugarRelation(ctx, nodes, at) {
105
207
  const node = nodes[at];
106
- const jeOffset = node.data?.jeOffset;
107
- if (typeof jeOffset !== "number")
108
- return null;
109
- ctx.variables[JE_OCTAVE_OFFSET] = (ctx.variables[JE_OCTAVE_OFFSET] ?? 0) + jeOffset;
208
+ ctx.variables[JE_OCTAVE_OFFSET] = (ctx.variables[JE_OCTAVE_OFFSET] ?? 0) + node.data;
110
209
  // JE 谱兼容:保留括号源码,并让关系语法糖像跳过普通文本一样跳过它。
111
210
  ctx.nodes.push(new ASTTextNode(node.span));
112
211
  return at + 1;
@@ -120,6 +219,8 @@ class NoteFunction extends ASTFunctionNode {
120
219
  octave;
121
220
  acc;
122
221
  color;
222
+ carry;
223
+ force;
123
224
  size;
124
225
  font;
125
226
  weight;
@@ -127,14 +228,27 @@ class NoteFunction extends ASTFunctionNode {
127
228
  jeOctaveOffset;
128
229
  // 源码改写时判断是否需要覆盖默认升降号
129
230
  hasDefaultAcc;
231
+ // 去糖时判断是否需要写明 carry、force
232
+ hasDefaultCarry;
233
+ hasDefaultForce;
130
234
  constructor(sourceSpan, args, ctx, parent = null) {
131
235
  super(sourceSpan, parent);
132
236
  this.hasDefaultAcc = Boolean(ctx.variables["note.acc"]);
133
- [this.name, this.acc, this.octave, this.color] = this.getArgValue(args, ctx);
237
+ this.hasDefaultCarry = Boolean(ctx.variables["note.carry"]);
238
+ this.hasDefaultForce = Boolean(ctx.variables["note.force"]);
239
+ [this.name, this.acc, this.octave, this.color, this.carry, this.force] =
240
+ this.getArgValue(args, ctx);
134
241
  this.font = ctx.variables.numberfont;
135
242
  this.weight = ctx.variables.numberweight;
136
243
  this.size = ctx.variables.fontsize;
137
244
  // 创建时就固化参数值
245
+ // name 末尾的 `!` 同简写,等价于 force=true;carry 仅命名,所以 force 的位置下标是 4
246
+ if (this.name.endsWith("!")) {
247
+ if ((args.get("force") ?? args.get(4)) === false)
248
+ throw new ErrorDiagnostic("E_NOTE_FORCE_CONFLICT", '函数 @note 的参数 "force=false" 与音符名称末尾的 "!" 冲突', sourceSpan);
249
+ this.name = this.name.slice(0, -1);
250
+ this.force = true;
251
+ }
138
252
  // 校验 note name
139
253
  const parseResult = parseNoteName(this.name);
140
254
  if (parseResult instanceof Diagnostic) {
@@ -163,12 +277,15 @@ class NoteFunction extends ASTFunctionNode {
163
277
  this.acc = parseResult.acc + this.acc;
164
278
  }
165
279
  toString() {
166
- return `@n(${this.name}, ${this.acc || '""'}, ${this.octave}, ${this.color})`;
280
+ // 外层开启过时写明,避免 false 去糖后继承外层的 true
281
+ const carry = this.carry || this.hasDefaultCarry ? `, carry=${this.carry}` : "";
282
+ const force = this.force || this.hasDefaultForce ? `, force=${this.force}` : "";
283
+ return `@n(${this.name}, ${this.acc || '""'}, ${this.octave}, ${this.color}${carry}${force})`;
167
284
  }
168
285
  }
169
286
  export const NoteNode = NoteFunction;
170
287
  import { DEFAULT_KEY, DEFAULT_TONALITY, DEFAULT_VELOCITY, TemporalNodeBase } from "../temporal.js";
171
- import { createDiatonicTranspose, resolveLetterNameToJianpu, resolveNoteMidi, } from "../../parser/parse-utils/note-utils.js";
288
+ import { acc2Offset, createDiatonicTranspose, offsetToAccidental, resolveLetterNameToJianpu, resolveNoteMidi, } from "../../parser/parse-utils/note-utils.js";
172
289
  // 8 是隐形占位,9 是固定打击音的节拍记号,空串表示不绘制
173
290
  const NOTE_GLYPH = { "8": "", "9": "X" };
174
291
  class NoteTemporalNode extends TemporalNodeBase {
@@ -179,6 +296,8 @@ class NoteTemporalNode extends TemporalNodeBase {
179
296
  name; // 数字
180
297
  acc; // 升降号
181
298
  octave; // 绝对值为点的个数
299
+ displayAcc; // carry 开启的字母音名或 force 推导出的显示记号;undefined 表示按 acc 显示
300
+ carrySlot; // 本音在变音记忆中的位置
182
301
  /** prepareLayout 生成的局部升降号位置 */
183
302
  accidentals = [];
184
303
  /** 字号和颜色在解析时已经固化,样式随之不再变 */
@@ -206,7 +325,7 @@ class NoteTemporalNode extends TemporalNodeBase {
206
325
  const mainMetrics = context.textMeasurer.measureText("0", this.numberStyle);
207
326
  this.numberY = mainMetrics.baseline;
208
327
  // 升降号盒直接紧挨数字盒左缘,按同一 baseline 排在数字左侧
209
- const { placed, right: mainX } = placeAccidentals(this.acc, size, 0, this.numberY);
328
+ const { placed, right: mainX } = placeAccidentals(this.displayAcc ?? this.acc, size, 0, this.numberY);
210
329
  this.accidentals = placed;
211
330
  this.box.w = mainX + mainMetrics.w;
212
331
  this.box.h = mainMetrics.h;
@@ -271,7 +390,7 @@ class NoteTemporalNode extends TemporalNodeBase {
271
390
  /** 固化记谱位置的音高、力度和音色,并保留基于该调性的相对移调能力 */
272
391
  onTimeState(state) {
273
392
  const keySignature = this.keySignature = state.keySignature;
274
- this.playbackState = { bpm: state.bpm, velocity: state.velocity, program: state.program };
393
+ this.playbackState = { velocity: state.velocity, program: state.program };
275
394
  this.resolvedMidi = resolveNoteMidi(this.name, this.acc, this.octave, keySignature);
276
395
  // 数字音名本身就是简谱显示形式,直接保留原始数字和相对八度
277
396
  if (this.name >= "0" && this.name <= "9") {
@@ -290,6 +409,30 @@ class NoteTemporalNode extends TemporalNodeBase {
290
409
  }
291
410
  }
292
411
  this.transposeDiatonic = createDiatonicTranspose(this.name, this.octave, keySignature);
412
+ this.applyAccidentals(state.accidentals);
413
+ }
414
+ /**
415
+ * 以显示出来的记号写入记忆;carry 下数字音名没写记号时沿用前文,字母音名按前文省略或补记。
416
+ * force 只改显示:写出实际生效的记号,没有变音时显示还原号。前文要到列末按时间先后结算
417
+ */
418
+ applyAccidentals(memory) {
419
+ const midi = this.resolvedMidi;
420
+ if (midi === null || !/^[1-7]$/.test(this.name))
421
+ return;
422
+ memory.read(this.track, `${this.name}:${this.octave}`, reading => {
423
+ const { prior } = this.carrySlot = reading;
424
+ const digit = /^[1-7]$/.test(this.ast.name);
425
+ const carried = this.ast.carry && digit && !this.acc;
426
+ const offset = carried ? prior : acc2Offset(this.acc);
427
+ if (carried)
428
+ this.resolvedMidi = midi + prior;
429
+ const shown = offsetToAccidental(offset) || "n";
430
+ if (this.ast.force)
431
+ this.displayAcc = shown;
432
+ else if (this.ast.carry && !digit)
433
+ this.displayAcc = offset === prior ? "" : shown;
434
+ return this.displayAcc ?? this.acc ? offset : undefined;
435
+ });
293
436
  }
294
437
  /** 发布完整音段或无声区间,实际 NoteOn/NoteOff 留到声音展开完成后生成 */
295
438
  emitPlayback(emitter) {
@@ -16,7 +16,10 @@ interface NoteSource {
16
16
  };
17
17
  resolvedMidi: number | null;
18
18
  keySignature: string;
19
+ displayAcc?: string;
19
20
  }
21
+ /** 未传 ranges 视为全选;否则音符须完整落入任一选区 */
22
+ export declare function selects(ranges: readonly SourceSpan[] | undefined, span: SourceSpan): boolean;
20
23
  /**
21
24
  * 仅在函数参数的顶层保护低八度逗号;已有大括号内的简写无需再包装。
22
25
  * 沿 AST 父链定位最近一层显式函数调用 `@call(...)` 及目标音符所属实参,
@@ -31,6 +34,9 @@ export interface NotePitch {
31
34
  }
32
35
  /** 改写显式 `@note(...)` 的音高:已有实参只改值,缺失的追加为命名参数;存在默认 acc 时显式写出 acc 以覆盖它 */
33
36
  export declare function rewriteNoteCall(source: string, masked: string, call: CallInfo, pitch: NotePitch, hasDefaultAcc: boolean, edits?: SourceEdit[]): SourceEdit[];
34
- /** edits 始终引用原文;参数只改值,默认参数只在当前调用覆盖,避免影响其他音符 */
35
- export declare function rewriteNotes(source: string, notes: readonly NoteSource[], operation: NoteTransform, ranges?: readonly SourceSpan[]): SourceEdit[];
37
+ /**
38
+ * edits 始终引用原文;参数只改值,默认参数只在当前调用覆盖,避免影响其他音符。
39
+ * pins 给指定音符强制写出升降号(升降半音后为保持 carry 下其他音高不变而补记)
40
+ */
41
+ export declare function rewriteNotes(source: string, notes: readonly NoteSource[], operation: NoteTransform, ranges?: readonly SourceSpan[], pins?: ReadonlyMap<ASTNodeBase, string>): SourceEdit[];
36
42
  export {};
@@ -1,12 +1,16 @@
1
1
  import { ErrorDiagnostic } from "../../diagnostic.js";
2
2
  import { preprocessSource } from "../../parser/preprocess.js";
3
3
  import { callArgName, readCall } from "../../parser/parse-utils/call-utils.js";
4
- import { findClosingQuote, quote } from "../../parser/parse-utils/string-utils.js";
4
+ import { findClosingQuote, quoteSourceString } from "../../parser/parse-utils/string-utils.js";
5
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
7
  function fail(span) {
8
8
  throw new ErrorDiagnostic("E_NOTE_TRANSFORM", "无法安全改写此音符的音高", span);
9
9
  }
10
+ /** 未传 ranges 视为全选;否则音符须完整落入任一选区 */
11
+ export function selects(ranges, span) {
12
+ return !ranges || ranges.some(range => range.start <= span.start && range.end >= span.end);
13
+ }
10
14
  /** 音高计算只读固化事实;互转保留调内级数,半音操作采用最少升降号的拼写 */
11
15
  function targetPitch(note, operation) {
12
16
  const absolute = operation === "to-absolute"
@@ -32,6 +36,8 @@ function targetPitch(note, operation) {
32
36
  if (!relative)
33
37
  fail(ast.sourceSpan);
34
38
  ({ renderName: name, renderAcc: acc, renderOctave: octave } = relative);
39
+ // carry 下按显示的记号写出,数字音名读回来音高不变
40
+ acc = note.displayAcc ?? acc;
35
41
  }
36
42
  else {
37
43
  const value = absolute ? midi : midi - tonic;
@@ -96,8 +102,10 @@ export function rewriteNoteCall(source, masked, call, pitch, hasDefaultAcc, edit
96
102
  const accSlot = slots.get("acc") ?? slots.get(1);
97
103
  const octaveSlot = slots.get("octave") ?? slots.get(2);
98
104
  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);
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;
101
109
  if (nameSlot)
102
110
  pushEdit(edits, source, masked, nameSlot, valueText(name, nameSlot));
103
111
  else
@@ -105,7 +113,7 @@ export function rewriteNoteCall(source, masked, call, pitch, hasDefaultAcc, edit
105
113
  if (accSlot)
106
114
  pushEdit(edits, source, masked, accSlot, valueText(pitch.acc, accSlot));
107
115
  else if (hasDefaultAcc)
108
- additions.push(`acc=${quote(pitch.acc)}`);
116
+ additions.push(`acc=${quoteSourceString(pitch.acc)}`);
109
117
  if (octaveSlot)
110
118
  pushEdit(edits, source, masked, octaveSlot, String(pitch.octave));
111
119
  if (additions.length) {
@@ -115,8 +123,11 @@ export function rewriteNoteCall(source, masked, call, pitch, hasDefaultAcc, edit
115
123
  }
116
124
  return edits;
117
125
  }
118
- /** edits 始终引用原文;参数只改值,默认参数只在当前调用覆盖,避免影响其他音符 */
119
- export function rewriteNotes(source, notes, operation, ranges) {
126
+ /**
127
+ * edits 始终引用原文;参数只改值,默认参数只在当前调用覆盖,避免影响其他音符。
128
+ * pins 给指定音符强制写出升降号(升降半音后为保持 carry 下其他音高不变而补记)
129
+ */
130
+ export function rewriteNotes(source, notes, operation, ranges, pins) {
120
131
  const { maskedSource: masked } = preprocessSource(source);
121
132
  const edits = [];
122
133
  const tokens = [];
@@ -129,16 +140,19 @@ export function rewriteNotes(source, notes, operation, ranges) {
129
140
  || operation === "to-relative" && /^[1-7]$/.test(ast.name);
130
141
  if (!explicit)
131
142
  tokens.push({ span, text: source.slice(span.start, span.end) });
132
- if (ranges && !ranges.some(range => range.start <= span.start && range.end >= span.end))
133
- continue;
134
- 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)
135
146
  continue;
136
- const pitch = targetPitch(note, operation);
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;
137
150
  if (explicit) {
138
151
  rewriteNoteCall(source, masked, call, pitch, ast.hasDefaultAcc, edits);
139
152
  continue;
140
153
  }
141
- let text = pitchToken(pitch);
154
+ // 简写末尾的 `!`(force)不属于音高,原样保留
155
+ let text = pitchToken(pitch) + (source[span.end - 1] === "!" ? "!" : "");
142
156
  if (text.includes(",") && needsBraces(masked, ast))
143
157
  text = `{${text}}`;
144
158
  tokens[tokens.length - 1].text = text;
@@ -171,18 +171,19 @@ class OttavaAttachment {
171
171
  parts.push(part(right - halfStroke, above ? -halfStroke : -hook - halfStroke, strokeWidth, hook + strokeWidth));
172
172
  const region = part(0, 0, 0, 0);
173
173
  unionLayoutBoxes(region, parts);
174
+ // 八度号只属于本轨:其他轨由纵向求解按占用推开,不在这里避让
175
+ const axis = context.getVisualAxis(line, track);
174
176
  let lineY = above ? Infinity : -Infinity;
175
177
  for (const part of parts) {
176
- for (const [lane, extent] of context.getHorizontalExtents(line, part.x, part.x + part.w)) {
177
- const axis = context.getVisualAxis(line, lane);
178
- lineY = above
179
- ? Math.min(lineY, axis + extent.top - gap - part.y - part.h)
180
- : Math.max(lineY, axis + extent.bottom + gap - part.y);
181
- }
178
+ const extent = context.getHorizontalExtents(line, part.x, part.x + part.w).get(track);
179
+ if (!extent)
180
+ continue;
181
+ lineY = above
182
+ ? Math.min(lineY, axis + extent.top - gap - part.y - part.h)
183
+ : Math.max(lineY, axis + extent.bottom + gap - part.y);
182
184
  }
183
185
  if (!Number.isFinite(lineY)) {
184
186
  const extent = context.getRangeExtents(line, first || last ? this.endPoints : undefined, track);
185
- const axis = context.getVisualAxis(line, track);
186
187
  lineY = above
187
188
  ? axis + (extent?.top ?? 0) - gap - (region.y + region.h)
188
189
  : axis + (extent?.bottom ?? 0) + gap - region.y;
@@ -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) {
@@ -44,7 +44,7 @@ class PageNumberAttachment {
44
44
  };
45
45
  }
46
46
  }
47
- export class PageFunction extends ASTFunctionNode {
47
+ class PageFunction extends ASTFunctionNode {
48
48
  static def = {
49
49
  name: ["page"],
50
50
  description: "设置文档页面",
@@ -52,11 +52,11 @@ export class PageFunction extends ASTFunctionNode {
52
52
  ~~~jpfun
53
53
  @page(
54
54
  width=794px, height=1123px, top=48px, bottom=48px,
55
- left=40px, right=40px, gap=1em, minGap=0.4em, fillRatio=0.5,
55
+ left=40px, right=40px, fillRatio=0.5,
56
56
  numbering="1/1", barNumbering="(1)"
57
57
  )
58
58
  ~~~
59
- 页边距和行距须非负;左右边距之和须小于页宽,固定页高时上下边距之和须小于页高。`,
59
+ 页边距须非负;左右边距之和须小于页宽,固定页高时上下边距之和须小于页高。行距由 \`@br\` 的 \`gap\`、\`minGap\` 设置。`,
60
60
  allowExtraArgs: false,
61
61
  args: [
62
62
  { name: "width", description: "页面宽度,须大于左右页边距之和", type: "length", default: px(DEFAULT_PAGE_CONFIG.width) },
@@ -65,8 +65,6 @@ export class PageFunction extends ASTFunctionNode {
65
65
  { name: "bottom", description: "页面下边距,启用页码时至少为 `16px`", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginBottom) },
66
66
  { name: "left", description: "页面左边距", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginLeft) },
67
67
  { name: "right", description: "页面右边距", type: "length", default: px(DEFAULT_PAGE_CONFIG.marginRight) },
68
- { name: "gap", description: "谱面行主旋律之间的标准间距", type: "length", default: { value: 1, unit: "em" } },
69
- { name: "minGap", description: "行间保留的最小间距", type: "length", default: { value: 0.4, unit: "em" } },
70
68
  { name: "numbering", description: "页码格式,空值隐藏;`1`:当前页,`1/1`:显示当前页/总页数", type: "string", default: "" },
71
69
  { name: "barNumbering", description: "行首小节号格式,默认空值隐藏;`1` 显示当前小节号,`(1)` 显示带括号的小节号", type: "string", default: "" },
72
70
  { name: "font", description: "页码/小节号字体,空值沿用当前字体设置", type: "string", default: "" },
@@ -91,15 +89,15 @@ export class PageFunction extends ASTFunctionNode {
91
89
  return;
92
90
  }
93
91
  ctx.documentDeclarations["page"] = true;
94
- const [w, h, t, b, l, r, g, mg, numbering, barNumbering, font, fillRatio,] = this.getArgValue(args, ctx);
92
+ const [w, h, t, b, l, r, numbering, barNumbering, font, fillRatio,] = this.getArgValue(args, ctx);
95
93
  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));
94
+ const [width, height, top, bottom, left, right] = [w, h, t, b, l, r].map(value => ctx.length2px(value));
97
95
  if (!Number.isFinite(width) || width <= 0)
98
96
  throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的 width 必须是正有限长度", sourceSpan);
99
97
  if (!Number.isFinite(height))
100
98
  throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的 height 必须是有限长度;小于等于 0 表示不自动分页", 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);
99
+ if ([top, bottom, left, right].some(value => !Number.isFinite(value) || value < 0))
100
+ throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的边距必须是非负有限长度", sourceSpan);
103
101
  if (left + right >= width)
104
102
  throw new ErrorDiagnostic("E_INVALID_PAGE_CONFIG", "@page 的左右边距没有留下可用内容宽度", sourceSpan);
105
103
  if (height > 0 && top + bottom >= height)
@@ -113,8 +111,6 @@ export class PageFunction extends ASTFunctionNode {
113
111
  marginBottom: bottom,
114
112
  marginLeft: left,
115
113
  marginRight: right,
116
- lineGap: gap,
117
- minLineGap: minGap,
118
114
  fillRatio,
119
115
  });
120
116
  this.numbering = numbering;
@@ -134,8 +130,8 @@ export class PageFunction extends ASTFunctionNode {
134
130
  toString() {
135
131
  if (!this.config)
136
132
  return "@page()";
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})`;
133
+ const { width, height, marginTop, marginBottom, marginLeft, marginRight, fillRatio } = this.config;
134
+ return `@page(width=${width}px, height=${Number.isFinite(height) ? height : 0}px, top=${marginTop}px, bottom=${marginBottom}px, left=${marginLeft}px, right=${marginRight}px, numbering=${quoteSourceString(this.numbering)}, barNumbering=${quoteSourceString(this.barNumbering)}, font=${quoteSourceString(this.font)}, fillRatio=${fillRatio})`;
139
135
  }
140
136
  }
141
137
  export const PageNode = PageFunction;
@@ -28,7 +28,8 @@ class PageBreakFunction extends ASTFunctionNode {
28
28
  const node = new TemporalNodeBase();
29
29
  node.ast = this;
30
30
  node.mergeKey = -1;
31
- node.addon = { breakBefore: 1, pageBreakBefore: this.justify };
31
+ // 新页首行没有行距
32
+ node.addon = { breakBefore: { gap: 0, minGap: 0 }, pageBreakBefore: this.justify };
32
33
  return [node];
33
34
  }
34
35
  toString() { return `@pagebreak(justify=${this.justify})`; }
@@ -1,5 +1,6 @@
1
1
  import { ErrorDiagnostic } from "../../diagnostic.js";
2
2
  import { Fraction } from "../../fraction.js";
3
+ import { TimeColumn } from "../../lowering/loweringContext.js";
3
4
  import { ASTFunctionNode, ASTNodeBase, } from "../ASTtypes.js";
4
5
  import { ANCHOR_KEY, isVisualTemporalNode, TemporalNodeBase } from "../temporal.js";
5
6
  // 同刻状态先固化,休止只与休止合列,普通音符随后进入
@@ -65,7 +66,7 @@ class RestFunction extends ASTFunctionNode {
65
66
  }
66
67
  static loweringFinalize(result) {
67
68
  // 没有全局休止列时,跳过索引扫描和边界补入
68
- if (!result.columns.some(column => column.some(node => node.mergeKey === REST_KEY)))
69
+ if (!result.columns.some(column => column.mergeKey === REST_KEY))
69
70
  return;
70
71
  let order = 0;
71
72
  const onsets = new Map();
@@ -110,7 +111,7 @@ class RestFunction extends ASTFunctionNode {
110
111
  }
111
112
  if (!longest)
112
113
  continue;
113
- const time = longest.t.clone();
114
+ const time = column.t.clone();
114
115
  // 按小节时长补入 n−1 个不可见边界;时间已固化,不再参与声部归并
115
116
  for (let index = 1; index < longest.ast.count; index++) {
116
117
  time.add(longest.measureDuration);
@@ -118,11 +119,11 @@ class RestFunction extends ASTFunctionNode {
118
119
  boundary.ast = new ASTNodeBase(longest.ast.sourceSpan, longest.ast);
119
120
  boundary.t.copyFrom(time);
120
121
  boundary.track = longest.track;
121
- boundary.layoutLine = longest.layoutLine;
122
+ boundary.layoutLine = column.layoutLine;
122
123
  boundary.order = order++;
123
124
  boundary.mergeKey = ANCHOR_KEY;
124
125
  result.astToTemporal.set(boundary.ast, [boundary]);
125
- columns.push([boundary]);
126
+ columns.push(new TimeColumn(boundary, column.bpm));
126
127
  }
127
128
  }
128
129
  result.columns = columns;
@@ -160,7 +161,6 @@ class RestTemporal extends TemporalNodeBase {
160
161
  if (!rest || this.order < rest.order)
161
162
  restsByHost.set(host, this);
162
163
  }
163
- this.playbackState = { bpm: state.bpm };
164
164
  return this.T;
165
165
  }
166
166
  emitPlayback(emitter) {