@chordproject/editor 1.0.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,836 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ createChordProEditor: () => createChordProEditor,
24
+ getChordCompletionPriorities: () => getChordCompletionPriorities,
25
+ getChordNotationSuggestions: () => getChordNotationSuggestions,
26
+ normalizeChordNotationText: () => normalizeChordNotationText
27
+ });
28
+ module.exports = __toCommonJS(index_exports);
29
+ var import_state2 = require("@codemirror/state");
30
+ var import_view5 = require("@codemirror/view");
31
+
32
+ // src/autocomplete/index.ts
33
+ var import_autocomplete2 = require("@codemirror/autocomplete");
34
+
35
+ // src/autocomplete/chordVocabulary.ts
36
+ var ROOTS = ["A", "A#", "Bb", "B", "C", "C#", "Db", "D", "D#", "Eb", "E", "F", "F#", "Gb", "G", "G#", "Ab"];
37
+ var QUALITIES = ["", "m", "7", "m7", "maj7", "sus2", "sus4", "6", "m6", "9", "add9", "dim", "dim7", "aug", "m7b5"];
38
+ var CHORD_VOCABULARY = ROOTS.flatMap((root) => QUALITIES.map((quality) => root + quality));
39
+
40
+ // src/autocomplete/chords.ts
41
+ var CHORD_TOKEN = /\[([A-G](?:#|b)?(?:min|mi|m(?!aj)|-)?[^\]\s-]*(?:\/[A-G](?:#|b)?)?)\]/g;
42
+ var FREQUENCY_BOOST = 100;
43
+ var TRANSITION_BOOST = 1e3;
44
+ var PATTERN_BOOST = 1e4;
45
+ function countUsedChords(state) {
46
+ const counts = /* @__PURE__ */ new Map();
47
+ for (const { name: chord } of getChordOccurrences(state.doc.toString())) {
48
+ counts.set(chord, (counts.get(chord) ?? 0) + 1);
49
+ }
50
+ return counts;
51
+ }
52
+ function getChordOccurrences(content) {
53
+ return [...content.matchAll(CHORD_TOKEN)].flatMap((match) => {
54
+ return match.index === void 0 ? [] : [{ name: match[1], from: match.index }];
55
+ });
56
+ }
57
+ function getChordCompletionPriorities(content, cursor) {
58
+ const history2 = getChordOccurrences(content).filter((occurrence) => occurrence.from < cursor - 1).map((occurrence) => occurrence.name);
59
+ const priorities = /* @__PURE__ */ new Map();
60
+ for (let index = 0; index < history2.length; index++) {
61
+ const candidate = history2[index];
62
+ if (index > 0 && history2[index - 1] === history2.at(-1)) {
63
+ priorities.set(candidate, (priorities.get(candidate) ?? 0) + TRANSITION_BOOST);
64
+ }
65
+ if (index > 1 && history2[index - 2] === history2.at(-2) && history2[index - 1] === history2.at(-1)) {
66
+ priorities.set(candidate, (priorities.get(candidate) ?? 0) + PATTERN_BOOST);
67
+ }
68
+ }
69
+ return priorities;
70
+ }
71
+ function applyChord(view, completion, from, to) {
72
+ const insert = completion.label;
73
+ const hasClosingBracket = view.state.sliceDoc(to, to + 1) === "]";
74
+ const cursor = from + insert.length + 1;
75
+ view.dispatch({
76
+ changes: hasClosingBracket ? { from, to, insert } : { from, to, insert: `${insert}]` },
77
+ selection: { anchor: cursor }
78
+ });
79
+ }
80
+ function buildOptions(used, priorities) {
81
+ const options = /* @__PURE__ */ new Map();
82
+ const rankedUsedChords = [...used.entries()].sort(([leftChord, leftCount], [rightChord, rightCount]) => {
83
+ const priorityDifference = (priorities.get(rightChord) ?? 0) - (priorities.get(leftChord) ?? 0);
84
+ return priorityDifference || rightCount - leftCount || leftChord.localeCompare(rightChord);
85
+ });
86
+ for (const [chord, count] of rankedUsedChords) {
87
+ options.set(chord, {
88
+ label: chord,
89
+ type: "chord-used",
90
+ boost: FREQUENCY_BOOST + count + (priorities.get(chord) ?? 0),
91
+ apply: applyChord
92
+ });
93
+ }
94
+ for (const chord of CHORD_VOCABULARY) {
95
+ if (!options.has(chord)) options.set(chord, { label: chord, type: "chord", apply: applyChord });
96
+ }
97
+ return [...options.values()];
98
+ }
99
+ function chordCompletionSource(context) {
100
+ const match = context.matchBefore(/\[[^\]\n]*/);
101
+ if (!match || match.from === match.to && !context.explicit) return null;
102
+ return {
103
+ from: match.from + 1,
104
+ options: buildOptions(
105
+ countUsedChords(context.state),
106
+ getChordCompletionPriorities(context.state.doc.toString(), match.from + 1)
107
+ ),
108
+ validFor: /^[^\]\n]*$/
109
+ };
110
+ }
111
+
112
+ // src/autocomplete/snippets.ts
113
+ var import_autocomplete = require("@codemirror/autocomplete");
114
+ var CHORDPRO_SNIPPETS = [
115
+ (0, import_autocomplete.snippetCompletion)("{album: ${value}}", { label: "album", type: "directive" }),
116
+ (0, import_autocomplete.snippetCompletion)("{arranger: ${value}}", { label: "arranger", type: "directive" }),
117
+ (0, import_autocomplete.snippetCompletion)("{artist: ${value}}", { label: "artist", type: "directive" }),
118
+ (0, import_autocomplete.snippetCompletion)("{artist: ${value}}", { label: "a", type: "directive", detail: "artist" }),
119
+ (0, import_autocomplete.snippetCompletion)("{capo: ${5}}", { label: "capo", type: "directive" }),
120
+ (0, import_autocomplete.snippetCompletion)("{composer: ${value}}", { label: "composer", type: "directive" }),
121
+ (0, import_autocomplete.snippetCompletion)("{copyright: ${value}}", { label: "copyright", type: "directive" }),
122
+ (0, import_autocomplete.snippetCompletion)("{duration: ${4}:${00}}", { label: "duration", type: "directive" }),
123
+ (0, import_autocomplete.snippetCompletion)("{key: ${Am}}", { label: "key", type: "directive" }),
124
+ (0, import_autocomplete.snippetCompletion)("{key: ${Am}}", { label: "k", type: "directive", detail: "key" }),
125
+ (0, import_autocomplete.snippetCompletion)("{lyricist: ${value}}", { label: "lyricist", type: "directive" }),
126
+ (0, import_autocomplete.snippetCompletion)("{tempo: ${120}}", { label: "tempo", type: "directive" }),
127
+ (0, import_autocomplete.snippetCompletion)("{time: ${4}/${4}}", { label: "time", type: "directive" }),
128
+ (0, import_autocomplete.snippetCompletion)("{title: ${value}}", { label: "title", type: "directive" }),
129
+ (0, import_autocomplete.snippetCompletion)("{title: ${value}}", { label: "t", type: "directive", detail: "title" }),
130
+ (0, import_autocomplete.snippetCompletion)("{subtitle: ${value}}", { label: "subtitle", type: "directive" }),
131
+ (0, import_autocomplete.snippetCompletion)("{subtitle: ${value}}", { label: "st", type: "directive", detail: "subtitle" }),
132
+ (0, import_autocomplete.snippetCompletion)("{year: ${2020}}", { label: "year", type: "directive" }),
133
+ (0, import_autocomplete.snippetCompletion)("{meta: ${label} ${value}}", { label: "meta", type: "directive" }),
134
+ (0, import_autocomplete.snippetCompletion)("{comment: ${value}}", { label: "comment", type: "directive" }),
135
+ (0, import_autocomplete.snippetCompletion)("{comment: ${value}}", { label: "c", type: "directive", detail: "comment" }),
136
+ (0, import_autocomplete.snippetCompletion)("{start_of_chorus: ${Chorus}}\n${lyrics}\n{end_of_chorus}", {
137
+ label: "chorus",
138
+ type: "directive"
139
+ }),
140
+ (0, import_autocomplete.snippetCompletion)("{start_of_chorus}", { label: "soc", type: "directive", detail: "start_of_chorus" }),
141
+ (0, import_autocomplete.snippetCompletion)("{end_of_chorus}", { label: "eoc", type: "directive", detail: "end_of_chorus" }),
142
+ (0, import_autocomplete.snippetCompletion)("{start_of_verse: ${Verse} ${1}}\n${lyrics}\n{end_of_verse}", {
143
+ label: "verse",
144
+ type: "directive"
145
+ }),
146
+ (0, import_autocomplete.snippetCompletion)("{start_of_verse}", { label: "sov", type: "directive", detail: "start_of_verse" }),
147
+ (0, import_autocomplete.snippetCompletion)("{end_of_verse}", { label: "eov", type: "directive", detail: "end_of_verse" }),
148
+ (0, import_autocomplete.snippetCompletion)("{start_of_bridge: ${Bridge}}\n${lyrics}\n{end_of_bridge}", {
149
+ label: "bridge",
150
+ type: "directive"
151
+ }),
152
+ (0, import_autocomplete.snippetCompletion)("{start_of_bridge}", { label: "sob", type: "directive", detail: "start_of_bridge" }),
153
+ (0, import_autocomplete.snippetCompletion)("{end_of_bridge}", { label: "eob", type: "directive", detail: "end_of_bridge" }),
154
+ (0, import_autocomplete.snippetCompletion)(
155
+ "{start_of_tab}\ne|-${1}--------------------------------|\nB|----------------------------------|\nG|----------------------------------|\nD|----------------------------------|\nA|----------------------------------|\nE|----------------------------------|\n{end_of_tab}",
156
+ { label: "tab", type: "directive" }
157
+ ),
158
+ (0, import_autocomplete.snippetCompletion)("{start_of_tab}", { label: "sot", type: "directive", detail: "start_of_tab" }),
159
+ (0, import_autocomplete.snippetCompletion)("{end_of_tab}", { label: "eot", type: "directive", detail: "end_of_tab" }),
160
+ (0, import_autocomplete.snippetCompletion)("{define: ${Am} base-fret ${1} frets ${0 0 0 0 0 0} fingers ${0 0 0 0 0 0}}", {
161
+ label: "define",
162
+ type: "directive"
163
+ }),
164
+ (0, import_autocomplete.snippetCompletion)("{define: ${Am} base-fret ${1} frets ${0 0 0 0 0 0} fingers ${0 0 0 0 0 0}}", {
165
+ label: "d",
166
+ type: "directive",
167
+ detail: "define"
168
+ }),
169
+ (0, import_autocomplete.snippetCompletion)("[${Am}]", { label: "[", type: "chord", detail: "insert a chord" }),
170
+ (0, import_autocomplete.snippetCompletion)(
171
+ "{title: ${value}}\n{artist: ${value}}\n{key: ${C}}\n\n${lyrics}\n{start_of_chorus}\n${lyrics}\n{end_of_chorus}",
172
+ { label: "!", type: "directive", detail: "new song template" }
173
+ )
174
+ ];
175
+
176
+ // src/autocomplete/index.ts
177
+ var completeSnippets = (0, import_autocomplete2.completeFromList)(CHORDPRO_SNIPPETS);
178
+ function chordProCompletionSource(context) {
179
+ const chordCompletions = chordCompletionSource(context);
180
+ if (chordCompletions) return chordCompletions;
181
+ return context.explicit ? completeSnippets(context) : null;
182
+ }
183
+ function chordProAutocomplete() {
184
+ return (0, import_autocomplete2.autocompletion)({ override: [chordProCompletionSource], activateOnTyping: true });
185
+ }
186
+ function openCompletionList(view) {
187
+ view.focus();
188
+ return (0, import_autocomplete2.startCompletion)(view);
189
+ }
190
+ function insertChord(view) {
191
+ const range = view.state.selection.main;
192
+ const selected = view.state.sliceDoc(range.from, range.to);
193
+ view.dispatch({
194
+ changes: { from: range.from, to: range.to, insert: `[${selected}]` },
195
+ selection: { anchor: range.from + 1 + selected.length }
196
+ });
197
+ view.focus();
198
+ (0, import_autocomplete2.startCompletion)(view);
199
+ return true;
200
+ }
201
+
202
+ // src/extensions.ts
203
+ var import_state = require("@codemirror/state");
204
+ var import_view = require("@codemirror/view");
205
+ var import_commands = require("@codemirror/commands");
206
+ var import_language = require("@codemirror/language");
207
+ var import_lint = require("@codemirror/lint");
208
+ var import_autocomplete3 = require("@codemirror/autocomplete");
209
+ function isInsideChordBrackets(view) {
210
+ const pos = view.state.selection.main.head;
211
+ const line = view.state.doc.lineAt(pos);
212
+ return /\[[^\]]*$/.test(line.text.slice(0, pos - line.from));
213
+ }
214
+ function chordAwareCompletion(view) {
215
+ return isInsideChordBrackets(view) ? (0, import_autocomplete3.startCompletion)(view) : insertChord(view);
216
+ }
217
+ var chordBracketInputHandler = import_view.EditorView.inputHandler.of((view, from, to, text) => {
218
+ if (text !== "[") return false;
219
+ const selected = view.state.sliceDoc(from, to);
220
+ view.dispatch({
221
+ changes: { from, to, insert: `[${selected}]` },
222
+ selection: { anchor: from + 1 + selected.length }
223
+ });
224
+ (0, import_autocomplete3.startCompletion)(view);
225
+ return true;
226
+ });
227
+ function basicSetup() {
228
+ return [
229
+ (0, import_language.foldGutter)(),
230
+ (0, import_lint.lintGutter)(),
231
+ (0, import_view.highlightSpecialChars)(),
232
+ (0, import_view.highlightActiveLine)(),
233
+ (0, import_commands.history)(),
234
+ (0, import_view.drawSelection)(),
235
+ (0, import_language.bracketMatching)(),
236
+ (0, import_autocomplete3.closeBrackets)(),
237
+ chordBracketInputHandler,
238
+ import_state.EditorState.allowMultipleSelections.of(true),
239
+ import_view.keymap.of([
240
+ // Insert a complete ChordPro token before opening suggestions so an unfinished "["
241
+ // is never momentarily interpreted as invalid song content.
242
+ { key: "[", run: insertChord },
243
+ ...import_autocomplete3.closeBracketsKeymap,
244
+ ...import_commands.defaultKeymap,
245
+ ...import_commands.historyKeymap,
246
+ ...import_language.foldKeymap,
247
+ ...import_lint.lintKeymap,
248
+ // Override completionKeymap's Ctrl-Space/Option-`/Option-i (same keys, listed first so
249
+ // they take precedence) to be chord-aware instead of plain startCompletion.
250
+ { key: "Ctrl-Space", run: chordAwareCompletion },
251
+ { mac: "Cmd-Shift-Space", run: chordAwareCompletion },
252
+ { mac: "Alt-`", run: chordAwareCompletion },
253
+ { mac: "Alt-i", run: chordAwareCompletion },
254
+ ...import_autocomplete3.completionKeymap,
255
+ // Tab accepts a completion/snippet field when the popup is open.
256
+ {
257
+ key: "Tab",
258
+ preventDefault: true,
259
+ run: (view) => (0, import_autocomplete3.completionStatus)(view.state) ? (0, import_autocomplete3.acceptCompletion)(view) : false
260
+ }
261
+ ])
262
+ ];
263
+ }
264
+
265
+ // src/folding.ts
266
+ var import_language2 = require("@codemirror/language");
267
+ var START_RE = /\{(so(?<name>v|b|c|t)|start_of_(?<longname>[^\s:}]+))(?:[: ][^}]*)?\}/i;
268
+ var END_RE = /\{(eo(?<name>v|b|c|t)|end_of_(?<longname>[^\s:}]+))\}/i;
269
+ var SHORT_TO_LONG = { v: "verse", b: "bridge", c: "chorus", t: "tab" };
270
+ function blockName(match) {
271
+ const name = match.groups?.name ?? match.groups?.longname;
272
+ if (!name) return null;
273
+ return (SHORT_TO_LONG[name.toLowerCase()] ?? name.toLowerCase()).replace(/s$/, "");
274
+ }
275
+ var chordProFolding = import_language2.foldService.of((state, lineStart, lineEnd) => {
276
+ const startMatch = state.doc.sliceString(lineStart, lineEnd).match(START_RE);
277
+ if (!startMatch) return null;
278
+ const name = blockName(startMatch);
279
+ if (!name) return null;
280
+ let pos = lineEnd;
281
+ while (pos < state.doc.length) {
282
+ const line = state.doc.lineAt(pos + 1);
283
+ const endMatch = line.text.match(END_RE);
284
+ if (endMatch && blockName(endMatch) === name) {
285
+ return line.to > lineEnd ? { from: lineEnd, to: line.to } : null;
286
+ }
287
+ pos = line.to;
288
+ }
289
+ return null;
290
+ });
291
+
292
+ // src/language/index.ts
293
+ var import_language4 = require("@codemirror/language");
294
+
295
+ // src/language/chordproStream.ts
296
+ var import_language3 = require("@codemirror/language");
297
+ var import_highlight = require("@lezer/highlight");
298
+
299
+ // src/language/tokens.ts
300
+ var PREAMBLE_DIRECTIVES = /^(new_song|ns)$/i;
301
+ var META_DIRECTIVES = /^(title|t|sorttitle|subtitle|st|artist|sortartist|composer|arranger|lyricist|copyright|album|year|key|time|tempo|duration|capo|tag|meta)$/i;
302
+ var FORMATTING_DIRECTIVES = /^(comment|c|highlight|comment_italic|ci|comment_box|cb|image)$/i;
303
+ var ENV_DIRECTIVES = /^(start_of_chorus|soc|end_of_chorus|eoc|chorus|start_of_verse|sov|end_of_verse|eov|start_of_bridge|sob|end_of_bridge|eob|start_of_tab|sot|end_of_tab|eot|start_of_grid|sog|end_of_grid|eog)$/i;
304
+ var DELEGATED_ENV_DIRECTIVES = /^(start_of_abc|end_of_abc|start_of_ly|end_of_ly|start_of_svg|end_of_svg|start_of_textblock|end_of_textblock)$/i;
305
+ var CHORD_DIAGRAM_DIRECTIVES = /^define$/i;
306
+ var CUSTOM_EXTENSION_DIRECTIVE = /^x_[\w]+$/i;
307
+ var KNOWN_DIRECTIVE_LISTS = [
308
+ PREAMBLE_DIRECTIVES,
309
+ META_DIRECTIVES,
310
+ FORMATTING_DIRECTIVES,
311
+ ENV_DIRECTIVES,
312
+ DELEGATED_ENV_DIRECTIVES,
313
+ CHORD_DIAGRAM_DIRECTIVES
314
+ ];
315
+ var TAB_START_DIRECTIVES = /^(start_of_tab|sot)$/i;
316
+ var DEFINE_DIRECTIVE = /^define$/i;
317
+ var DIRECTIVE_NAME = /^[A-Za-z_][\w]*(?:-[\w!]+)?/;
318
+ var DEFINE_KEYWORD = /^(fingers|frets|base-fret)\b/i;
319
+ function baseDirectiveName(name) {
320
+ return name.replace(/-[\w!]+$/, "");
321
+ }
322
+ function isKnownDirective(name) {
323
+ const base = baseDirectiveName(name);
324
+ if (CUSTOM_EXTENSION_DIRECTIVE.test(base)) return true;
325
+ return KNOWN_DIRECTIVE_LISTS.some((re) => re.test(base));
326
+ }
327
+ var CHORD_TEXT = /^(\*.+|[A-G](?:#{1,2}|b{1,2}|x)?[^\]]*)/i;
328
+
329
+ // src/language/chordproStream.ts
330
+ function startState() {
331
+ return { mode: "default", pendingName: "" };
332
+ }
333
+ function copyState(state) {
334
+ return { ...state };
335
+ }
336
+ function token(stream, state) {
337
+ if (state.mode === "tab") {
338
+ if (stream.match(/^\{\s*(end_of_tab|eot)\s*\}/i)) {
339
+ state.mode = "default";
340
+ return "directiveBrace";
341
+ }
342
+ if (stream.match(/^-+/)) return "tabDash";
343
+ if (stream.match(/^\|+/)) return "tabChar";
344
+ if (stream.match(/^[A-Ga-g][b#]?/)) return "tabString";
345
+ if (stream.match(/^[0-9]+/)) return "tabNumber";
346
+ stream.next();
347
+ return "tabText";
348
+ }
349
+ if (state.mode === "define") {
350
+ if (stream.match(/^\}/)) {
351
+ state.mode = "default";
352
+ return "directiveBrace";
353
+ }
354
+ if (stream.eatSpace()) return null;
355
+ if (stream.match(/^[0-9]+/)) return "defineNumber";
356
+ if (stream.match(DEFINE_KEYWORD)) return "defineKeyword";
357
+ stream.match(/^[^\s0-9}]+/) || stream.next();
358
+ return "defineValue";
359
+ }
360
+ if (state.mode === "directiveValue") {
361
+ if (stream.match(/^\}/)) {
362
+ state.mode = "default";
363
+ return "directiveBrace";
364
+ }
365
+ stream.match(/^(\\.|[^\\}])+/) || stream.next();
366
+ return "directiveValue";
367
+ }
368
+ if (state.mode === "directiveName") {
369
+ stream.eatSpace();
370
+ const match = stream.match(DIRECTIVE_NAME);
371
+ if (match) {
372
+ const name = match[0];
373
+ state.pendingName = name;
374
+ state.mode = "afterName";
375
+ return isKnownDirective(name) ? "directiveName" : "directiveNameInvalid";
376
+ }
377
+ state.mode = "default";
378
+ if (stream.match(/^\}/)) return "directiveBrace";
379
+ stream.next();
380
+ return "directiveNameInvalid";
381
+ }
382
+ if (state.mode === "afterName") {
383
+ const name = baseDirectiveName(state.pendingName);
384
+ if (stream.match(/^:/)) {
385
+ state.mode = DEFINE_DIRECTIVE.test(name) ? "define" : "directiveValue";
386
+ return "directiveColon";
387
+ }
388
+ if (stream.match(/^\}/)) {
389
+ state.mode = TAB_START_DIRECTIVES.test(name) ? "tab" : "default";
390
+ return "directiveBrace";
391
+ }
392
+ if (stream.eatSpace()) {
393
+ state.mode = DEFINE_DIRECTIVE.test(name) ? "define" : "directiveValue";
394
+ return null;
395
+ }
396
+ state.mode = "default";
397
+ stream.next();
398
+ return "directiveNameInvalid";
399
+ }
400
+ if (state.mode === "chord" || state.mode === "afterChord" || state.mode === "afterChordInvalid") {
401
+ if (stream.eat("]")) {
402
+ state.mode = "default";
403
+ return "chordBracket";
404
+ }
405
+ if (state.mode === "chord") {
406
+ const match = stream.match(CHORD_TEXT);
407
+ state.mode = match ? "afterChord" : "afterChordInvalid";
408
+ if (!match) stream.match(/^[^\]]+/);
409
+ return match ? "chord" : "chordInvalid";
410
+ }
411
+ stream.match(/^[^\]]+/);
412
+ return "chordInvalid";
413
+ }
414
+ if (stream.sol() && stream.match(/^#.*/)) return "comment";
415
+ if (stream.match(/^\{/)) {
416
+ state.mode = "directiveName";
417
+ return "directiveBrace";
418
+ }
419
+ if (stream.eat("[")) {
420
+ state.mode = "chord";
421
+ return "chordBracket";
422
+ }
423
+ stream.match(/^[^{[]+/) || stream.next();
424
+ return null;
425
+ }
426
+ var tokenTable = {
427
+ directiveBrace: import_highlight.tags.meta,
428
+ directiveName: import_highlight.tags.attributeName,
429
+ directiveNameInvalid: import_highlight.tags.invalid,
430
+ directiveColon: import_highlight.tags.punctuation,
431
+ directiveValue: import_highlight.tags.string,
432
+ defineKeyword: import_highlight.tags.keyword,
433
+ defineNumber: import_highlight.tags.number,
434
+ defineValue: import_highlight.tags.string,
435
+ chordBracket: import_highlight.tags.character,
436
+ chord: import_highlight.tags.keyword,
437
+ chordInvalid: import_highlight.tags.invalid,
438
+ comment: import_highlight.tags.lineComment,
439
+ tabDash: import_highlight.tags.comment,
440
+ tabChar: import_highlight.tags.character,
441
+ tabString: import_highlight.tags.string,
442
+ tabNumber: import_highlight.tags.number,
443
+ tabText: import_highlight.tags.comment
444
+ };
445
+ var chordProLanguage = import_language3.StreamLanguage.define({
446
+ startState,
447
+ copyState,
448
+ token,
449
+ tokenTable,
450
+ languageData: {
451
+ commentTokens: { line: "#" }
452
+ }
453
+ });
454
+
455
+ // src/language/index.ts
456
+ function chordPro() {
457
+ return new import_language4.LanguageSupport(chordProLanguage);
458
+ }
459
+
460
+ // src/linting.ts
461
+ var import_lint2 = require("@codemirror/lint");
462
+ var import_parser = require("@chordproject/parser");
463
+
464
+ // src/chordNotation.ts
465
+ var CHORD_TOKEN2 = /\[([A-G](?:#|b)?)([^/\]\s]*)(\/[A-G](?:#|b)?)?\]/g;
466
+ var CHORD_TYPE_ALIASES = {
467
+ sus: { canonical: "sus4", reason: '"sus" se interpreta como sus4; escr\xEDbelo expl\xEDcitamente.' },
468
+ "2": { canonical: "sus2", reason: '"sus2" identifica el acorde suspendido de segunda.' },
469
+ "+": { canonical: "aug", reason: '"aug" es la notaci\xF3n expl\xEDcita para quinta aumentada.' },
470
+ M7: { canonical: "maj7", reason: '"maj7" identifica expl\xEDcitamente la s\xE9ptima mayor.' },
471
+ Maj7: { canonical: "maj7", reason: '"maj7" identifica expl\xEDcitamente la s\xE9ptima mayor.' }
472
+ };
473
+ function findChordNotationReplacements(content) {
474
+ const replacements = [];
475
+ for (const match of content.matchAll(CHORD_TOKEN2)) {
476
+ const alias = CHORD_TYPE_ALIASES[match[2]];
477
+ if (!alias || match.index === void 0) continue;
478
+ const replacement = `${match[1]}${alias.canonical}${match[3] ?? ""}`;
479
+ replacements.push({
480
+ from: match.index,
481
+ to: match.index + match[0].length,
482
+ original: match[0].slice(1, -1),
483
+ replacement,
484
+ reason: alias.reason
485
+ });
486
+ }
487
+ return replacements;
488
+ }
489
+ function getChordNotationSuggestions(content) {
490
+ const grouped = /* @__PURE__ */ new Map();
491
+ for (const replacement of findChordNotationReplacements(content)) {
492
+ const key = `${replacement.original}\0${replacement.replacement}`;
493
+ const suggestion = grouped.get(key);
494
+ if (suggestion) {
495
+ suggestion.occurrences++;
496
+ } else {
497
+ grouped.set(key, {
498
+ original: replacement.original,
499
+ replacement: replacement.replacement,
500
+ occurrences: 1,
501
+ reason: replacement.reason
502
+ });
503
+ }
504
+ }
505
+ return [...grouped.values()];
506
+ }
507
+ function normalizeChordNotationText(content) {
508
+ const replacements = findChordNotationReplacements(content);
509
+ const normalizedContent = [...replacements].reverse().reduce((result, replacement) => {
510
+ return `${result.slice(0, replacement.from)}[${replacement.replacement}]${result.slice(replacement.to)}`;
511
+ }, content);
512
+ return {
513
+ content: normalizedContent,
514
+ suggestions: getChordNotationSuggestions(content)
515
+ };
516
+ }
517
+
518
+ // src/linting.ts
519
+ var SINGULAR_DIRECTIVES = {
520
+ title: "title",
521
+ t: "title",
522
+ subtitle: "subtitle",
523
+ st: "subtitle",
524
+ year: "year",
525
+ copyright: "copyright",
526
+ key: "key",
527
+ capo: "capo",
528
+ duration: "duration",
529
+ tempo: "tempo",
530
+ time: "time"
531
+ };
532
+ var DIRECTIVE_LINE = /^\s*\{\s*([A-Za-z_][\w]*)\b/;
533
+ var duplicateDirectiveLinter = (0, import_lint2.linter)((view) => {
534
+ const diagnostics = [];
535
+ const firstSeenAtLine = /* @__PURE__ */ new Map();
536
+ for (let lineNumber = 1; lineNumber <= view.state.doc.lines; lineNumber++) {
537
+ const line = view.state.doc.line(lineNumber);
538
+ const match = line.text.match(DIRECTIVE_LINE);
539
+ if (!match) continue;
540
+ const canonical = SINGULAR_DIRECTIVES[match[1].toLowerCase()];
541
+ if (!canonical) continue;
542
+ const firstLine = firstSeenAtLine.get(canonical);
543
+ if (firstLine === void 0) {
544
+ firstSeenAtLine.set(canonical, lineNumber);
545
+ continue;
546
+ }
547
+ diagnostics.push({
548
+ from: line.from,
549
+ to: line.from + match[0].length,
550
+ severity: "warning",
551
+ message: `"${canonical}" ya se defini\xF3 en la l\xEDnea ${firstLine}; este valor la reemplaza.`
552
+ });
553
+ }
554
+ return diagnostics;
555
+ });
556
+ var parserWarningLinter = (0, import_lint2.linter)((view) => {
557
+ const parser = new import_parser.ChordProParser();
558
+ parser.parse(view.state.doc.toString());
559
+ return parser.warnings.flatMap((warning) => {
560
+ if (warning.lineNumber < 1 || warning.lineNumber > view.state.doc.lines) {
561
+ return [];
562
+ }
563
+ const line = view.state.doc.line(warning.lineNumber);
564
+ return [{
565
+ from: line.from,
566
+ to: line.to,
567
+ severity: "warning",
568
+ message: warning.message
569
+ }];
570
+ });
571
+ });
572
+ var chordNotationLinter = (0, import_lint2.linter)((view) => {
573
+ const diagnostics = [];
574
+ for (const replacement of findChordNotationReplacements(view.state.doc.toString())) {
575
+ diagnostics.push({
576
+ from: replacement.from,
577
+ to: replacement.to,
578
+ severity: "info",
579
+ message: `Usa "${replacement.replacement}". ${replacement.reason}`,
580
+ actions: [{
581
+ name: `Reemplazar por ${replacement.replacement}`,
582
+ apply: (targetView, actionFrom, actionTo) => {
583
+ targetView.dispatch({ changes: { from: actionFrom, to: actionTo, insert: `[${replacement.replacement}]` } });
584
+ }
585
+ }]
586
+ });
587
+ }
588
+ return diagnostics;
589
+ });
590
+
591
+ // src/themes/base.ts
592
+ var import_view2 = require("@codemirror/view");
593
+ var baseTheme = import_view2.EditorView.baseTheme({
594
+ "&": {
595
+ height: "100%"
596
+ },
597
+ ".cm-scroller": {
598
+ flex: "1",
599
+ overflow: "auto"
600
+ },
601
+ ".cm-lintRange-info": {
602
+ backgroundImage: 'url("data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="6" height="3"><path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="%23dc2626" fill="none" stroke-width="1"/></svg>") !important'
603
+ },
604
+ ".cm-lintRange-warning": {
605
+ backgroundImage: 'url("data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="6" height="3"><path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="%23d97706" fill="none" stroke-width="1"/></svg>") !important'
606
+ },
607
+ ".cm-lintRange-error": {
608
+ backgroundImage: 'url("data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="6" height="3"><path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="%23dc2626" fill="none" stroke-width="1"/></svg>") !important'
609
+ }
610
+ });
611
+
612
+ // src/themes/dark.ts
613
+ var import_view3 = require("@codemirror/view");
614
+ var import_language5 = require("@codemirror/language");
615
+ var import_highlight2 = require("@lezer/highlight");
616
+ var editorTheme = import_view3.EditorView.theme(
617
+ {
618
+ "&": {
619
+ backgroundColor: "var(--color-neutral-900, #18181b)",
620
+ color: "var(--color-neutral-100, #f4f4f5)"
621
+ },
622
+ ".cm-content": {
623
+ caretColor: "var(--color-neutral-100, #f4f4f5)"
624
+ },
625
+ ".cm-cursor, .cm-dropCursor": {
626
+ borderLeftColor: "var(--color-neutral-100, #f4f4f5)"
627
+ },
628
+ "&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": {
629
+ backgroundColor: "color-mix(in oklch, var(--color-primary-400, #60a5fa) 88%, transparent) !important"
630
+ },
631
+ "&.cm-focused .cm-content:focus::selection, &.cm-focused .cm-content .cm-line::selection": {
632
+ backgroundColor: "color-mix(in oklch, var(--color-primary-400, #60a5fa) 54%, transparent) !important",
633
+ color: "inherit !important"
634
+ },
635
+ ".cm-selectionLayer .cm-selectionBackground": {
636
+ boxShadow: "inset 0 -2px 0 var(--color-primary-200, #bfdbfe)"
637
+ },
638
+ ".cm-activeLine": {
639
+ backgroundColor: "var(--color-neutral-800, #27272a)"
640
+ },
641
+ ".cm-gutters": {
642
+ backgroundColor: "var(--color-neutral-900, #18181b)",
643
+ color: "var(--color-neutral-400, #a1a1aa)",
644
+ border: "none"
645
+ },
646
+ ".cm-activeLineGutter": {
647
+ backgroundColor: "var(--color-neutral-800, #27272a)"
648
+ },
649
+ ".cm-completionIcon-chord-used + .cm-completionLabel": {
650
+ color: "var(--color-primary-300, #93c5fd)",
651
+ fontWeight: "600"
652
+ },
653
+ '.cm-tooltip-autocomplete > ul > li[aria-selected="true"] .cm-completionIcon-chord-used + .cm-completionLabel': {
654
+ color: "var(--color-white, #ffffff)"
655
+ },
656
+ ".cm-lintRange-info": {
657
+ backgroundImage: 'url("data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="6" height="3"%3E%3Cpath d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="%23f87171" fill="none" stroke-width="1"/%3E%3C/svg%3E") !important',
658
+ backgroundSize: "6px 3px",
659
+ backgroundPosition: "left bottom",
660
+ backgroundRepeat: "no-repeat"
661
+ },
662
+ ".cm-lintRange-warning": {
663
+ backgroundImage: 'url("data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="6" height="3"%3E%3Cpath d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="%23fcd34d" fill="none" stroke-width="1"/%3E%3C/svg%3E") !important',
664
+ backgroundSize: "6px 3px",
665
+ backgroundPosition: "left bottom",
666
+ backgroundRepeat: "no-repeat"
667
+ },
668
+ ".cm-lintRange-error": {
669
+ backgroundImage: 'url("data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="6" height="3"%3E%3Cpath d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="%23f87171" fill="none" stroke-width="1"/%3E%3C/svg%3E") !important',
670
+ backgroundSize: "6px 3px",
671
+ backgroundPosition: "left bottom",
672
+ backgroundRepeat: "no-repeat"
673
+ }
674
+ },
675
+ { dark: true }
676
+ );
677
+ var highlightStyle = import_language5.HighlightStyle.define([
678
+ { tag: import_highlight2.tags.keyword, color: "var(--color-error-400, #f87171)" },
679
+ { tag: [import_highlight2.tags.meta, import_highlight2.tags.attributeName], color: "var(--color-primary-300, #93c5fd)" },
680
+ { tag: [import_highlight2.tags.constant(import_highlight2.tags.name), import_highlight2.tags.character, import_highlight2.tags.number], color: "var(--color-neutral-400, #a1a1aa)" },
681
+ { tag: import_highlight2.tags.invalid, color: "var(--color-error-200, #fecaca)", backgroundColor: "color-mix(in oklch, var(--color-error-600, #dc2626) 30%, transparent)" },
682
+ { tag: import_highlight2.tags.string, color: "var(--color-neutral-300, #d4d4d8)" },
683
+ { tag: [import_highlight2.tags.comment, import_highlight2.tags.lineComment], fontStyle: "italic", color: "#79c98d" },
684
+ { tag: import_highlight2.tags.heading, color: "var(--color-primary-300, #93c5fd)" }
685
+ ]);
686
+ var darkTheme = [editorTheme, (0, import_language5.syntaxHighlighting)(highlightStyle)];
687
+
688
+ // src/themes/light.ts
689
+ var import_view4 = require("@codemirror/view");
690
+ var import_language6 = require("@codemirror/language");
691
+ var import_highlight3 = require("@lezer/highlight");
692
+ var editorTheme2 = import_view4.EditorView.theme(
693
+ {
694
+ "&": {
695
+ backgroundColor: "var(--color-white, #ffffff)",
696
+ color: "var(--color-neutral-950, #09090b)"
697
+ },
698
+ ".cm-content": {
699
+ caretColor: "var(--color-neutral-950, #09090b)"
700
+ },
701
+ ".cm-cursor, .cm-dropCursor": {
702
+ borderLeftColor: "var(--color-neutral-950, #09090b)"
703
+ },
704
+ "&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": {
705
+ backgroundColor: "color-mix(in oklch, var(--color-primary-500, #3b82f6) 78%, transparent) !important"
706
+ },
707
+ "&.cm-focused .cm-content:focus::selection, &.cm-focused .cm-content .cm-line::selection": {
708
+ backgroundColor: "color-mix(in oklch, var(--color-primary-500, #3b82f6) 52%, transparent) !important",
709
+ color: "inherit !important"
710
+ },
711
+ ".cm-selectionLayer .cm-selectionBackground": {
712
+ boxShadow: "inset 0 -2px 0 var(--color-primary-700, #1d4ed8)"
713
+ },
714
+ ".cm-activeLine": {
715
+ backgroundColor: "var(--color-neutral-100, #f4f4f5)"
716
+ },
717
+ ".cm-gutters": {
718
+ backgroundColor: "var(--color-neutral-50, #fafafa)",
719
+ color: "var(--color-neutral-500, #71717a)",
720
+ border: "none"
721
+ },
722
+ ".cm-activeLineGutter": {
723
+ backgroundColor: "var(--color-neutral-100, #f4f4f5)"
724
+ },
725
+ ".cm-completionIcon-chord-used + .cm-completionLabel": {
726
+ color: "var(--color-primary-700, #1d4ed8)",
727
+ fontWeight: "600"
728
+ },
729
+ '.cm-tooltip-autocomplete > ul > li[aria-selected="true"] .cm-completionIcon-chord-used + .cm-completionLabel': {
730
+ color: "var(--color-white, #ffffff)"
731
+ },
732
+ ".cm-lintRange-info": {
733
+ backgroundImage: 'url("data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="6" height="3"%3E%3Cpath d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="%23dc2626" fill="none" stroke-width="1"/%3E%3C/svg%3E") !important',
734
+ backgroundSize: "6px 3px",
735
+ backgroundPosition: "left bottom",
736
+ backgroundRepeat: "no-repeat"
737
+ },
738
+ ".cm-lintRange-warning": {
739
+ backgroundImage: 'url("data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="6" height="3"%3E%3Cpath d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="%23d97706" fill="none" stroke-width="1"/%3E%3C/svg%3E") !important',
740
+ backgroundSize: "6px 3px",
741
+ backgroundPosition: "left bottom",
742
+ backgroundRepeat: "no-repeat"
743
+ },
744
+ ".cm-lintRange-error": {
745
+ backgroundImage: 'url("data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="6" height="3"%3E%3Cpath d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="%23dc2626" fill="none" stroke-width="1"/%3E%3C/svg%3E") !important',
746
+ backgroundSize: "6px 3px",
747
+ backgroundPosition: "left bottom",
748
+ backgroundRepeat: "no-repeat"
749
+ }
750
+ },
751
+ { dark: false }
752
+ );
753
+ var highlightStyle2 = import_language6.HighlightStyle.define([
754
+ { tag: import_highlight3.tags.keyword, color: "var(--color-error-600, #dc2626)" },
755
+ { tag: [import_highlight3.tags.meta, import_highlight3.tags.attributeName], color: "var(--color-primary-600, #2563eb)" },
756
+ { tag: [import_highlight3.tags.constant(import_highlight3.tags.name), import_highlight3.tags.character, import_highlight3.tags.number], color: "var(--color-neutral-600, #52525b)" },
757
+ { tag: import_highlight3.tags.invalid, color: "var(--color-error-700, #b91c1c)", backgroundColor: "var(--color-error-100, #fee2e2)" },
758
+ { tag: import_highlight3.tags.string, color: "var(--color-neutral-700, #3f3f46)" },
759
+ { tag: [import_highlight3.tags.comment, import_highlight3.tags.lineComment], fontStyle: "italic", color: "#4d9f68" },
760
+ { tag: import_highlight3.tags.heading, color: "var(--color-primary-600, #2563eb)" }
761
+ ]);
762
+ var lightTheme = [editorTheme2, (0, import_language6.syntaxHighlighting)(highlightStyle2)];
763
+
764
+ // src/themes/index.ts
765
+ function themeExtension(name) {
766
+ return [baseTheme, ...name === "dark" ? darkTheme : lightTheme];
767
+ }
768
+
769
+ // src/index.ts
770
+ function createChordProEditor(options) {
771
+ const themeCompartment = new import_state2.Compartment();
772
+ const updateListener = import_view5.EditorView.updateListener.of((update) => {
773
+ if (update.docChanged) {
774
+ options.onChange?.(update.state.doc.toString());
775
+ }
776
+ if (update.focusChanged) {
777
+ (update.view.hasFocus ? options.onFocus : options.onBlur)?.();
778
+ }
779
+ });
780
+ const state = import_state2.EditorState.create({
781
+ doc: options.doc ?? "",
782
+ extensions: [
783
+ basicSetup(),
784
+ chordPro(),
785
+ chordProFolding,
786
+ duplicateDirectiveLinter,
787
+ parserWarningLinter,
788
+ chordNotationLinter,
789
+ chordProAutocomplete(),
790
+ themeCompartment.of(themeExtension(options.theme ?? "light")),
791
+ updateListener,
792
+ ...options.extensions ?? []
793
+ ]
794
+ });
795
+ const view = new import_view5.EditorView({ state, parent: options.parent });
796
+ return {
797
+ view,
798
+ getValue: () => view.state.doc.toString(),
799
+ setValue: (value) => {
800
+ view.dispatch({
801
+ changes: { from: 0, to: view.state.doc.length, insert: value }
802
+ });
803
+ },
804
+ setTheme: (theme) => {
805
+ view.dispatch({ effects: themeCompartment.reconfigure(themeExtension(theme)) });
806
+ },
807
+ insertChord: () => {
808
+ insertChord(view);
809
+ },
810
+ openCompletionList: () => {
811
+ openCompletionList(view);
812
+ },
813
+ getChordNotationSuggestions: () => getChordNotationSuggestions(view.state.doc.toString()),
814
+ normalizeChordNotation: () => {
815
+ const content = view.state.doc.toString();
816
+ const normalization = normalizeChordNotationText(content);
817
+ const replacements = findChordNotationReplacements(content);
818
+ if (replacements.length > 0) {
819
+ view.dispatch({
820
+ changes: replacements.map(({ from, to, replacement }) => ({ from, to, insert: `[${replacement}]` }))
821
+ });
822
+ }
823
+ return normalization.suggestions;
824
+ },
825
+ focus: () => view.focus(),
826
+ destroy: () => view.destroy()
827
+ };
828
+ }
829
+ // Annotate the CommonJS export names for ESM import in node:
830
+ 0 && (module.exports = {
831
+ createChordProEditor,
832
+ getChordCompletionPriorities,
833
+ getChordNotationSuggestions,
834
+ normalizeChordNotationText
835
+ });
836
+ //# sourceMappingURL=index.cjs.map