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:
@@ -1,8 +1,12 @@
|
|||||||
import { zodResolver } from '@hookform/resolvers/zod'
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
|
import type { ListItem } from '@superlist/shared'
|
||||||
import { PlusIcon, SearchIcon } from 'lucide-react'
|
import { PlusIcon, SearchIcon } from 'lucide-react'
|
||||||
import { useForm } from 'react-hook-form'
|
import { type ClipboardEvent, useState } from 'react'
|
||||||
|
import { useForm, useWatch } from 'react-hook-form'
|
||||||
|
import { toast } from 'sonner'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
import { ItemInputPreview, type PreviewItem } from '@/components/items/item-input-preview'
|
||||||
import { Field, FieldError } from '@/components/ui/field'
|
import { Field, FieldError } from '@/components/ui/field'
|
||||||
import {
|
import {
|
||||||
InputGroup,
|
InputGroup,
|
||||||
@@ -10,11 +14,15 @@ import {
|
|||||||
InputGroupButton,
|
InputGroupButton,
|
||||||
InputGroupInput,
|
InputGroupInput,
|
||||||
} from '@/components/ui/input-group'
|
} from '@/components/ui/input-group'
|
||||||
import { useCreateItem } from '@/hooks/use-items'
|
import { isOptimisticItem, useCreateItem, useItems, useUpdateItem } from '@/hooks/use-items'
|
||||||
import { ApiError } from '@/lib/api-client'
|
import { ApiError } from '@/lib/api-client'
|
||||||
|
import { findDuplicate, mergeBatch, mergeInto } from '@/lib/natural-input/merge'
|
||||||
|
import { isPlainItem, literalItem, parseItemInput } from '@/lib/natural-input/parse-item'
|
||||||
|
|
||||||
|
// The input may hold several items ("leche, pan y 2 pascualinas" or a pasted list);
|
||||||
|
// each one is checked against the API limits once the text is read.
|
||||||
const createItemSchema = z.object({
|
const createItemSchema = z.object({
|
||||||
name: z.string().trim().min(1, 'Escribe un artículo').max(120, 'Máximo 120 caracteres'),
|
name: z.string().trim().min(1, 'Escribe un artículo').max(2000, 'Máximo 2000 caracteres'),
|
||||||
})
|
})
|
||||||
|
|
||||||
type CreateItemValues = z.infer<typeof createItemSchema>
|
type CreateItemValues = z.infer<typeof createItemSchema>
|
||||||
@@ -47,32 +55,111 @@ export function refocusNewItemInput(): void {
|
|||||||
document.getElementById(NEW_ITEM_INPUT_ID)?.focus()
|
document.getElementById(NEW_ITEM_INPUT_ID)?.focus()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Input to add an item to a list. Submits with Enter or the button. */
|
/** Why a read item cannot be sent as is, mirroring the API limits, or `null`. */
|
||||||
|
function itemLimitError(item: PreviewItem): string | null {
|
||||||
|
if (item.name.length > 120) return `«${item.name.slice(0, 20)}…»: máximo 120 caracteres`
|
||||||
|
if ((item.quantity?.length ?? 0) > 40) return `«${item.name}»: la cantidad es demasiado larga`
|
||||||
|
if ((item.notes?.length ?? 0) > 280) return `«${item.name}»: la nota es demasiado larga`
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Input to add items to a list. Submits with Enter or the button. The text is read
|
||||||
|
* as natural language ("400 de jamon", "Queso crema. Solo Tregar", "leche, pan y
|
||||||
|
* 2 pascualinas"), previewed while typing, and an item already pending is added to
|
||||||
|
* instead of repeated.
|
||||||
|
*/
|
||||||
export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProps) {
|
export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProps) {
|
||||||
const createItem = useCreateItem(listId)
|
const createItem = useCreateItem(listId)
|
||||||
|
const updateItem = useUpdateItem(listId)
|
||||||
|
const { data: items } = useItems(listId)
|
||||||
|
// The text the user asked to add as typed; editing it brings the reading back.
|
||||||
|
const [literalText, setLiteralText] = useState<string | null>(null)
|
||||||
|
|
||||||
const form = useForm<CreateItemValues>({
|
const form = useForm<CreateItemValues>({
|
||||||
resolver: zodResolver(createItemSchema),
|
resolver: zodResolver(createItemSchema),
|
||||||
defaultValues: { name: '' },
|
defaultValues: { name: '' },
|
||||||
})
|
})
|
||||||
|
|
||||||
// The input clears at once (the item is added optimistically) so several items
|
const text = useWatch({ control: form.control, name: 'name' })
|
||||||
// can be typed in a row; if the request fails the text comes back with the error.
|
const literal = literalText !== null && literalText === text
|
||||||
|
// Placeholders have no server id yet, so they cannot be added to.
|
||||||
|
const existing = (items ?? []).filter((item) => !isOptimisticItem(item))
|
||||||
|
const preview = readItems(text, literal, existing)
|
||||||
|
const showPreview =
|
||||||
|
text.trim() !== '' &&
|
||||||
|
(literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate))
|
||||||
|
|
||||||
|
const restoreText = (source: string, message: string) => {
|
||||||
|
const current = form.getValues('name').trim()
|
||||||
|
form.setValue('name', current ? `${current}; ${source}` : source)
|
||||||
|
form.setError('name', { message })
|
||||||
|
}
|
||||||
|
|
||||||
|
// The input clears at once (items are added optimistically) so several items can be
|
||||||
|
// typed in a row; if a request fails its text comes back with the error.
|
||||||
const onSubmit = form.handleSubmit((values) => {
|
const onSubmit = form.handleSubmit((values) => {
|
||||||
|
const toAdd = readItems(values.name, literal, existing)
|
||||||
|
|
||||||
|
const limitError = toAdd.map(itemLimitError).find(Boolean)
|
||||||
|
if (limitError) {
|
||||||
|
form.setError('name', { message: limitError })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
form.reset()
|
form.reset()
|
||||||
|
setLiteralText(null)
|
||||||
form.setFocus('name')
|
form.setFocus('name')
|
||||||
createItem.mutate(values, {
|
|
||||||
onError: (error) => {
|
for (const item of toAdd) {
|
||||||
form.setValue('name', values.name)
|
if (item.duplicate) {
|
||||||
form.setError('name', {
|
const patch = mergeInto(item.duplicate, item)
|
||||||
message:
|
if (patch.quantity !== undefined || patch.notes !== undefined) {
|
||||||
|
updateItem.mutate({ itemId: item.duplicate.id, ...patch })
|
||||||
|
}
|
||||||
|
toast(
|
||||||
|
patch.quantity
|
||||||
|
? `Se sumó a «${item.duplicate.name}» (${patch.quantity})`
|
||||||
|
: `«${item.duplicate.name}» ya está en la lista`,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
createItem.mutate(
|
||||||
|
{ name: item.name, quantity: item.quantity ?? undefined, notes: item.notes ?? undefined },
|
||||||
|
{
|
||||||
|
onError: (error) =>
|
||||||
|
restoreText(
|
||||||
|
item.source,
|
||||||
error instanceof ApiError
|
error instanceof ApiError
|
||||||
? (error.problem.detail ?? error.problem.title)
|
? (error.problem.detail ?? error.problem.title)
|
||||||
: 'No pudimos añadir el artículo.',
|
: 'No pudimos añadir el artículo.',
|
||||||
})
|
),
|
||||||
},
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// An <input> drops line breaks, so a pasted list keeps one item per line as "; ".
|
||||||
|
const onPaste = (event: ClipboardEvent<HTMLInputElement>) => {
|
||||||
|
const pasted = event.clipboardData.getData('text')
|
||||||
|
if (!/[\r\n]/.test(pasted)) return
|
||||||
|
|
||||||
|
event.preventDefault()
|
||||||
|
const input = event.currentTarget
|
||||||
|
const start = input.selectionStart ?? input.value.length
|
||||||
|
const end = input.selectionEnd ?? start
|
||||||
|
const lines = pasted
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
.join('; ')
|
||||||
|
|
||||||
|
form.setValue('name', input.value.slice(0, start) + lines + input.value.slice(end), {
|
||||||
|
shouldDirty: true,
|
||||||
})
|
})
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form onSubmit={onSubmit}>
|
<form onSubmit={onSubmit}>
|
||||||
@@ -86,9 +173,10 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
aria-label="Nuevo artículo"
|
aria-label="Nuevo artículo"
|
||||||
aria-invalid={!!form.formState.errors.name}
|
aria-invalid={!!form.formState.errors.name}
|
||||||
autoComplete="off"
|
autoComplete="off"
|
||||||
placeholder="Añadir un artículo…"
|
placeholder="Ej: 400 g de jamón. Feteado fino"
|
||||||
autoFocus={autoFocus}
|
autoFocus={autoFocus}
|
||||||
className="text-base"
|
className="text-base"
|
||||||
|
onPaste={onPaste}
|
||||||
{...form.register('name')}
|
{...form.register('name')}
|
||||||
/>
|
/>
|
||||||
<InputGroupAddon align="inline-end" className="pr-2">
|
<InputGroupAddon align="inline-end" className="pr-2">
|
||||||
@@ -107,7 +195,23 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
</InputGroupAddon>
|
</InputGroupAddon>
|
||||||
</InputGroup>
|
</InputGroup>
|
||||||
<FieldError errors={[form.formState.errors.name]} className="px-5" />
|
<FieldError errors={[form.formState.errors.name]} className="px-5" />
|
||||||
|
{showPreview && (
|
||||||
|
<ItemInputPreview
|
||||||
|
items={preview}
|
||||||
|
literal={literal}
|
||||||
|
onLiteralChange={(value) => setLiteralText(value ? text : null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</Field>
|
</Field>
|
||||||
</form>
|
</form>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The items `text` adds, each with the pending item it repeats, if any. */
|
||||||
|
function readItems(text: string, literal: boolean, existing: ListItem[]): PreviewItem[] {
|
||||||
|
if (!text.trim()) return []
|
||||||
|
|
||||||
|
const items = literal ? [literalItem(text)] : mergeBatch(parseItemInput(text))
|
||||||
|
|
||||||
|
return items.map((item) => ({ ...item, duplicate: findDuplicate(existing, item.name) }))
|
||||||
|
}
|
||||||
|
|||||||
55
apps/web/src/components/items/item-input-preview.tsx
Normal file
55
apps/web/src/components/items/item-input-preview.tsx
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import type { ListItem } from '@superlist/shared'
|
||||||
|
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import type { ParsedItem } from '@/lib/natural-input/parse-item'
|
||||||
|
|
||||||
|
export type PreviewItem = ParsedItem & {
|
||||||
|
/** The pending item this one will be added to instead of creating a new row. */
|
||||||
|
duplicate?: ListItem
|
||||||
|
}
|
||||||
|
|
||||||
|
type ItemInputPreviewProps = {
|
||||||
|
items: PreviewItem[]
|
||||||
|
/** The text will be added untouched, as a single item. */
|
||||||
|
literal: boolean
|
||||||
|
onLiteralChange: (literal: boolean) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shows how the text in the "add an item" input will be read — name, quantity, note,
|
||||||
|
* and whether it adds to an item already on the list — with a way to add it as typed
|
||||||
|
* when the reading is wrong ("7 up").
|
||||||
|
*/
|
||||||
|
export function ItemInputPreview({ items, literal, onLiteralChange }: ItemInputPreviewProps) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-wrap items-center gap-1.5 px-5 text-sm" aria-live="polite">
|
||||||
|
{items.map((item) => (
|
||||||
|
<span
|
||||||
|
key={item.source}
|
||||||
|
className="bg-muted inline-flex max-w-full items-baseline gap-1.5 truncate rounded-full px-3 py-1"
|
||||||
|
>
|
||||||
|
<span className="truncate font-medium">{item.name}</span>
|
||||||
|
{item.quantity && <span className="text-muted-foreground">· {item.quantity}</span>}
|
||||||
|
{item.notes && (
|
||||||
|
<span className="text-muted-foreground truncate italic">· {item.notes}</span>
|
||||||
|
)}
|
||||||
|
{item.duplicate && (
|
||||||
|
<span className="text-primary text-xs">se suma a «{item.duplicate.name}»</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="xs"
|
||||||
|
className="text-muted-foreground"
|
||||||
|
// Keep the focus (and the mobile keyboard) in the input.
|
||||||
|
onMouseDown={(event) => event.preventDefault()}
|
||||||
|
onClick={() => onLiteralChange(!literal)}
|
||||||
|
>
|
||||||
|
{literal ? 'Interpretar' : 'Agregar tal cual'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -87,19 +87,21 @@ describe('splitItems', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('quantityLabel', () => {
|
describe('quantityLabel', () => {
|
||||||
it('shows quantities above one, with their unit when present', () => {
|
it('shows numeric quantities, with their unit when present', () => {
|
||||||
expect(quantityLabel('2')).toBe('2')
|
expect(quantityLabel('2')).toBe('2')
|
||||||
expect(quantityLabel('2 kg')).toBe('2 kg')
|
expect(quantityLabel('2 kg')).toBe('2 kg')
|
||||||
expect(quantityLabel('1,5')).toBe('1,5')
|
expect(quantityLabel('1,5')).toBe('1,5')
|
||||||
expect(quantityLabel(' 3 ')).toBe('3')
|
expect(quantityLabel(' 3 ')).toBe('3')
|
||||||
|
expect(quantityLabel('1 kg')).toBe('1 kg')
|
||||||
|
expect(quantityLabel('0,5')).toBe('0,5')
|
||||||
|
expect(quantityLabel('½ kg')).toBe('½ kg')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('hides empty, absent and exactly-one quantities', () => {
|
it('hides empty, absent and plain-one quantities', () => {
|
||||||
expect(quantityLabel(null)).toBeNull()
|
expect(quantityLabel(null)).toBeNull()
|
||||||
expect(quantityLabel('')).toBeNull()
|
expect(quantityLabel('')).toBeNull()
|
||||||
expect(quantityLabel('1')).toBeNull()
|
expect(quantityLabel('1')).toBeNull()
|
||||||
expect(quantityLabel('1 kg')).toBeNull()
|
expect(quantityLabel(' 1 ')).toBeNull()
|
||||||
expect(quantityLabel('0,5')).toBeNull()
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('hides quantities whose text does not start with a number', () => {
|
it('hides quantities whose text does not start with a number', () => {
|
||||||
|
|||||||
@@ -41,16 +41,15 @@ export function splitItems(items: ListItem[], now: Date): SplitItems {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The quantity to show at the right of an item's name, or `null` when it must
|
* The quantity to show at the right of an item's name, or `null` when it must
|
||||||
* stay hidden. Only quantities above one earn their place in the row, so a
|
* stay hidden. A plain "1" adds no information, so it is hidden, as is anything
|
||||||
* plain "1" does not add noise: the leading number of the string is parsed
|
* that does not start with a number ("un par"); every other quantity is shown,
|
||||||
* ("2" → 2, "2 kg" → 2, "0,5" → 0.5) and anything without one is hidden.
|
* including fractions and quantities with a unit ("½ kg", "1 kg", "0,5").
|
||||||
*/
|
*/
|
||||||
export function quantityLabel(quantity: string | null): string | null {
|
export function quantityLabel(quantity: string | null): string | null {
|
||||||
if (!quantity) return null
|
if (!quantity) return null
|
||||||
|
|
||||||
const trimmed = quantity.trim()
|
const trimmed = quantity.trim()
|
||||||
const leadingNumber = /^(\d+(?:[.,]\d+)?)/.exec(trimmed)
|
if (!/^(\d|[½¼¾])/.test(trimmed)) return null
|
||||||
if (!leadingNumber) return null
|
|
||||||
|
|
||||||
return Number.parseFloat(leadingNumber[1].replace(',', '.')) > 1 ? trimmed : null
|
return trimmed === '1' ? null : trimmed
|
||||||
}
|
}
|
||||||
|
|||||||
154
apps/web/src/lib/natural-input/lexicon.ts
Normal file
154
apps/web/src/lib/natural-input/lexicon.ts
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
import { normalizeWord } from './text'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Grocery words that are usually typed without their accent. The parser restores it
|
||||||
|
* (`jamon` → `jamón`), keyed by the word with accents stripped. Words that are spelled
|
||||||
|
* the same with or without an accent elsewhere (`papa`/`papá`) are deliberately left out.
|
||||||
|
*/
|
||||||
|
const ACCENTED_WORDS = [
|
||||||
|
// Almacén
|
||||||
|
'azúcar',
|
||||||
|
'café',
|
||||||
|
'té',
|
||||||
|
'puré',
|
||||||
|
'sémola',
|
||||||
|
'fécula',
|
||||||
|
'orégano',
|
||||||
|
'pimentón',
|
||||||
|
'cúrcuma',
|
||||||
|
'ají',
|
||||||
|
'maní',
|
||||||
|
'almíbar',
|
||||||
|
'dátiles',
|
||||||
|
'garrapiñada',
|
||||||
|
'ñoquis',
|
||||||
|
'ñoqui',
|
||||||
|
'budín',
|
||||||
|
'budines',
|
||||||
|
'turrón',
|
||||||
|
'bombón',
|
||||||
|
'bombones',
|
||||||
|
'sándwich',
|
||||||
|
'sándwiches',
|
||||||
|
'tónica',
|
||||||
|
// Frutas y verduras
|
||||||
|
'limón',
|
||||||
|
'melón',
|
||||||
|
'sandía',
|
||||||
|
'plátano',
|
||||||
|
'plátanos',
|
||||||
|
'ananá',
|
||||||
|
'maracuyá',
|
||||||
|
'arándano',
|
||||||
|
'arándanos',
|
||||||
|
'brócoli',
|
||||||
|
'rúcula',
|
||||||
|
'morrón',
|
||||||
|
'champiñón',
|
||||||
|
'espárrago',
|
||||||
|
'espárragos',
|
||||||
|
'rábano',
|
||||||
|
'rábanos',
|
||||||
|
'maíz',
|
||||||
|
// Carnes y pescados
|
||||||
|
'jamón',
|
||||||
|
'salchichón',
|
||||||
|
'salmón',
|
||||||
|
'atún',
|
||||||
|
'camarón',
|
||||||
|
'vacío',
|
||||||
|
'entraña',
|
||||||
|
'hígado',
|
||||||
|
'riñón',
|
||||||
|
// Limpieza y perfumería
|
||||||
|
'jabón',
|
||||||
|
'jabones',
|
||||||
|
'champú',
|
||||||
|
'algodón',
|
||||||
|
'fósforos',
|
||||||
|
'pañales',
|
||||||
|
'pañuelos',
|
||||||
|
'higiénico',
|
||||||
|
// Adjetivos frecuentes
|
||||||
|
'líquido',
|
||||||
|
'líquida',
|
||||||
|
'lácteo',
|
||||||
|
'árabe',
|
||||||
|
'francés',
|
||||||
|
'dietético',
|
||||||
|
'dietética',
|
||||||
|
'orgánico',
|
||||||
|
'orgánica',
|
||||||
|
'clásico',
|
||||||
|
'clásica',
|
||||||
|
'ácido',
|
||||||
|
'ácida',
|
||||||
|
]
|
||||||
|
|
||||||
|
export const ACCENTS: Record<string, string> = Object.fromEntries(
|
||||||
|
ACCENTED_WORDS.map((word) => [normalizeWord(word), word]),
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Spanish number words, keyed without accents. */
|
||||||
|
export const NUMBER_WORDS: Record<string, number> = {
|
||||||
|
un: 1,
|
||||||
|
uno: 1,
|
||||||
|
una: 1,
|
||||||
|
dos: 2,
|
||||||
|
tres: 3,
|
||||||
|
cuatro: 4,
|
||||||
|
cinco: 5,
|
||||||
|
seis: 6,
|
||||||
|
siete: 7,
|
||||||
|
ocho: 8,
|
||||||
|
nueve: 9,
|
||||||
|
diez: 10,
|
||||||
|
once: 11,
|
||||||
|
doce: 12,
|
||||||
|
quince: 15,
|
||||||
|
veinte: 20,
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Packaging units: kept as a word in the quantity and pluralized (`2 paquetes`). */
|
||||||
|
export const CONTAINER_UNITS = new Set([
|
||||||
|
'paquete',
|
||||||
|
'caja',
|
||||||
|
'lata',
|
||||||
|
'botella',
|
||||||
|
'bolsa',
|
||||||
|
'sobre',
|
||||||
|
'frasco',
|
||||||
|
'atado',
|
||||||
|
'maple',
|
||||||
|
'pack',
|
||||||
|
])
|
||||||
|
|
||||||
|
/** Unit spellings → canonical unit. `''` means "a unit that adds nothing" (`unidades`). */
|
||||||
|
export const UNIT_ALIASES: Record<string, string> = {
|
||||||
|
g: 'g',
|
||||||
|
gr: 'g',
|
||||||
|
grs: 'g',
|
||||||
|
gramo: 'g',
|
||||||
|
gramos: 'g',
|
||||||
|
kg: 'kg',
|
||||||
|
kgs: 'kg',
|
||||||
|
k: 'kg',
|
||||||
|
kilo: 'kg',
|
||||||
|
kilos: 'kg',
|
||||||
|
l: 'l',
|
||||||
|
lt: 'l',
|
||||||
|
lts: 'l',
|
||||||
|
litro: 'l',
|
||||||
|
litros: 'l',
|
||||||
|
ml: 'ml',
|
||||||
|
cc: 'ml',
|
||||||
|
u: '',
|
||||||
|
unidad: '',
|
||||||
|
unidades: '',
|
||||||
|
...Object.fromEntries(
|
||||||
|
[...CONTAINER_UNITS].flatMap((unit) => [
|
||||||
|
[unit, unit],
|
||||||
|
[`${unit}s`, unit],
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
}
|
||||||
61
apps/web/src/lib/natural-input/merge.test.ts
Normal file
61
apps/web/src/lib/natural-input/merge.test.ts
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import type { ListItem } from '@superlist/shared'
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import { findDuplicate, mergeBatch, mergeInto } from './merge'
|
||||||
|
import { parseItemInput } from './parse-item'
|
||||||
|
|
||||||
|
function item(overrides: Partial<ListItem>): ListItem {
|
||||||
|
return {
|
||||||
|
id: 'item-1',
|
||||||
|
listId: 'list-1',
|
||||||
|
name: 'Jamón',
|
||||||
|
completed: false,
|
||||||
|
boughtAt: null,
|
||||||
|
quantity: null,
|
||||||
|
notes: null,
|
||||||
|
order: 0,
|
||||||
|
createdAt: '2026-10-15T10:00:00.000Z',
|
||||||
|
updatedAt: '2026-10-15T10:00:00.000Z',
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('findDuplicate', () => {
|
||||||
|
it('matches pending items ignoring case, accents and a final "s"', () => {
|
||||||
|
const jamon = item({})
|
||||||
|
const pascualinas = item({ id: 'item-2', name: 'Pascualinas' })
|
||||||
|
|
||||||
|
expect(findDuplicate([jamon, pascualinas], 'jamon')).toBe(jamon)
|
||||||
|
expect(findDuplicate([jamon, pascualinas], 'Pascualina')).toBe(pascualinas)
|
||||||
|
expect(findDuplicate([jamon], 'Queso')).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('ignores items already bought', () => {
|
||||||
|
expect(findDuplicate([item({ completed: true })], 'Jamón')).toBeUndefined()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('mergeInto', () => {
|
||||||
|
it('sums quantities and appends new notes', () => {
|
||||||
|
expect(
|
||||||
|
mergeInto({ quantity: '400 g', notes: 'Feteado' }, { quantity: '200 g', notes: 'Cocido' }),
|
||||||
|
).toEqual({ quantity: '600 g', notes: 'Feteado · Cocido' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('leaves out what does not change', () => {
|
||||||
|
expect(
|
||||||
|
mergeInto({ quantity: '400 g', notes: 'Feteado' }, { quantity: null, notes: 'feteado' }),
|
||||||
|
).toEqual({})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('mergeBatch', () => {
|
||||||
|
it('folds repeated items of one input', () => {
|
||||||
|
const merged = mergeBatch(parseItemInput('pan, leche, 2 panes'))
|
||||||
|
|
||||||
|
expect(merged.map(({ name, quantity }) => ({ name, quantity }))).toEqual([
|
||||||
|
{ name: 'Pan', quantity: '3' },
|
||||||
|
{ name: 'Leche', quantity: null },
|
||||||
|
])
|
||||||
|
})
|
||||||
|
})
|
||||||
73
apps/web/src/lib/natural-input/merge.ts
Normal file
73
apps/web/src/lib/natural-input/merge.ts
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
import type { ListItem } from '@superlist/shared'
|
||||||
|
|
||||||
|
import type { ParsedItem } from './parse-item'
|
||||||
|
import { addQuantities } from './quantity'
|
||||||
|
import { normalizeWord } from './text'
|
||||||
|
|
||||||
|
/** A name without case, accents or extra spaces. */
|
||||||
|
function itemKey(name: string): string {
|
||||||
|
return normalizeWord(name).replace(/\s+/g, ' ').trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether two names are the same item, singular or plural ("pan"/"panes", "leche"/"leches"). */
|
||||||
|
function sameItem(a: string, b: string): boolean {
|
||||||
|
const [short, long] = [itemKey(a), itemKey(b)].sort((x, y) => x.length - y.length)
|
||||||
|
|
||||||
|
return long === short || long === `${short}s` || long === `${short}es`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The pending item that `name` repeats ("jamon" matches "Jamón", "pascualina" "Pascualinas"). */
|
||||||
|
export function findDuplicate(items: ListItem[], name: string): ListItem | undefined {
|
||||||
|
return items.find((item) => !item.completed && sameItem(item.name, name))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Appends a note unless it is already there. */
|
||||||
|
function joinNotes(a: string | null, b: string | null): string | null {
|
||||||
|
if (!b) return a
|
||||||
|
if (!a) return b
|
||||||
|
if (normalizeWord(a).includes(normalizeWord(b))) return a
|
||||||
|
|
||||||
|
return `${a} · ${b}`.slice(0, 280)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The `PATCH` body that adds `incoming` to an item already on the list: quantities are
|
||||||
|
* summed and notes appended. Only changed fields are included, so it may be empty.
|
||||||
|
*/
|
||||||
|
export function mergeInto(
|
||||||
|
existing: Pick<ListItem, 'quantity' | 'notes'>,
|
||||||
|
incoming: Pick<ParsedItem, 'quantity' | 'notes'>,
|
||||||
|
): { quantity?: string | null; notes?: string | null } {
|
||||||
|
const patch: { quantity?: string | null; notes?: string | null } = {}
|
||||||
|
|
||||||
|
const quantity = addQuantities(existing.quantity, incoming.quantity)
|
||||||
|
if (quantity !== existing.quantity) patch.quantity = quantity
|
||||||
|
|
||||||
|
const notes = joinNotes(existing.notes, incoming.notes)
|
||||||
|
if (notes !== existing.notes) patch.notes = notes
|
||||||
|
|
||||||
|
return patch
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Folds repeated items of one input into one ("pan, leche, pan" → Pan · 2, Leche). */
|
||||||
|
export function mergeBatch(items: ParsedItem[]): ParsedItem[] {
|
||||||
|
const merged: ParsedItem[] = []
|
||||||
|
|
||||||
|
for (const item of items) {
|
||||||
|
const index = merged.findIndex((previous) => sameItem(previous.name, item.name))
|
||||||
|
|
||||||
|
if (index === -1) {
|
||||||
|
merged.push(item)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
const previous = merged[index]
|
||||||
|
merged[index] = {
|
||||||
|
...previous,
|
||||||
|
...mergeInto(previous, item),
|
||||||
|
source: `${previous.source}; ${item.source}`,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return merged
|
||||||
|
}
|
||||||
110
apps/web/src/lib/natural-input/parse-item.test.ts
Normal file
110
apps/web/src/lib/natural-input/parse-item.test.ts
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import { isPlainItem, literalItem, parseItemInput, parseSingleItem } from './parse-item'
|
||||||
|
|
||||||
|
function parsed(text: string) {
|
||||||
|
const { name, quantity, notes } = parseSingleItem(text)
|
||||||
|
|
||||||
|
return { name, quantity, notes }
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('parseSingleItem', () => {
|
||||||
|
it.each([
|
||||||
|
['400 de jamon', 'Jamón', '400', null],
|
||||||
|
['2 pascualinas', 'Pascualinas', '2', null],
|
||||||
|
['Queso crema. Solo si hay marca Tregar', 'Queso crema', null, 'Solo si hay marca Tregar'],
|
||||||
|
['Pan - el integral', 'Pan', null, 'El integral'],
|
||||||
|
['Leche (descremada)', 'Leche', null, 'Descremada'],
|
||||||
|
['medio kilo de pan', 'Pan', '½ kg', null],
|
||||||
|
['un cuarto de jamon', 'Jamón', '¼ kg', null],
|
||||||
|
['medio de helado', 'Helado', '½ kg', null],
|
||||||
|
['una docena de huevos', 'Huevos', '12', null],
|
||||||
|
['media docena de facturas', 'Facturas', '6', null],
|
||||||
|
['dos paquetes de fideos', 'Fideos', '2 paquetes', null],
|
||||||
|
['1 lata de atun', 'Atún', '1 lata', null],
|
||||||
|
['1,5 kg de papas', 'Papas', '1,5 kg', null],
|
||||||
|
['1 kilo y medio de papas', 'Papas', '1,5 kg', null],
|
||||||
|
['1.5 kg de papas', 'Papas', '1,5 kg', null],
|
||||||
|
['400g de queso', 'Queso', '400 g', null],
|
||||||
|
['2 litros de leche', 'Leche', '2 l', null],
|
||||||
|
['6 unidades de yogur', 'Yogur', '6', null],
|
||||||
|
['leche x2', 'Leche', '2', null],
|
||||||
|
['pan x 3', 'Pan', '3', null],
|
||||||
|
['jamon 400 g', 'Jamón', '400 g', null],
|
||||||
|
['Coca 1,5l', 'Coca', '1,5 l', null],
|
||||||
|
['400 de jamon. Feteado fino', 'Jamón', '400', 'Feteado fino'],
|
||||||
|
])('reads "%s"', (text, name, quantity, notes) => {
|
||||||
|
expect(parsed(text)).toEqual({ name, quantity, notes })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps names that only look like quantities', () => {
|
||||||
|
expect(parsed('coca-cola')).toEqual({ name: 'Coca-cola', quantity: null, notes: null })
|
||||||
|
expect(parsed('Sprite 2.25')).toEqual({ name: 'Sprite 2.25', quantity: null, notes: null })
|
||||||
|
expect(parsed('Pilas AA 2')).toEqual({ name: 'Pilas AA 2', quantity: null, notes: null })
|
||||||
|
expect(parsed('medio pollo')).toEqual({ name: 'Medio pollo', quantity: null, notes: null })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('takes the whole text as the name when nothing is left after the quantity', () => {
|
||||||
|
expect(parsed('400 g')).toEqual({ name: '400 g', quantity: null, notes: null })
|
||||||
|
expect(parsed('2')).toEqual({ name: '2', quantity: null, notes: null })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('restores accents without touching brand names', () => {
|
||||||
|
expect(parsed('Jamon cocido').name).toBe('Jamón cocido')
|
||||||
|
expect(parsed('cafe LA VIRGINIA').name).toBe('Café LA VIRGINIA')
|
||||||
|
expect(parsed('pan frances').name).toBe('Pan francés')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('ignores a trailing full stop', () => {
|
||||||
|
expect(parsed('Manteca.')).toEqual({ name: 'Manteca', quantity: null, notes: null })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('parseItemInput', () => {
|
||||||
|
const names = (text: string) => parseItemInput(text).map((item) => item.name)
|
||||||
|
|
||||||
|
it('splits on commas, a final "y", semicolons and line breaks', () => {
|
||||||
|
expect(names('leche, pan y 2 pascualinas')).toEqual(['Leche', 'Pan', 'Pascualinas'])
|
||||||
|
expect(names('leche; pan')).toEqual(['Leche', 'Pan'])
|
||||||
|
expect(names('- leche\n- pan\n\n1. queso')).toEqual(['Leche', 'Pan', 'Queso'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps commas of a note and decimal commas', () => {
|
||||||
|
expect(parseItemInput('Queso. Si no hay, el otro')).toEqual([
|
||||||
|
{
|
||||||
|
name: 'Queso',
|
||||||
|
quantity: null,
|
||||||
|
notes: 'Si no hay, el otro',
|
||||||
|
source: 'Queso. Si no hay, el otro',
|
||||||
|
},
|
||||||
|
])
|
||||||
|
expect(names('1,5 kg de papas, cebolla')).toEqual(['Papas', 'Cebolla'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not split "y medio" off a quantity', () => {
|
||||||
|
expect(names('pan y medio kilo de queso')).toEqual(['Pan', 'Queso'])
|
||||||
|
expect(names('1 kilo y medio de papas, cebolla')).toEqual(['Papas', 'Cebolla'])
|
||||||
|
expect(names('1 kilo y medio')).toEqual(['1 kilo y medio'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('drops empty segments', () => {
|
||||||
|
expect(parseItemInput(' ; ,\n')).toEqual([])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('literalItem / isPlainItem', () => {
|
||||||
|
it('builds an untouched item', () => {
|
||||||
|
expect(literalItem(' 7 up ')).toEqual({
|
||||||
|
name: '7 up',
|
||||||
|
quantity: null,
|
||||||
|
notes: null,
|
||||||
|
source: '7 up',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('tells when parsing adds nothing to the text', () => {
|
||||||
|
expect(isPlainItem(parseItemInput('leche'), 'leche')).toBe(true)
|
||||||
|
expect(isPlainItem(parseItemInput('jamon'), 'jamon')).toBe(false)
|
||||||
|
expect(isPlainItem(parseItemInput('2 panes'), '2 panes')).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
136
apps/web/src/lib/natural-input/parse-item.ts
Normal file
136
apps/web/src/lib/natural-input/parse-item.ts
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
import { ACCENTS } from './lexicon'
|
||||||
|
import { formatQuantity, readLeadingQuantity, readTrailingQuantity, splitTokens } from './quantity'
|
||||||
|
import { capitalize, normalizeWord } from './text'
|
||||||
|
|
||||||
|
/** An item as read from free text, ready to be sent to `POST /lists/:listId/items`. */
|
||||||
|
export type ParsedItem = {
|
||||||
|
name: string
|
||||||
|
quantity: string | null
|
||||||
|
notes: string | null
|
||||||
|
/** The text this item was read from, given back to the input if adding it fails. */
|
||||||
|
source: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What separates an item from its note: "Queso crema. Solo Tregar", "Pan - el integral". */
|
||||||
|
const NOTE_SEPARATORS = ['. ', ' - ', ' – ', ' — ']
|
||||||
|
|
||||||
|
/** A trailing parenthesis is a note too: "Leche (descremada)". */
|
||||||
|
const TRAILING_PARENTHESIS = /^(.*\S)\s*\(([^()]*)\)\s*$/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The "y"/"e" that separates two items. Before "medio"/"media" it is part of a quantity
|
||||||
|
* when it follows a unit or a number ("1 kilo y medio de papas") and a separator
|
||||||
|
* otherwise ("pan y medio kilo de queso").
|
||||||
|
*/
|
||||||
|
const AND =
|
||||||
|
/(?<!(?:kilos?|kgs?|litros?|lts?|docenas?|\d))\s+[ye]\s+(?=medi[oa]\b)|\s+[ye]\s+(?!medi[oa]\b)/i
|
||||||
|
|
||||||
|
/** List markers that pasted lists bring along: "- ", "• ", "1. ", "2) ", "[ ] ". */
|
||||||
|
const LIST_MARKER = /^(?:[-*•·]|\d+[.)]|\[[ xX]?\])\s+/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads every item in `text`. Semicolons and line breaks always separate items; commas
|
||||||
|
* and a final "y"/"e" do too ("leche, pan y 2 pascualinas"), except on a line that has a
|
||||||
|
* note, whose commas belong to the note ("Queso. Si no hay, el otro").
|
||||||
|
*/
|
||||||
|
export function parseItemInput(text: string): ParsedItem[] {
|
||||||
|
return text
|
||||||
|
.split(/[;\n]+/)
|
||||||
|
.map((line) => line.trim().replace(LIST_MARKER, ''))
|
||||||
|
.flatMap(splitLine)
|
||||||
|
.map(parseSingleItem)
|
||||||
|
.filter((item) => item.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The whole text as one item, untouched: the way out when the parser gets it wrong. */
|
||||||
|
export function literalItem(text: string): ParsedItem {
|
||||||
|
return { name: text.trim(), quantity: null, notes: null, source: text.trim() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the parsed items say nothing more than the text itself (so no preview is needed). */
|
||||||
|
export function isPlainItem(items: ParsedItem[], text: string): boolean {
|
||||||
|
if (items.length !== 1) return false
|
||||||
|
const [item] = items
|
||||||
|
|
||||||
|
return !item.quantity && !item.notes && item.name.toLowerCase() === text.trim().toLowerCase()
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasNote(line: string): boolean {
|
||||||
|
return NOTE_SEPARATORS.some((separator) => line.includes(separator)) || /\)\s*$/.test(line)
|
||||||
|
}
|
||||||
|
|
||||||
|
function splitLine(line: string): string[] {
|
||||||
|
if (!line) return []
|
||||||
|
if (hasNote(line)) return [line]
|
||||||
|
|
||||||
|
// A comma between digits is a decimal ("1,5 kg").
|
||||||
|
return line
|
||||||
|
.split(/\s*,\s*(?!\d)/)
|
||||||
|
.flatMap((part) => part.split(AND))
|
||||||
|
.map((part) => part.trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads one item: "400 de jamon" → Jamón · 400, "2 pascualinas" → Pascualinas · 2,
|
||||||
|
* "Queso crema. Solo Tregar" → Queso crema + note, "leche x2" → Leche · 2.
|
||||||
|
*/
|
||||||
|
export function parseSingleItem(source: string): ParsedItem {
|
||||||
|
let text = source.trim()
|
||||||
|
let notes: string | null = null
|
||||||
|
|
||||||
|
const separator = NOTE_SEPARATORS.map((value) => ({ value, index: text.indexOf(value) }))
|
||||||
|
.filter(({ index }) => index > 0)
|
||||||
|
.sort((a, b) => a.index - b.index)[0]
|
||||||
|
|
||||||
|
if (separator) {
|
||||||
|
notes = text.slice(separator.index + separator.value.length)
|
||||||
|
text = text.slice(0, separator.index)
|
||||||
|
} else {
|
||||||
|
const parenthesis = TRAILING_PARENTHESIS.exec(text)
|
||||||
|
if (parenthesis) {
|
||||||
|
text = parenthesis[1]
|
||||||
|
notes = parenthesis[2]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
text = text.replace(/\.+$/, '').trim()
|
||||||
|
notes = notes?.trim() ? capitalize(notes.trim()) : null
|
||||||
|
|
||||||
|
const tokens = splitTokens(text)
|
||||||
|
// A quantity with nothing left for the name ("400 g") is the name itself.
|
||||||
|
const leading = readLeadingQuantity(tokens)
|
||||||
|
const trailing = readTrailingQuantity(tokens)
|
||||||
|
let quantity: string | null = null
|
||||||
|
let nameWords = text.split(/\s+/)
|
||||||
|
|
||||||
|
if (leading && leading.consumed < tokens.length) {
|
||||||
|
quantity = formatQuantity(leading.quantity)
|
||||||
|
nameWords = tokens.slice(leading.consumed)
|
||||||
|
} else if (trailing && trailing.consumed < tokens.length) {
|
||||||
|
quantity = formatQuantity(trailing.quantity)
|
||||||
|
nameWords = tokens.slice(0, tokens.length - trailing.consumed)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: capitalize(nameWords.map(restoreAccent).join(' ')),
|
||||||
|
quantity,
|
||||||
|
notes,
|
||||||
|
source: source.trim(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Restores the accent of a known grocery word typed without it, keeping a leading capital
|
||||||
|
* (`jamon` → `jamón`, `Jamon` → `Jamón`). Upper-case or mixed-case words are brand names
|
||||||
|
* and stay as typed.
|
||||||
|
*/
|
||||||
|
function restoreAccent(word: string): string {
|
||||||
|
const lower = word.toLowerCase()
|
||||||
|
if (word !== lower && word !== capitalize(lower)) return word
|
||||||
|
|
||||||
|
const accented = ACCENTS[normalizeWord(word)]
|
||||||
|
if (!accented) return word
|
||||||
|
|
||||||
|
return word === lower ? accented : capitalize(accented)
|
||||||
|
}
|
||||||
46
apps/web/src/lib/natural-input/quantity.test.ts
Normal file
46
apps/web/src/lib/natural-input/quantity.test.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import { addQuantities, parseQuantity } from './quantity'
|
||||||
|
|
||||||
|
describe('parseQuantity', () => {
|
||||||
|
it('reads stored quantities', () => {
|
||||||
|
expect(parseQuantity('2')).toEqual({ amount: 2, unit: null })
|
||||||
|
expect(parseQuantity('400 g')).toEqual({ amount: 400, unit: 'g' })
|
||||||
|
expect(parseQuantity('½ kg')).toEqual({ amount: 0.5, unit: 'kg' })
|
||||||
|
expect(parseQuantity('2 paquetes')).toEqual({ amount: 2, unit: 'paquete' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects free text', () => {
|
||||||
|
expect(parseQuantity('un par')).toBeNull()
|
||||||
|
expect(parseQuantity('')).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('addQuantities', () => {
|
||||||
|
it('sums compatible quantities', () => {
|
||||||
|
expect(addQuantities('2', '3')).toBe('5')
|
||||||
|
expect(addQuantities('400 g', '200 g')).toBe('600 g')
|
||||||
|
expect(addQuantities('400 g', '0,2 kg')).toBe('600 g')
|
||||||
|
expect(addQuantities('½ kg', '600 g')).toBe('1,1 kg')
|
||||||
|
expect(addQuantities('1 l', '500 ml')).toBe('1,5 l')
|
||||||
|
expect(addQuantities('1 paquete', '1 paquete')).toBe('2 paquetes')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('reads a large bare number next to a weight as that weight', () => {
|
||||||
|
expect(addQuantities('400', '200 g')).toBe('600 g')
|
||||||
|
expect(addQuantities('400', '1 kg')).toBe('1,4 kg')
|
||||||
|
expect(addQuantities('2', '200 g')).toBe('2 + 200 g')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('counts an empty quantity as one unit of a plain count', () => {
|
||||||
|
expect(addQuantities(null, null)).toBe('2')
|
||||||
|
expect(addQuantities(null, '3')).toBe('4')
|
||||||
|
expect(addQuantities(null, '400 g')).toBe('400 g')
|
||||||
|
expect(addQuantities('400 g', null)).toBe('400 g')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('joins incompatible quantities', () => {
|
||||||
|
expect(addQuantities('2 paquetes', '1 kg')).toBe('2 paquetes + 1 kg')
|
||||||
|
expect(addQuantities('un par', '2')).toBe('un par + 2')
|
||||||
|
})
|
||||||
|
})
|
||||||
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 }
|
||||||
|
}
|
||||||
9
apps/web/src/lib/natural-input/text.ts
Normal file
9
apps/web/src/lib/natural-input/text.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
/** Lowercases and strips accents (`Jamón` → `jamon`, `Ñoquis` → `noquis`) for comparisons. */
|
||||||
|
export function normalizeWord(word: string): string {
|
||||||
|
return word.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Upper-cases the first letter and leaves the rest as typed. */
|
||||||
|
export function capitalize(text: string): string {
|
||||||
|
return text.charAt(0).toUpperCase() + text.slice(1)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user