@dsebastien/music-notation 0.18.0 → 0.19.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.
@@ -851,6 +851,28 @@ function svgRoot(doc, width, height, cls, label) {
851
851
  "aria-labelledby": id
852
852
  }, [svg(doc, "defs", {}, [title])]);
853
853
  }
854
+ function describeDiagram(diagram, text) {
855
+ if (!text)
856
+ return;
857
+ const defs = [...diagram.children].find((c) => c.tagName.toLowerCase() === "defs");
858
+ if (!defs)
859
+ return;
860
+ const id = `${NAME_PREFIX}${++names}`;
861
+ const desc = svg(diagram.ownerDocument, "desc", { class: "mn-desc", id });
862
+ desc.textContent = text;
863
+ defs.appendChild(desc);
864
+ diagram.setAttribute("aria-describedby", id);
865
+ }
866
+ function descriptionOf(diagram) {
867
+ const id = diagram.getAttribute("aria-describedby");
868
+ if (!id)
869
+ return null;
870
+ for (const candidate of diagram.querySelectorAll("desc")) {
871
+ if (candidate.getAttribute("id") === id)
872
+ return candidate.textContent;
873
+ }
874
+ return null;
875
+ }
854
876
  var nameElement = (el) => {
855
877
  const id = el.getAttribute("aria-labelledby");
856
878
  if (!id)
@@ -887,719 +909,382 @@ function playableMark(doc, area, ...children) {
887
909
  return svg(doc, "g", { class: "mn-mark" }, [hit, ...children]);
888
910
  }
889
911
 
890
- // src/render/layout.ts
891
- function parseOrientation(text) {
892
- const value = text.trim().toLowerCase();
893
- if (value === "vertical" || value === "horizontal")
894
- return value;
895
- throw new Error(`Unknown orientation "${text}": use vertical or horizontal`);
912
+ // src/render/root-mark.ts
913
+ var ROOT_MARKS = ["color", "shape"];
914
+ var ROOT_MARK_ERROR = "root-mark: write color or shape";
915
+ function rootMarkOf(value) {
916
+ if (typeof value !== "string")
917
+ return null;
918
+ const text = value.trim().toLowerCase();
919
+ if (text === "color" || text === "colour")
920
+ return "color";
921
+ if (text === "shape")
922
+ return "shape";
923
+ return null;
896
924
  }
897
- function parseHand(text) {
898
- const value = text.trim().toLowerCase();
899
- if (value === "left" || value === "right")
900
- return value;
901
- throw new Error(`Unknown hand "${text}": use left or right`);
925
+ function parseRootMark(text) {
926
+ const mark = rootMarkOf(text);
927
+ if (!mark)
928
+ throw new Error(`${ROOT_MARK_ERROR}, got "${text.trim()}"`);
929
+ return mark;
930
+ }
931
+ var ROOT_MARK_LINE = /^\s*root-mark\s*:\s*(.*)$/i;
932
+ var MARKED_LANGUAGES = new Set(["chord", "keyboard", "fretboard", "progression"]);
933
+ function rootMarkInBlock(language, text) {
934
+ if (!MARKED_LANGUAGES.has(language))
935
+ return { text, mark: null };
936
+ let mark = null;
937
+ const lines = [];
938
+ for (const line of text.split(`
939
+ `)) {
940
+ const own = ROOT_MARK_LINE.exec(line);
941
+ if (!own)
942
+ lines.push(line);
943
+ else
944
+ mark = parseRootMark(own[1]);
945
+ }
946
+ return { text: mark === null ? text : lines.join(`
947
+ `), mark };
902
948
  }
903
- function layoutDefaults(value) {
904
- const result = {};
905
- if (!value || typeof value !== "object")
906
- return result;
907
- const word = (v) => typeof v === "string" ? v.trim().toLowerCase() : undefined;
949
+ var current2 = "color";
950
+ function withRootMark(mark, draw) {
951
+ const before = current2;
952
+ current2 = mark;
908
953
  try {
909
- const { orientation, hand } = value;
910
- const h = word(hand);
911
- if (h === "left" || h === "right")
912
- result.hand = h;
913
- if (orientation && typeof orientation === "object") {
914
- for (const language of ["chord", "keyboard", "fretboard"]) {
915
- const o = word(orientation[language]);
916
- if (o === "vertical" || o === "horizontal")
917
- (result.orientation ??= {})[language] = o;
918
- }
919
- }
920
- } catch {}
921
- return result;
922
- }
923
- function titleWidth(title) {
924
- if (!title)
925
- return 0;
926
- let width = 8;
927
- for (const ch of title) {
928
- width += ch.codePointAt(0) > 591 ? 15 : /[A-Z0-9#♯♭]/.test(ch) ? 10.5 : 8;
954
+ return draw();
955
+ } finally {
956
+ current2 = before;
929
957
  }
930
- return Math.ceil(width);
931
958
  }
932
- var MAX_TITLE_LINES = 3;
933
- var TITLE_LINE = 17;
934
- function titleLineWidth(text) {
935
- if (!text)
936
- return 0;
937
- let width = 8;
938
- for (const ch of text) {
939
- const code = ch.codePointAt(0);
940
- width += code > 591 ? 15 : ch === " " || ".,:;'!|".includes(ch) ? 4 : "()[]-/".includes(ch) || "iljfrt".includes(ch) ? 5 : "mwMW".includes(ch) ? 12 : /[A-Z0-9#♯♭]/.test(ch) ? 9.5 : 7.8;
941
- }
942
- return Math.ceil(width);
959
+ var rootAsShape = () => current2 === "shape";
960
+ function noteMark(doc, root, { cx, cy, r, class: cls, ...rest }) {
961
+ if (!root || current2 !== "shape")
962
+ return svg(doc, "circle", { class: cls, cx, cy, r, ...rest });
963
+ const half = Math.round(0.9 * r * 10) / 10;
964
+ return svg(doc, "rect", {
965
+ class: `${cls ?? ""} mn-root-shape`.trim(),
966
+ x: cx - half,
967
+ y: cy - half,
968
+ width: 2 * half,
969
+ height: 2 * half,
970
+ rx: Math.round(r / 4 * 10) / 10,
971
+ ...rest
972
+ });
943
973
  }
944
- function titleLines(title, width) {
945
- const fits = (text) => titleLineWidth(text) <= width;
946
- const squeeze = (text) => ({
947
- text,
948
- textLength: fits(text) ? null : Math.max(1, width - 8)
974
+
975
+ // src/chord/generate.ts
976
+ var isBarreShape = (shape) => shape === "E shape" || shape === "A shape";
977
+ var MAX_GENERATED_STRINGS = 8;
978
+ var MAX_SPAN = 6;
979
+ function chordInfo(symbol) {
980
+ const set = chordNoteSet(symbol);
981
+ const parts = splitChordSymbol(symbol);
982
+ if (!set || !parts)
983
+ return null;
984
+ const bass = parts.bass ? chromaOf(parts.bass) : null;
985
+ const members = set.members.filter((m) => m.interval !== null);
986
+ const parsed = members.map((m) => {
987
+ const hit = /^(\d+)([PMmdA]+)$/.exec(m.interval);
988
+ return { member: m, number: Number(hit?.[1] ?? 0), quality: hit?.[2] ?? "" };
949
989
  });
950
- if (fits(title))
951
- return [{ text: title, textLength: null }];
952
- const phrases = title.split(/(?<=,)\s+|\s+(?=\()/).flatMap((phrase) => fits(phrase) ? [phrase] : phrase.split(/\s+/)).filter(Boolean);
953
- const lines = [];
954
- let line = "";
955
- for (const phrase of phrases) {
956
- const next = line ? `${line} ${phrase}` : phrase;
957
- if (!line || fits(next))
958
- line = next;
959
- else {
960
- lines.push(line);
961
- line = phrase;
962
- }
963
- }
964
- if (line)
965
- lines.push(line);
966
- if (lines.length > MAX_TITLE_LINES) {
967
- const kept = lines.slice(0, MAX_TITLE_LINES - 1);
968
- kept.push(lines.slice(MAX_TITLE_LINES - 1).join(" "));
969
- return kept.map(squeeze);
990
+ const natural = (p) => p.number > 7 && (p.quality === "M" || p.quality === "P");
991
+ const highest = Math.max(0, ...parsed.filter(natural).map((p) => p.number));
992
+ const eleventh = parsed.some((p) => p.number === 11 && p.quality === "P");
993
+ const tones = parsed.map((p) => {
994
+ let required = true;
995
+ if (p.number === 5 && p.quality === "P")
996
+ required = members.length === 2;
997
+ else if (natural(p) && p.number < highest)
998
+ required = false;
999
+ else if (p.number === 3 && p.quality === "M" && eleventh)
1000
+ required = false;
1001
+ return { chroma: p.member.chroma, number: p.number, required };
1002
+ });
1003
+ if (bass !== null && !tones.some((t) => t.chroma === bass)) {
1004
+ tones.push({ chroma: bass, number: 0, required: true });
970
1005
  }
971
- return lines.map(squeeze);
972
- }
973
- function drawTitle(doc, root, lines, x, y) {
974
- const NS = "http://www.w3.org/2000/svg";
975
- const text = doc.createElementNS(NS, "text");
976
- text.setAttribute("class", "mn-title");
977
- text.setAttribute("x", String(x));
978
- text.setAttribute("y", String(y));
979
- text.setAttribute("text-anchor", "middle");
980
- const squeeze = (el, line) => {
981
- if (line.textLength === null)
982
- return;
983
- el.setAttribute("textLength", String(line.textLength));
984
- el.setAttribute("lengthAdjust", "spacingAndGlyphs");
1006
+ return {
1007
+ tones,
1008
+ members,
1009
+ bass,
1010
+ root: chromaOf(parts.root),
1011
+ suffix: canonicalSuffix(parts.suffix)
985
1012
  };
986
- if (lines.length === 1) {
987
- text.textContent = lines[0].text;
988
- squeeze(text, lines[0]);
989
- } else {
990
- lines.forEach((line, i) => {
991
- const span = doc.createElementNS(NS, "tspan");
992
- span.setAttribute("x", String(x));
993
- if (i > 0)
994
- span.setAttribute("dy", String(TITLE_LINE));
995
- span.textContent = i > 0 ? ` ${line.text}` : line.text;
996
- squeeze(span, line);
997
- text.appendChild(span);
998
- });
999
- }
1000
- root.setAttribute("data-mn-title-lines", String(lines.length));
1001
- root.appendChild(text);
1002
- return text;
1003
1013
  }
1004
- function alignTitleLines(diagrams) {
1005
- const list = [...diagrams].filter((d) => d.hasAttribute("data-mn-title-lines"));
1006
- const most = Math.max(0, ...list.map((d) => Number(d.getAttribute("data-mn-title-lines"))));
1007
- for (const d of list) {
1008
- const missing = most - Number(d.getAttribute("data-mn-title-lines"));
1009
- if (missing <= 0)
1010
- continue;
1011
- const shift = missing * TITLE_LINE;
1012
- const doc = d.ownerDocument;
1013
- const g = doc.createElementNS("http://www.w3.org/2000/svg", "g");
1014
- g.setAttribute("class", "mn-title-pad");
1015
- g.setAttribute("transform", `translate(0 ${shift})`);
1016
- for (const child of [...d.children]) {
1017
- if (child.tagName.toLowerCase() !== "defs")
1018
- g.appendChild(child);
1014
+ function groupingsAt(fret, strings, frets) {
1015
+ const result = [];
1016
+ const walk = (i, acc) => {
1017
+ if (i === strings.length) {
1018
+ result.push(acc);
1019
+ return;
1019
1020
  }
1020
- d.appendChild(g);
1021
- const [x, y, w, h] = (d.getAttribute("viewBox") ?? "0 0 0 0").split(/\s+/).map(Number);
1022
- d.setAttribute("viewBox", `${x} ${y} ${w} ${h + shift}`);
1023
- if (d.hasAttribute("height"))
1024
- d.setAttribute("height", String(Number(d.getAttribute("height")) + shift));
1025
- d.setAttribute("data-mn-title-lines", String(most));
1026
- }
1027
- }
1028
- function neckFrame(n) {
1029
- const vertical = n.orientation === "vertical";
1030
- const left = n.hand === "left";
1031
- const content = vertical ? n.low + n.across + n.high : n.before + n.along + n.after;
1032
- const shift = n.minWidth && n.minWidth > content ? (n.minWidth - content) / 2 : 0;
1033
- const height = n.top + (vertical ? n.before + n.along + n.after : n.high + n.across + n.low);
1034
- const at = (across, along) => {
1035
- if (vertical) {
1036
- const x = left ? n.high + (n.across - across) : n.low + across;
1037
- return [shift + x, n.top + n.before + along];
1021
+ for (let j = i;j < strings.length; j++) {
1022
+ const from = strings[i];
1023
+ const to = strings[j];
1024
+ let ok = true;
1025
+ let under = false;
1026
+ for (let s = from;s <= to; s++) {
1027
+ const f = frets[s];
1028
+ if (f === null || f === undefined || f < fret) {
1029
+ ok = false;
1030
+ break;
1031
+ }
1032
+ if (f > fret)
1033
+ under = true;
1034
+ }
1035
+ if (!ok)
1036
+ break;
1037
+ walk(j + 1, [...acc, { fret, from, to, strings: strings.slice(i, j + 1), under }]);
1038
1038
  }
1039
- const x = left ? content - n.before - along : n.before + along;
1040
- return [shift + x, n.top + n.high + (n.across - across)];
1041
- };
1042
- const box = (a1, l1, a2, l2) => {
1043
- const [x1, y1] = at(a1, l1);
1044
- const [x2, y2] = at(a2, l2);
1045
- return {
1046
- x: Math.min(x1, x2),
1047
- y: Math.min(y1, y2),
1048
- width: Math.abs(x2 - x1),
1049
- height: Math.abs(y2 - y1)
1050
- };
1051
1039
  };
1052
- return { width: content + 2 * shift, height, at, box };
1053
- }
1054
-
1055
- // src/chord/guitar.ts
1056
- var STANDARD_TUNING = [40, 45, 50, 55, 59, 64];
1057
- function chartNoteName(name) {
1058
- if (!/^[A-G](##|bb)$/.test(name))
1059
- return name;
1060
- return nameOf(chromaOf(name), name.endsWith("b"));
1040
+ walk(0, []);
1041
+ return result;
1061
1042
  }
1062
- function parseFrets(text) {
1063
- const trimmed = text.trim();
1064
- const tokens = /[\s,-]/.test(trimmed) ? trimmed.split(/[\s,-]+/) : [...trimmed];
1065
- const frets = tokens.filter(Boolean).map((t) => /^[xX]$/.test(t) ? null : /^\d+$/.test(t) ? Number(t) : NaN);
1066
- return frets.length >= 2 && frets.every((f) => f === null || Number.isInteger(f) && f <= 36) ? frets : null;
1043
+ function fingerChoices(count) {
1044
+ const out = [];
1045
+ const walk = (start, acc) => {
1046
+ if (acc.length === count) {
1047
+ out.push(acc);
1048
+ return;
1049
+ }
1050
+ for (let f = start;f <= 4 - (count - acc.length - 1); f++)
1051
+ walk(f + 1, [...acc, f]);
1052
+ };
1053
+ walk(1, []);
1054
+ return out;
1067
1055
  }
1068
- function parseFingers(text) {
1069
- const trimmed = text.trim();
1070
- const tokens = /[\s,]/.test(trimmed) || trimmed.includes("-", 1) ? trimmed.split(/[\s,-]+/) : [...trimmed];
1071
- return tokens.filter(Boolean).map((t) => /^[0xX]$/.test(t) ? null : t.toUpperCase());
1056
+ function bestFingering(frets, pinkyBarre = false) {
1057
+ const empty = frets.map(() => null);
1058
+ const byFret = new Map;
1059
+ frets.forEach((fret, s) => {
1060
+ if (fret !== null && fret > 0)
1061
+ byFret.set(fret, [...byFret.get(fret) ?? [], s]);
1062
+ });
1063
+ if (!byFret.size)
1064
+ return { fingers: empty, cost: 0, awkward: false, fullBarre: false };
1065
+ const fretList = [...byFret.keys()].sort((a, b) => a - b);
1066
+ const lowest = fretList[0];
1067
+ const top = frets.reduce((t, f, s) => f === null ? t : s, -1);
1068
+ const options = fretList.map((f) => groupingsAt(f, byFret.get(f), frets));
1069
+ let best = null;
1070
+ const consider = (groups) => {
1071
+ if (groups.length > 4)
1072
+ return;
1073
+ const sorted = [...groups].sort((a, b) => a.fret - b.fret || a.from - b.from);
1074
+ for (const choice of fingerChoices(sorted.length)) {
1075
+ let ok = true;
1076
+ for (let i = 0;i < sorted.length && ok; i++) {
1077
+ const g = sorted[i];
1078
+ if (g.under && (choice[i] !== 1 || g.fret !== lowest))
1079
+ ok = false;
1080
+ const topTwo = g.from === frets.length - 2 && g.to === frets.length - 1;
1081
+ const pinky = pinkyBarre && choice[i] === 4 && topTwo;
1082
+ if (g.strings.length > 1 && choice[i] !== 1 && choice[i] !== 3 && !pinky)
1083
+ ok = false;
1084
+ for (let j = i + 1;j < sorted.length && ok; j++) {
1085
+ if (sorted[j].fret - g.fret > choice[j] - choice[i] + 1)
1086
+ ok = false;
1087
+ }
1088
+ }
1089
+ if (!ok)
1090
+ continue;
1091
+ let cost = sorted.length;
1092
+ let awkward = false;
1093
+ sorted.forEach((g, i) => {
1094
+ const finger = choice[i];
1095
+ if (g.strings.length > 1) {
1096
+ cost += finger === 4 ? 3.5 : 2.5;
1097
+ if (finger === 1 && g.fret === lowest && g.to === top && !g.under)
1098
+ cost -= 2;
1099
+ }
1100
+ cost += 0.1 * Math.abs(g.fret - lowest - (finger - 1));
1101
+ });
1102
+ const index = choice.indexOf(1);
1103
+ const middle = choice.indexOf(2);
1104
+ if (index >= 0 && middle >= 0) {
1105
+ cost += 0.2 * Math.max(0, sorted[middle].fret - sorted[index].fret - 1);
1106
+ }
1107
+ for (const a of sorted)
1108
+ for (const b of sorted)
1109
+ if (a !== b && a.fret === b.fret && b.from - a.to >= 3) {
1110
+ if (sorted.some((c) => c.fret > a.fret && c.from > a.to && c.to < b.from))
1111
+ awkward = true;
1112
+ }
1113
+ if (awkward)
1114
+ cost += 1.5;
1115
+ if (!best || cost < best.cost - 0.000000001) {
1116
+ const fingers = [...empty];
1117
+ sorted.forEach((g, i) => {
1118
+ for (const s of g.strings)
1119
+ fingers[s] = String(choice[i]);
1120
+ });
1121
+ const fullBarre = sorted.some((g) => g.strings.length > 1 && (g.under || g.strings.length > 3));
1122
+ best = { fingers, cost, awkward, fullBarre };
1123
+ }
1124
+ }
1125
+ };
1126
+ const walk = (i, acc) => {
1127
+ if (acc.length > 4)
1128
+ return;
1129
+ if (i === options.length) {
1130
+ consider(acc);
1131
+ return;
1132
+ }
1133
+ for (const grouping of options[i])
1134
+ walk(i + 1, [...acc, ...grouping]);
1135
+ };
1136
+ walk(0, []);
1137
+ return best;
1072
1138
  }
1073
- function baseFretOf(frets) {
1074
- const fretted = frets.filter((f) => f !== null && f > 0);
1075
- if (!fretted.length || Math.max(...fretted) <= 4)
1076
- return 1;
1077
- return Math.min(...fretted);
1139
+ function fingerVoicing(frets) {
1140
+ return bestFingering(frets, true)?.fingers ?? null;
1078
1141
  }
1079
- function barresOf(voicing, capoFret) {
1080
- const byKey = new Map;
1081
- voicing.frets.forEach((fret, string) => {
1082
- const finger = voicing.fingers[string];
1083
- if (fret === null || fret === 0 || fret === capoFret || !finger)
1084
- return;
1085
- const key = `${finger}@${fret}`;
1086
- byKey.set(key, [...byKey.get(key) ?? [], string]);
1087
- });
1088
- const barres = [];
1089
- for (const [key, strings] of byKey) {
1090
- if (strings.length < 2)
1091
- continue;
1092
- const [finger, fretText] = key.split("@");
1093
- const fret = Number(fretText);
1094
- const from = Math.min(...strings);
1095
- const to = Math.max(...strings);
1096
- let under = false;
1097
- for (let s = from + 1;s < to; s++) {
1098
- const f = voicing.frets[s];
1099
- if (!strings.includes(s) && f !== null && f !== undefined && f > fret)
1100
- under = true;
1142
+ var CAGED_ROOT_STRING = {
1143
+ C: 1,
1144
+ A: 1,
1145
+ G: 0,
1146
+ E: 0,
1147
+ D: 2
1148
+ };
1149
+ var OPEN_CHORDS = new Set([
1150
+ "x32010 x02220 320003 320033 022100 xx0232",
1151
+ "x02210 022000 xx0231",
1152
+ "x32310 x02020 x02223 320001 020100 022130 xx0212 x21202",
1153
+ "x02010 x02213 020000 022030 022033 xx0211",
1154
+ "x32000 x02120 320002 xx0222 021100 xx3210",
1155
+ "x02200 x02230 xx0230 xx0233 022200",
1156
+ "x32030 x32033 x02222 x32210 xx0202 022120 320000 x02212 022020 xx0201",
1157
+ "x20003 332010 200232 032010 330013 330033"
1158
+ ].join(" ").split(" "));
1159
+ var compact = (frets) => frets.some((f) => f !== null && f > 9) ? frets.map((f) => f === null ? "x" : f).join("-") : frets.map((f) => f === null ? "x" : f).join("");
1160
+ var sameTuning = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
1161
+ var hasBarre = (frets, fingers) => {
1162
+ const counts = new Map;
1163
+ frets.forEach((fret, s) => {
1164
+ const finger = fingers[s];
1165
+ if (fret && finger) {
1166
+ const key = `${finger}@${fret}`;
1167
+ counts.set(key, (counts.get(key) ?? 0) + 1);
1101
1168
  }
1102
- barres.push({ fret, from, to, finger, strings, full: under || strings.length > 3 });
1169
+ });
1170
+ return [...counts.values()].some((n) => n >= 2);
1171
+ };
1172
+ function cagedTargets(info) {
1173
+ const targets = new Map;
1174
+ for (const letter of ["E", "A", "C", "G", "D"]) {
1175
+ const set = chordNoteSet(letter + info.suffix);
1176
+ targets.set(letter, set ? new Set(set.members.map((m) => m.chroma)) : null);
1103
1177
  }
1104
- return barres;
1178
+ return targets;
1105
1179
  }
1106
- function barreKind(voicing) {
1107
- const barres = barresOf(voicing, null);
1108
- if (!barres.length)
1180
+ function shapeOf(frets, info, targets, tuning) {
1181
+ const sounding = frets.flatMap((f, s) => f === null ? [] : [s]);
1182
+ if (!sounding.length || tuning.length !== frets.length)
1109
1183
  return null;
1110
- return barres.some((b) => b.full) ? "full" : "partial";
1111
- }
1112
- var isBarreVoicing = (voicing) => barreKind(voicing) !== null;
1113
- var SPACING = 18;
1114
- var ROW = 20;
1115
- var MARKERS = 16;
1116
- var HIT_ALONG = 44;
1117
- var BASE = 30;
1118
- var TITLE = 22;
1119
- var CAPTION = 18;
1120
- var capoCaption = (capo, sounds) => `Capo ${capo}${sounds ? `, sounds ${sounds}` : ""}`;
1121
- function renderGuitarDiagram(doc, voicing, options = {}) {
1122
- const strings = voicing.frets.length;
1123
- const base = voicing.baseFret ?? baseFretOf(voicing.frets);
1124
- const fretted = voicing.frets.filter((f) => f !== null && f > 0);
1125
- const rows = Math.max(4, fretted.length ? Math.max(...fretted) - base + 1 : 0);
1126
- const orientation = options.orientation ?? "vertical";
1127
- const vertical = orientation === "vertical";
1128
- const capo = options.capo && options.capo > 0 ? options.capo : 0;
1129
- const fromNut = capo > 0 && options.fretsFrom === "nut";
1130
- const capoFret = fromNut ? capo : null;
1131
- const caption = capo && options.caption !== false ? shown(capoCaption(capo, options.sounds)) : undefined;
1132
- const layout = {
1133
- orientation,
1134
- hand: options.hand ?? "right",
1135
- across: (strings - 1) * SPACING,
1136
- along: rows * ROW,
1137
- before: MARKERS,
1138
- after: 10,
1139
- low: vertical || base > 1 ? BASE : 10,
1140
- high: vertical ? 14 : 10,
1141
- top: 4,
1142
- minWidth: titleWidth(caption)
1143
- };
1144
- const lines = options.title ? titleLines(shown(options.title), neckFrame(layout).width) : [];
1145
- const frame = neckFrame({
1146
- ...layout,
1147
- top: lines.length ? TITLE + (lines.length - 1) * TITLE_LINE : 4
1148
- });
1149
- const across = (string) => string * SPACING;
1150
- const along = (row) => row * ROW;
1151
- const at = (string, row) => frame.at(across(string), along(row));
1152
- const label = `${options.title ? `${options.title} chord diagram` : "Chord diagram"}${capo ? `, ${capoCaption(capo, options.sounds).replace(/^Capo/, "capo")}` : ""}`;
1153
- const height = frame.height + (caption ? CAPTION : 0);
1154
- const root = svgRoot(doc, frame.width, height, "mn-guitar-chord", label);
1155
- root.setAttribute("data-mn-hand", options.hand ?? "right");
1156
- const fretText = voicing.frets.map((f) => f === null ? "x" : String(f));
1157
- root.setAttribute("data-mn-voicing", fretText.some((f) => f.length > 1) ? fretText.join("-") : fretText.join(""));
1158
- if (caption) {
1159
- root.appendChild(svgText(doc, caption, {
1160
- class: "mn-caption",
1161
- x: frame.width / 2,
1162
- y: height - 6,
1163
- "text-anchor": "middle"
1164
- }));
1184
+ const chromas = new Set(sounding.map((s) => (tuning[s] + frets[s]) % 12));
1185
+ if (info.members.length === 2 && info.tones.every((t) => t.number === 1 || t.number === 5)) {
1186
+ return "Power chord";
1165
1187
  }
1166
- if (capo) {
1167
- root.setAttribute("data-mn-capo", String(capo));
1168
- root.setAttribute("data-mn-frets-from", fromNut ? "nut" : "capo");
1188
+ const lowest = (tuning[sounding[0]] + frets[sounding[0]]) % 12;
1189
+ const shell = sounding.length === 3 && chromas.size === 3 && lowest === info.root && info.tones.some((t) => t.number === 7 || t.number === 6) && [...chromas].every((c) => info.tones.some((t) => t.chroma === c && [1, 3, 6, 7].includes(t.number)));
1190
+ if (shell)
1191
+ return "Shell";
1192
+ const adjacent = sounding[sounding.length - 1] - sounding[0] === sounding.length - 1;
1193
+ if (sounding.length === 3 && adjacent && chromas.size === 3)
1194
+ return "Triad";
1195
+ const fretted = sounding.map((s) => frets[s]).filter((f) => f > 0);
1196
+ const open = sounding.some((s) => frets[s] === 0);
1197
+ if (open && sounding.length >= 4 && (!fretted.length || Math.max(...fretted) <= 4)) {
1198
+ return "Open";
1169
1199
  }
1170
- if (lines.length)
1171
- drawTitle(doc, root, lines, frame.width / 2, 15);
1172
- for (let row = 0;row <= rows; row++) {
1173
- const cls = row === 0 && base === 1 && (!capo || fromNut) ? "mn-nut" : "mn-fret";
1174
- root.appendChild(svgLine(doc, at(0, row), at(strings - 1, row), cls));
1200
+ if (sameTuning(tuning, STANDARD_TUNING) && !open && fretted.length) {
1201
+ const lowest = Math.min(...fretted);
1202
+ for (const letter of ["E", "A", "C", "G", "D"]) {
1203
+ if (sounding[0] !== CAGED_ROOT_STRING[letter])
1204
+ continue;
1205
+ const target = targets.get(letter);
1206
+ if (!target)
1207
+ continue;
1208
+ const base = ((info.root - chromaOf(letter)) % 12 + 12) % 12;
1209
+ for (const shift of [base, base + 12]) {
1210
+ if (shift === 0 || lowest < shift)
1211
+ continue;
1212
+ const moved = frets.map((f) => f === null ? null : f - shift);
1213
+ if (moved.some((f) => f !== null && f > 4))
1214
+ continue;
1215
+ if (!sounding.every((s) => target.has((tuning[s] + moved[s]) % 12)))
1216
+ continue;
1217
+ return `${letter} shape`;
1218
+ }
1219
+ }
1175
1220
  }
1176
- const capoRow = fromNut ? capo - base + 0.5 : base === 1 ? 0 : null;
1177
- if (capo && capoRow !== null && capoRow >= 0 && capoRow <= rows) {
1178
- root.appendChild(svg(doc, "rect", {
1179
- class: "mn-capo",
1180
- ...frame.box(across(0) - 8, along(capoRow) - 3, across(strings - 1) + 8, along(capoRow) + 3),
1181
- rx: 3
1182
- }));
1183
- }
1184
- for (let s = 0;s < strings; s++) {
1185
- root.appendChild(svgLine(doc, at(s, 0), at(s, rows), "mn-string"));
1186
- }
1187
- if (base > 1) {
1188
- const label = `${base}fr`;
1189
- root.appendChild(vertical ? svgLabel(doc, label, frame.at(-10, along(0.5)), "mn-base-fret", options.hand === "left" ? "start" : "end") : svgLabel(doc, label, frame.at(-16, along(0.5)), "mn-base-fret"));
1221
+ return null;
1222
+ }
1223
+ var OPEN_CHORD_FRETS = [...OPEN_CHORDS].map((t) => [...t].map((c) => c === "x" ? null : Number(c)));
1224
+ function stringsText(sounding, count) {
1225
+ const numbers = sounding.map((s) => count - s).sort((a, b) => a - b);
1226
+ const runs = [];
1227
+ for (let i = 0;i < numbers.length; ) {
1228
+ let j = i;
1229
+ while (j + 1 < numbers.length && numbers[j + 1] === numbers[j] + 1)
1230
+ j++;
1231
+ runs.push(i === j ? `${numbers[i]}` : `${numbers[i]}-${numbers[j]}`);
1232
+ i = j + 1;
1190
1233
  }
1191
- const textOf = (s) => (options.labels ? options.labels[s] : voicing.fingers[s]) ?? null;
1192
- const quiet = new Set;
1193
- const fingered = voicing.fingers.some((f) => f);
1194
- const barres = fingered ? barresOf(voicing, capoFret) : options.barreFingers ? barresOf({ frets: voicing.frets, fingers: [...options.barreFingers] }, capoFret).filter((b) => b.full) : [];
1195
- for (const barre of barres) {
1196
- const texts = new Set(barre.strings.map(textOf));
1197
- if (texts.size === 1) {
1198
- for (const s of barre.strings)
1199
- if (s !== barre.from)
1200
- quiet.add(s);
1201
- } else if (!barre.full) {
1234
+ return runs.join(", ");
1235
+ }
1236
+ function cagedPartOf(frets, sounding, info) {
1237
+ if (info.bass !== null || sounding.length < 3)
1238
+ return null;
1239
+ if (sounding.some((s) => frets[s] === 0))
1240
+ return null;
1241
+ for (const letter of ["E", "A", "C", "G", "D"]) {
1242
+ const target = chordInfo(letter + info.suffix);
1243
+ if (!target)
1202
1244
  continue;
1203
- }
1204
- const middle = along(barre.fret - base + 0.5);
1205
- root.appendChild(svg(doc, "rect", {
1206
- class: "mn-barre",
1207
- ...frame.box(across(barre.from) - 7, middle - 7, across(barre.to) + 7, middle + 7),
1208
- rx: 7,
1209
- "data-mn-fret": barre.fret,
1210
- "data-mn-finger": barre.finger,
1211
- "data-mn-from": strings - barre.from,
1212
- "data-mn-to": strings - barre.to
1213
- }));
1214
- }
1215
- const tuning = options.tuning ?? (strings === 6 ? STANDARD_TUNING : undefined);
1216
- voicing.frets.forEach((fret, s) => {
1217
- const markAlong = -8;
1218
- const mark = frame.at(across(s), markAlong);
1219
- const string = strings - s;
1220
- if (fret === null) {
1221
- const [x, y] = mark;
1222
- const d = 3.5;
1223
- root.appendChild(svg(doc, "path", {
1224
- class: "mn-muted",
1225
- d: `M${x - d} ${y - d}L${x + d} ${y + d}M${x + d} ${y - d}L${x - d} ${y + d}`,
1226
- "data-mn-string": string
1227
- }));
1228
- return;
1229
- }
1230
- const openString = tuning?.[s];
1231
- const open = openString === undefined ? undefined : openString + (fromNut ? 0 : capo);
1232
- const isRoot = options.root !== undefined && options.root !== null && open !== undefined && (open + fret) % 12 === options.root;
1233
- const midi = {
1234
- "data-mn-string": string,
1235
- "data-mn-fret": fret,
1236
- ...open !== undefined ? { "data-midi": open + fret } : {}
1237
- };
1238
- const place = (markAt, ...els) => {
1239
- if (open === undefined) {
1240
- for (const el of els)
1241
- root.appendChild(el);
1242
- return;
1245
+ const tones = new Set(target.tones.map((t) => t.chroma));
1246
+ const base = ((info.root - chromaOf(letter)) % 12 + 12) % 12;
1247
+ for (const open of OPEN_CHORD_FRETS) {
1248
+ const strings = open.flatMap((f, s) => f === null ? [] : [s]);
1249
+ if (strings[0] !== CAGED_ROOT_STRING[letter] || strings.length <= sounding.length) {
1250
+ continue;
1251
+ }
1252
+ const chromas = strings.map((s) => (STANDARD_TUNING[s] + open[s]) % 12);
1253
+ if (chromas[0] !== chromaOf(letter))
1254
+ continue;
1255
+ if (!chromas.every((c) => tones.has(c)))
1256
+ continue;
1257
+ if (!target.tones.every((t) => !t.required || chromas.includes(t.chroma)))
1258
+ continue;
1259
+ for (const shift of [base, base + 12]) {
1260
+ if (shift === 0)
1261
+ continue;
1262
+ if (sounding.every((s) => open[s] !== null && frets[s] === open[s] + shift)) {
1263
+ return letter;
1264
+ }
1243
1265
  }
1244
- const area = frame.box(across(s) - SPACING / 2, markAt - HIT_ALONG / 2, across(s) + SPACING / 2, markAt + HIT_ALONG / 2);
1245
- root.appendChild(playableMark(doc, area, ...els));
1246
- };
1247
- if (fret === 0) {
1248
- const [cx, cy] = mark;
1249
- place(markAlong, svg(doc, "circle", {
1250
- class: `mn-open${isRoot ? " mn-root" : ""}`,
1251
- cx,
1252
- cy,
1253
- r: 4,
1254
- ...midi
1255
- }));
1256
- return;
1257
- }
1258
- const row = along(fret - base + 0.5);
1259
- const center = at(s, fret - base + 0.5);
1260
- const [cx, cy] = center;
1261
- if (fret === capoFret) {
1262
- place(row, svg(doc, "circle", {
1263
- class: `mn-capo-open${isRoot ? " mn-root" : ""}`,
1264
- cx,
1265
- cy,
1266
- r: 4,
1267
- ...midi
1268
- }));
1269
- return;
1270
1266
  }
1271
- const text = quiet.has(s) ? null : textOf(s);
1272
- place(row, svg(doc, "circle", {
1273
- class: `mn-dot${isRoot ? " mn-root" : ""}${options.marks?.[s] ? ` mn-${options.marks[s]}` : ""}`,
1274
- cx,
1275
- cy,
1276
- r: 7,
1277
- ...midi
1278
- }), ...text ? [dotLabel(doc, text, center, 7)] : []);
1279
- });
1280
- if (tuning) {
1281
- const shift = fromNut ? 0 : capo;
1282
- const pitches = voicing.frets.flatMap((f, s) => f === null ? [] : [tuning[s] + shift + f]);
1283
- root.setAttribute("data-mn-pitches", pitches.join(" "));
1284
- root.setAttribute("data-mn-play", "chord");
1285
- root.setAttribute("data-mn-sound", "guitar");
1286
1267
  }
1287
- return root;
1268
+ return null;
1288
1269
  }
1289
-
1290
- // src/chord/generate.ts
1291
- var isBarreShape = (shape) => shape === "E shape" || shape === "A shape";
1292
- var MAX_GENERATED_STRINGS = 8;
1293
- var MAX_SPAN = 6;
1294
- function chordInfo(symbol) {
1295
- const set = chordNoteSet(symbol);
1296
- const parts = splitChordSymbol(symbol);
1297
- if (!set || !parts)
1270
+ function dropOf(pitches) {
1271
+ if (pitches.length !== 4 || new Set(pitches.map((p) => p % 12)).size !== 4)
1298
1272
  return null;
1299
- const bass = parts.bass ? chromaOf(parts.bass) : null;
1300
- const members = set.members.filter((m) => m.interval !== null);
1301
- const parsed = members.map((m) => {
1302
- const hit = /^(\d+)([PMmdA]+)$/.exec(m.interval);
1303
- return { member: m, number: Number(hit?.[1] ?? 0), quality: hit?.[2] ?? "" };
1304
- });
1305
- const natural = (p) => p.number > 7 && (p.quality === "M" || p.quality === "P");
1306
- const highest = Math.max(0, ...parsed.filter(natural).map((p) => p.number));
1307
- const eleventh = parsed.some((p) => p.number === 11 && p.quality === "P");
1308
- const tones = parsed.map((p) => {
1309
- let required = true;
1310
- if (p.number === 5 && p.quality === "P")
1311
- required = members.length === 2;
1312
- else if (natural(p) && p.number < highest)
1313
- required = false;
1314
- else if (p.number === 3 && p.quality === "M" && eleventh)
1315
- required = false;
1316
- return { chroma: p.member.chroma, number: p.number, required };
1317
- });
1318
- if (bass !== null && !tones.some((t) => t.chroma === bass)) {
1319
- tones.push({ chroma: bass, number: 0, required: true });
1320
- }
1321
- return {
1322
- tones,
1323
- members,
1324
- bass,
1325
- root: chromaOf(parts.root),
1326
- suffix: canonicalSuffix(parts.suffix)
1327
- };
1328
- }
1329
- function groupingsAt(fret, strings, frets) {
1330
- const result = [];
1331
- const walk = (i, acc) => {
1332
- if (i === strings.length) {
1333
- result.push(acc);
1334
- return;
1335
- }
1336
- for (let j = i;j < strings.length; j++) {
1337
- const from = strings[i];
1338
- const to = strings[j];
1339
- let ok = true;
1340
- let under = false;
1341
- for (let s = from;s <= to; s++) {
1342
- const f = frets[s];
1343
- if (f === null || f === undefined || f < fret) {
1344
- ok = false;
1345
- break;
1346
- }
1347
- if (f > fret)
1348
- under = true;
1349
- }
1350
- if (!ok)
1351
- break;
1352
- walk(j + 1, [...acc, { fret, from, to, strings: strings.slice(i, j + 1), under }]);
1353
- }
1354
- };
1355
- walk(0, []);
1356
- return result;
1273
+ const sorted = [...pitches].sort((a, b) => a - b);
1274
+ const raised = sorted[0] + 12;
1275
+ const close = [...sorted.slice(1), raised].sort((a, b) => a - b);
1276
+ if (close[3] - close[0] >= 12)
1277
+ return null;
1278
+ const fromTop = 3 - close.indexOf(raised);
1279
+ return fromTop === 1 ? 2 : fromTop === 2 ? 3 : null;
1357
1280
  }
1358
- function fingerChoices(count) {
1359
- const out = [];
1360
- const walk = (start, acc) => {
1361
- if (acc.length === count) {
1362
- out.push(acc);
1363
- return;
1364
- }
1365
- for (let f = start;f <= 4 - (count - acc.length - 1); f++)
1366
- walk(f + 1, [...acc, f]);
1367
- };
1368
- walk(1, []);
1369
- return out;
1370
- }
1371
- function bestFingering(frets, pinkyBarre = false) {
1372
- const empty = frets.map(() => null);
1373
- const byFret = new Map;
1374
- frets.forEach((fret, s) => {
1375
- if (fret !== null && fret > 0)
1376
- byFret.set(fret, [...byFret.get(fret) ?? [], s]);
1377
- });
1378
- if (!byFret.size)
1379
- return { fingers: empty, cost: 0, awkward: false, fullBarre: false };
1380
- const fretList = [...byFret.keys()].sort((a, b) => a - b);
1381
- const lowest = fretList[0];
1382
- const top = frets.reduce((t, f, s) => f === null ? t : s, -1);
1383
- const options = fretList.map((f) => groupingsAt(f, byFret.get(f), frets));
1384
- let best = null;
1385
- const consider = (groups) => {
1386
- if (groups.length > 4)
1387
- return;
1388
- const sorted = [...groups].sort((a, b) => a.fret - b.fret || a.from - b.from);
1389
- for (const choice of fingerChoices(sorted.length)) {
1390
- let ok = true;
1391
- for (let i = 0;i < sorted.length && ok; i++) {
1392
- const g = sorted[i];
1393
- if (g.under && (choice[i] !== 1 || g.fret !== lowest))
1394
- ok = false;
1395
- const topTwo = g.from === frets.length - 2 && g.to === frets.length - 1;
1396
- const pinky = pinkyBarre && choice[i] === 4 && topTwo;
1397
- if (g.strings.length > 1 && choice[i] !== 1 && choice[i] !== 3 && !pinky)
1398
- ok = false;
1399
- for (let j = i + 1;j < sorted.length && ok; j++) {
1400
- if (sorted[j].fret - g.fret > choice[j] - choice[i] + 1)
1401
- ok = false;
1402
- }
1403
- }
1404
- if (!ok)
1405
- continue;
1406
- let cost = sorted.length;
1407
- let awkward = false;
1408
- sorted.forEach((g, i) => {
1409
- const finger = choice[i];
1410
- if (g.strings.length > 1) {
1411
- cost += finger === 4 ? 3.5 : 2.5;
1412
- if (finger === 1 && g.fret === lowest && g.to === top && !g.under)
1413
- cost -= 2;
1414
- }
1415
- cost += 0.1 * Math.abs(g.fret - lowest - (finger - 1));
1416
- });
1417
- const index = choice.indexOf(1);
1418
- const middle = choice.indexOf(2);
1419
- if (index >= 0 && middle >= 0) {
1420
- cost += 0.2 * Math.max(0, sorted[middle].fret - sorted[index].fret - 1);
1421
- }
1422
- for (const a of sorted)
1423
- for (const b of sorted)
1424
- if (a !== b && a.fret === b.fret && b.from - a.to >= 3) {
1425
- if (sorted.some((c) => c.fret > a.fret && c.from > a.to && c.to < b.from))
1426
- awkward = true;
1427
- }
1428
- if (awkward)
1429
- cost += 1.5;
1430
- if (!best || cost < best.cost - 0.000000001) {
1431
- const fingers = [...empty];
1432
- sorted.forEach((g, i) => {
1433
- for (const s of g.strings)
1434
- fingers[s] = String(choice[i]);
1435
- });
1436
- const fullBarre = sorted.some((g) => g.strings.length > 1 && (g.under || g.strings.length > 3));
1437
- best = { fingers, cost, awkward, fullBarre };
1438
- }
1439
- }
1440
- };
1441
- const walk = (i, acc) => {
1442
- if (acc.length > 4)
1443
- return;
1444
- if (i === options.length) {
1445
- consider(acc);
1446
- return;
1447
- }
1448
- for (const grouping of options[i])
1449
- walk(i + 1, [...acc, ...grouping]);
1450
- };
1451
- walk(0, []);
1452
- return best;
1453
- }
1454
- function fingerVoicing(frets) {
1455
- return bestFingering(frets, true)?.fingers ?? null;
1456
- }
1457
- var CAGED_ROOT_STRING = {
1458
- C: 1,
1459
- A: 1,
1460
- G: 0,
1461
- E: 0,
1462
- D: 2
1463
- };
1464
- var OPEN_CHORDS = new Set([
1465
- "x32010 x02220 320003 320033 022100 xx0232",
1466
- "x02210 022000 xx0231",
1467
- "x32310 x02020 x02223 320001 020100 022130 xx0212 x21202",
1468
- "x02010 x02213 020000 022030 022033 xx0211",
1469
- "x32000 x02120 320002 xx0222 021100 xx3210",
1470
- "x02200 x02230 xx0230 xx0233 022200",
1471
- "x32030 x32033 x02222 x32210 xx0202 022120 320000 x02212 022020 xx0201",
1472
- "x20003 332010 200232 032010 330013 330033"
1473
- ].join(" ").split(" "));
1474
- var compact = (frets) => frets.some((f) => f !== null && f > 9) ? frets.map((f) => f === null ? "x" : f).join("-") : frets.map((f) => f === null ? "x" : f).join("");
1475
- var sameTuning = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
1476
- var hasBarre = (frets, fingers) => {
1477
- const counts = new Map;
1478
- frets.forEach((fret, s) => {
1479
- const finger = fingers[s];
1480
- if (fret && finger) {
1481
- const key = `${finger}@${fret}`;
1482
- counts.set(key, (counts.get(key) ?? 0) + 1);
1483
- }
1484
- });
1485
- return [...counts.values()].some((n) => n >= 2);
1486
- };
1487
- function cagedTargets(info) {
1488
- const targets = new Map;
1489
- for (const letter of ["E", "A", "C", "G", "D"]) {
1490
- const set = chordNoteSet(letter + info.suffix);
1491
- targets.set(letter, set ? new Set(set.members.map((m) => m.chroma)) : null);
1492
- }
1493
- return targets;
1494
- }
1495
- function shapeOf(frets, info, targets, tuning) {
1496
- const sounding = frets.flatMap((f, s) => f === null ? [] : [s]);
1497
- if (!sounding.length || tuning.length !== frets.length)
1498
- return null;
1499
- const chromas = new Set(sounding.map((s) => (tuning[s] + frets[s]) % 12));
1500
- if (info.members.length === 2 && info.tones.every((t) => t.number === 1 || t.number === 5)) {
1501
- return "Power chord";
1502
- }
1503
- const lowest = (tuning[sounding[0]] + frets[sounding[0]]) % 12;
1504
- const shell = sounding.length === 3 && chromas.size === 3 && lowest === info.root && info.tones.some((t) => t.number === 7 || t.number === 6) && [...chromas].every((c) => info.tones.some((t) => t.chroma === c && [1, 3, 6, 7].includes(t.number)));
1505
- if (shell)
1506
- return "Shell";
1507
- const adjacent = sounding[sounding.length - 1] - sounding[0] === sounding.length - 1;
1508
- if (sounding.length === 3 && adjacent && chromas.size === 3)
1509
- return "Triad";
1510
- const fretted = sounding.map((s) => frets[s]).filter((f) => f > 0);
1511
- const open = sounding.some((s) => frets[s] === 0);
1512
- if (open && sounding.length >= 4 && (!fretted.length || Math.max(...fretted) <= 4)) {
1513
- return "Open";
1514
- }
1515
- if (sameTuning(tuning, STANDARD_TUNING) && !open && fretted.length) {
1516
- const lowest = Math.min(...fretted);
1517
- for (const letter of ["E", "A", "C", "G", "D"]) {
1518
- if (sounding[0] !== CAGED_ROOT_STRING[letter])
1519
- continue;
1520
- const target = targets.get(letter);
1521
- if (!target)
1522
- continue;
1523
- const base = ((info.root - chromaOf(letter)) % 12 + 12) % 12;
1524
- for (const shift of [base, base + 12]) {
1525
- if (shift === 0 || lowest < shift)
1526
- continue;
1527
- const moved = frets.map((f) => f === null ? null : f - shift);
1528
- if (moved.some((f) => f !== null && f > 4))
1529
- continue;
1530
- if (!sounding.every((s) => target.has((tuning[s] + moved[s]) % 12)))
1531
- continue;
1532
- return `${letter} shape`;
1533
- }
1534
- }
1535
- }
1536
- return null;
1537
- }
1538
- var OPEN_CHORD_FRETS = [...OPEN_CHORDS].map((t) => [...t].map((c) => c === "x" ? null : Number(c)));
1539
- function stringsText(sounding, count) {
1540
- const numbers = sounding.map((s) => count - s).sort((a, b) => a - b);
1541
- const runs = [];
1542
- for (let i = 0;i < numbers.length; ) {
1543
- let j = i;
1544
- while (j + 1 < numbers.length && numbers[j + 1] === numbers[j] + 1)
1545
- j++;
1546
- runs.push(i === j ? `${numbers[i]}` : `${numbers[i]}-${numbers[j]}`);
1547
- i = j + 1;
1548
- }
1549
- return runs.join(", ");
1550
- }
1551
- function cagedPartOf(frets, sounding, info) {
1552
- if (info.bass !== null || sounding.length < 3)
1553
- return null;
1554
- if (sounding.some((s) => frets[s] === 0))
1555
- return null;
1556
- for (const letter of ["E", "A", "C", "G", "D"]) {
1557
- const target = chordInfo(letter + info.suffix);
1558
- if (!target)
1559
- continue;
1560
- const tones = new Set(target.tones.map((t) => t.chroma));
1561
- const base = ((info.root - chromaOf(letter)) % 12 + 12) % 12;
1562
- for (const open of OPEN_CHORD_FRETS) {
1563
- const strings = open.flatMap((f, s) => f === null ? [] : [s]);
1564
- if (strings[0] !== CAGED_ROOT_STRING[letter] || strings.length <= sounding.length) {
1565
- continue;
1566
- }
1567
- const chromas = strings.map((s) => (STANDARD_TUNING[s] + open[s]) % 12);
1568
- if (chromas[0] !== chromaOf(letter))
1569
- continue;
1570
- if (!chromas.every((c) => tones.has(c)))
1571
- continue;
1572
- if (!target.tones.every((t) => !t.required || chromas.includes(t.chroma)))
1573
- continue;
1574
- for (const shift of [base, base + 12]) {
1575
- if (shift === 0)
1576
- continue;
1577
- if (sounding.every((s) => open[s] !== null && frets[s] === open[s] + shift)) {
1578
- return letter;
1579
- }
1580
- }
1581
- }
1582
- }
1583
- return null;
1584
- }
1585
- function dropOf(pitches) {
1586
- if (pitches.length !== 4 || new Set(pitches.map((p) => p % 12)).size !== 4)
1587
- return null;
1588
- const sorted = [...pitches].sort((a, b) => a - b);
1589
- const raised = sorted[0] + 12;
1590
- const close = [...sorted.slice(1), raised].sort((a, b) => a - b);
1591
- if (close[3] - close[0] >= 12)
1592
- return null;
1593
- const fromTop = 3 - close.indexOf(raised);
1594
- return fromTop === 1 ? 2 : fromTop === 2 ? 3 : null;
1595
- }
1596
- function isHendrixChord(frets, info, tuning) {
1597
- if (!sameTuning(tuning, STANDARD_TUNING) || !isJazzGrip(frets) || frets[1] === null)
1598
- return false;
1599
- if (frets[0] !== null || (tuning[1] + frets[1]) % 12 !== info.root)
1600
- return false;
1601
- const chromas = new Set(info.tones.map((t) => t.chroma));
1602
- return chromas.has((info.root + 3) % 12) && chromas.has((info.root + 4) % 12);
1281
+ function isHendrixChord(frets, info, tuning) {
1282
+ if (!sameTuning(tuning, STANDARD_TUNING) || !isJazzGrip(frets) || frets[1] === null)
1283
+ return false;
1284
+ if (frets[0] !== null || (tuning[1] + frets[1]) % 12 !== info.root)
1285
+ return false;
1286
+ const chromas = new Set(info.tones.map((t) => t.chroma));
1287
+ return chromas.has((info.root + 3) % 12) && chromas.has((info.root + 4) % 12);
1603
1288
  }
1604
1289
  function otherNameOf(frets, info, tuning) {
1605
1290
  const sounding = frets.flatMap((f, s) => f === null ? [] : [s]);
@@ -1792,88 +1477,669 @@ function generateVoicings(symbol, options = {}) {
1792
1477
  difficulty += 0.5;
1793
1478
  reasons.push("no fifth");
1794
1479
  }
1795
- const jazz = standard && isJazzGrip(candidate);
1796
- if (jazz) {
1797
- difficulty -= 2 * inner + strings.filter((s) => s > last).length * 1.5;
1798
- reasons.push("jazz grip");
1480
+ const jazz = standard && isJazzGrip(candidate);
1481
+ if (jazz) {
1482
+ difficulty -= 2 * inner + strings.filter((s) => s > last).length * 1.5;
1483
+ reasons.push("jazz grip");
1484
+ }
1485
+ if (usual)
1486
+ difficulty -= 3;
1487
+ else if (jazz)
1488
+ difficulty -= 1.5;
1489
+ else if (isBarreShape(shape) && barre)
1490
+ difficulty -= 2;
1491
+ else if (shape && KNOWN_SHAPES.has(shape))
1492
+ difficulty -= 1.5;
1493
+ const lowChroma = low % 12;
1494
+ const inBass = members.findIndex((m) => m.chroma === lowChroma);
1495
+ return {
1496
+ frets: [...candidate],
1497
+ fingers,
1498
+ baseFret: base,
1499
+ bassString,
1500
+ inversion: inBass < 0 ? null : inBass,
1501
+ shape: isHendrixChord(candidate, info, tuning) ? "Hendrix chord" : shape ?? otherNameOf(candidate, info, tuning),
1502
+ difficulty: Math.max(0, Math.round(difficulty * 10) / 10),
1503
+ reasons
1504
+ };
1505
+ };
1506
+ const results = new Map;
1507
+ const frets = new Array(count).fill(null);
1508
+ const visit = (s, min, max, have, sounded, closed) => {
1509
+ if (s === count) {
1510
+ if (sounded < minStrings || (required & ~have) !== 0)
1511
+ return;
1512
+ const voicing = evaluate(frets);
1513
+ if (voicing)
1514
+ results.set(frets.join(","), voicing);
1515
+ return;
1516
+ }
1517
+ const left = closed ? 0 : (allowed.has(s) ? 1 : 0) + allowedAfter[s];
1518
+ if (bits(required & ~have) > left || sounded + left < minStrings)
1519
+ return;
1520
+ for (const fret of choices[s]) {
1521
+ if (fret === null) {
1522
+ frets[s] = null;
1523
+ visit(s + 1, min, max, have, sounded, closed || sounded > 0 && !options.gaps);
1524
+ continue;
1525
+ }
1526
+ if (closed)
1527
+ continue;
1528
+ const fretted = fret > 0;
1529
+ const nextMin = fretted ? Math.min(min, fret) : min;
1530
+ const nextMax = fretted ? Math.max(max, fret) : max;
1531
+ if (fretted && nextMax - nextMin + 1 > maxSpan)
1532
+ continue;
1533
+ frets[s] = fret;
1534
+ visit(s + 1, nextMin, nextMax, have | 1 << (tuning[s] + fret) % 12, sounded + 1, false);
1535
+ }
1536
+ frets[s] = null;
1537
+ };
1538
+ visit(0, Infinity, -Infinity, 0, 0, false);
1539
+ if (standard && !options.gaps) {
1540
+ for (const { rootString, offsets } of JAZZ_GRIPS) {
1541
+ if (!allowed.has(rootString))
1542
+ continue;
1543
+ const rootFret = ((info.root - tuning[rootString]) % 12 + 12) % 12;
1544
+ for (const at of [rootFret, rootFret + 12]) {
1545
+ const candidate = offsets.map((o) => o === null ? null : at + o);
1546
+ if (candidate.some((f, s) => f !== null && (f < 1 || !choices[s].includes(f))))
1547
+ continue;
1548
+ const have = candidate.reduce((mask, f, s) => f === null ? mask : mask | 1 << (tuning[s] + f) % 12, 0);
1549
+ if ((required & ~have) !== 0)
1550
+ continue;
1551
+ const key = candidate.join(",");
1552
+ if (results.has(key))
1553
+ continue;
1554
+ const voicing = evaluate(candidate);
1555
+ if (voicing)
1556
+ results.set(key, voicing);
1557
+ }
1558
+ }
1559
+ }
1560
+ const sounding = (v) => v.frets.filter((f) => f !== null).length;
1561
+ return [...results.values()].sort((a, b) => a.difficulty - b.difficulty || sounding(b) - sounding(a) || a.baseFret - b.baseFret || a.frets.join(",").localeCompare(b.frets.join(",")));
1562
+ }
1563
+
1564
+ // src/chord/fingering-words.ts
1565
+ import { Note as Note2 } from "tonal";
1566
+ var ordinal = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["th", "st", "nd", "rd"][n % 10] ?? "th"}`;
1567
+ var GUITAR_FINGERS = {
1568
+ "1": "Index",
1569
+ "2": "Middle",
1570
+ "3": "Ring",
1571
+ "4": "Pinky",
1572
+ T: "Thumb"
1573
+ };
1574
+ var PIANO_FINGERS = {
1575
+ "1": "thumb",
1576
+ "2": "index finger",
1577
+ "3": "middle finger",
1578
+ "4": "ring finger",
1579
+ "5": "little finger"
1580
+ };
1581
+ var capitalized = (s) => s.charAt(0).toUpperCase() + s.slice(1);
1582
+ var andList = (items) => items.length < 2 ? items[0] ?? "" : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
1583
+ var letter = (midi) => noteOf(midi).replace(/-?\d+$/, "");
1584
+ function stringNames(tuning, count, spelled) {
1585
+ const letters = tuning?.map((p, s) => spelled?.[s] ?? letter(p)) ?? [];
1586
+ const repeated = letters.filter((name, i) => letters.indexOf(name) !== i);
1587
+ const byName = tuning !== null && (repeated.length === 0 || repeated.length === 1 && letters[0] === letters[count - 1] && count > 2);
1588
+ return Array.from({ length: count }, (_, s) => {
1589
+ if (!byName)
1590
+ return numbered(tuning, count, s, spelled);
1591
+ const name = letters[s];
1592
+ if (repeated.length && s === 0)
1593
+ return `the low ${name} string`;
1594
+ if (repeated.length && s === count - 1)
1595
+ return `the high ${name} string`;
1596
+ return `the ${name} string`;
1597
+ });
1598
+ }
1599
+ function numbered(tuning, count, s, spelled) {
1600
+ const name = tuning ? spelled?.[s] ?? letter(tuning[s]) : null;
1601
+ return `the ${ordinal(count - s)} string${name ? ` (${name})` : ""}`;
1602
+ }
1603
+ var range = (from, to) => Array.from({ length: to - from + 1 }, (_, i) => from + i);
1604
+ var together = (names) => names.every((n) => /^the [^(]+ string$/.test(n)) ? `the ${andList(names.map((n) => n.slice(4, -7)))} strings` : andList(names);
1605
+ function guitarWords(input) {
1606
+ const { frets } = input;
1607
+ const count = frets.length;
1608
+ const tuning = input.tuning ?? (count === 6 ? STANDARD_TUNING : null);
1609
+ const spelled = input.tuningNames?.length === count ? input.tuningNames : undefined;
1610
+ const names = stringNames(tuning, count, spelled);
1611
+ const capo = input.capo ?? 0;
1612
+ const fromNut = capo > 0 && input.fretsFrom === "nut";
1613
+ const shape = frets.map((f) => f === null ? null : fromNut ? Math.max(0, f - capo) : f);
1614
+ const fingers = input.fingers?.some((f) => f) ? input.fingers : fingerVoicing(shape) ?? frets.map(() => null);
1615
+ const sentences = [];
1616
+ if (capo) {
1617
+ sentences.push(`Capo on the ${ordinal(capo)} fret${fromNut ? "" : ": frets count from the capo"}.`);
1618
+ }
1619
+ const sounding = frets.flatMap((f, s) => f !== null ? [s] : []);
1620
+ if (!sounding.length)
1621
+ return [...sentences, "Every string is muted: no note sounds."];
1622
+ const low = sounding[0];
1623
+ const high = sounding.at(-1);
1624
+ if (low === 0 && high === count - 1) {
1625
+ sentences.push(count === 6 ? "Strum all six strings." : "Strum every string.");
1626
+ } else if (high === count - 1) {
1627
+ sentences.push(`Strum from ${numbered(tuning, count, low, spelled)}.`);
1628
+ } else {
1629
+ sentences.push(`Strum from ${numbered(tuning, count, low, spelled)} to ${numbered(tuning, count, high, spelled)}.`);
1630
+ }
1631
+ const barred = new Set;
1632
+ const byFinger = new Map;
1633
+ shape.forEach((f, s) => {
1634
+ const finger = fingers[s];
1635
+ if (f !== null && f > 0 && finger)
1636
+ byFinger.set(finger, [...byFinger.get(finger) ?? [], s]);
1637
+ });
1638
+ const said = new Set;
1639
+ const fingerName = (finger) => GUITAR_FINGERS[finger] ?? `Finger ${finger}`;
1640
+ frets.forEach((fret, s) => {
1641
+ if (fret === null || shape[s] === 0)
1642
+ return;
1643
+ const finger = fingers[s];
1644
+ if (!finger) {
1645
+ sentences.push(`Press ${names[s]} at the ${ordinal(fret)} fret.`);
1646
+ return;
1647
+ }
1648
+ if (said.has(finger))
1649
+ return;
1650
+ said.add(finger);
1651
+ const strings = byFinger.get(finger).filter((t) => frets[t] === fret);
1652
+ const between = strings.length > 1 ? range(strings[0], strings.at(-1)) : [];
1653
+ const flat = between.every((t) => shape[t] === null || shape[t] >= shape[s]);
1654
+ if (strings.length > 1 && !flat) {
1655
+ sentences.push(`${fingerName(finger)} on ${together(strings.map((t) => names[t]))}, ${ordinal(fret)} fret.`);
1656
+ } else if (strings.length > 1) {
1657
+ const from = count - strings.at(-1);
1658
+ const to = count - strings[0];
1659
+ for (const t of strings)
1660
+ barred.add(t);
1661
+ sentences.push(`${fingerName(finger)} bars the ${ordinal(fret)} fret, strings ${from} to ${to}.`);
1662
+ } else {
1663
+ sentences.push(`${fingerName(finger)} on ${names[s]}, ${ordinal(fret)} fret.`);
1664
+ }
1665
+ for (const t of byFinger.get(finger)) {
1666
+ if (frets[t] !== fret) {
1667
+ sentences.push(`${fingerName(finger)} also on ${names[t]}, ${ordinal(frets[t])} fret.`);
1668
+ }
1669
+ }
1670
+ });
1671
+ const muted = frets.flatMap((f, s) => f === null && s > low && s < high ? [names[s]] : []);
1672
+ if (muted.length) {
1673
+ sentences.push(`Mute ${andList(muted)}: let a fretting finger touch ${muted.length > 1 ? "them" : "it"} lightly.`);
1674
+ }
1675
+ const open = shape.flatMap((f, s) => f === 0 && !barred.has(s) ? [names[s]] : []);
1676
+ if (open.length) {
1677
+ const where = capo ? " at the capo" : " open";
1678
+ const plural = open.length > 1;
1679
+ sentences.push(open.every((n) => /^the [^(]+ string$/.test(n)) ? `The ${andList(open.map((n) => n.slice(4, -7)))} ${plural ? "strings ring" : "string rings"}${where}.` : `${capitalized(andList(open))} ${plural ? "ring" : "rings"}${where}.`);
1680
+ }
1681
+ return sentences;
1682
+ }
1683
+ function pianoWords(input) {
1684
+ const keys = [...input.keys].sort((a, b) => a - b);
1685
+ if (!keys.length)
1686
+ return [];
1687
+ const plain = (midi) => input.names?.get(midi % 12) ?? letter(midi);
1688
+ const octaves = new Set(keys.map(plain)).size < keys.length;
1689
+ const keyName = (midi) => {
1690
+ const name = plain(midi);
1691
+ if (!octaves)
1692
+ return name;
1693
+ return `${name}${Math.floor((midi - (Note2.get(name).alt || 0)) / 12) - 1}`;
1694
+ };
1695
+ const part = (group) => {
1696
+ const withFinger = group.filter((k) => input.fingers?.has(k));
1697
+ const without = group.filter((k) => !input.fingers?.has(k)).map(keyName);
1698
+ const fingered = withFinger.map((k) => {
1699
+ const finger = input.fingers.get(k);
1700
+ return `${PIANO_FINGERS[finger] ?? `finger ${finger}`} on ${keyName(k)}`;
1701
+ });
1702
+ if (!fingered.length)
1703
+ return andList(without);
1704
+ if (!without.length)
1705
+ return fingered.join(", ");
1706
+ return `${fingered.join(", ")}, and also play ${andList(without)}`;
1707
+ };
1708
+ const hands = input.hands;
1709
+ if (!hands?.size) {
1710
+ return [
1711
+ keys.some((k) => input.fingers?.has(k)) ? `${capitalized(part(keys))}.` : `Play ${part(keys)}.`
1712
+ ];
1713
+ }
1714
+ return ["left", "right"].flatMap((hand) => {
1715
+ const group = keys.filter((k) => (hands.get(k) ?? "right") === hand);
1716
+ return group.length ? [`${capitalized(hand)} hand: ${part(group)}.`] : [];
1717
+ });
1718
+ }
1719
+ function fingeringInWords(chord) {
1720
+ return "frets" in chord ? guitarWords(chord) : pianoWords(chord);
1721
+ }
1722
+
1723
+ // src/render/layout.ts
1724
+ function parseOrientation(text) {
1725
+ const value = text.trim().toLowerCase();
1726
+ if (value === "vertical" || value === "horizontal")
1727
+ return value;
1728
+ throw new Error(`Unknown orientation "${text}": use vertical or horizontal`);
1729
+ }
1730
+ function parseHand(text) {
1731
+ const value = text.trim().toLowerCase();
1732
+ if (value === "left" || value === "right")
1733
+ return value;
1734
+ throw new Error(`Unknown hand "${text}": use left or right`);
1735
+ }
1736
+ function layoutDefaults(value) {
1737
+ const result = {};
1738
+ if (!value || typeof value !== "object")
1739
+ return result;
1740
+ const word = (v) => typeof v === "string" ? v.trim().toLowerCase() : undefined;
1741
+ try {
1742
+ const { orientation, hand } = value;
1743
+ const h = word(hand);
1744
+ if (h === "left" || h === "right")
1745
+ result.hand = h;
1746
+ if (orientation && typeof orientation === "object") {
1747
+ for (const language of ["chord", "keyboard", "fretboard"]) {
1748
+ const o = word(orientation[language]);
1749
+ if (o === "vertical" || o === "horizontal")
1750
+ (result.orientation ??= {})[language] = o;
1751
+ }
1752
+ }
1753
+ } catch {}
1754
+ return result;
1755
+ }
1756
+ function titleWidth(title) {
1757
+ if (!title)
1758
+ return 0;
1759
+ let width = 8;
1760
+ for (const ch of title) {
1761
+ width += ch.codePointAt(0) > 591 ? 15 : /[A-Z0-9#♯♭]/.test(ch) ? 10.5 : 8;
1762
+ }
1763
+ return Math.ceil(width);
1764
+ }
1765
+ var MAX_TITLE_LINES = 3;
1766
+ var TITLE_LINE = 17;
1767
+ function titleLineWidth(text) {
1768
+ if (!text)
1769
+ return 0;
1770
+ let width = 8;
1771
+ for (const ch of text) {
1772
+ const code = ch.codePointAt(0);
1773
+ width += code > 591 ? 15 : ch === " " || ".,:;'!|".includes(ch) ? 4 : "()[]-/".includes(ch) || "iljfrt".includes(ch) ? 5 : "mwMW".includes(ch) ? 12 : /[A-Z0-9#♯♭]/.test(ch) ? 9.5 : 7.8;
1774
+ }
1775
+ return Math.ceil(width);
1776
+ }
1777
+ function titleLines(title, width) {
1778
+ const fits = (text) => titleLineWidth(text) <= width;
1779
+ const squeeze = (text) => ({
1780
+ text,
1781
+ textLength: fits(text) ? null : Math.max(1, width - 8)
1782
+ });
1783
+ if (fits(title))
1784
+ return [{ text: title, textLength: null }];
1785
+ const phrases = title.split(/(?<=,)\s+|\s+(?=\()/).flatMap((phrase) => fits(phrase) ? [phrase] : phrase.split(/\s+/)).filter(Boolean);
1786
+ const lines = [];
1787
+ let line = "";
1788
+ for (const phrase of phrases) {
1789
+ const next = line ? `${line} ${phrase}` : phrase;
1790
+ if (!line || fits(next))
1791
+ line = next;
1792
+ else {
1793
+ lines.push(line);
1794
+ line = phrase;
1795
+ }
1796
+ }
1797
+ if (line)
1798
+ lines.push(line);
1799
+ if (lines.length > MAX_TITLE_LINES) {
1800
+ const kept = lines.slice(0, MAX_TITLE_LINES - 1);
1801
+ kept.push(lines.slice(MAX_TITLE_LINES - 1).join(" "));
1802
+ return kept.map(squeeze);
1803
+ }
1804
+ return lines.map(squeeze);
1805
+ }
1806
+ function drawTitle(doc, root, lines, x, y) {
1807
+ const NS = "http://www.w3.org/2000/svg";
1808
+ const text = doc.createElementNS(NS, "text");
1809
+ text.setAttribute("class", "mn-title");
1810
+ text.setAttribute("x", String(x));
1811
+ text.setAttribute("y", String(y));
1812
+ text.setAttribute("text-anchor", "middle");
1813
+ const squeeze = (el, line) => {
1814
+ if (line.textLength === null)
1815
+ return;
1816
+ el.setAttribute("textLength", String(line.textLength));
1817
+ el.setAttribute("lengthAdjust", "spacingAndGlyphs");
1818
+ };
1819
+ if (lines.length === 1) {
1820
+ text.textContent = lines[0].text;
1821
+ squeeze(text, lines[0]);
1822
+ } else {
1823
+ lines.forEach((line, i) => {
1824
+ const span = doc.createElementNS(NS, "tspan");
1825
+ span.setAttribute("x", String(x));
1826
+ if (i > 0)
1827
+ span.setAttribute("dy", String(TITLE_LINE));
1828
+ span.textContent = i > 0 ? ` ${line.text}` : line.text;
1829
+ squeeze(span, line);
1830
+ text.appendChild(span);
1831
+ });
1832
+ }
1833
+ root.setAttribute("data-mn-title-lines", String(lines.length));
1834
+ root.appendChild(text);
1835
+ return text;
1836
+ }
1837
+ function alignTitleLines(diagrams) {
1838
+ const list = [...diagrams].filter((d) => d.hasAttribute("data-mn-title-lines"));
1839
+ const most = Math.max(0, ...list.map((d) => Number(d.getAttribute("data-mn-title-lines"))));
1840
+ for (const d of list) {
1841
+ const missing = most - Number(d.getAttribute("data-mn-title-lines"));
1842
+ if (missing <= 0)
1843
+ continue;
1844
+ const shift = missing * TITLE_LINE;
1845
+ const doc = d.ownerDocument;
1846
+ const g = doc.createElementNS("http://www.w3.org/2000/svg", "g");
1847
+ g.setAttribute("class", "mn-title-pad");
1848
+ g.setAttribute("transform", `translate(0 ${shift})`);
1849
+ for (const child of [...d.children]) {
1850
+ if (child.tagName.toLowerCase() !== "defs")
1851
+ g.appendChild(child);
1852
+ }
1853
+ d.appendChild(g);
1854
+ const [x, y, w, h] = (d.getAttribute("viewBox") ?? "0 0 0 0").split(/\s+/).map(Number);
1855
+ d.setAttribute("viewBox", `${x} ${y} ${w} ${h + shift}`);
1856
+ if (d.hasAttribute("height"))
1857
+ d.setAttribute("height", String(Number(d.getAttribute("height")) + shift));
1858
+ d.setAttribute("data-mn-title-lines", String(most));
1859
+ }
1860
+ }
1861
+ function neckFrame(n) {
1862
+ const vertical = n.orientation === "vertical";
1863
+ const left = n.hand === "left";
1864
+ const content = vertical ? n.low + n.across + n.high : n.before + n.along + n.after;
1865
+ const shift = n.minWidth && n.minWidth > content ? (n.minWidth - content) / 2 : 0;
1866
+ const height = n.top + (vertical ? n.before + n.along + n.after : n.high + n.across + n.low);
1867
+ const at = (across, along) => {
1868
+ if (vertical) {
1869
+ const x = left ? n.high + (n.across - across) : n.low + across;
1870
+ return [shift + x, n.top + n.before + along];
1871
+ }
1872
+ const x = left ? content - n.before - along : n.before + along;
1873
+ return [shift + x, n.top + n.high + (n.across - across)];
1874
+ };
1875
+ const box = (a1, l1, a2, l2) => {
1876
+ const [x1, y1] = at(a1, l1);
1877
+ const [x2, y2] = at(a2, l2);
1878
+ return {
1879
+ x: Math.min(x1, x2),
1880
+ y: Math.min(y1, y2),
1881
+ width: Math.abs(x2 - x1),
1882
+ height: Math.abs(y2 - y1)
1883
+ };
1884
+ };
1885
+ return { width: content + 2 * shift, height, at, box };
1886
+ }
1887
+
1888
+ // src/chord/guitar.ts
1889
+ var STANDARD_TUNING = [40, 45, 50, 55, 59, 64];
1890
+ function chartNoteName(name) {
1891
+ if (!/^[A-G](##|bb)$/.test(name))
1892
+ return name;
1893
+ return nameOf(chromaOf(name), name.endsWith("b"));
1894
+ }
1895
+ function parseFrets(text) {
1896
+ const trimmed = text.trim();
1897
+ const tokens = /[\s,-]/.test(trimmed) ? trimmed.split(/[\s,-]+/) : [...trimmed];
1898
+ const frets = tokens.filter(Boolean).map((t) => /^[xX]$/.test(t) ? null : /^\d+$/.test(t) ? Number(t) : NaN);
1899
+ return frets.length >= 2 && frets.every((f) => f === null || Number.isInteger(f) && f <= 36) ? frets : null;
1900
+ }
1901
+ function parseFingers(text) {
1902
+ const trimmed = text.trim();
1903
+ const tokens = /[\s,]/.test(trimmed) || trimmed.includes("-", 1) ? trimmed.split(/[\s,-]+/) : [...trimmed];
1904
+ return tokens.filter(Boolean).map((t) => /^[0xX]$/.test(t) ? null : t.toUpperCase());
1905
+ }
1906
+ function baseFretOf(frets) {
1907
+ const fretted = frets.filter((f) => f !== null && f > 0);
1908
+ if (!fretted.length || Math.max(...fretted) <= 4)
1909
+ return 1;
1910
+ return Math.min(...fretted);
1911
+ }
1912
+ function barresOf(voicing, capoFret) {
1913
+ const byKey = new Map;
1914
+ voicing.frets.forEach((fret, string) => {
1915
+ const finger = voicing.fingers[string];
1916
+ if (fret === null || fret === 0 || fret === capoFret || !finger)
1917
+ return;
1918
+ const key = `${finger}@${fret}`;
1919
+ byKey.set(key, [...byKey.get(key) ?? [], string]);
1920
+ });
1921
+ const barres = [];
1922
+ for (const [key, strings] of byKey) {
1923
+ if (strings.length < 2)
1924
+ continue;
1925
+ const [finger, fretText] = key.split("@");
1926
+ const fret = Number(fretText);
1927
+ const from = Math.min(...strings);
1928
+ const to = Math.max(...strings);
1929
+ let under = false;
1930
+ for (let s = from + 1;s < to; s++) {
1931
+ const f = voicing.frets[s];
1932
+ if (!strings.includes(s) && f !== null && f !== undefined && f > fret)
1933
+ under = true;
1934
+ }
1935
+ barres.push({ fret, from, to, finger, strings, full: under || strings.length > 3 });
1936
+ }
1937
+ return barres;
1938
+ }
1939
+ function barreKind(voicing) {
1940
+ const barres = barresOf(voicing, null);
1941
+ if (!barres.length)
1942
+ return null;
1943
+ return barres.some((b) => b.full) ? "full" : "partial";
1944
+ }
1945
+ var isBarreVoicing = (voicing) => barreKind(voicing) !== null;
1946
+ var SPACING = 18;
1947
+ var ROW = 20;
1948
+ var MARKERS = 16;
1949
+ var HIT_ALONG = 44;
1950
+ var BASE = 30;
1951
+ var TITLE = 22;
1952
+ var CAPTION = 18;
1953
+ var capoCaption = (capo, sounds) => `Capo ${capo}${sounds ? `, sounds ${sounds}` : ""}`;
1954
+ function renderGuitarDiagram(doc, voicing, options = {}) {
1955
+ const strings = voicing.frets.length;
1956
+ const base = voicing.baseFret ?? baseFretOf(voicing.frets);
1957
+ const fretted = voicing.frets.filter((f) => f !== null && f > 0);
1958
+ const rows = Math.max(4, fretted.length ? Math.max(...fretted) - base + 1 : 0);
1959
+ const orientation = options.orientation ?? "vertical";
1960
+ const vertical = orientation === "vertical";
1961
+ const capo = options.capo && options.capo > 0 ? options.capo : 0;
1962
+ const fromNut = capo > 0 && options.fretsFrom === "nut";
1963
+ const capoFret = fromNut ? capo : null;
1964
+ const caption = capo && options.caption !== false ? shown(capoCaption(capo, options.sounds)) : undefined;
1965
+ const layout = {
1966
+ orientation,
1967
+ hand: options.hand ?? "right",
1968
+ across: (strings - 1) * SPACING,
1969
+ along: rows * ROW,
1970
+ before: MARKERS,
1971
+ after: 10,
1972
+ low: vertical || base > 1 ? BASE : 10,
1973
+ high: vertical ? 14 : 10,
1974
+ top: 4,
1975
+ minWidth: titleWidth(caption)
1976
+ };
1977
+ const lines = options.title ? titleLines(shown(options.title), neckFrame(layout).width) : [];
1978
+ const frame = neckFrame({
1979
+ ...layout,
1980
+ top: lines.length ? TITLE + (lines.length - 1) * TITLE_LINE : 4
1981
+ });
1982
+ const across = (string) => string * SPACING;
1983
+ const along = (row) => row * ROW;
1984
+ const at = (string, row) => frame.at(across(string), along(row));
1985
+ const label = `${options.title ? `${options.title} chord diagram` : "Chord diagram"}${capo ? `, ${capoCaption(capo, options.sounds).replace(/^Capo/, "capo")}` : ""}`;
1986
+ const height = frame.height + (caption ? CAPTION : 0);
1987
+ const root = svgRoot(doc, frame.width, height, "mn-guitar-chord", label);
1988
+ root.setAttribute("data-mn-hand", options.hand ?? "right");
1989
+ const fretText = voicing.frets.map((f) => f === null ? "x" : String(f));
1990
+ root.setAttribute("data-mn-voicing", fretText.some((f) => f.length > 1) ? fretText.join("-") : fretText.join(""));
1991
+ if (caption) {
1992
+ root.appendChild(svgText(doc, caption, {
1993
+ class: "mn-caption",
1994
+ x: frame.width / 2,
1995
+ y: height - 6,
1996
+ "text-anchor": "middle"
1997
+ }));
1998
+ }
1999
+ if (capo) {
2000
+ root.setAttribute("data-mn-capo", String(capo));
2001
+ root.setAttribute("data-mn-frets-from", fromNut ? "nut" : "capo");
2002
+ }
2003
+ if (lines.length)
2004
+ drawTitle(doc, root, lines, frame.width / 2, 15);
2005
+ for (let row = 0;row <= rows; row++) {
2006
+ const cls = row === 0 && base === 1 && (!capo || fromNut) ? "mn-nut" : "mn-fret";
2007
+ root.appendChild(svgLine(doc, at(0, row), at(strings - 1, row), cls));
2008
+ }
2009
+ const capoRow = fromNut ? capo - base + 0.5 : base === 1 ? 0 : null;
2010
+ if (capo && capoRow !== null && capoRow >= 0 && capoRow <= rows) {
2011
+ root.appendChild(svg(doc, "rect", {
2012
+ class: "mn-capo",
2013
+ ...frame.box(across(0) - 8, along(capoRow) - 3, across(strings - 1) + 8, along(capoRow) + 3),
2014
+ rx: 3
2015
+ }));
2016
+ }
2017
+ for (let s = 0;s < strings; s++) {
2018
+ root.appendChild(svgLine(doc, at(s, 0), at(s, rows), "mn-string"));
2019
+ }
2020
+ if (base > 1) {
2021
+ const label = `${base}fr`;
2022
+ root.appendChild(vertical ? svgLabel(doc, label, frame.at(-10, along(0.5)), "mn-base-fret", options.hand === "left" ? "start" : "end") : svgLabel(doc, label, frame.at(-16, along(0.5)), "mn-base-fret"));
2023
+ }
2024
+ const textOf = (s) => (options.labels ? options.labels[s] : voicing.fingers[s]) ?? null;
2025
+ const quiet = new Set;
2026
+ const fingered = voicing.fingers.some((f) => f);
2027
+ const barres = fingered ? barresOf(voicing, capoFret) : options.barreFingers ? barresOf({ frets: voicing.frets, fingers: [...options.barreFingers] }, capoFret).filter((b) => b.full) : [];
2028
+ for (const barre of barres) {
2029
+ const texts = new Set(barre.strings.map(textOf));
2030
+ if (texts.size === 1) {
2031
+ for (const s of barre.strings)
2032
+ if (s !== barre.from)
2033
+ quiet.add(s);
2034
+ } else if (!barre.full) {
2035
+ continue;
1799
2036
  }
1800
- if (usual)
1801
- difficulty -= 3;
1802
- else if (jazz)
1803
- difficulty -= 1.5;
1804
- else if (isBarreShape(shape) && barre)
1805
- difficulty -= 2;
1806
- else if (shape && KNOWN_SHAPES.has(shape))
1807
- difficulty -= 1.5;
1808
- const lowChroma = low % 12;
1809
- const inBass = members.findIndex((m) => m.chroma === lowChroma);
1810
- return {
1811
- frets: [...candidate],
1812
- fingers,
1813
- baseFret: base,
1814
- bassString,
1815
- inversion: inBass < 0 ? null : inBass,
1816
- shape: isHendrixChord(candidate, info, tuning) ? "Hendrix chord" : shape ?? otherNameOf(candidate, info, tuning),
1817
- difficulty: Math.max(0, Math.round(difficulty * 10) / 10),
1818
- reasons
2037
+ const middle = along(barre.fret - base + 0.5);
2038
+ root.appendChild(svg(doc, "rect", {
2039
+ class: "mn-barre",
2040
+ ...frame.box(across(barre.from) - 7, middle - 7, across(barre.to) + 7, middle + 7),
2041
+ rx: 7,
2042
+ "data-mn-fret": barre.fret,
2043
+ "data-mn-finger": barre.finger,
2044
+ "data-mn-from": strings - barre.from,
2045
+ "data-mn-to": strings - barre.to
2046
+ }));
2047
+ }
2048
+ const tuning = options.tuning ?? (strings === 6 ? STANDARD_TUNING : undefined);
2049
+ const roots = [];
2050
+ voicing.frets.forEach((fret, s) => {
2051
+ const markAlong = -8;
2052
+ const mark = frame.at(across(s), markAlong);
2053
+ const string = strings - s;
2054
+ if (fret === null) {
2055
+ const [x, y] = mark;
2056
+ const d = 3.5;
2057
+ root.appendChild(svg(doc, "path", {
2058
+ class: "mn-muted",
2059
+ d: `M${x - d} ${y - d}L${x + d} ${y + d}M${x + d} ${y - d}L${x - d} ${y + d}`,
2060
+ "data-mn-string": string
2061
+ }));
2062
+ return;
2063
+ }
2064
+ const openString = tuning?.[s];
2065
+ const open = openString === undefined ? undefined : openString + (fromNut ? 0 : capo);
2066
+ const isRoot = options.root !== undefined && options.root !== null && open !== undefined && (open + fret) % 12 === options.root;
2067
+ if (isRoot)
2068
+ roots.push(string);
2069
+ const midi = {
2070
+ "data-mn-string": string,
2071
+ "data-mn-fret": fret,
2072
+ ...open !== undefined ? { "data-midi": open + fret } : {}
1819
2073
  };
1820
- };
1821
- const results = new Map;
1822
- const frets = new Array(count).fill(null);
1823
- const visit = (s, min, max, have, sounded, closed) => {
1824
- if (s === count) {
1825
- if (sounded < minStrings || (required & ~have) !== 0)
2074
+ const place = (markAt, ...els) => {
2075
+ if (open === undefined) {
2076
+ for (const el of els)
2077
+ root.appendChild(el);
1826
2078
  return;
1827
- const voicing = evaluate(frets);
1828
- if (voicing)
1829
- results.set(frets.join(","), voicing);
2079
+ }
2080
+ const area = frame.box(across(s) - SPACING / 2, markAt - HIT_ALONG / 2, across(s) + SPACING / 2, markAt + HIT_ALONG / 2);
2081
+ root.appendChild(playableMark(doc, area, ...els));
2082
+ };
2083
+ if (fret === 0) {
2084
+ const [cx, cy] = mark;
2085
+ place(markAlong, noteMark(doc, isRoot, {
2086
+ class: `mn-open${isRoot ? " mn-root" : ""}`,
2087
+ cx,
2088
+ cy,
2089
+ r: 4,
2090
+ ...midi
2091
+ }));
1830
2092
  return;
1831
2093
  }
1832
- const left = closed ? 0 : (allowed.has(s) ? 1 : 0) + allowedAfter[s];
1833
- if (bits(required & ~have) > left || sounded + left < minStrings)
2094
+ const row = along(fret - base + 0.5);
2095
+ const center = at(s, fret - base + 0.5);
2096
+ const [cx, cy] = center;
2097
+ if (fret === capoFret) {
2098
+ place(row, noteMark(doc, isRoot, {
2099
+ class: `mn-capo-open${isRoot ? " mn-root" : ""}`,
2100
+ cx,
2101
+ cy,
2102
+ r: 4,
2103
+ ...midi
2104
+ }));
1834
2105
  return;
1835
- for (const fret of choices[s]) {
1836
- if (fret === null) {
1837
- frets[s] = null;
1838
- visit(s + 1, min, max, have, sounded, closed || sounded > 0 && !options.gaps);
1839
- continue;
1840
- }
1841
- if (closed)
1842
- continue;
1843
- const fretted = fret > 0;
1844
- const nextMin = fretted ? Math.min(min, fret) : min;
1845
- const nextMax = fretted ? Math.max(max, fret) : max;
1846
- if (fretted && nextMax - nextMin + 1 > maxSpan)
1847
- continue;
1848
- frets[s] = fret;
1849
- visit(s + 1, nextMin, nextMax, have | 1 << (tuning[s] + fret) % 12, sounded + 1, false);
1850
- }
1851
- frets[s] = null;
1852
- };
1853
- visit(0, Infinity, -Infinity, 0, 0, false);
1854
- if (standard && !options.gaps) {
1855
- for (const { rootString, offsets } of JAZZ_GRIPS) {
1856
- if (!allowed.has(rootString))
1857
- continue;
1858
- const rootFret = ((info.root - tuning[rootString]) % 12 + 12) % 12;
1859
- for (const at of [rootFret, rootFret + 12]) {
1860
- const candidate = offsets.map((o) => o === null ? null : at + o);
1861
- if (candidate.some((f, s) => f !== null && (f < 1 || !choices[s].includes(f))))
1862
- continue;
1863
- const have = candidate.reduce((mask, f, s) => f === null ? mask : mask | 1 << (tuning[s] + f) % 12, 0);
1864
- if ((required & ~have) !== 0)
1865
- continue;
1866
- const key = candidate.join(",");
1867
- if (results.has(key))
1868
- continue;
1869
- const voicing = evaluate(candidate);
1870
- if (voicing)
1871
- results.set(key, voicing);
1872
- }
1873
2106
  }
2107
+ const text = quiet.has(s) ? null : textOf(s);
2108
+ place(row, noteMark(doc, isRoot, {
2109
+ class: `mn-dot${isRoot ? " mn-root" : ""}${options.marks?.[s] ? ` mn-${options.marks[s]}` : ""}`,
2110
+ cx,
2111
+ cy,
2112
+ r: 7,
2113
+ ...midi
2114
+ }), ...text ? [dotLabel(doc, text, center, 7)] : []);
2115
+ });
2116
+ describeDiagram(root, chordWords(voicing, tuning, capo, fromNut, roots));
2117
+ if (tuning) {
2118
+ const shift = fromNut ? 0 : capo;
2119
+ const pitches = voicing.frets.flatMap((f, s) => f === null ? [] : [tuning[s] + shift + f]);
2120
+ root.setAttribute("data-mn-pitches", pitches.join(" "));
2121
+ root.setAttribute("data-mn-play", "chord");
2122
+ root.setAttribute("data-mn-sound", "guitar");
1874
2123
  }
1875
- const sounding = (v) => v.frets.filter((f) => f !== null).length;
1876
- return [...results.values()].sort((a, b) => a.difficulty - b.difficulty || sounding(b) - sounding(a) || a.baseFret - b.baseFret || a.frets.join(",").localeCompare(b.frets.join(",")));
2124
+ return root;
2125
+ }
2126
+ function chordWords(voicing, tuning, capo, fromNut, roots) {
2127
+ let words;
2128
+ try {
2129
+ words = fingeringInWords({
2130
+ frets: voicing.frets,
2131
+ fingers: voicing.fingers,
2132
+ ...tuning ? { tuning } : {},
2133
+ ...capo ? { capo, fretsFrom: fromNut ? "nut" : "capo" } : {}
2134
+ });
2135
+ } catch {
2136
+ words = [];
2137
+ }
2138
+ if (roots.length) {
2139
+ const list = roots.length === 1 ? `string ${roots[0]}` : `strings ${roots.slice(0, -1).join(", ")} and ${roots[roots.length - 1]}`;
2140
+ words.push(`The root is on ${list}.`);
2141
+ }
2142
+ return words.join(" ");
1877
2143
  }
1878
2144
 
1879
2145
  // src/voicings/check.ts
@@ -2172,5 +2438,5 @@ export {
2172
2438
  voicingCount
2173
2439
  };
2174
2440
 
2175
- //# debugId=92E85F892552F21C64756E2164756E21
2441
+ //# debugId=B2DD9AF0815FCC3564756E2164756E21
2176
2442
  //# sourceMappingURL=index.js.map