@k-l-lambda/lilylet 0.1.69 → 0.1.70

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.
@@ -0,0 +1,226 @@
1
+ /**
2
+ * Staff-layout parser, ported from FindLab starry (app/staffLayout/).
3
+ *
4
+ * The layout string uses STAFF as the leaf unit (distinct from ABC's %%score,
5
+ * which is voice-leaf). Brackets group staves: `{}` = Brace (grand staff),
6
+ * `<>` = Bracket, `[]` = Square; conjunctions between consecutive staves:
7
+ * `,` = Blank, `-` = Solid, `.` = Dashed. Staff ids are [a-zA-Z_0-9]+; a slot
8
+ * with no id is an anonymous staff (auto-named "1","2",…).
9
+ *
10
+ * Example: "<[v1-v2].va> {pl-pr} <b>" → 6 staves v1,v2,va,pl,pr,b grouped as
11
+ * a Bracket over { a Square [v1-v2] dashed-joined to va }, a Brace {pl-pr},
12
+ * and a Bracket <b>.
13
+ */
14
+ export var StaffGroupType;
15
+ (function (StaffGroupType) {
16
+ StaffGroupType[StaffGroupType["Default"] = 0] = "Default";
17
+ StaffGroupType[StaffGroupType["Brace"] = 1] = "Brace";
18
+ StaffGroupType[StaffGroupType["Bracket"] = 2] = "Bracket";
19
+ StaffGroupType[StaffGroupType["Square"] = 3] = "Square";
20
+ })(StaffGroupType || (StaffGroupType = {}));
21
+ export var StaffConjunctionType;
22
+ (function (StaffConjunctionType) {
23
+ StaffConjunctionType[StaffConjunctionType["Blank"] = 0] = "Blank";
24
+ StaffConjunctionType[StaffConjunctionType["Dashed"] = 1] = "Dashed";
25
+ StaffConjunctionType[StaffConjunctionType["Solid"] = 2] = "Solid";
26
+ })(StaffConjunctionType || (StaffConjunctionType = {}));
27
+ const singleGroup = (id) => ({ type: StaffGroupType.Default, staff: id });
28
+ const BOUNDS_TO_GROUPTYPE = {
29
+ "{": StaffGroupType.Brace,
30
+ "}": StaffGroupType.Brace,
31
+ "<": StaffGroupType.Bracket,
32
+ ">": StaffGroupType.Bracket,
33
+ "[": StaffGroupType.Square,
34
+ "]": StaffGroupType.Square,
35
+ };
36
+ const OPEN_BOUNDS = "{<[";
37
+ const CLOSE_BOUNDS = "}>]";
38
+ const CONJUNCTIONS_MAP = {
39
+ ",": StaffConjunctionType.Blank,
40
+ "-": StaffConjunctionType.Solid,
41
+ ".": StaffConjunctionType.Dashed,
42
+ };
43
+ // MEI staffGrp @symbol by StaffGroupType (Default → none). MEI's allowed values
44
+ // are brace | bracket | bracketsq | line | none — note the square variant is
45
+ // "bracketsq", NOT "square" (the latter is MusicXML's <group-symbol> value).
46
+ const GROUP_SYMBOLS_MEI = [null, "brace", "bracket", "bracketsq"];
47
+ const randomB64 = () => {
48
+ const code = Buffer.from(Math.random().toString().slice(2)).toString("base64").replace(/=/g, "");
49
+ return code.split("").reverse().slice(0, 6).join("");
50
+ };
51
+ const makeUniqueName = (set, index, prefix) => {
52
+ let name = prefix;
53
+ if (!name)
54
+ name = index.toString();
55
+ else if (set.has(name))
56
+ name += "_" + index.toString();
57
+ while (set.has(name))
58
+ name = (prefix ? prefix + "_" : "") + randomB64();
59
+ return name;
60
+ };
61
+ // Tokenize a layout string into RawItem[] (one per staff slot). Lexer: whitespace
62
+ // skipped, single chars [-,.{}<>[]] are bounds/conjunctions, [a-zA-Z_0-9]+ is an id.
63
+ // An item accumulates leading open-bounds (leftBounds), an optional id, trailing
64
+ // close-bounds (rightBounds); a conjunction terminates the item and starts the next.
65
+ const tokenize = (code) => {
66
+ const tokens = code.match(/[A-Za-z0-9_]+|[-,.{}<>\[\]]/g) || [];
67
+ const items = [];
68
+ let cur = { id: null, leftBounds: [], rightBounds: [], conjunction: null };
69
+ let seenId = false; // id slot filled for the current item
70
+ let seenRight = false; // started collecting right bounds / closing
71
+ const pushItem = () => {
72
+ items.push(cur);
73
+ cur = { id: null, leftBounds: [], rightBounds: [], conjunction: null };
74
+ seenId = false;
75
+ seenRight = false;
76
+ };
77
+ for (const tok of tokens) {
78
+ if (tok in CONJUNCTIONS_MAP) {
79
+ cur.conjunction = tok;
80
+ pushItem();
81
+ continue;
82
+ }
83
+ if (OPEN_BOUNDS.includes(tok)) {
84
+ // An open bound after the id/closing starts a fresh item's left bounds.
85
+ if (seenId || seenRight)
86
+ pushItem();
87
+ cur.leftBounds.push(tok);
88
+ continue;
89
+ }
90
+ if (CLOSE_BOUNDS.includes(tok)) {
91
+ cur.rightBounds.push(tok);
92
+ seenRight = true;
93
+ continue;
94
+ }
95
+ // id token
96
+ if (seenId || seenRight)
97
+ pushItem();
98
+ cur.id = tok;
99
+ seenId = true;
100
+ }
101
+ // Flush the final item if it carries any content.
102
+ if (cur.id !== null || cur.leftBounds.length || cur.rightBounds.length)
103
+ pushItem();
104
+ return items;
105
+ };
106
+ const makeGroupsFromRaw = (parent, seq) => {
107
+ let remains = seq;
108
+ while (remains.length) {
109
+ const word = remains.shift();
110
+ const bound = BOUNDS_TO_GROUPTYPE[word];
111
+ if (bound !== undefined) {
112
+ if (CLOSE_BOUNDS.includes(word) && bound === parent.type)
113
+ break;
114
+ if (OPEN_BOUNDS.includes(word)) {
115
+ const group = { type: bound, level: Number.isFinite(parent.level) ? parent.level + 1 : 0 };
116
+ remains = makeGroupsFromRaw(group, remains);
117
+ parent.subs = parent.subs || [];
118
+ parent.subs.push(group);
119
+ }
120
+ }
121
+ else {
122
+ parent.subs = parent.subs || [];
123
+ parent.subs.push(singleGroup(word));
124
+ }
125
+ }
126
+ while (parent.type === StaffGroupType.Default && parent.subs && parent.subs.length === 1) {
127
+ const sub = parent.subs[0];
128
+ parent.type = sub.type;
129
+ parent.subs = sub.subs;
130
+ parent.staff = sub.staff;
131
+ parent.level = sub.level;
132
+ }
133
+ while (parent.subs && parent.subs.length === 1 && parent.subs[0].type === StaffGroupType.Default) {
134
+ const sub = parent.subs[0];
135
+ parent.subs = sub.subs;
136
+ parent.staff = sub.staff;
137
+ }
138
+ parent.grand = parent.type === StaffGroupType.Brace && !!parent.subs && parent.subs.every(sub => !!sub.staff);
139
+ return remains;
140
+ };
141
+ const groupHead = (group) => {
142
+ if (group.staff)
143
+ return group.staff;
144
+ else if (group.subs)
145
+ return groupHead(group.subs[0]);
146
+ };
147
+ const groupTail = (group) => {
148
+ if (group.staff)
149
+ return group.staff;
150
+ else if (group.subs)
151
+ return groupTail(group.subs[group.subs.length - 1]);
152
+ };
153
+ export const groupKey = (group) => {
154
+ if (group.staff)
155
+ return group.staff;
156
+ else if (group.subs)
157
+ return `${groupHead(group)}-${groupTail(group)}`;
158
+ };
159
+ const groupDict = (group, dict) => {
160
+ const key = groupKey(group);
161
+ if (key !== undefined)
162
+ dict[key] = group;
163
+ if (group.subs)
164
+ group.subs.forEach(sub => groupDict(sub, dict));
165
+ };
166
+ export class StaffLayout {
167
+ staffIds;
168
+ conjunctions;
169
+ group;
170
+ groups;
171
+ constructor(raw) {
172
+ // make unique ids (anonymous slots get "1","2",… ; named collisions disambiguated)
173
+ const ids = new Set();
174
+ raw.forEach((item, i) => {
175
+ item.id = makeUniqueName(ids, i + 1, item.id || undefined);
176
+ ids.add(item.id);
177
+ });
178
+ this.staffIds = raw.map(item => item.id);
179
+ this.conjunctions = raw.slice(0, raw.length - 1).map(item => item.conjunction ? CONJUNCTIONS_MAP[item.conjunction] : StaffConjunctionType.Blank);
180
+ // make groups
181
+ const seq = [].concat(...raw.map(item => [...item.leftBounds, item.id, ...item.rightBounds]));
182
+ this.group = { type: StaffGroupType.Default };
183
+ makeGroupsFromRaw(this.group, seq);
184
+ const dict = {};
185
+ groupDict(this.group, dict);
186
+ this.groups = Object.entries(dict).map(([key, group]) => {
187
+ let ids = key.split("-");
188
+ if (ids.length === 1)
189
+ ids = [ids[0], ids[0]];
190
+ const range = ids.map(id => this.staffIds.indexOf(id));
191
+ const cons = this.conjunctions.slice(range[0], range[1]);
192
+ const bar = cons.length ? Math.min(...cons) : 0;
193
+ group.key = key;
194
+ group.bar = bar;
195
+ return { group, range, key };
196
+ });
197
+ }
198
+ get stavesCount() {
199
+ return this.staffIds.length;
200
+ }
201
+ }
202
+ export const parseStaffLayout = (code) => new StaffLayout(tokenize(code));
203
+ // ── MEI staffGrp encoding (ported from FindLab staffLayout/encoding.js encodeMEI) ──
204
+ // Recursively emit nested <staffGrp> with symbol (brace/bracket/square) and bar.thru,
205
+ // with <staffDef n="..."> leaves keyed by staff index. nameDict maps a group key to a
206
+ // label. Returns the inner XML (no <scoreDef> wrapper); the caller positions it.
207
+ const bool = (x) => (x ? "true" : "false");
208
+ const stateMEIGroup = (statements, group, nameDict, ids, indent, tab) => {
209
+ const pad = tab.repeat(indent);
210
+ const name = group.key !== undefined ? nameDict[group.key] : undefined;
211
+ if (group.subs) {
212
+ const symbol = GROUP_SYMBOLS_MEI[group.type] ? ` symbol="${GROUP_SYMBOLS_MEI[group.type]}"` : "";
213
+ statements.push(`${pad}<staffGrp bar.thru="${bool((group.bar ?? 0) > 1)}"${symbol}>`);
214
+ if (name)
215
+ statements.push(`${pad}${tab}<label>${name}</label>`);
216
+ group.subs.forEach(sub => stateMEIGroup(statements, sub, nameDict, ids, indent + 1, tab));
217
+ statements.push(`${pad}</staffGrp>`);
218
+ }
219
+ if (group.staff)
220
+ statements.push(`${pad}<staffDef n="${ids.indexOf(group.staff) + 1}">`);
221
+ };
222
+ export const encodeStaffLayoutMEI = (layout, nameDict = {}, indent = 0, tab = "\t") => {
223
+ const statements = [];
224
+ stateMEIGroup(statements, layout.group, nameDict, layout.staffIds, indent, tab);
225
+ return statements.join("\n");
226
+ };
@@ -239,8 +239,16 @@ export interface Metadata {
239
239
  opus?: string;
240
240
  instrument?: string;
241
241
  genre?: string;
242
+ staves?: string;
243
+ instruments?: {
244
+ [key: string]: InstrumentName;
245
+ };
242
246
  autoBeam?: 'auto' | 'on' | 'off';
243
247
  }
