feat(items): read quantity, unit and notes from natural-language input
"400 de jamon" adds Jamón · 400, "Queso crema. Solo Tregar" adds a note, "leche, pan y 2 pascualinas" adds three items and a pasted list adds one per line. Units are normalized (½ kg, 1,5 l, 2 paquetes), common accents are restored, and a pending duplicate gets its quantity summed instead of a new row. A preview under the input shows the reading, with a way to add the text as typed. quantityLabel now shows any quantity except a plain "1". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
241
apps/web/src/lib/natural-input/quantity.ts
Normal file
241
apps/web/src/lib/natural-input/quantity.ts
Normal file
@@ -0,0 +1,241 @@
|
||||
import { CONTAINER_UNITS, NUMBER_WORDS, UNIT_ALIASES } from './lexicon'
|
||||
import { normalizeWord } from './text'
|
||||
|
||||
/** A parsed quantity: an amount plus its canonical unit (`null` for a plain count). */
|
||||
export type Quantity = { amount: number; unit: string | null }
|
||||
|
||||
/** Units that measure weight or volume, with their factor to the base unit (g / ml). */
|
||||
const MEASURES: Record<string, { base: string; factor: number }> = {
|
||||
g: { base: 'g', factor: 1 },
|
||||
kg: { base: 'g', factor: 1000 },
|
||||
ml: { base: 'ml', factor: 1 },
|
||||
l: { base: 'ml', factor: 1000 },
|
||||
}
|
||||
|
||||
const FRACTION_GLYPHS: Record<string, number> = { '½': 0.5, '¼': 0.25, '¾': 0.75 }
|
||||
const GLYPH_FOR: [number, string][] = [
|
||||
[0.5, '½'],
|
||||
[0.25, '¼'],
|
||||
[0.75, '¾'],
|
||||
]
|
||||
|
||||
/** Parses a number token: `2`, `1,5`, `1.5`, `1/2`, `½`. */
|
||||
export function parseNumber(token: string): number | null {
|
||||
if (token in FRACTION_GLYPHS) return FRACTION_GLYPHS[token]
|
||||
|
||||
if (/^\d+(?:[.,]\d+)?$/.test(token)) return Number.parseFloat(token.replace(',', '.'))
|
||||
|
||||
const fraction = /^(\d+)\/(\d+)$/.exec(token)
|
||||
if (fraction && Number(fraction[2]) > 0) return Number(fraction[1]) / Number(fraction[2])
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** Parses a number written as a word (`dos`, `una`, `doce`). */
|
||||
function parseNumberWord(token: string): number | null {
|
||||
return NUMBER_WORDS[normalizeWord(token)] ?? null
|
||||
}
|
||||
|
||||
/** The canonical unit for a token (`kilos` → `kg`), `''` for a unit to drop, `null` if none. */
|
||||
export function parseUnit(token: string): string | null {
|
||||
return UNIT_ALIASES[normalizeWord(token).replace(/\.$/, '')] ?? null
|
||||
}
|
||||
|
||||
function formatAmount(amount: number): string {
|
||||
const glyph = GLYPH_FOR.find(([value]) => Math.abs(value - amount) < 1e-9)
|
||||
if (glyph) return glyph[1]
|
||||
|
||||
const rounded = Math.round(amount * 100) / 100
|
||||
|
||||
return String(rounded).replace('.', ',')
|
||||
}
|
||||
|
||||
/** Renders a quantity the way it is stored: `400`, `½ kg`, `1,5 l`, `2 paquetes`. */
|
||||
export function formatQuantity({ amount, unit }: Quantity): string {
|
||||
const number = formatAmount(amount)
|
||||
if (!unit) return number
|
||||
|
||||
const plural = CONTAINER_UNITS.has(unit) && amount > 1
|
||||
|
||||
return `${number} ${plural ? `${unit}s` : unit}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a quantity from the start of `tokens`, Spanish style: `2`, `400 g`, `400g`,
|
||||
* `dos paquetes`, `medio kilo`, `un cuarto`, `una docena`, `media docena`, each optionally
|
||||
* followed by `de`. Returns the quantity and how many tokens it used, or `null` when the
|
||||
* tokens do not start with one.
|
||||
*/
|
||||
export function readLeadingQuantity(
|
||||
tokens: string[],
|
||||
): { quantity: Quantity; consumed: number } | null {
|
||||
const words = tokens.map(normalizeWord)
|
||||
let index = 0
|
||||
let amount: number | null = null
|
||||
let unit: string | null = null
|
||||
|
||||
// "medio"/"media"/"cuarto" (optionally after "un"/"una") only count as a quantity when a
|
||||
// unit or "de" follows: "medio kilo de pan", "un cuarto de jamón", but not "medio pollo".
|
||||
const fractionStart = words[0] === 'un' || words[0] === 'una' ? 1 : 0
|
||||
const fractionWord = words[fractionStart]
|
||||
if (fractionWord === 'medio' || fractionWord === 'media' || fractionWord === 'cuarto') {
|
||||
const value = fractionWord === 'cuarto' ? 0.25 : 0.5
|
||||
const next = words[fractionStart + 1]
|
||||
|
||||
if (next === 'docena') {
|
||||
amount = value * 12
|
||||
index = fractionStart + 2
|
||||
} else if (next !== undefined && parseUnit(next)) {
|
||||
amount = value
|
||||
unit = parseUnit(next)
|
||||
index = fractionStart + 2
|
||||
} else if (next === 'de') {
|
||||
// "medio de helado", "un cuarto de jamón": a kilo is implied.
|
||||
amount = value
|
||||
unit = 'kg'
|
||||
index = fractionStart + 1
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
} else {
|
||||
amount = parseNumber(words[0] ?? '') ?? parseNumberWord(words[0] ?? '')
|
||||
if (amount === null) return null
|
||||
index = 1
|
||||
|
||||
if (words[index] === 'docena' || words[index] === 'docenas') {
|
||||
amount *= 12
|
||||
index += 1
|
||||
} else if (words[index] !== undefined && parseUnit(words[index]) !== null) {
|
||||
unit = parseUnit(words[index])
|
||||
index += 1
|
||||
}
|
||||
|
||||
// "1 kilo y medio", "2 litros y medio"
|
||||
if (words[index] === 'y' && (words[index + 1] === 'medio' || words[index + 1] === 'media')) {
|
||||
amount += 0.5
|
||||
index += 2
|
||||
}
|
||||
}
|
||||
|
||||
if (words[index] === 'de' || words[index] === 'del') index += 1
|
||||
|
||||
return { quantity: { amount, unit: unit || null }, consumed: index }
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a quantity from the end of `tokens`: `x2`, `x 3`, `400 g`, `2 paquetes`. A bare
|
||||
* trailing number is not taken (`Sprite 2.25`, `Pilas AA 2` keep it in the name).
|
||||
*/
|
||||
export function readTrailingQuantity(
|
||||
tokens: string[],
|
||||
): { quantity: Quantity; consumed: number } | null {
|
||||
const words = tokens.map(normalizeWord)
|
||||
const last = words.length - 1
|
||||
if (last < 1) return null
|
||||
|
||||
// "x2" / "x 2" (also "x 2 kg")
|
||||
for (const [xIndex, consumed] of [
|
||||
[last - 1, 2],
|
||||
[last - 2, 3],
|
||||
] as const) {
|
||||
if (xIndex < 1 || words[xIndex] !== 'x') continue
|
||||
const amount = parseNumber(words[xIndex + 1])
|
||||
if (amount === null) continue
|
||||
if (consumed === 2) return { quantity: { amount, unit: null }, consumed }
|
||||
|
||||
const unit = parseUnit(words[last])
|
||||
if (unit !== null) return { quantity: { amount, unit: unit || null }, consumed }
|
||||
}
|
||||
|
||||
// "400 g", "2 paquetes"
|
||||
const amount = parseNumber(words[last - 1])
|
||||
const unit = parseUnit(words[last])
|
||||
if (last >= 2 && amount !== null && unit !== null) {
|
||||
return { quantity: { amount, unit: unit || null }, consumed: 2 }
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** Parses a stored quantity string (`2`, `400 g`, `½ kg`), or `null` if it is free text. */
|
||||
export function parseQuantity(text: string): Quantity | null {
|
||||
const tokens = splitTokens(text)
|
||||
if (tokens.length === 0) return null
|
||||
|
||||
const leading = readLeadingQuantity(tokens)
|
||||
|
||||
return leading && leading.consumed === tokens.length ? leading.quantity : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits text into whitespace tokens, also separating a number glued to a known unit
|
||||
* (`400g` → `400 g`) and the `x` glued to a number (`x2` → `x 2`).
|
||||
*/
|
||||
export function splitTokens(text: string): string[] {
|
||||
return text
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter(Boolean)
|
||||
.flatMap((token) => {
|
||||
const times = /^x(\d+(?:[.,]\d+)?)$/i.exec(token)
|
||||
if (times) return ['x', times[1]]
|
||||
|
||||
const glued = /^(\d+(?:[.,]\d+)?|[½¼¾])([a-zA-Z]+\.?)$/.exec(token)
|
||||
if (glued && parseUnit(glued[2]) !== null) return [glued[1], glued[2]]
|
||||
|
||||
return [token]
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds two stored quantities, used when an item is added again. Compatible quantities
|
||||
* are summed (`400 g` + `0,2 kg` → `600 g`, `2` + `3` → `5`); an empty one counts as
|
||||
* one unit when the other is a plain count (so adding "leche" twice gives `2`) and is
|
||||
* otherwise ignored; incompatible ones are joined with `+`.
|
||||
*/
|
||||
export function addQuantities(a: string | null, b: string | null): string | null {
|
||||
if (!a && !b) return '2'
|
||||
|
||||
const left = a ? parseQuantity(a) : { amount: 1, unit: null }
|
||||
const right = b ? parseQuantity(b) : { amount: 1, unit: null }
|
||||
|
||||
if (left && right) {
|
||||
const sum = sumQuantities(left, right)
|
||||
if (sum) return formatQuantity(sum)
|
||||
}
|
||||
|
||||
if (!a) return b
|
||||
if (!b) return a
|
||||
|
||||
return `${a} + ${b}`.slice(0, 40)
|
||||
}
|
||||
|
||||
/** Bare numbers from here up are weights/volumes, not counts: "400 de jamón" is 400 g. */
|
||||
const IMPLIED_MEASURE_FROM = 50
|
||||
|
||||
function sumQuantities(a: Quantity, b: Quantity): Quantity | null {
|
||||
if (a.unit === b.unit) return { amount: a.amount + b.amount, unit: a.unit }
|
||||
|
||||
// A bare "400" next to grams or millilitres is in that same base unit.
|
||||
for (const [bare, measured] of [
|
||||
[a, b],
|
||||
[b, a],
|
||||
]) {
|
||||
const base = measured.unit ? MEASURES[measured.unit]?.base : undefined
|
||||
if (!bare.unit && base && bare.amount >= IMPLIED_MEASURE_FROM) {
|
||||
return sumQuantities({ ...bare, unit: base }, measured)
|
||||
}
|
||||
}
|
||||
|
||||
const measureA = a.unit ? MEASURES[a.unit] : undefined
|
||||
const measureB = b.unit ? MEASURES[b.unit] : undefined
|
||||
if (!measureA || !measureB || measureA.base !== measureB.base) return null
|
||||
|
||||
const total = a.amount * measureA.factor + b.amount * measureB.factor
|
||||
const big = measureA.factor > 1 ? a.unit : b.unit
|
||||
|
||||
// Mixed units: kilos/litres once the total reaches one, grams/millilitres below it.
|
||||
return total >= 1000 && big
|
||||
? { amount: total / 1000, unit: big }
|
||||
: { amount: total, unit: measureA.base }
|
||||
}
|
||||
Reference in New Issue
Block a user