feat: Add optional note field to ingredient parsing and update related components

This commit is contained in:
Nils-Johan Gynther
2026-04-12 10:30:05 +02:00
parent 03727ee3c5
commit 9ca7fcce96
7 changed files with 158 additions and 34 deletions
+88 -29
View File
@@ -9,6 +9,7 @@ export interface ParsedRecipe {
quantity: number;
unit: string;
name: string;
note?: string;
}>;
instructions?: string;
}
@@ -29,61 +30,119 @@ export abstract class RecipeParser {
* Hanterar format som:
* - "3 ägg"
* - "150 g lax"
* - "1/2 citron"
* - "1 msk senap"
* - "salt och peppar"
* - "1 förp handskalade räkor i lake (à 570 g)"
*/
protected parseIngredientLine(line: string): {
quantity: number;
unit: string;
name: string;
note?: string;
} | null {
const cleaned = line.replace(/<[^>]+>/g, '').trim();
let cleaned = line.replace(/<[^>]+>/g, '').trim();
if (!cleaned) return null;
// Kända enheter
const knownUnits = [
'g', 'kg', 'hg', 'ml', 'dl', 'l',
'g', 'kg', 'hg', 'mg', 'ml', 'dl', 'l', 'tl',
'st', 'tsk', 'msk', 'krm', 'matsked', 'tesked',
'pris', 'portion', 'burk', 'förp', 'paket',
];
// Försök extrahera: [quantity] [unit?] [productName]
// Regex: början med valfri mängd, sedan valfritt ord (potentiell enhet), sedan resten
const match = cleaned.match(/^([\d.,]+)?\s*([a-zåäö]*)\s*(.*)$/i);
// Extrahera parentetisk info
let parentheticalText = '';
const parentheteMatch = cleaned.match(/\s*\(([^)]*)\)/);
if (parentheteMatch) {
parentheticalText = parentheteMatch[1].trim();
cleaned = cleaned.replace(/\s*\([^)]*\)/, '').trim();
}
if (!match) {
// Hantera bråkdelar: "1/2" eller "1 / 2"
const fractionMatch = cleaned.match(/^([\d.]+)\s*\/\s*([\d.]+)/);
let quantity = 0;
let remainingText = cleaned;
if (fractionMatch) {
const numerator = parseFloat(fractionMatch[1]);
const denominator = parseFloat(fractionMatch[2]);
quantity = numerator / denominator;
remainingText = cleaned.substring(fractionMatch[0].length).trim();
} else {
const numberMatch = remainingText.match(/^([\d.,]+)/);
if (numberMatch) {
quantity = parseFloat(numberMatch[1].replace(',', '.'));
remainingText = remainingText.substring(numberMatch[0].length).trim();
}
}
// Extrahera potentiell enhet
let potentialUnit = '';
let productName = remainingText;
if (remainingText) {
const unitMatch = remainingText.match(/^([a-zåäö]+)\b/i);
if (unitMatch) {
const candidateUnit = unitMatch[1].toLowerCase();
if (knownUnits.includes(candidateUnit)) {
potentialUnit = candidateUnit;
productName = remainingText.substring(candidateUnit.length).trim();
}
}
}
// Analysera parenthetical text för måttenhet
let parenthHasUnit = false;
if (parentheticalText) {
for (const unit of knownUnits) {
if (parentheticalText.toLowerCase().includes(unit)) {
parenthHasUnit = true;
break;
}
}
}
let note: string | undefined = undefined;
// Om vi hade quantity i huvuddelen och parenthetical innehåller unit
// → spara parenthetical som note
if (quantity > 0 && parenthHasUnit) {
note = parentheticalText;
}
// Om ingen mängd i huvuddelen men parenthetical hade både mängd och unit
// → parse parenthetical som quantity + unit
if (quantity === 0 && parentheticalText) {
const parenthMatch = parentheticalText.match(/^[\D]*?([\d.,]+)?\s*([a-zåäö]*)?\s*(.*)$/i);
if (parenthMatch) {
let pQuantity = parenthMatch[1] ? parseFloat(parenthMatch[1].replace(',', '.')) : 0;
let pUnit = parenthMatch[2]?.toLowerCase() || '';
let pRest = parenthMatch[3]?.trim() || '';
if (knownUnits.includes(pUnit) && pQuantity > 0) {
quantity = pQuantity;
potentialUnit = pUnit;
note = parentheticalText;
}
}
}
// Om ingen mängd och enhet, bara returna produktnamnet
if (quantity === 0) {
return {
quantity: 0,
unit: 'st',
unit: '',
name: cleaned,
note: parentheticalText || undefined,
};
}
let quantity = match[1] ? parseFloat(match[1].replace(',', '.')) : 0;
let potentialUnit = match[2]?.toLowerCase().trim() || '';
let productName = match[3]?.trim() || '';
// Om potentialUnit är inte en känd enhet, lägg det tillbaka i produktnamnet
if (potentialUnit && !knownUnits.includes(potentialUnit)) {
productName = potentialUnit + (productName ? ' ' + productName : '');
potentialUnit = '';
}
// Om inget produktnamn men vi hade potentialUnit, denna är faktiskt produktnamnet
if (!productName && potentialUnit) {
productName = potentialUnit;
potentialUnit = '';
}
// Fallback: om vi har mängd men inget annat, vara produktnamn
if (quantity > 0 && !potentialUnit && !productName) {
return null; // Ogiltigt
}
return {
quantity,
unit: potentialUnit || 'st',
unit: potentialUnit,
name: productName,
note: note,
};
}
}
@@ -43,7 +43,7 @@ export class GenericRecipeParser extends RecipeParser {
private extractFromJsonLd(recipe: any): ParsedRecipe {
const name = recipe.name || '';
const ingredients: Array<{ quantity: number; unit: string; name: string }> = [];
const ingredients: Array<{ quantity: number; unit: string; name: string; note?: string }> = [];
if (recipe.recipeIngredient && Array.isArray(recipe.recipeIngredient)) {
for (const ing of recipe.recipeIngredient) {
const parsed = this.parseIngredientLine(ing);
@@ -91,7 +91,7 @@ export class GenericRecipeParser extends RecipeParser {
}
// Försöka extrahera ingredienser från vanliga strukturer
const ingredients: Array<{ quantity: number; unit: string; name: string }> = [];
const ingredients: Array<{ quantity: number; unit: string; name: string; note?: string }> = [];
// Testa olika ingredient-selectors
const ingredientPatterns = [
@@ -46,7 +46,7 @@ export class IcaRecipeParser extends RecipeParser {
const name = recipe.name || '';
// Extrahera ingredienser
const ingredients: Array<{ quantity: number; unit: string; name: string }> = [];
const ingredients: Array<{ quantity: number; unit: string; name: string; note?: string }> = [];
if (recipe.recipeIngredient && Array.isArray(recipe.recipeIngredient)) {
for (const ing of recipe.recipeIngredient) {
const parsed = this.parseIngredientLine(ing);
@@ -96,7 +96,7 @@ export class IcaRecipeParser extends RecipeParser {
}
}
const ingredients: Array<{ quantity: number; unit: string; name: string }> = [];
const ingredients: Array<{ quantity: number; unit: string; name: string; note?: string }> = [];
const ingredientRegex =
/<li[^>]*class="[^"]*ingredient[^"]*"[^>]*>([^<]+)<\/li>/gi;
let match;
@@ -155,6 +155,7 @@ export class QuickImportService {
quantity: number;
unit: string;
name: string;
note?: string;
}>;
instructions?: string;
},
@@ -178,7 +179,8 @@ export class QuickImportService {
for (const ing of recipe.ingredients) {
const quantity = ing.quantity > 0 ? `${ing.quantity} ` : '';
const unit = ing.unit ? `${ing.unit} ` : '';
lines.push(`- ${quantity}${unit}${ing.name}`);
const note = ing.note ? ` (${ing.note})` : '';
lines.push(`- ${quantity}${unit}${ing.name}${note}`);
}
lines.push('');
}
@@ -126,6 +126,7 @@ export default function CreateRecipePage() {
{ value: 'st', label: 'st (styck)' },
{ value: 'tsk', label: 'tsk (tesked)' },
{ value: 'msk', label: 'msk (matsked)' },
{ value: 'krm', label: 'krm (kryddmått)' },
];
const LOCATION_OPTIONS = [
@@ -44,6 +44,7 @@ const UNIT_OPTIONS = [
{ value: 'st', label: 'st (styck)' },
{ value: 'tsk', label: 'tsk (tesked)' },
{ value: 'msk', label: 'msk (matsked)' },
{ value: 'krm', label: 'krm (kryddmått)' },
];
type Step = 'input' | 'review' | 'saving';
@@ -43,6 +43,7 @@ const UNIT_OPTIONS = [
{ value: 'st', label: 'st (styck)' },
{ value: 'tsk', label: 'tsk (tesked)' },
{ value: 'msk', label: 'msk (matsked)' },
{ value: 'krm', label: 'krm (kryddmått)' },
];
type Step = 'input' | 'review' | 'saving';
@@ -60,6 +61,7 @@ export default function WriteRecipePage() {
const [isParsing, setIsParsing] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [showDebugPanel, setShowDebugPanel] = useState(false);
useEffect(() => {
// Hämta produkter från databas
@@ -310,6 +312,65 @@ Stek löken i lite smör. Tillsätt köttfärsen...`}</pre>
{/* STEG 2: Granskning */}
{step === 'review' && parsed && (
<section style={{ display: 'grid', gap: '1.5rem' }}>
{/* Debug Panel - Import Output */}
<details
open={showDebugPanel}
onChange={(e) => setShowDebugPanel((e.target as HTMLDetailsElement).open)}
style={{
border: '1px solid #ddd',
borderRadius: '8px',
padding: '1rem',
background: '#f9f9f9',
}}
>
<summary style={{ cursor: 'pointer', fontWeight: 600, fontSize: '0.95rem', color: '#666' }}>
🔍 Import Debug Output {showDebugPanel ? '▼' : '▶'}
</summary>
<div style={{ marginTop: '1rem', display: 'grid', gap: '1rem' }}>
{/* Raw Markdown */}
<div>
<h4 style={{ margin: '0 0 0.5rem 0', fontSize: '0.85rem', color: '#555' }}>Raw Markdown:</h4>
<pre
style={{
background: 'white',
border: '1px solid #ddd',
borderRadius: '4px',
padding: '0.75rem',
fontSize: '0.8rem',
overflow: 'auto',
maxHeight: '200px',
margin: 0,
fontFamily: 'monospace',
color: '#333',
}}
>
{markdown}
</pre>
</div>
{/* Parse Results as JSON */}
<div>
<h4 style={{ margin: '0 0 0.5rem 0', fontSize: '0.85rem', color: '#555' }}>Parse Result:</h4>
<pre
style={{
background: 'white',
border: '1px solid #ddd',
borderRadius: '4px',
padding: '0.75rem',
fontSize: '0.75rem',
overflow: 'auto',
maxHeight: '250px',
margin: 0,
fontFamily: 'monospace',
color: '#333',
}}
>
{JSON.stringify(parsed, null, 2)}
</pre>
</div>
</div>
</details>
{/* Receptdetaljer */}
<div style={{ display: 'grid', gap: '1rem', padding: '1rem', border: '1px solid #ddd', borderRadius: '8px' }}>
<h2 style={{ margin: 0, fontSize: '1.1rem' }}>Receptdetaljer</h2>