2022-04-24 13:00:04 -08:00
|
|
|
// @ts-ignore DOMPurify has no types
|
|
|
|
import DOMPurify from "dompurify";
|
2021-11-06 11:28:47 -08:00
|
|
|
import { useFraction } from "./use-fraction";
|
|
|
|
import { RecipeIngredient } from "~/types/api-types/recipe";
|
|
|
|
const { frac } = useFraction();
|
|
|
|
|
2022-04-24 13:00:04 -08:00
|
|
|
function sanitizeIngredientHTML(rawHtml: string) {
|
|
|
|
return DOMPurify.sanitize(rawHtml, {
|
|
|
|
"USE_PROFILES": {html: true},
|
|
|
|
"ALLOWED_TAGS": ["b", "q", "i", "strong", "sup"]
|
|
|
|
}) as string
|
|
|
|
}
|
|
|
|
|
2022-01-09 07:15:23 +01:00
|
|
|
export function parseIngredientText(ingredient: RecipeIngredient, disableAmount: boolean, scale = 1): string {
|
2021-11-06 11:28:47 -08:00
|
|
|
if (disableAmount) {
|
2022-01-09 07:15:23 +01:00
|
|
|
return ingredient.note || "";
|
2021-11-06 11:28:47 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
const { quantity, food, unit, note } = ingredient;
|
|
|
|
|
|
|
|
let returnQty = "";
|
2022-01-09 07:15:23 +01:00
|
|
|
if (quantity !== undefined && quantity !== 0) {
|
|
|
|
if (unit?.fraction) {
|
|
|
|
const fraction = frac(quantity * scale, 10, true);
|
|
|
|
if (fraction[0] !== undefined && fraction[0] > 0) {
|
|
|
|
returnQty += fraction[0];
|
|
|
|
}
|
2021-11-06 11:28:47 -08:00
|
|
|
|
2022-01-09 07:15:23 +01:00
|
|
|
if (fraction[1] > 0) {
|
|
|
|
returnQty += ` <sup>${fraction[1]}</sup>⁄<sub>${fraction[2]}</sub>`;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
returnQty = (quantity * scale).toString();
|
2021-11-06 11:28:47 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-24 13:00:04 -08:00
|
|
|
const text = `${returnQty} ${unit?.name || " "} ${food?.name || " "} ${note || " "}`.replace(/ {2,}/g, " ");
|
|
|
|
return sanitizeIngredientHTML(text);
|
2021-11-06 11:28:47 -08:00
|
|
|
}
|