jpfun 0.8.0 → 0.9.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 (97) hide show
  1. package/dist/converter/midi/convert.js +8 -55
  2. package/dist/converter/musicxml/features.d.ts +1 -1
  3. package/dist/converter/musicxml/features.js +1 -1
  4. package/dist/converter/musicxml/index.js +8 -18
  5. package/dist/converter/source.d.ts +4 -7
  6. package/dist/converter/source.js +11 -9
  7. package/dist/functions/ASTtypes.d.ts +1 -14
  8. package/dist/functions/ASTtypes.js +5 -36
  9. package/dist/functions/adjust/index.js +45 -33
  10. package/dist/functions/arpeggio/index.js +42 -45
  11. package/dist/functions/arpeggio/shape.d.ts +2 -3
  12. package/dist/functions/arpeggio/shape.js +20 -50
  13. package/dist/functions/bar/index.js +3 -8
  14. package/dist/functions/beam/auto.js +54 -123
  15. package/dist/functions/beam/index.js +4 -9
  16. package/dist/functions/box/index.js +0 -6
  17. package/dist/functions/dash/index.js +3 -4
  18. package/dist/functions/div/index.d.ts +2 -4
  19. package/dist/functions/div/index.js +10 -10
  20. package/dist/functions/dot/index.js +3 -9
  21. package/dist/functions/dyn/index.js +6 -26
  22. package/dist/functions/gliss/index.js +95 -89
  23. package/dist/functions/grace/index.d.ts +2 -5
  24. package/dist/functions/grace/index.js +44 -89
  25. package/dist/functions/head/index.js +9 -6
  26. package/dist/functions/key/index.js +6 -6
  27. package/dist/functions/meter/index.js +3 -3
  28. package/dist/functions/note/index.js +1 -1
  29. package/dist/functions/note/source-transform.js +2 -5
  30. package/dist/functions/ottava/index.js +11 -32
  31. package/dist/functions/page/index.js +13 -16
  32. package/dist/functions/rest/index.js +2 -4
  33. package/dist/functions/slide/index.js +0 -1
  34. package/dist/functions/stack/index.js +8 -57
  35. package/dist/functions/temporal.d.ts +2 -2
  36. package/dist/functions/temporal.js +7 -0
  37. package/dist/functions/text/index.js +24 -30
  38. package/dist/functions/tie/index.js +14 -37
  39. package/dist/functions/tremolo/index.js +0 -1
  40. package/dist/functions/tuplet/index.js +0 -6
  41. package/dist/functions/up/index.js +79 -83
  42. package/dist/functions/voice/connections.d.ts +2 -1
  43. package/dist/functions/voice/connections.js +48 -10
  44. package/dist/functions/voice/index.d.ts +2 -3
  45. package/dist/functions/voice/index.js +2 -970
  46. package/dist/functions/voice/lyrics.d.ts +30 -0
  47. package/dist/functions/voice/lyrics.js +289 -0
  48. package/dist/functions/voice/voice.d.ts +63 -0
  49. package/dist/functions/voice/voice.js +373 -0
  50. package/dist/functions/voice/voices.d.ts +106 -0
  51. package/dist/functions/voice/voices.js +423 -0
  52. package/dist/functions/volta/index.js +5 -23
  53. package/dist/jpfun.core.min.js +65 -56
  54. package/dist/jpfun.from-midi.min.js +5 -5
  55. package/dist/jpfun.from-musicxml.min.js +7 -7
  56. package/dist/jpfun.min.js +68 -59
  57. package/dist/layout/engine.js +30 -18
  58. package/dist/layout/model.d.ts +0 -1
  59. package/dist/layout/model.js +1 -4
  60. package/dist/layout/page.d.ts +2 -1
  61. package/dist/layout/page.js +14 -14
  62. package/dist/layout/range.d.ts +7 -6
  63. package/dist/layout/range.js +23 -14
  64. package/dist/layout/types.d.ts +9 -28
  65. package/dist/lowering/loweringContext.d.ts +8 -11
  66. package/dist/lowering/loweringContext.js +7 -13
  67. package/dist/lowering/track.d.ts +8 -1
  68. package/dist/lowering/types.d.ts +12 -8
  69. package/dist/parser/parse-utils/call-utils.d.ts +1 -2
  70. package/dist/parser/parse-utils/call-utils.js +6 -34
  71. package/dist/parser/parse-utils/note-utils.d.ts +3 -3
  72. package/dist/parser/parse-utils/note-utils.js +17 -28
  73. package/dist/parser/parse-utils/string-utils.d.ts +1 -1
  74. package/dist/parser/parse-utils/string-utils.js +8 -6
  75. package/dist/parser/parserContext.d.ts +9 -9
  76. package/dist/parser/parserContext.js +54 -10
  77. package/dist/pipeline.js +2 -2
  78. package/dist/playback/compile.js +13 -14
  79. package/dist/playback/event.d.ts +6 -6
  80. package/dist/playback/event.js +13 -49
  81. package/dist/render/canvas.d.ts +0 -2
  82. package/dist/render/canvas.js +0 -21
  83. package/dist/render/svg.d.ts +0 -1
  84. package/dist/render/svg.js +33 -31
  85. package/dist/render/text.d.ts +36 -1
  86. package/dist/render/text.js +134 -0
  87. package/dist/render/types.d.ts +0 -2
  88. package/grammar.md +16 -13
  89. package/package.json +1 -1
  90. package/dist/iife/core.d.ts +0 -1
  91. package/dist/iife/core.js +0 -3
  92. package/dist/iife/from-midi.d.ts +0 -1
  93. package/dist/iife/from-midi.js +0 -15
  94. package/dist/iife/from-musicxml.d.ts +0 -1
  95. package/dist/iife/from-musicxml.js +0 -3
  96. package/dist/iife/full.d.ts +0 -1
  97. package/dist/iife/full.js +0 -3
