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
@@ -12,7 +12,7 @@ const FIELD_SLOT = {
12
12
  signature: "left", tempo: "left", left: "left", center: "center", right: "right",
13
13
  };
14
14
  const TEXT_PRESET = {
15
- title: [2, "center"], subtitle: [0.85, "center"], author: [0.8, "right"],
15
+ title: [2, "center"], subtitle: [1, "center"], author: [0.88, "right"],
16
16
  };
17
17
  const ITEM_GAP_EM = 0.25;
18
18
  const DEFAULT_GAP_PX = 5;
@@ -346,12 +346,17 @@ H.tempo: 94
346
346
  const explicitContent = source[contentStart] === "@" || source[contentStart] === "{";
347
347
  // 裸文本整行归 Head 所有,直接越过可避免其中的 F 等字符被识别成音符
348
348
  // 显式 DSL 仍从冒号后继续扫描,保留内部函数高亮
349
+ const last = skipSpacesBack(source, lineEnd - 1, contentStart);
350
+ const contentSpan = explicitContent ? undefined : { start: contentStart, end: Math.max(contentStart, last + 1) };
349
351
  return {
350
352
  next: explicitContent ? pos : lineEnd,
351
353
  node: {
352
354
  kind: "sugar",
353
- data: { class: HeadFunction, field },
355
+ data: { class: HeadFunction, field, contentSpan },
354
356
  span: { start, end: pos },
357
+ syntaxKind: contentSpan && field !== "signature" && field !== "tempo" && contentSpan.start < contentSpan.end
358
+ ? [{ kind: "operator", span: { start, end: pos } }, { kind: "string", span: contentSpan }]
359
+ : undefined,
355
360
  },
356
361
  };
357
362
  }
@@ -361,39 +366,26 @@ H.tempo: 94
361
366
  return null;
362
367
  const field = sugar.data.field;
363
368
  let breakAt = at;
364
- for (; breakAt < nodes.length; breakAt++) {
365
- const node = nodes[breakAt];
366
- if (typeof node === "number" && (ctx.source[node] === "\r" || ctx.source[node] === "\n"))
367
- break;
368
- if (typeof node !== "number" && node.kind === "sugar" && node.data?.class === HeadFunction)
369
- break;
370
- }
371
- const stop = nodes[breakAt];
372
- // 裸文本在第一轮被整体越过,EOF 时 nodes 中没有末尾标记,需从源码恢复边界
373
- let boundary;
374
- if (typeof stop === "number")
375
- boundary = stop;
376
- else if (stop)
377
- boundary = stop.span.start;
378
- else if (breakAt > at) {
379
- const last = nodes[breakAt - 1];
380
- boundary = typeof last === "number" ? last + 1 : last.span.end;
381
- }
382
- else
383
- boundary = findLineEnd(ctx.source, sugar.span.end);
384
- const start = skipSpaces(ctx.source, sugar.span.end, boundary);
385
- const last = skipSpacesBack(ctx.source, boundary - 1, start);
386
- const span = { start, end: Math.max(start, last + 1) };
387
- if (span.start >= span.end) {
388
- throw new ErrorDiagnostic("E_HEAD_EMPTY_DECLARATION", "H.{field}: 后必须有内容", sugar.span, { field });
389
- }
390
- const text = ctx.source.slice(span.start, span.end).trim();
369
+ let span = sugar.data.contentSpan;
391
370
  let parsed;