248
+ export interface InstrumentName {
249
+ name: string;
250
+ shortName?: string;
251
+ }
244
252
  export interface Part {
245
253
  name?: string;
246
254
  voices: Voice[];
@@ -0,0 +1 @@
1
+ export * from "./lilylet/staffLayout.js";
@@ -0,0 +1 @@
1
+ export * from "./lilylet/staffLayout.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@k-l-lambda/lilylet",
3
- "version": "0.1.69",
3
+ "version": "0.1.70",
4
4
  "description": "Lilylet is a lilyopnd-like sheet music language designed for Markdown rendering and symbolic music representation in AIGC applications.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -361,7 +361,7 @@ staff_layout
361
361
  staff_layout_items
362
362
  : staff_layout_item -> [$1]
363
363
  | staff_layout_items staff_layout_item -> [...$1, $2]
364
- | staff_layout_items '|' -> $1
364
+ | staff_layout_items '|' { if ($1.length) $1[$1.length - 1].barThruAfter = true; $$ = $1; }
365
365
  ;
366
366
 
367
367
  staff_layout_item
package/source/abc/abc.ts CHANGED
@@ -130,6 +130,7 @@ namespace ABC {
130
130
  export interface StaffGroup {
131
131
  items: (StaffGroup | string)[];
132
132
  bound?: 'arc' | 'square' | 'curly';
133
+ barThruAfter?: boolean; // a '|' followed this sibling in %%score (barlines run through)
133
134
  };
134
135
 
135
136
 
@@ -95,7 +95,7 @@ break;
95
95
  case 4:
96
96
  this.$ = tune($$[$0-1], $$[$0]);
97
97
  break;
98
- case 11: case 12: case 13: case 14: case 16: case 20: case 67: case 101: case 104: case 105: case 106: case 107: case 136: case 137: case 163: case 164: case 222:
98
+ case 11: case 12: case 13: case 14: case 16: case 67: case 101: case 104: case 105: case 106: case 107: case 136: case 137: case 163: case 164: case 222:
99
99
  this.$ = $$[$0-1];
100
100
  break;
101
101
  case 15:
@@ -104,6 +104,9 @@ break;
104
104
  case 17:
105
105
  this.$ = ({staffLayout: $$[$0]});
106
106
  break;
107
+ case 20:
108
+ if ($$[$0-1].length) $$[$0-1][$$[$0-1].length - 1].barThruAfter = true; this.$ = $$[$0-1];
109
+ break;
107
110
  case 21:
108
111
  this.$ = staffGroup([$$[$0]]);
109
112
  break;
@@ -37,7 +37,9 @@ import {
37
37
  MarkupEvent,
38
38
  DynamicEvent,
39
39
  Placement,
40
+ InstrumentName,
40
41
  } from "./types";
42
+ import { parseStaffLayout, StaffGroup, StaffGroupType } from "./staffLayout";
41
43
 
42
44
 
43
45
  // ============ Constants ============
@@ -395,6 +397,9 @@ const convertClef = (clefStr: string): Clef | undefined => {
395
397
  // Split off an optional ABC octave shift suffix: "treble-8", "bass+8", "treble-15".
396
398
  // ABC: "-N" lowers the sounding pitch (small N drawn below), "+N" raises it.
397
399
  // LilyPond/Lilylet: "_N" = below, "^N" = above. Translate the sign accordingly.
400
+ // (Only octave amounts 8/15 are handled here; the Lilylet "_N"/"^N" clef suffix
401
+ // itself accepts arbitrary diatonic intervals — see meiEncoder.resolveClef — and a
402
+ // voice's transpose= property is folded into the same suffix via transposeClefSuffix.)
398
403
  const shift = clefStr?.match(/^(.*?)([+-])(8|15)$/);
399
404
  const base = shift ? shift[1] : clefStr;
400
405
  let resolved: string | undefined;
@@ -408,6 +413,29 @@ const convertClef = (clefStr: string): Clef | undefined => {
408
413
  return resolved as Clef;
409
414
  };
410
415
 
416
+ /**
417
+ * Fold an ABC voice `transpose=N` property (a written→sounding shift in
418
+ * SEMITONES) into the Lilylet clef-suffix form `_M` / `^M`, where M is a
419
+ * diatonic interval number. ABC carries only semitones, so the diatonic
420
+ * interval is approximated by the nearest scale-step count
421
+ * (steps = round(semi * 7/12), interval number = |steps| + 1); `_` lowers,
422
+ * `^` raises. The Lilylet→MEI encoder later expands the suffix back into
423
+ * trans.diat / trans.semi (see meiEncoder.resolveClef). This is exact when the
424
+ * semitone count is a major/perfect interval (e.g. -2, -9, +2, ±12) and a
425
+ * nearest-interval approximation otherwise.
426
+ */
427
+ const transposeClefSuffix = (clef: Clef | undefined, semitones: number): Clef | undefined => {
428
+ if (!clef || !semitones) return clef;
429
+ // A clef that already carries an octave suffix (treble_8 etc.) is left as-is;
430
+ // stacking another shift on top is not meaningful for ABC sources.
431
+ if (/[_^]\d+$/.test(clef as string)) return clef;
432
+ const steps = Math.round((semitones * 7) / 12);
433
+ if (steps === 0) return clef;
434
+ const num = Math.abs(steps) + 1;
435
+ const suffix = (steps < 0 ? "_" : "^") + num;
436
+ return (clef + suffix) as Clef;
437
+ };
438
+
411
439
  /**
412
440
  * Convert ABC barline to Lilylet barline style
413
441
  */
@@ -516,6 +544,161 @@ const parseScoreLayout = (
516
544
  };
517
545
 
518
546
 
547
+ /**
548
+ * Translate an ABC %%score layout into the equivalent lilylet staves expression.
549
+ *
550
+ * The two models differ in their leaf unit: ABC %%score is VOICE-leaf (an arc `( … )`
551
+ * collapses several voices onto one staff), whereas lilylet staves is STAFF-leaf. So
552
+ * each ABC staff becomes exactly one lilylet staff id, named (per spec) by the FIRST
553
+ * voice token inside its arc.
554
+ *
555
+ * Bracket mapping (ABC → lilylet):
556
+ * ( … ) arc → one staff leaf (id = first voice) e.g. (1 3) → "1"
557
+ * bare leaf → one staff leaf (id = that voice) e.g. 7 → "7"
558
+ * { … } curly → brace (grand staff) → { … }
559
+ * [ … ] square → bracket (orchestral) → < … >
560
+ *
561
+ * Conjunction between two siblings: a trailing `|` in %%score means barlines run through
562
+ * the two staves, mapped to the solid conjunction `-`; otherwise the blank `,` is used.
563
+ */
564
+ const abcLayoutToStaves = (layout: ABC.StaffGroup[]): string | null => {
565
+ // First voice token under a node (the staff's lilylet id).
566
+ const firstVoice = (node: ABC.StaffGroup | string): string | null => {
567
+ if (typeof node === "string") return node;
568
+ for (const item of node.items || []) {
569
+ const v = firstVoice(item);
570
+ if (v !== null) return v;
571
+ }
572
+ return null;
573
+ };
574
+
575
+ // A node is a single staff (an arc, or a bare leaf) iff it has no curly/square nesting.
576
+ const isStaffLeaf = (node: ABC.StaffGroup | string): boolean => {
577
+ if (typeof node === "string") return true;
578
+ if (node.bound === "curly" || node.bound === "square") return false;
579
+ // arc or unbounded: a staff only if every descendant is too (no nested groups)
580
+ return (node.items || []).every(isStaffLeaf);
581
+ };
582
+
583
+ const emit = (node: ABC.StaffGroup | string): string => {
584
+ if (isStaffLeaf(node)) return firstVoice(node) || "";
585
+
586
+ const group = node as ABC.StaffGroup;
587
+ const open = group.bound === "curly" ? "{" : "<"; // square → bracket <>, curly → brace {}
588
+ const close = group.bound === "curly" ? "}" : ">";
589
+
590
+ const items = group.items || [];
591
+ let inner = "";
592
+ items.forEach((item, i) => {
593
+ inner += emit(item);
594
+ if (i < items.length - 1) {
595
+ const conj = (item as ABC.StaffGroup).barThruAfter ? "-" : ",";
596
+ inner += conj;
597
+ }
598
+ });
599
+ return `${open}${inner}${close}`;
600
+ };
601
+
602
+ const tops = layout.map((top, i) => {
603
+ let s = emit(top);
604
+ // A bare top-level staff leaf (e.g. the `9` in `[ … ] 9 [ … ]`) still occupies a slot;
605
+ // emit() already yields its id with no wrapper, which is the desired output.
606
+ return { s, barThru: !!top.barThruAfter, isLast: i === layout.length - 1 };
607
+ });
608
+
609
+ let out = "";
610
+ tops.forEach((t, i) => {
611
+ out += t.s;
612
+ if (i < tops.length - 1) out += t.barThru ? " - " : " ";
613
+ });
614
+
615
+ out = out.trim();
616
+ return out.length > 0 ? out : null;
617
+ };
618
+
619
+
620
+ /**
621
+ * Translate ABC voice instrument names (V:n nm="…" snm="…") into a lilylet `instruments`
622
+ * map keyed by staff-layout group key.
623
+ *
624
+ * ABC names sit on individual voices; lilylet staves are staff-leaf (an arc's first voice
625
+ * is the staff id). So we first collect a per-staff name from the staff-id voice. Then,
626
+ * per the user's rule: if a GROUP carries an instrument only on its first staff and the
627
+ * rest of the group is unnamed, the name belongs to the whole group — hoist it to the
628
+ * group key and drop it from the leaf. This matches engraving convention (one bracketed
629
+ * section, e.g. "Violini", named once for the group rather than on its top staff).
630
+ *
631
+ * `voiceInstr` maps an ABC voice number to its {name, shortName}. The layout's staff ids
632
+ * are arc-first voice numbers, so a staff id "5" looks up voice 5's name.
633
+ */
634
+ const abcInstrumentsToLilylet = (
635
+ stavesCode: string,
636
+ voiceInstr: Map<number, InstrumentName>,
637
+ ): { [key: string]: InstrumentName } | null => {
638
+ const layout = parseStaffLayout(stavesCode);
639
+ const result: { [key: string]: InstrumentName } = {};
640
+
641
+ // Per-staff instrument, keyed by staff id (the arc-first voice number as a string).
642
+ const staffInstr = new Map<string, InstrumentName>();
643
+ for (const id of layout.staffIds) {
644
+ const v = parseInt(id, 10);
645
+ if (!isNaN(v) && voiceInstr.has(v)) staffInstr.set(id, voiceInstr.get(v)!);
646
+ }
647
+
648
+ // First staff id under a group (in layout order).
649
+ const firstStaffId = (group: StaffGroup): string | undefined => {
650
+ if (group.staff) return group.staff;
651
+ for (const sub of group.subs || []) {
652
+ const id = firstStaffId(sub);
653
+ if (id !== undefined) return id;
654
+ }
655
+ return undefined;
656
+ };
657
+
658
+ // All staff ids under a group except the first.
659
+ const restStaffIds = (group: StaffGroup): string[] => {
660
+ const all: string[] = [];
661
+ const collect = (g: StaffGroup) => {
662
+ if (g.staff) all.push(g.staff);
663
+ (g.subs || []).forEach(collect);
664
+ };
665
+ collect(group);
666
+ return all.slice(1);
667
+ };
668
+
669
+ // Walk groups top-down; hoist a first-staff-only name onto the group, else keep leaves.
670
+ const walk = (group: StaffGroup) => {
671
+ const isLeaf = !!group.staff && (!group.subs || group.subs.length === 0);
672
+ if (isLeaf) {
673
+ // A plain leaf keeps its own name (assigned in the flush pass below).
674
+ return;
675
+ }
676
+
677
+ const first = firstStaffId(group);
678
+ const firstInstr = first !== undefined ? staffInstr.get(first) : undefined;
679
+ const rest = restStaffIds(group);
680
+ const restNamed = rest.some(id => staffInstr.has(id));
681
+
682
+ // Group with a real grouping symbol, named only on its first staff → hoist.
683
+ const hasSymbol = group.type !== StaffGroupType.Default;
684
+ if (hasSymbol && firstInstr && !restNamed && group.key !== undefined) {
685
+ result[group.key] = firstInstr;
686
+ staffInstr.delete(first!); // consumed by the group
687
+ return; // children below the hoisted name carry nothing
688
+ }
689
+
690
+ for (const sub of group.subs || []) walk(sub);
691
+ };
692
+
693
+ walk(layout.group);
694
+
695
+ // Flush any per-staff names that weren't hoisted onto a group.
696
+ for (const [id, instr] of staffInstr) result[id] = instr;
697
+
698
+ return Object.keys(result).length > 0 ? result : null;
699
+ };
700
+
701
+
519
702
  // ============ Marks/Decorations Conversion ============
520
703
 
521
704
  const convertArticulationMark = (artName: string): Mark | undefined => {
@@ -1103,7 +1286,17 @@ const decodeTune = (tune: ABC.Tune, options: DecodeOptions = {}): LilyletDoc =>
1103
1286
  properties: voiceValue?.properties,
1104
1287
  });
1105
1288
  if (clefStr) {
1106
- const clef = convertClef(clefStr);
1289
+ let clef = convertClef(clefStr);
1290
+ // Fold a voice transpose= (semitones) into the clef suffix so it
1291
+ // survives to MEI as trans.diat/trans.semi (transposing instruments
1292
+ // like "Clarinet transpose=-2", "Horn transpose=-9").
1293
+ const transposeRaw = (voiceValue as any)?.properties?.transpose;
1294
+ const transposeSemi = typeof transposeRaw === "number"
1295
+ ? transposeRaw
1296
+ : (transposeRaw != null ? Number(transposeRaw) : NaN);
1297
+ if (clef && Number.isFinite(transposeSemi) && transposeSemi !== 0) {
1298
+ clef = transposeClefSuffix(clef, transposeSemi);
1299
+ }
1107
1300
  if (clef) voiceClefs.set(voiceId, clef);
1108
1301
  }
1109
1302
  }
@@ -1115,6 +1308,36 @@ const decodeTune = (tune: ABC.Tune, options: DecodeOptions = {}): LilyletDoc =>
1115
1308
  // Parse score layout
1116
1309
  const scoreLayout = parseScoreLayout(headers);
1117
1310
 
1311
+ // Translate the ABC %%score layout into a lilylet staves expression (staff-leaf model).
1312
+ const layoutHeader = headers.find((h: any) => h.staffLayout);
1313
+ if (layoutHeader) {
1314
+ const staves = abcLayoutToStaves((layoutHeader as any).staffLayout);
1315
+ if (staves) metadata.staves = staves;
1316
+
1317
+ // Translate per-voice nm/snm into a lilylet instruments map. Collect names by ABC
1318
+ // voice number (the staff id is the arc-first voice), then let abcInstrumentsToLilylet
1319
+ // apply the first-staff-only → whole-group hoisting rule.
1320
+ if (metadata.staves) {
1321
+ const voiceInstr = new Map<number, InstrumentName>();
1322
+ for (const [vid, config] of voiceConfigs) {
1323
+ const props = config.properties;
1324
+ if (!props) continue;
1325
+ const name = props.nm ?? props.name;
1326
+ if (typeof name !== "string" || !name.length) continue;
1327
+ const v = typeof vid === "number" ? vid : parseInt(String(vid), 10);
1328
+ if (isNaN(v)) continue;
1329
+ const short = props.snm ?? props.sname;
1330
+ voiceInstr.set(v, typeof short === "string" && short.length
1331
+ ? { name, shortName: short }
1332
+ : { name });
1333
+ }
1334
+ if (voiceInstr.size > 0) {
1335
+ const instruments = abcInstrumentsToLilylet(metadata.staves, voiceInstr);
1336
+ if (instruments) metadata.instruments = instruments;
1337
+ }
1338
+ }
1339
+ }
1340
+
1118
1341
  // Group measures by voice
1119
1342
  // ABC measures contain BarPatches, each with a voice control V:n
1120
1343
  const measures = body.measures;