@@ -10,14 +10,13 @@
10
10
  */
11
11
  import { DEFAULT_BPM } from "../../functions/temporal.js";
12
12
  import { identifyTriplets } from "./triplet.js";
13
- import { attachAbove, quote, renderHead, renderPitch, renderSystems } from "../source.js";
13
+ import { attachAbove, quote, renderAbsolutePitch, renderHead, renderRelativePitch, renderSystems } from "../source.js";
14
14
  import { SHARP_NOTE_NAMES as ABSOLUTE_NAMES } from "../../parser/parse-utils/note-utils.js";
15
15
  const DEFAULT_TIME_SIGNATURE = [4, 4];
16
16
  const AUTO_LINE_TARGET_RATIO = 1.03;
17
17
  const AUTO_LINE_LIMIT_RATIO = 1.25;
18
18
  const AUTO_LINE_UNDERFILL_PENALTY = 4;
19
19
  const AUTO_LINE_MAX_BARS = 8;
20
- const RELATIVE_NAMES = ["1", "1#", "2", "2#", "3", "4", "4#", "5", "5#", "6", "6#", "7"];
21
20
  function expectSafeInteger(value, name, min = 0, max = Number.MAX_SAFE_INTEGER) {
22
21
  if (!Number.isSafeInteger(value) || value < min || value > max) {
23
22
  throw new RangeError(`${name} must be an integer in ${min}..${max}`);
@@ -39,47 +38,11 @@ function coalesceSorted(items) {
39
38
  result.set(item.at, item);
40
39
  return [...result.values()];
41
40
  }
42
- function heapPush(heap, value, compare) {
43
- let index = heap.length;
44
- heap.push(value);
45
- while (index > 0) {
46
- const parent = (index - 1) >> 1;
47
- if (compare(heap[parent], value) <= 0)
48
- break;
49
- heap[index] = heap[parent];
50
- index = parent;
51
- }
52
- heap[index] = value;
53
- }
54
- function heapPop(heap, compare) {
55
- const result = heap[0];
56
- const value = heap.pop();
57
- if (heap.length === 0)
58
- return result;
59
- let index = 0;
60
- while (true) {
61
- const left = index * 2 + 1;
62
- if (left >= heap.length)
63
- break;
64
- const right = left + 1;
65
- const child = right < heap.length && compare(heap[right], heap[left]) < 0 ? right : left;
66
- if (compare(heap[child], value) >= 0)
67
- break;
68
- heap[index] = heap[child];
69
- index = child;
70
- }
71
- heap[index] = value;
72
- return result;
73
- }
74
41
  function noteName(midi, mode) {
75
- const pitchClass = midi % 12;
76
- const octave = Math.floor(midi / 12) - 1;
77
- const source = mode === "absolute" ? ABSOLUTE_NAMES[pitchClass] : RELATIVE_NAMES[pitchClass];
78
- return renderPitch({
79
- name: source[0],
80
- accidental: source.slice(1),
81
- octave: mode === "absolute" ? octave : octave - 4,
82
- }, mode);
42
+ if (mode === "relative")
43
+ return renderRelativePitch(midi - 60);
44
+ const source = ABSOLUTE_NAMES[midi % 12];
45
+ return renderAbsolutePitch(source[0], source.slice(1), Math.floor(midi / 12) - 1);
83
46
  }
84
47
  function meterDuration(point, scale) {
85
48
  return point.numerator * 4 * scale / point.denominator;
@@ -189,21 +152,11 @@ function groupTriplets(chords) {
189
152
  */
190
153
  function splitLanes(items) {
191
154
  const lanes = [];
192
- // active 按结束时间回收 lane,available 按原索引优先复用空闲 lane
193
- const active = [];
194
- const available = [];
195
- const compareActive = (left, right) => left.end - right.end || left.laneIndex - right.laneIndex;
196
- const compareLaneIndex = (left, right) => left - right;
197
155
  for (const item of items) {
198
- while (active.length > 0 && active[0].end <= item.start) {
199
- heapPush(available, heapPop(active, compareActive).laneIndex, compareLaneIndex);
200
- }
201
- const laneIndex = available.length > 0 ? heapPop(available, compareLaneIndex) : lanes.length;
202
- const lane = lanes[laneIndex] ?? { items: [] };
203
- if (laneIndex === lanes.length)
204
- lanes.push(lane);
156
+ let lane = lanes.find(candidate => candidate.items.at(-1).end <= item.start);
157
+ if (!lane)
158
+ lanes.push(lane = { items: [] });
205
159
  lane.items.push(item);
206
- heapPush(active, { end: item.end, laneIndex }, compareActive);
207
160
  }
208
161
  // 低音 lane 排在前面,最高 lane 固定承载全谱状态以保持输出稳定
209
162
  const averagePitch = (lane) => {
@@ -35,7 +35,7 @@ declare const DIAGNOSTICS: {
35
35
  readonly glissStart: readonly ["UNRESOLVED_RELATION", "Glissando stop has no matching start and was omitted."];
36
36
  readonly glissStop: readonly ["UNRESOLVED_RELATION", "Glissando start has no matching stop and was omitted."];
37
37
  readonly glissReplaced: readonly ["UNRESOLVED_RELATION", "Glissando start was replaced before a matching stop and was omitted."];
38
- readonly glissEndpoints: readonly ["UNRESOLVED_RELATION", "Glissando endpoints are simultaneous or cross a score line and were omitted."];
38
+ readonly glissEndpoints: readonly ["UNRESOLVED_RELATION", "Glissando endpoints are simultaneous and were omitted."];
39
39
  readonly glissStyle: readonly ["APPROXIMATED", "MusicXML <{value}> was converted to a straight glissando arrow."];
40
40
  readonly symbolStyle: readonly ["APPROXIMATED", "MusicXML <{value}> was mapped to the default symbol shape."];
41
41
  };
@@ -51,7 +51,7 @@ const DIAGNOSTICS = {
51
51
  glissStart: ["UNRESOLVED_RELATION", "Glissando stop has no matching start and was omitted."],
52
52
  glissStop: ["UNRESOLVED_RELATION", "Glissando start has no matching stop and was omitted."],
53
53
  glissReplaced: ["UNRESOLVED_RELATION", "Glissando start was replaced before a matching stop and was omitted."],
54
- glissEndpoints: ["UNRESOLVED_RELATION", "Glissando endpoints are simultaneous or cross a score line and were omitted."],
54
+ glissEndpoints: ["UNRESOLVED_RELATION", "Glissando endpoints are simultaneous and were omitted."],
55
55
  glissStyle: ["APPROXIMATED", "MusicXML <{value}> was converted to a straight glissando arrow."],
56
56
  symbolStyle: ["APPROXIMATED", "MusicXML <{value}> was mapped to the default symbol shape."],
57
57
  };
@@ -12,12 +12,10 @@ import { Fraction } from "../../fraction.js";
12
12
  import { NoteNameMap } from "../../parser/parse-utils/note-utils.js";
13
13
  import { child, children, nameOf, number, text, } from "./dom.js";
14
14
  import { MusicXmlReader, acceptTuplets, directionDynamic, directionTexts, endingPasses, metronomeBpm, mergeArpeggio, noteArpeggio, noteGlissandi, noteLyrics, noteModifiers, parsePitch, parseTimeSignature, partMeasures, readInstrument, reportDiagnostic, scoreMetadata, soundRepeats, timeModification, transposePitch, } from "./features.js";
15
- import { attachAbove, quote, renderHead, renderPitch, renderSystems } from "../source.js";
15
+ import { attachAbove, quote, renderAbsolutePitch, renderHead, renderRelativePitch, renderSystems } from "../source.js";
16
16
  import { matchingLanes, resolveRelations, resolveVoices } from "./resolve.js";
17
17
  const MAJOR_KEYS = ["Cb", "Gb", "Db", "Ab", "Eb", "Bb", "F", "C", "G", "D", "A", "E", "B", "F#", "C#"];
18
18
  const MINOR_KEYS = ["Ab", "Eb", "Bb", "F", "C", "G", "D", "A", "E", "B", "F#", "C#", "G#", "D#", "A#"];
19
- // name = token[0] acc = token.slice(1)
20
- const RELATIVE_NAMES = ["1", "1#", "2", "2#", "3", "4", "4#", "5", "5#", "6", "6#", "7"];
21
19
  function add(left, right) {
22
20
  return left.clone().add(right);
23
21
  }
@@ -47,7 +45,7 @@ function insideSpan(spans, at) {
47
45
  function lyricToken(value) {
48
46
  const continuation = value.endsWith("-");
49
47
  const body = continuation ? value.slice(0, -1) : value;
50
- const escaped = body.replace(/[\\{}@-]/g, "\\$&") + (continuation ? "-" : "");
48
+ const escaped = body.replace(/[\\{}@\-*_^]/g, "\\$&") + (continuation ? "-" : "");
51
49
  // 花括号让会被歌词词法拆分的一个 XML lyric 仍只占一个歌词槽。
52
50
  const hasNonAscii = [...body].some(char => char.codePointAt(0) > 0x7f);
53
51
  return /\s/.test(body) || (hasNonAscii && ([...body].length > 1 || body.length > 1 || continuation))
@@ -594,26 +592,19 @@ function pointAt(points, at) {
594
592
  }
595
593
  /** 生成单个音高;octave=0 等有歧义的情况回退到显式 note */
596
594
  function pitchSource(pitch, mode, key, metadata, suffix = "") {
597
- let name;
598
- let accidental;
599
- let octave;
595
+ let token;
600
596
  if (mode === "absolute") {
601
- name = pitch.step;
602
- accidental = pitch.alter > 0 ? "#".repeat(pitch.alter) : "b".repeat(-pitch.alter);
603
- octave = pitch.octave;
597
+ const accidental = pitch.alter > 0 ? "#".repeat(pitch.alter) : "b".repeat(-pitch.alter);
598
+ token = renderAbsolutePitch(pitch.step, accidental, pitch.octave);
604
599
  }
605
600
  else {
606
601
  const midi = (pitch.octave + 1) * 12 + NoteNameMap[pitch.step] + pitch.alter;
607
602
  const tonic = tonicName(key);
608
603
  const tonicAlter = tonic[1] === "#" ? 1 : tonic[1] === "b" ? -1 : 0;
609
- const difference = midi - 60 - NoteNameMap[tonic[0]] - tonicAlter;
610
- const pitchClass = ((difference % 12) + 12) % 12;
611
- name = RELATIVE_NAMES[pitchClass][0];
612
- accidental = RELATIVE_NAMES[pitchClass].slice(1);
613
- octave = Math.floor(difference / 12);
604
+ token = renderRelativePitch(midi - 60 - NoteNameMap[tonic[0]] - tonicAlter);
614
605
  }
615
606
  const label = metadata.labels.get(pitch);
616
- return renderPitch({ name, accidental, octave }, mode, suffix) + (label ? `@${label}` : "");
607
+ return `${token}${suffix}${label ? `@${label}` : ""}`;
617
608
  }
618
609
  /** 把和弦、倚音、力度和文字组合成一个 jpFun 原子表达式 */
619
610
  function eventSource(event, mode, key, metadata, diagnostics, suffix = "") {
@@ -880,7 +871,6 @@ function labelRelations(score, diagnostics) {
880
871
  after.push(source);
881
872
  };
882
873
  const activeGlissandi = new Map();
883
- const glissLineBreaks = [...score.lineBreaks].map(fractionFromKey);
884
874
  const glissandi = [];
885
875
  const active = new Map();
886
876
  const unmatchedTies = new Set();
@@ -942,7 +932,7 @@ function labelRelations(score, diagnostics) {
942
932
  activeGlissandi.delete(key);
943
933
  if (!previous)
944
934
  reportDiagnostic(diagnostics, "glissStart", pitch.location);
945
- else if (previous.event.start.equals(event.start) || glissLineBreaks.some(time => time.compare(previous.event.start) > 0 && time.compare(event.start) <= 0)) {
935
+ else if (previous.event.start.equals(event.start)) {
946
936
  reportDiagnostic(diagnostics, "glissEndpoints", pitch.location);
947
937
  }
948
938
  else
@@ -1,10 +1,5 @@
1
1
  export { quote } from "../parser/parse-utils/string-utils.js";
2
2
  export type PitchMode = "relative" | "absolute";
3
- export interface SourcePitch {
4
- name: string;
5
- accidental: string;
6
- octave: number;
7
- }
8
3
  interface HeadOptions {
9
4
  title?: string;
10
5
  subtitle?: string;
@@ -15,8 +10,10 @@ interface HeadOptions {
15
10
  }
16
11
  /** 按书写顺序把多个零时长标记叠到主体上方。 */
17
12
  export declare function attachAbove(source: string, additions: readonly string[]): string;
18
- /** 把已解释为目标记谱方式的音高写成 jpFun token。 */
19
- export declare function renderPitch(pitch: SourcePitch, mode: PitchMode, suffix?: string): string;
13
+ /** 将相对主音的半音差写成简谱音高 token。 */
14
+ export declare function renderRelativePitch(semitoneOffset: number): string;
15
+ /** 将绝对音名、升降号与八度写成 jpFun 音高 token。 */
16
+ export declare function renderAbsolutePitch(name: string, accidental: string, octave: number): string;
20
17
  export declare function renderHead(options: HeadOptions): string;
21
18
  /** 把“每个声部的各系统”转置成“每个系统的完整声部组” */
22
19
  export declare function renderSystems(groups: readonly (readonly string[])[]): string;
@@ -6,6 +6,7 @@ const HEAD_TEXT_PRESET = {
6
6
  subtitle: "size=0.85em, align=center",
7
7
  author: "size=0.8em, align=right",
8
8
  };
9
+ const RELATIVE_NAMES = ["1", "#1", "2", "#2", "3", "4", "#4", "5", "#5", "6", "#6", "7"];
9
10
  /** 按书写顺序把多个零时长标记叠到主体上方。 */
10
11
  export function attachAbove(source, additions) {
11
12
  for (let index = additions.length - 1; index >= 0; index--) {
@@ -13,15 +14,16 @@ export function attachAbove(source, additions) {
13
14
  }
14
15
  return source;
15
16
  }
16
- /** 把已解释为目标记谱方式的音高写成 jpFun token。 */
17
- export function renderPitch(pitch, mode, suffix = "") {
18
- if (mode === "absolute") {
19
- return pitch.octave === 0
20
- ? `@note(${pitch.name}, ${pitch.accidental}, 0)${suffix}`
21
- : `${pitch.name}${pitch.accidental}${pitch.octave}${suffix}`;
22
- }
23
- const octaveMarks = pitch.octave > 0 ? "'".repeat(pitch.octave) : ",".repeat(-pitch.octave);
24
- return `${pitch.accidental}${pitch.name}${octaveMarks}${suffix}`;
17
+ /** 将相对主音的半音差写成简谱音高 token。 */
18
+ export function renderRelativePitch(semitoneOffset) {
19
+ const pitchClass = ((semitoneOffset % 12) + 12) % 12;
20
+ const octave = Math.floor(semitoneOffset / 12);
21
+ const octaveMarks = octave > 0 ? "'".repeat(octave) : ",".repeat(-octave);
22
+ return `${RELATIVE_NAMES[pitchClass]}${octaveMarks}`;
23
+ }
24
+ /** 将绝对音名、升降号与八度写成 jpFun 音高 token。 */
25
+ export function renderAbsolutePitch(name, accidental, octave) {
26
+ return octave === 0 ? `@note(${name}, ${accidental}, 0)` : `${name}${accidental}${octave}`;
25
27
  }
26
28
  function renderHeadText(field, value) {
27
29
  // 会被注释、续行或 DSL 语法误读的文本改用显式 @text,其余保留简洁的 H.* 裸文本
@@ -29,7 +29,7 @@ export declare class ASTNodeBase {
29
29
  * 时间求解模式
30
30
  * loweringEnter 返回的事件已规范化并加入索引后调用,决定子节点的展开方式。
31
31
  * 需要本轮事件时通过 ctx.getTemporalNodes 查询
32
- * @returns 返回 null 表示没有子元素,返回对象表示参与时间求解
32
+ * @returns 返回 null 表示不由通用递归器展开子元素;默认将 children 按 sequence 依次展开
33
33
  */
34
34
  timeFlowModel(_ctx: LoweringContext): TimeFlowModel | null;
35
35
  /**
@@ -54,12 +54,6 @@ export declare class ASTBraceNode extends ASTNodeBase {
54
54
  content: ASTNodeBase[];
55
55
  get children(): ASTNodeBase[];
56
56
  constructor(sourceSpan: SourceSpan, content: ASTNodeBase[], parent?: ASTNodeBase | null);
57
- innerSpan(): SourceSpan;
58
- static getContentSpan(content: ASTNodeBase[] | ASTNodeBase): SourceSpan;
59
- timeFlowModel(): {
60
- children: ASTNodeBase[];
61
- mode: "sequence";
62
- };
63
57
  toString(source: string): string;
64
58
  }
65
59
  export interface FunctionArgDef {
@@ -96,9 +90,7 @@ export declare class ASTFunctionNode extends ASTNodeBase {
96
90
  get def(): FunctionDef | undefined;
97
91
  get callName(): string;
98
92
  static deSugarAtom: deSugarAtomFunction;
99
- get deSugarAtom(): deSugarAtomFunction;
100
93
  static deSugarRelation: deSugarRelationFunction;
101
- get deSugarRelation(): deSugarRelationFunction;
102
94
  getArgValue(args: FunctionArgs, ctx: ParserContext): paramValue[];
103
95
  toString(source: string): string;
104
96
  /**
@@ -114,10 +106,5 @@ export declare class ASTFunctionNode extends ASTNodeBase {
114
106
  * 只有函数节点声明 labelable,别的节点读到的必是 undefined,所以无需 instanceof
115
107
  */
116
108
  static findLabelable(node: ASTNodeBase): ASTFunctionNode | null;
117
- /**
118
- * 用于语法糖向前结合
119
- * 从指定位置向前寻找最后一个可由后缀语法糖包装的节点,跳过不产生语义对象的文本
120
- */
121
- static findLastFuncContentIndex(nodes: ASTNodeBase[], i: number): number;
122
109
  }
123
110
  export type ASTFunctionClass = (new (sourceSpan: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent: ASTNodeBase | null) => ASTFunctionNode) & Pick<typeof ASTFunctionNode, "prototype" | "def" | "deSugarAtom" | "deSugarRelation" | "layoutDecorationHandler">;
@@ -26,9 +26,12 @@ export class ASTNodeBase {
26
26
  * 时间求解模式
27
27
  * loweringEnter 返回的事件已规范化并加入索引后调用,决定子节点的展开方式。
28
28
  * 需要本轮事件时通过 ctx.getTemporalNodes 查询
29
- * @returns 返回 null 表示没有子元素,返回对象表示参与时间求解
29
+ * @returns 返回 null 表示不由通用递归器展开子元素;默认将 children 按 sequence 依次展开
30
30
  */
31
- timeFlowModel(_ctx) { return null; }
31
+ timeFlowModel(_ctx) {
32
+ const children = this.children;
33
+ return children ? { mode: "sequence", children } : null;
34
+ }
32
35
  /**
33
36
  * 离开当前层级的回调 同 loweringEnter
34
37
  *
@@ -72,27 +75,6 @@ export class ASTBraceNode extends ASTNodeBase {
72
75
  this.content = content;
73
76
  this.content.forEach(item => item.parent = this);
74
77
  }
75
- innerSpan() {
76
- return ASTBraceNode.getContentSpan(this.content);
77
- }
78
- // 是复制的
79
- static getContentSpan(content) {
80
- if (Array.isArray(content)) {
81
- if (content.length === 0)
82
- return { start: 0, end: 0 };
83
- const firstSpan = ASTBraceNode.getContentSpan(content[0]);
84
- const lastSpan = ASTBraceNode.getContentSpan(content[content.length - 1]);
85
- return { start: firstSpan.start, end: lastSpan.end };
86
- }
87
- else
88
- return { start: content.sourceSpan.start, end: content.sourceSpan.end };
89
- }
90
- timeFlowModel() {
91
- return {
92
- children: this.content,
93
- mode: "sequence",
94
- };
95
- }
96
78
  toString(source) {
97
79
  return `{${this.content.map(item => item.toString(source)).join("")}}`;
98
80
  }
@@ -134,9 +116,7 @@ export class ASTFunctionNode extends ASTNodeBase {
134
116
  }
135
117
  // 去糖函数 详见 ParserContext 中 deSugarAtomFns 和 deSugarRelationFns 的定义
136
118
  static deSugarAtom = () => null; // 默认没有去糖,子类只需要定义static deSugarAtom方法即可
137
- get deSugarAtom() { return this.constructor.deSugarAtom; }
138
119
  static deSugarRelation = () => null;
139
- get deSugarRelation() { return this.constructor.deSugarRelation; }
140
120
  // 按声明顺序取值,位置编号独立于仅命名参数
141
121
  getArgValue(args, ctx) {
142
122
  const def = this.def;
@@ -185,15 +165,4 @@ export class ASTFunctionNode extends ASTNodeBase {
185
165
  }
186
166
  return null;
187
167
  }
188
- /**
189
- * 用于语法糖向前结合
190
- * 从指定位置向前寻找最后一个可由后缀语法糖包装的节点,跳过不产生语义对象的文本
191
- */
192
- static findLastFuncContentIndex(nodes, i) {
193
- for (; i >= 0; i--) {
194
- if (nodes[i] instanceof ASTFunctionNode || nodes[i] instanceof ASTBraceNode)
195
- return i;
196
- }
197
- return -1;
198
- }
199
168
  }
@@ -52,38 +52,34 @@ class AdjustFunction extends ASTFunctionNode {
52
52
  dw;
53
53
  dh;
54
54
  get children() { return [this.target]; }
55
- timeFlowModel() {
56
- return {
57
- children: [this.target],
58
- mode: "sequence",
59
- };
60
- }
61
55
  /** 微调不创建时间事件,只收集作用域内的对象与关系对象 */
62
56
  loweringEnter(ctx) {
63
- const targets = { temporal: 0, attachment: 0 };
64
57
  const group = {
65
- targets,
58
+ temporals: 0,
59
+ attachments: [],
66
60
  onTemporal: node => {
67
61
  if (!isVisualTemporalNode(node))
68
62
  return;
69
- targets.temporal++;
63
+ group.temporals++;
70
64
  offsetTemporal(node, this);
71
65
  },
72
66
  onAttachment: attachment => {
73
- if (!isLayoutAttachment(attachment))
74
- return;
75
- targets.attachment++;
76
- offsetAttachment(attachment, targets, this.dx, this.dy);
67
+ if (isLayoutAttachment(attachment))
68
+ group.attachments.push(attachment);
77
69
  },
78
70
  };
79
71
  ctx.beginLoweringGroup(this, group);
80
72
  return [];
81
73
  }
82
74
  loweringExit(ctx) {
83
- const group = ctx.endLoweringGroup(this);
84
- if (group.targets.temporal === 0 && group.targets.attachment === 0) {
75
+ const { temporals, attachments } = ctx.endLoweringGroup(this);
76
+ if (temporals === 0 && attachments.length === 0) {
85
77
  ctx.diagnostics.push(new WarningDiagnostic("W_ADJUST_NO_TARGET", "@adjust 没有找到可调整的对象", this.sourceSpan));
86
78
  }
79
+ else if (temporals === 0 && (this.dx !== 0 || this.dy !== 0)) {
80
+ for (const attachment of attachments)
81
+ offsetAttachment(attachment, this.dx, this.dy);
82
+ }
87
83
  return [];
88
84
  }
89
85
  constructor(sourceSpan, args, ctx, parent = null) {
@@ -102,58 +98,74 @@ class AdjustFunction extends ASTFunctionNode {
102
98
  }
103
99
  export const AdjustNode = AdjustFunction;
104
100
  /** 在原对象上组合布局生命周期,保持布局索引依赖的对象身份 */
105
- function offsetTemporal(node, owner) {
106
- const { dx, dy, dw, dh } = owner;
101
+ function offsetTemporal(node, { dx, dy, dw, dh }) {
107
102
  if (dx === 0 && dy === 0 && dw === 0 && dh === 0)
108
103
  return;
104
+ const firstOffset = !node.placementOffset && (dx !== 0 || dy !== 0);
109
105
  if (dx !== 0 || dy !== 0) {
110
106
  node.placementOffset = { x: (node.placementOffset?.x ?? 0) + dx, y: (node.placementOffset?.y ?? 0) + dy };
111
107
  }
112
108
  let placedX;
113
109
  let placedY;
114
110
  const finalize = node.finalizeLayout;
115
- const onPlaced = node.onPlaced;
116
111
  node.finalizeLayout = (context) => {
117
112
  finalize?.call(node, context);
113
+ placedX = placedY = undefined;
118
114
  const width = Math.max(0, node.box.w + dw);
119
115
  node.box.anchor = node.box.w > 0 ? node.box.anchor * width / node.box.w : 0;
120
116
  node.box.w = width;
121
117
  node.box.h = Math.max(0, node.box.h + dh);
122
118
  };
119
+ if (!firstOffset)
120
+ return;
121
+ let { x, y } = node.box;
122
+ Object.defineProperties(node.box, {
123
+ x: {
124
+ get: () => x,
125
+ set(v) { if (v === placedX && x === placedX)
126
+ placedX = undefined; x = v; }
127
+ },
128
+ y: {
129
+ get: () => y,
130
+ set(v) { if (v === placedY && y === placedY)
131
+ placedY = undefined; y = v; }
132
+ },
133
+ });
134
+ const onPlaced = node.onPlaced;
123
135
  node.onPlaced = () => {
124
- if (node.box.x !== placedX)
125
- node.box.x += dx;
126
- if (node.box.y !== placedY)
127
- node.box.y += dy;
136
+ if (x !== placedX)
137
+ x += node.placementOffset.x;
138
+ if (y !== placedY)
139
+ y += node.placementOffset.y;
128
140
  onPlaced?.call(node);
129
- placedX = node.box.x;
130
- placedY = node.box.y;
141
+ placedX = x;
142
+ placedY = y;
131
143
  };
132
144
  }
133
145
  /**
134
146
  * 平移一条关系对象
135
147
  *
136
148
  * 在原 Attachment 上组合 createGeometry,保留依赖查找与 instanceof 所需的对象身份
137
- * 作用域里只要有对象被平移过,关系对象就已经跟着端点走了,这里不能再平移第二次
149
+ * 仅在作用域里没有时间对象时调用,避免关系对象既跟端点走又被重复平移
138
150
  */
139
- function offsetAttachment(attachment, targets, dx, dy) {
140
- if (targets.temporal > 0 || (dx === 0 && dy === 0))
141
- return;
151
+ function offsetAttachment(attachment, dx, dy) {
152
+ const firstOffset = !attachment.placementOffset;
142
153
  attachment.placementOffset = { x: (attachment.placementOffset?.x ?? 0) + dx, y: (attachment.placementOffset?.y ?? 0) + dy };
154
+ if (!firstOffset)
155
+ return;
143
156
  const createGeometry = attachment.createGeometry;
144
157
  attachment.createGeometry = (context) => {
145
158
  const geometry = createGeometry.call(attachment, context);
146
- if (targets.temporal > 0 || context.layoutOnly)
159
+ if (context.layoutOnly)
147
160
  return geometry;
148
- const shift = (region) => region.line === void 0
149
- ? { x: region.x + dx, y: region.y + dy, w: region.w, h: region.h }
150
- : { x: region.x + dx, y: region.y + dy, w: region.w, h: region.h, line: region.line, track: region.track };
161
+ const { x, y } = attachment.placementOffset;
162
+ const shift = (region) => ({ ...region, x: region.x + x, y: region.y + y });
151
163
  return {
152
164
  regions: geometry.regions.map(shift),
153
165
  occupancy: geometry.occupancy?.map(shift),
154
166
  paint(painter) {
155
167
  // attachment 的绘制大多用闭包存储了,所以只能代理 painter
156
- geometry.paint(new TranslatingPainter(painter, dx, dy));
168
+ geometry.paint(new TranslatingPainter(painter, x, y));
157
169
  },
158
170
  };
159
171
  };