392
- if (text.startsWith("@") || text.startsWith("{")) {
371
+ if (!span) {
372
+ for (; breakAt < nodes.length; breakAt++) {
373
+ const node = nodes[breakAt];
374
+ if (typeof node === "number" && (ctx.source[node] === "\r" || ctx.source[node] === "\n"))
375
+ break;
376
+ if (typeof node !== "number" && node.kind === "sugar" && node.data?.class === HeadFunction)
377
+ break;
378
+ }
393
379
  const sub = new ParserContext(ctx);
394
380
  sub.makeNodes(nodes.slice(at, breakAt));
395
381
  parsed = sub.nodes;
382
+ const last = parsed.at(-1)?.sourceSpan.end ?? sugar.span.end;
383
+ span = { start: skipSpaces(ctx.source, sugar.span.end, last), end: last };
396
384
  }
385
+ if (span.start >= span.end) {
386
+ throw new ErrorDiagnostic("E_HEAD_EMPTY_DECLARATION", "H.{field}: 后必须有内容", sugar.span, { field });
387
+ }
388
+ const text = ctx.source.slice(span.start, span.end);
397
389
  const previous = ctx.nodes.at(-1);
398
390
  // 只有相邻的 H.* 声明合并;普通节点或空行都会切断组合
399
391
  const head = previous instanceof HeadFunction && previous.createdBySugar
@@ -405,6 +397,7 @@ H.tempo: 94
405
397
  head.sourceSpan.end = span.end;
406
398
  if (head !== previous)
407
399
  ctx.pushNode(head);
400
+ const stop = nodes[breakAt];
408
401
  if (typeof stop !== "number")
409
402
  return breakAt;
410
403
  let next = breakAt + 1;
@@ -2,7 +2,7 @@ import { DEFAULT_TONALITY, TemporalNodeBase } from "../temporal.js";
2
2
  import { ASTFunctionNode } from "../ASTtypes.js";
3
3
  import { ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
4
4
  import { parseNoteName } from "../note/noteName.js";
5
- import { acc2Offset, NoteNameMap } from "../../parser/parse-utils/note-utils.js";
5
+ import { acc2Offset, FLAT_NOTE_NAMES, NoteNameMap, SHARP_NOTE_NAMES, wrapPitchClass } from "../../parser/parse-utils/note-utils.js";
6
6
  import { paintAccidental, placeAccidentals } from "../note/accidentals.js";
7
7
  /**
8
8
  * 把宽松的调性写法收敛成 tonality2Midi 认得的 [音名][最多一个 #b][绝对八度]
@@ -23,9 +23,8 @@ function normalizeTonality(tonality) {
23
23
  const midi = (octave + 1) * 12 + pitchClass + offset;
24
24
  if (!Number.isSafeInteger(midi))
25
25
  return null;
26
- // NoteNameMap 里同一音高的升号拼写在前、降号在后,正好用来挑方向;数字音名不参与拼写
27
- const spellings = Object.keys(NoteNameMap).filter(name => NoteNameMap[name] === ((midi % 12) + 12) % 12 && /^[A-G]/.test(name));
28
- return (offset < 0 ? spellings.at(-1) : spellings[0]) + (Math.floor(midi / 12) - 1);
26
+ const spelling = (offset < 0 ? FLAT_NOTE_NAMES : SHARP_NOTE_NAMES)[wrapPitchClass(midi)];
27
+ return spelling + (Math.floor(midi / 12) - 1);
29
28
  }
30
29
  class KeyFunction extends ASTFunctionNode {
31
30
  static def = {
@@ -65,7 +64,6 @@ class KeyFunction extends ASTFunctionNode {
65
64
  super(sourceSpan, parent);
66
65
  const [tonality, size] = this.getArgValue(args, ctx);
67
66
  this.font = ctx.variables.numberfont;
68
- this.tonality = tonality;
69
67
  this.size = ctx.length2px(size);
70
68
  const normalized = normalizeTonality(tonality);
71
69
  this.tonality = normalized ?? DEFAULT_TONALITY;
@@ -105,14 +103,14 @@ class KeyTemporalNode extends TemporalNodeBase {
105
103
  }
106
104
  onTimeState(state) {
107
105
  state.keySignature = this.ast.tonality;
106
+ state.accidentals.clear();
108
107
  }
109
108
  prepareLayout(context) {
110
109
  const size = this.ast.size;
111
110
  const style = this.style;
112
111
  const prefix = context.textMeasurer.measureText(PREFIX, style);
113
112
  const name = context.textMeasurer.measureText(this.ast.displayName, style);
114
- const accidentalGap = size * 0.02;
115
- const { placed, right, top } = placeAccidentals(this.ast.displayAcc, size, prefix.w, prefix.baseline, accidentalGap);
113
+ const { placed, right, top } = placeAccidentals(this.ast.displayAcc, size, prefix.w, prefix.baseline);
116
114
  this.accidentals = placed;
117
115
  // 升降号抬高后可能高过文字,整块下移把它装回盒子里
118
116
  const shift = -top;
@@ -30,6 +30,7 @@ declare class MeterFunction extends ASTFunctionNode {
30
30
  readonly size: number;
31
31
  readonly strict: boolean;
32
32
  readonly font: string;
33
+ readonly weight: number;
33
34
  constructor(span: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent?: ASTNodeBase | null);
34
35
  loweringEnter(ctx: LoweringContext): MeterTemporal[];
35
36
  /**
@@ -56,10 +56,12 @@ class MeterFunction extends ASTFunctionNode {
56
56
  size;
57
57
  strict;
58
58
  font;
59
+ weight;
59
60
  constructor(span, args, ctx, parent = null) {
60
61
  super(span, parent);
61
62
  let [num, den, size] = this.getArgValue(args, ctx);
62
63
  this.font = ctx.variables.numberfont;
64
+ this.weight = ctx.variables.numberweight;
63
65
  if (!Number.isSafeInteger(num) || !Number.isSafeInteger(num * 4) || num < 0
64
66
  || !Number.isSafeInteger(den) || den < 0) {
65
67
  const message = `@meter 的分子和分母必须是非负整数`;
@@ -147,6 +149,7 @@ class MeterTemporal extends TemporalNodeBase {
147
149
  this.style = {
148
150
  fontSize: ast.size,
149
151
  fontFamily: ast.font,
152
+ fontWeight: ast.weight,
150
153
  textAlign: "center",
151
154
  fill: "#000",
152
155
  };
@@ -1,3 +1,3 @@
1
1
  import { type SymbolShape } from "../symbol/shape.js";
2
2
  export declare const sanbanShapes: readonly SymbolShape[];
3
- export declare const sanbanBounds: import("../../core.js").Rect;
3
+ export declare const sanbanBounds: import("../../index.js").Rect;
@@ -3,6 +3,7 @@ export interface PreparedAccidental {
3
3
  w: number;
4
4
  h: number;
5
5
  baseline: number;
6
+ fill?: boolean;
6
7
  strokeWidth: number;
7
8
  commands: readonly PathCommand[];
8
9
  }
@@ -13,13 +14,12 @@ export interface PlacedAccidental {
13
14
  y: number;
14
15
  }
15
16
  /**
16
- * 把升降号串按同一基线依次排在 x 右侧
17
+ * 把升降号串按同一基线依次紧挨着排在 x 右侧
17
18
  * @param size 宿主数字的字号
18
19
  * @param baselineY 宿主文字基线在宿主盒局部坐标中的 y
19
- * @param gap 相邻升降号之间的间隔;末尾也留一份,宿主据此得到 right
20
20
  * @returns right 是下一个字形的起点,top 是最高处(可能为负,宿主自行决定是否下移)
21
21
  */
22
- export declare function placeAccidentals(symbols: string, size: number, x: number, baselineY: number, gap: number): {
22
+ export declare function placeAccidentals(symbols: string, size: number, x: number, baselineY: number): {
23
23
  placed: PlacedAccidental[];
24
24
  right: number;
25
25
  top: number;
@@ -5,18 +5,31 @@ const STROKE_RATIO = 0.06;
5
5
  const RAISE_RATIO = 0.42;
6
6
  const ACCIDENTALS = {
7
7
  "#": {
8
- w: 0.46,
9
- h: 0.78,
10
- baseline: 0.63,
8
+ w: 0.42,
9
+ h: 0.82,
10
+ baseline: 0.67,
11
+ fill: true,
11
12
  commands: [
12
- { op: "M", x: 0.34, y: 0.05 },
13
- { op: "L", x: 0.27, y: 0.95 },
14
- { op: "M", x: 0.72, y: 0.05 },
15
- { op: "L", x: 0.65, y: 0.95 },
16
- { op: "M", x: 0.08, y: 0.38 },
17
- { op: "L", x: 0.9, y: 0.28 },
18
- { op: "M", x: 0.05, y: 0.72 },
19
- { op: "L", x: 0.87, y: 0.62 },
13
+ { op: "M", x: 0.22, y: 0.07 },
14
+ { op: "L", x: 0.35, y: 0.07 },
15
+ { op: "L", x: 0.35, y: 1 },
16
+ { op: "L", x: 0.22, y: 1 },
17
+ { op: "Z" },
18
+ { op: "M", x: 0.65, y: 0 },
19
+ { op: "L", x: 0.78, y: 0 },
20
+ { op: "L", x: 0.78, y: 0.93 },
21
+ { op: "L", x: 0.65, y: 0.93 },
22
+ { op: "Z" },
23
+ { op: "M", x: 0, y: 0.33 },
24
+ { op: "L", x: 1, y: 0.18 },
25
+ { op: "L", x: 1, y: 0.32 },
26
+ { op: "L", x: 0, y: 0.47 },
27
+ { op: "Z" },
28
+ { op: "M", x: 0, y: 0.68 },
29
+ { op: "L", x: 1, y: 0.53 },
30
+ { op: "L", x: 1, y: 0.67 },
31
+ { op: "L", x: 0, y: 0.82 },
32
+ { op: "Z" },
20
33
  ],
21
34
  },
22
35
  b: {
@@ -47,13 +60,12 @@ const ACCIDENTALS = {
47
60
  },
48
61
  };
49
62
  /**
50
- * 把升降号串按同一基线依次排在 x 右侧
63
+ * 把升降号串按同一基线依次紧挨着排在 x 右侧
51
64
  * @param size 宿主数字的字号
52
65
  * @param baselineY 宿主文字基线在宿主盒局部坐标中的 y
53
- * @param gap 相邻升降号之间的间隔;末尾也留一份,宿主据此得到 right
54
66
  * @returns right 是下一个字形的起点,top 是最高处(可能为负,宿主自行决定是否下移)
55
67
  */
56
- export function placeAccidentals(symbols, size, x, baselineY, gap) {
68
+ export function placeAccidentals(symbols, size, x, baselineY) {
57
69
  const placed = [];
58
70
  const glyphSize = size * GLYPH_SCALE;
59
71
  const raise = size * RAISE_RATIO;
@@ -67,6 +79,7 @@ export function placeAccidentals(symbols, size, x, baselineY, gap) {
67
79
  w: definition.w * glyphSize,
68
80
  h: definition.h * glyphSize,
69
81
  baseline: definition.baseline * glyphSize,
82
+ fill: definition.fill,
70
83
  strokeWidth: size * STROKE_RATIO,
71
84
  commands: definition.commands,
72
85
  };
@@ -74,11 +87,11 @@ export function placeAccidentals(symbols, size, x, baselineY, gap) {
74
87
  placed.push({ shape, x: right, y });
75
88
  if (y < top)
76
89
  top = y;
77
- right += shape.w + gap;
90
+ right += shape.w;
78
91
  }
79
92
  return { placed, right, top };
80
93
  }
81
94
  /** commands 是 0..1 归一化坐标,必须配回字形自己的 w/h 才不会画歪 */
82
95
  export function paintAccidental(painter, { shape, x, y }, origin, color) {
83
- painter.drawPath(shape.commands, { stroke: color, strokeWidth: shape.strokeWidth }, { x: origin.x + x, y: origin.y + y, scaleX: shape.w, scaleY: shape.h });
96
+ painter.drawPath(shape.commands, shape.fill ? { fill: color } : { stroke: color, strokeWidth: shape.strokeWidth }, { x: origin.x + x, y: origin.y + y, scaleX: shape.w, scaleY: shape.h });
84
97
  }
@@ -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 (Math.abs(offset) > 2 || (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) {
@@ -86,20 +182,25 @@ class NoteFunction extends ASTFunctionNode {
86
182
  const parseResult = parseNoteName(source, start, end, false);
87
183
  if (!parseResult)
88
184
  return null;
185
+ // 末尾的 `!` 是 force=true 的简写;没写时继承 @set(note.force=...)
186
+ const force = parseResult.next < end && source[parseResult.next] === "!";
187
+ const next = parseResult.next + (force ? 1 : 0);
89
188
  const argMap = new Map();
90
189
  argMap.set("name", parseResult.name);
91
190
  if (parseResult.octave !== null)
92
191
  argMap.set("octave", parseResult.octave);
93
192
  argMap.set("acc", parseResult.acc ?? ""); // 必须覆盖不然会用到 set 的默认值
193
+ if (force)
194
+ argMap.set("force", true);
94
195
  const node = {
95
196
  kind: "call",
96
197
  typed: true,
97
198
  name: "note",
98
199
  args: argMap,
99
- span: { start, end: parseResult.next },
200
+ span: { start, end: next },
100
201
  syntaxKind: "atom",
101
202
  };
102
- return { next: parseResult.next, node };
203
+ return { next, node };
103
204
  }
104
205
  static deSugarRelation(ctx, nodes, at) {
105
206
  const node = nodes[at];
@@ -120,19 +221,36 @@ class NoteFunction extends ASTFunctionNode {
120
221
  octave;
121
222
  acc;
122
223
  color;
224
+ carry;
225
+ force;
123
226
  size;
124
227
  font;
228
+ weight;
125
229
  // JE 八度偏移量
126
230
  jeOctaveOffset;
127
231
  // 源码改写时判断是否需要覆盖默认升降号
128
232
  hasDefaultAcc;
233
+ // 去糖时判断是否需要写明 carry、force
234
+ hasDefaultCarry;
235
+ hasDefaultForce;
129
236
  constructor(sourceSpan, args, ctx, parent = null) {
130
237
  super(sourceSpan, parent);
131
238
  this.hasDefaultAcc = Boolean(ctx.variables["note.acc"]);
132
- [this.name, this.acc, this.octave, this.color] = this.getArgValue(args, ctx);
239
+ this.hasDefaultCarry = Boolean(ctx.variables["note.carry"]);
240
+ this.hasDefaultForce = Boolean(ctx.variables["note.force"]);
241
+ [this.name, this.acc, this.octave, this.color, this.carry, this.force] =
242
+ this.getArgValue(args, ctx);
133
243
  this.font = ctx.variables.numberfont;
244
+ this.weight = ctx.variables.numberweight;
134
245
  this.size = ctx.variables.fontsize;
135
246
  // 创建时就固化参数值
247
+ // name 末尾的 `!` 同简写,等价于 force=true;carry 仅命名,所以 force 的位置下标是 4
248
+ if (this.name.endsWith("!")) {
249
+ if ((args.get("force") ?? args.get(4)) === false)
250
+ throw new ErrorDiagnostic("E_NOTE_FORCE_CONFLICT", '函数 @note 的参数 "force=false" 与音符名称末尾的 "!" 冲突', sourceSpan);
251
+ this.name = this.name.slice(0, -1);
252
+ this.force = true;
253
+ }
136
254
  // 校验 note name
137
255
  const parseResult = parseNoteName(this.name);
138
256
  if (parseResult instanceof Diagnostic) {
@@ -161,22 +279,27 @@ class NoteFunction extends ASTFunctionNode {
161
279
  this.acc = parseResult.acc + this.acc;
162
280
  }
163
281
  toString() {
164
- return `@n(${this.name}, ${this.acc || '""'}, ${this.octave}, ${this.color})`;
282
+ // 外层开启过时写明,避免 false 去糖后继承外层的 true
283
+ const carry = this.carry || this.hasDefaultCarry ? `, carry=${this.carry}` : "";
284
+ const force = this.force || this.hasDefaultForce ? `, force=${this.force}` : "";
285
+ return `@n(${this.name}, ${this.acc || '""'}, ${this.octave}, ${this.color}${carry}${force})`;
165
286
  }
166
287
  }
167
288
  export const NoteNode = NoteFunction;
168
- import { DEFAULT_KEY, DEFAULT_VELOCITY, TemporalNodeBase } from "../temporal.js";
169
- import { createDiatonicTranspose, resolveLetterNameToJianpu, resolveNoteMidi, } from "../../parser/parse-utils/note-utils.js";
289
+ import { DEFAULT_KEY, DEFAULT_TONALITY, DEFAULT_VELOCITY, TemporalNodeBase } from "../temporal.js";
290
+ import { acc2Offset, createDiatonicTranspose, offsetToAccidental, resolveLetterNameToJianpu, resolveNoteMidi, } from "../../parser/parse-utils/note-utils.js";
170
291
  // 8 是隐形占位,9 是固定打击音的节拍记号,空串表示不绘制
171
292
  const NOTE_GLYPH = { "8": "", "9": "X" };
172
293
  class NoteTemporalNode extends TemporalNodeBase {
173
294
  // 时间固化后的参数
174
295
  resolvedMidi = null; // 按调性解析的记谱音高,不含播放偏移
175
- keySignature = "C4"; // 用于转调时记录大环境
296
+ keySignature = DEFAULT_TONALITY; // 用于转调时记录大环境
176
297
  transposeDiatonic;
177
298
  name; // 数字
178
299
  acc; // 升降号
179
300
  octave; // 绝对值为点的个数
301
+ displayAcc; // carry 开启的字母音名或 force 推导出的显示记号;undefined 表示按 acc 显示
302
+ carrySlot; // 本音在变音记忆中的位置
180
303
  /** prepareLayout 生成的局部升降号位置 */
181
304
  accidentals = [];
182
305
  /** 字号和颜色在解析时已经固化,样式随之不再变 */
@@ -193,7 +316,7 @@ class NoteTemporalNode extends TemporalNodeBase {
193
316
  this.numberStyle = {
194
317
  fontSize: ast.size,
195
318
  fontFamily: ast.font,
196
- fontWeight: 400,
319
+ fontWeight: ast.weight,
197
320
  textAlign: "center",
198
321
  fill: ast.color,
199
322
  };
@@ -203,10 +326,8 @@ class NoteTemporalNode extends TemporalNodeBase {
203
326
  const { size, color } = this.ast;
204
327
  const mainMetrics = context.textMeasurer.measureText("0", this.numberStyle);
205
328
  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);
329
+ // 升降号盒直接紧挨数字盒左缘,按同一 baseline 排在数字左侧
330
+ const { placed, right: mainX } = placeAccidentals(this.displayAcc ?? this.acc, size, 0, this.numberY);
210
331
  this.accidentals = placed;
211
332
  this.box.w = mainX + mainMetrics.w;
212
333
  this.box.h = mainMetrics.h;
@@ -254,12 +375,10 @@ class NoteTemporalNode extends TemporalNodeBase {
254
375
  }
255
376
  finalizeLayout() {
256
377
  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
- }
378
+ this.ports["tie.top"] = {
379
+ x: this.box.anchor,
380
+ y: getLayoutBounds(this, true).y - this.box.y - this.ast.size * 0.1,
381
+ };
263
382
  }
264
383
  paint(painter) {
265
384
  const color = this.ast.color;
@@ -292,6 +411,30 @@ class NoteTemporalNode extends TemporalNodeBase {
292
411
  }
293
412
  }
294
413
  this.transposeDiatonic = createDiatonicTranspose(this.name, this.octave, keySignature);
414
+ this.applyAccidentals(state.accidentals);
415
+ }
416
+ /**
417
+ * 以显示出来的记号写入记忆;carry 下数字音名没写记号时沿用前文,字母音名按前文省略或补记。
418
+ * force 只改显示:写出实际生效的记号,没有变音时显示还原号。前文要到列末按时间先后结算
419
+ */
420
+ applyAccidentals(memory) {
421
+ const midi = this.resolvedMidi;
422
+ if (midi === null || !/^[1-7]$/.test(this.name))
423
+ return;
424
+ memory.read(this.track, `${this.name}:${this.octave}`, reading => {
425
+ const { prior } = this.carrySlot = reading;
426
+ const digit = /^[1-7]$/.test(this.ast.name);
427
+ const carried = this.ast.carry && digit && !this.acc;
428
+ const offset = carried ? prior : acc2Offset(this.acc);
429
+ if (carried)
430
+ this.resolvedMidi = midi + prior;
431
+ const shown = offsetToAccidental(offset) || "n";
432
+ if (this.ast.force)
433
+ this.displayAcc = shown;
434
+ else if (this.ast.carry && !digit)
435
+ this.displayAcc = offset === prior ? "" : shown;
436
+ return this.displayAcc ?? this.acc ? offset : undefined;
437
+ });
295
438
  }
296
439
  /** 发布完整音段或无声区间,实际 NoteOn/NoteOff 留到声音展开完成后生成 */
297
440
  emitPlayback(emitter) {
@@ -1,5 +1,6 @@
1
1
  import type { ASTNodeBase } from "../ASTtypes.js";
2
2
  import type { SourceSpan } from "../../parser/types.js";
3
+ import type { CallInfo } from "../../parser/grammarType.js";
3
4
  export type NoteTransform = "to-absolute" | "to-relative" | "semitone-up" | "semitone-down";
4
5
  export interface SourceEdit {
5
6
  span: SourceSpan;
@@ -15,7 +16,27 @@ interface NoteSource {
15
16
  };
16
17
  resolvedMidi: number | null;
17
18
  keySignature: string;
19
+ displayAcc?: string;
18
20
  }
19
- /** edits 始终引用原文;参数只改值,默认参数只在当前调用覆盖,避免影响其他音符 */
20
- export declare function rewriteNotes(source: string, notes: readonly NoteSource[], operation: NoteTransform, ranges?: readonly SourceSpan[]): SourceEdit[];
21
+ /** 未传 ranges 视为全选;否则音符须完整落入任一选区 */
22
+ export declare function selects(ranges: readonly SourceSpan[] | undefined, span: SourceSpan): boolean;
23
+ /**
24
+ * 仅在函数参数的顶层保护低八度逗号;已有大括号内的简写无需再包装。
25
+ * 沿 AST 父链定位最近一层显式函数调用 `@call(...)` 及目标音符所属实参,
26
+ * 统计实参起点到音符前的 `{}` 深度(跳过双引号字符串字面量)。
27
+ */
28
+ export declare function needsBraces(masked: string, ast: ASTNodeBase): boolean;
29
+ export interface NotePitch {
30
+ name: string;
31
+ acc: string;
32
+ octave: number;
33
+ absolute: boolean;
34
+ }
35
+ /** 改写显式 `@note(...)` 的音高:已有实参只改值,缺失的追加为命名参数;存在默认 acc 时显式写出 acc 以覆盖它 */
36
+ export declare function rewriteNoteCall(source: string, masked: string, call: CallInfo, pitch: NotePitch, hasDefaultAcc: boolean, edits?: SourceEdit[]): 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[];
21
42
  export {};