-
-
Notifications
You must be signed in to change notification settings - Fork 64
/
parsers.ts
354 lines (304 loc) · 10.5 KB
/
parsers.ts
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
342
343
344
345
346
347
348
349
350
351
352
353
354
import _FractionJS from "fraction.js";
import * as FractionJSModule from "fraction.js";
import { unitNames } from "./units";
// Fix for https://github.com/rawify/Fraction.js/issues/72
const FractionJS =
_FractionJS || (FractionJSModule as unknown as typeof _FractionJS);
const fractionMatchers = {
// Regex & replacement value by charcode
189: [/ ?\u00BD/g, " 1/2"], // ½ \u00BD;
8531: [/ ?\u2153/g, " 1/3"], // ⅓ \u2153;
8532: [/ ?\u2154/g, " 2/3"], // ⅔ \u2154;
188: [/ ?\u00BC/g, " 1/4"], // ¼ \u00BC;
190: [/ ?\u00BE/g, " 3/4"], // ¾ \u00BE;
8533: [/ ?\u2155/g, " 1/5"], // ⅕ \u2155;
8534: [/ ?\u2156/g, " 2/5"], // ⅖ \u2156;
8535: [/ ?\u2157/g, " 3/5"], // ⅗ \u2157;
8536: [/ ?\u2158/g, " 4/5"], // ⅘ \u2158;
8537: [/ ?\u2159/g, " 1/6"], // ⅙ \u2159;
8538: [/ ?\u215A/g, " 5/6"], // ⅚ \u215A;
8528: [/ ?\u2150/g, " 1/7"], // ⅐ \u2150;
8539: [/ ?\u215B/g, " 1/8"], // ⅛ \u215B;
8540: [/ ?\u215C/g, " 3/8"], // ⅜ \u215C;
8541: [/ ?\u215D/g, " 5/8"], // ⅝ \u215D;
8542: [/ ?\u215E/g, " 7/8"], // ⅞ \u215E;
8529: [/ ?\u2151/g, " 1/9"], // ⅑ \u2151;
8530: [/ ?\u2152/g, " 1/10"], // ⅒ \u2152;
} as { [key: number]: [RegExp, string] };
const fractionMatchRegexp = new RegExp(
Object.values(fractionMatchers)
.map((matcher) => matcher[0].source)
.join("|"),
"g",
);
const replaceFractionsInText = (rawText: string): string => {
return rawText.replace(fractionMatchRegexp, (match) => {
const matcher = fractionMatchers[match.trim().charCodeAt(0)];
return matcher ? matcher[1] : match; // Fallback on original value if not found
});
};
// Starts with [, anything inbetween, ends with ]
const headerRegexp = /^\[.*\]$/;
const multipartQuantifierRegexp = / \+ | plus | or /;
const measurementRegexp =
/((\d+ )?\d+([/.]\d+)?((-)|( to )|( - ))(\d+ )?\d+([/.]\d+)?)|((\d+ )?\d+[/.]\d+)|\d+/;
// TODO: Replace measurementRegexp with this:
// var measurementRegexp = /(( ?\d+([\/\.]\d+)?){1,2})(((-)|( to )|( - ))(( ?\d+([\/\.]\d+)?){1,2}))?/; // Simpler version of above, but has a bug where it removes some spacing
const quantityRegexp = new RegExp(
`(${unitNames.join("|").replace(/[.*+?^${}()[\]\\]/g, "\\$&")})s?(\\.)?( |$)`,
);
const measurementQuantityRegExp = new RegExp(
`^(${measurementRegexp.source}) *(${quantityRegexp.source})?`,
); // Should always be used with 'i' flag
const fillerWordsRegexp =
/(cubed|peeled|minced|grated|heaped|chopped|about|(slice(s)?)) /;
const notesRegexp = /\(.*?\)/;
const stripNotes = (ingredient: string): string => {
return ingredient.replace(new RegExp(notesRegexp, "g"), "").trim();
};
export const getMeasurementsForIngredient = (ingredient: string): string[] => {
const strippedIngredient = replaceFractionsInText(ingredient);
return strippedIngredient
.split(multipartQuantifierRegexp)
.map((ingredientPart) => {
const measurementMatch = stripNotes(ingredientPart).match(
new RegExp(measurementQuantityRegExp.source, "i"),
);
if (measurementMatch) return measurementMatch[0].trim();
return null;
})
.filter((measurement): measurement is string => !!measurement);
};
export const getTitleForIngredient = (ingredient: string): string => {
const strippedIngredient = replaceFractionsInText(ingredient);
const ingredientPartDelimiters = strippedIngredient.match(
new RegExp(multipartQuantifierRegexp, "ig"),
);
return strippedIngredient
.split(multipartQuantifierRegexp)
.map((ingredientPart) => {
return stripNotes(ingredientPart).replace(
new RegExp(measurementQuantityRegExp, "i"),
"",
);
})
.reduce(
(acc, ingredientPart, idx) =>
acc +
ingredientPart +
(ingredientPartDelimiters ? ingredientPartDelimiters[idx] || "" : ""),
"",
)
.trim();
};
export const stripIngredient = (ingredient: string): string => {
const trimmed = replaceFractionsInText(ingredient)
.trim()
.replace(new RegExp(`^(${measurementRegexp.source})`), "")
.trim()
.replace(new RegExp(`^(${quantityRegexp.source})`, "i"), "")
.trim()
.replace(new RegExp(`^(${fillerWordsRegexp.source})`, "i"), "")
.trim();
if (trimmed !== ingredient) {
return stripIngredient(trimmed);
} else {
return trimmed;
}
};
export const parseIngredients = (
ingredients: string,
scale: number,
boldify?: boolean,
): {
content: string;
originalContent: string;
complete: boolean;
isHeader: boolean;
isRtl: boolean;
}[] => {
if (!ingredients) return [];
ingredients = replaceFractionsInText(ingredients);
const lines =
ingredients.match(/[^\r\n]+/g)?.map((match) => ({
content: match,
originalContent: match,
complete: false,
isHeader: false,
isRtl: isRtlText(match),
})) || [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i].content.trim(); // Trim only spaces (no newlines)
const headerMatches = line.match(headerRegexp);
const ingredientPartDelimiters = line.match(
new RegExp(multipartQuantifierRegexp, "g"),
); // Multipart measurements (1 cup + 1 tablespoon)
const ingredientParts = line.split(multipartQuantifierRegexp); // Multipart measurements (1 cup + 1 tablespoon)
const measurementMatches = ingredientParts.map((linePart) =>
linePart.match(measurementRegexp),
);
if (headerMatches && headerMatches.length > 0) {
const header = headerMatches[0];
let headerContent = header.substring(1, header.length - 1); // Chop off brackets
if (boldify)
headerContent = `<b class="sectionHeader">${headerContent}</b>`;
lines[i].content = headerContent;
lines[i].isHeader = true;
} else if (measurementMatches.find((el) => el && el.length > 0)) {
const updatedIngredientParts = measurementMatches.map((el, idx) => {
if (!el) return ingredientParts[idx];
try {
const measurement = el[0];
const measurementPartDelimiters =
measurement.match(/(-)|( to )|( - )/g);
const measurementParts = measurement.split(/-|to/);
for (let j = 0; j < measurementParts.length; j++) {
// console.log(measurementParts[j].trim())
const frac = new FractionJS(measurementParts[j].trim()).mul(scale);
let scaledMeasurement = frac.toString();
// Preserve original fraction format if entered
if (measurementParts[j].indexOf("/") > -1) {
scaledMeasurement = frac.toFraction(true);
}
if (boldify)
measurementParts[j] =
'<b class="ingredientMeasurement">' +
scaledMeasurement +
"</b>";
else measurementParts[j] = scaledMeasurement.toString();
}
let updatedMeasurement: string;
if (measurementPartDelimiters) {
updatedMeasurement = measurementParts.reduce(
(acc, measurementPart, idx) =>
acc + measurementPart + (measurementPartDelimiters[idx] || ""),
"",
);
} else {
updatedMeasurement = measurementParts.join(" to ");
}
return ingredientParts[idx].replace(
measurementRegexp,
updatedMeasurement,
);
} catch (e) {
console.error("failed to parse", e);
return ingredientParts[idx];
}
});
if (ingredientPartDelimiters) {
lines[i].content = updatedIngredientParts.reduce(
(acc, ingredientPart, idx) =>
acc + ingredientPart + (ingredientPartDelimiters[idx] || ""),
"",
);
lines[i].isRtl = isRtlText(lines[i].originalContent);
} else {
lines[i].content = updatedIngredientParts.join(" + ");
lines[i].isRtl = isRtlText(lines[i].originalContent);
}
lines[i].isHeader = false;
}
}
return lines;
};
export const parseInstructions = (
instructions: string,
): {
content: string;
isHeader: boolean;
count: number;
complete: boolean;
isRtl: boolean;
}[] => {
instructions = replaceFractionsInText(instructions);
// Starts with [, anything inbetween, ends with ]
const headerRegexp = /^\[.*\]$/;
let stepCount = 1;
return instructions
.split(/\r?\n/)
.filter((instruction) => instruction.trim().length)
.map((instruction) => {
const line = instruction.trim();
const headerMatches = line.match(headerRegexp);
if (headerMatches && headerMatches.length > 0) {
const header = headerMatches[0];
const headerContent = header.substring(1, header.length - 1); // Chop off brackets
stepCount = 1;
return {
content: headerContent,
isHeader: true,
count: 0,
complete: false,
isRtl: isRtlText(headerContent, true),
};
} else {
return {
content: line,
isHeader: false,
count: stepCount++,
complete: false,
isRtl: isRtlText(line, true),
};
}
});
};
export const parseNotes = (
notes: string,
): {
content: string;
isHeader: boolean;
isRtl: boolean;
}[] => {
// Starts with [, anything inbetween, ends with ]
const headerRegexp = /^\[.*\]$/;
return notes.split(/\r?\n/).map((note) => {
const line = note.trim();
const headerMatches = line.match(headerRegexp);
if (headerMatches && headerMatches.length > 0) {
const header = headerMatches[0];
const headerContent = header.substring(1, header.length - 1); // Chop off brackets
return {
content: headerContent,
isHeader: true,
isRtl: isRtlText(headerContent),
};
} else {
return {
content: line,
isHeader: false,
isRtl: isRtlText(line),
};
}
});
};
/* eslint-disable no-control-regex */
export const isRtlText = (text: string, onlyFirstWord = true): boolean => {
const rtlChars = new RegExp("[\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC]");
const ltrChars = new RegExp(
"[\u0000-\u0590\u2000-\u202E\u202A-\u202E\uFB00-\uFB4F]",
);
const aToZ = new RegExp("[a-zA-Z]");
let rtlCount = 0;
let ltrCount = 0;
if (onlyFirstWord) {
const splits = text.split(" ");
for (let i = 0; i < splits.length; i++) {
if (
rtlChars.test(splits[i].charAt(0)) ||
aToZ.test(splits[i].charAt(0))
) {
text = splits[i];
break;
}
}
}
for (let i = 0; i < text.length; i++) {
if (rtlChars.test(text[i])) {
rtlCount++;
} else if (ltrChars.test(text[i])) {
ltrCount++;
}
}
return rtlCount > ltrCount;
};