/
parseChordLine.js
341 lines (293 loc) · 9.39 KB
/
parseChordLine.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/* eslint-disable max-lines-per-function */
import _isEqual from 'lodash/isEqual';
import _escapeRegExp from 'lodash/escapeRegExp';
import _cloneDeep from 'lodash/cloneDeep';
import syntax, { defaultTimeSignature } from './syntax';
import clearSpaces from './helper/clearSpaces';
import isTimeSignatureString from './matchers/isTimeSignatureString';
import parseChord from './parseChord';
import parseTimeSignature from './parseTimeSignature';
import InvalidBeatCountException from './exceptions/InvalidBeatCountException';
import InvalidChordRepetitionException from './exceptions/InvalidChordRepetitionException';
import InvalidSubBeatGroupException from './exceptions/InvalidSubBeatGroupException';
import InvalidBarRepeatException from './exceptions/InvalidBarRepeatException';
import { getParseableChordLine, cleanToken } from './matchers/isChordLine';
const chordBeatCountSymbols = new RegExp(
_escapeRegExp(syntax.chordBeatCount),
'g'
);
const barRepeatSymbols = new RegExp(
'^' + _escapeRegExp(syntax.barRepeat) + '+$'
);
/**
* @typedef {Object} ChordLine
* @type {Object}
* @property {Bar[]} allBars
* @property {Boolean} hasPositionedChords
*/
/**
* @typedef {Object} Bar
* @type {Object}
* @property {TimeSignature} timeSignature
* @property {ChordLineChord[]} allChords
* @property {Boolean} isRepeated - the bar has been created with the bar repeat symbol
* @property {Boolean} hasUnevenChordsDurations - the chords in the bar do not have the same duration
* @property {Boolean} lineHadTimeSignatureChange - there has been an inline time signature change.
* This value will be `true` for all the bars after the time signature change occurred,
* even if the TS is changed back again to the context one.
*/
/**
* @typedef {Object} ChordLineChord
* @type {Object}
* @property {String} string - original chord string
* @property {ChordDef|String} model - parsed chord or "NC" if "no chord" symbol
* @property {Number} duration - number of beats the chord lasts
* @property {Number} beat - beat on which the chord starts
* @property {Boolean} isPositioned - whether this chord has been positioned over a specific lyric or not
* @property {Boolean} isInSubBeatGroup - whether this chord has a sub-beat duration
* @property {Boolean} [isFirstOfSubBeat] - Only present if `isInSubBeatGroup` is true.
* @property {Boolean} [isLastOfSubBeat] - Only present if `isInSubBeatGroup` is true.
*/
/**
* @param {String} chordLine
* @param {TimeSignature} timeSignature
* @returns {ChordLine}
*/
export default function parseChordLine(
chordLine,
{ timeSignature = defaultTimeSignature } = {}
) {
let { beatCount } = timeSignature;
const allBars = [];
const emptyBar = { allChords: [] };
const subBeatGroupsChordCount = {};
let bar = _cloneDeep(emptyBar);
let chord = {};
let cleanedToken;
let currentBeatCount = 0;
let previousBar;
let isInSubBeatGroup = false;
let subBeatGroupIndex = 0;
let lineHadTimeSignatureChange = false;
checkSubBeatConsistency(chordLine);
const allTokens = clearSpaces(getParseableChordLine(chordLine)).split(' ');
allTokens.forEach((token, tokenIndex) => {
if (token.match(barRepeatSymbols)) {
repeatPreviousBars(token);
} else if (isTimeSignatureString(token)) {
changeTimeSignature(token);
} else {
parseChordToken(token);
if (shouldChangeBar(currentBeatCount, beatCount)) {
changeBar();
} else {
checkInvalidBeatCount(
chord,
currentBeatCount,
beatCount,
allTokens.length === tokenIndex + 1
);
}
}
});
setSubBeatInfo(allBars, subBeatGroupsChordCount);
return {
allBars,
};
function repeatPreviousBars(token) {
if (
currentBeatCount === 0 &&
previousBar &&
_isEqual(timeSignature, previousBar.timeSignature)
) {
const repeatedBar = _cloneDeep(previousBar);
repeatedBar.isRepeated = true;
for (let i = 0; i < token.length; i++) {
allBars.push(_cloneDeep(repeatedBar));
}
} else {
throw new InvalidBarRepeatException({ string: chordLine });
}
}
function changeTimeSignature(token) {
timeSignature = parseTimeSignature(token);
beatCount = timeSignature.beatCount;
lineHadTimeSignatureChange = true;
}
function parseChordToken(token) {
if (token.startsWith(syntax.subBeatOpener)) {
isInSubBeatGroup = true;
}
if (isInSubBeatGroup) {
checkSubBeatGroupToken(chordLine, token);
updateSubBeatGroupsChordCount(token);
}
cleanedToken = cleanToken(token);
chord = {
string: token,
duration: getChordDuration(token, beatCount, isInSubBeatGroup),
model: isNoChordSymbol(cleanedToken)
? syntax.noChord
: parseChord(cleanedToken),
beat: currentBeatCount + 1,
isInSubBeatGroup,
};
currentBeatCount += chord.duration;
checkInvalidChordRepetition(bar, chord);
bar.allChords.push(chord);
if (token.endsWith(syntax.subBeatCloser)) {
checkSubBeatGroupChordCount(token);
isInSubBeatGroup = false;
subBeatGroupIndex++;
currentBeatCount += 1;
}
}
function updateSubBeatGroupsChordCount() {
if (subBeatGroupsChordCount[subBeatGroupIndex]) {
subBeatGroupsChordCount[subBeatGroupIndex]++;
} else {
subBeatGroupsChordCount[subBeatGroupIndex] = 1;
}
}
function checkSubBeatGroupChordCount(token) {
if (
subBeatGroupsChordCount[subBeatGroupIndex] === 1 ||
subBeatGroupsChordCount[subBeatGroupIndex] > 4
)
throw new InvalidSubBeatGroupException({
chordLine,
symbol: token,
position: 0, // duh
});
}
function changeBar() {
bar.timeSignature = timeSignature;
bar.lineHadTimeSignatureChange = lineHadTimeSignatureChange;
bar.hasUnevenChordsDurations = hasUnevenChordsDurations(bar);
const barClone = _cloneDeep(bar);
bar.isRepeated = _isEqual(bar, previousBar);
allBars.push(_cloneDeep(bar));
previousBar = barClone;
bar = _cloneDeep(emptyBar);
currentBeatCount = 0;
}
}
function checkSubBeatGroupToken(chordLine, token) {
if (hasBeatCount(token)) {
throw new InvalidSubBeatGroupException({
chordLine,
symbol: token,
position: 0, // duh
});
}
}
function hasBeatCount(token) {
return token.indexOf(syntax.chordBeatCount) > -1;
}
function isNoChordSymbol(token) {
return token === syntax.noChord;
}
function getChordDuration(token, beatCount, isInSubBeatGroup) {
if (isInSubBeatGroup) return 0; // duration is computed during post-processing for sub-beats duration
return (token.match(chordBeatCountSymbols) || []).length || beatCount;
}
function checkInvalidChordRepetition(bar, currentChord) {
if (bar.allChords.length > 0) {
const previousChord = bar.allChords[bar.allChords.length - 1];
if (
_isEqual(previousChord.model, currentChord.model) &&
!isChordRepetitionAllowed(previousChord, currentChord)
) {
throw new InvalidChordRepetitionException({
string: currentChord.string,
});
}
}
}
function isChordRepetitionAllowed(previousChord, currentChord) {
return (
currentChord.string.startsWith(syntax.subBeatOpener) ||
(previousChord.string.endsWith(syntax.subBeatCloser) &&
!currentChord.model.isInSubBeatGroup)
);
}
function shouldChangeBar(currentBeatCount, beatCount) {
return currentBeatCount === beatCount;
}
function checkInvalidBeatCount(chord, currentBeatCount, beatCount, isLast) {
if (hasInvalidBeatCount(currentBeatCount, beatCount, isLast)) {
throw new InvalidBeatCountException({
string: chord.string,
duration: chord.duration,
currentBeatCount,
beatCount,
});
}
}
function hasInvalidBeatCount(currentBeatCount, barBeatCount, isLast) {
return (
hasTooManyBeats(currentBeatCount, barBeatCount) ||
hasTooFewBeats(currentBeatCount, barBeatCount, isLast)
);
}
function hasTooManyBeats(currentBeatCount, barBeatCount) {
return currentBeatCount > barBeatCount;
}
function hasTooFewBeats(currentBeatCount, barBeatCount, isLast) {
return isLast && currentBeatCount < barBeatCount;
}
function hasUnevenChordsDurations(bar) {
let firstChordDuration = bar.allChords[0].duration;
return bar.allChords.some((chord) => chord.duration !== firstChordDuration);
}
function setSubBeatInfo(allBars, subBeatGroupsChordCount) {
let subBeatGroupIndex = -1;
let subBeatChordIndex = 0;
let previousChordBeatId = '';
allBars.forEach((bar, barIndex) => {
bar.allChords.forEach((chord) => {
if (chord.isInSubBeatGroup) {
const chordBeatId = barIndex + chord.beat;
if (chordBeatId !== previousChordBeatId) {
subBeatGroupIndex++;
subBeatChordIndex = 0;
}
const durationString = (
1 / subBeatGroupsChordCount[subBeatGroupIndex]
).toPrecision(2);
chord.duration = Number.parseFloat(durationString);
chord.isFirstOfSubBeat = subBeatChordIndex === 0;
chord.isLastOfSubBeat =
subBeatChordIndex ===
subBeatGroupsChordCount[subBeatGroupIndex] - 1;
previousChordBeatId = chordBeatId;
subBeatChordIndex++;
}
});
});
}
function checkSubBeatConsistency(line) {
const errorParameters = {};
let inSubBeat = false;
let match;
const regexp = new RegExp(
syntax.subBeatOpener + '|' + syntax.subBeatCloser,
'g'
);
while ((match = regexp.exec(line))) {
const symbol = match[0];
errorParameters.chordLine = line;
errorParameters.symbol = symbol;
errorParameters.position = regexp.lastIndex - 1;
if (match[0] === syntax.subBeatOpener) {
if (inSubBeat)
throw new InvalidSubBeatGroupException(errorParameters);
inSubBeat = true;
} else {
if (!inSubBeat)
throw new InvalidSubBeatGroupException(errorParameters);
inSubBeat = false;
}
}
if (inSubBeat) throw new InvalidSubBeatGroupException(errorParameters);
}