feat(items): voice dictation with Gemma 4 and a reworked list UI
Dictation: a mic button in the add field uses the Web Speech API (es-AR) and
shows the partial transcript in the input. POST /api/voice/split asks Gemma 4
(Gemini API, plain fetch) to split the sentence into one string per item,
written the way the existing parser reads typed text; each string then goes
through the usual add flow. The endpoint never fails because of the model:
missing key, timeout, 429 or invalid JSON fall back to splitting on commas,
semicolons, " y " and " e ". A toast offers "Deshacer" for the whole dictation;
if the request fails, the transcript is added as a single item.
UI: "+" instead of the search icon, quantity tags ("2 L", "×12", "1 kg"), the
list name with a list switcher and the pending/bought count in the header,
"Comprados (N)" folded by default, and a bottom sheet to edit name, quantity
(− / + and unit), note and delete. PATCH items now accepts a name.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,58 +1,63 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { ChevronDownIcon } from 'lucide-react'
|
||||
import { CheckIcon, ChevronDownIcon } from 'lucide-react'
|
||||
|
||||
import { Card } from '@/components/ui/card'
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
|
||||
import type { useUpdateItem } from '@/hooks/use-items'
|
||||
|
||||
import { ItemRow, type ItemRowProps } from './item-row'
|
||||
import { ItemRow } from './item-row'
|
||||
|
||||
type BoughtItemListProps = {
|
||||
items: ListItem[]
|
||||
updateItem: ReturnType<typeof useUpdateItem>
|
||||
savingIds: string[]
|
||||
/** The editing state of each row, owned by the parent so only one row edits at a time. */
|
||||
editingProps: (itemId: string) => Pick<ItemRowProps, 'editing' | 'onEditingChange'>
|
||||
onEdit: (item: ListItem) => void
|
||||
onMove: (item: ListItem) => void
|
||||
onDelete: (item: ListItem) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapsible "Comprados" card below the pending items. Expanded by default so
|
||||
* marking an item visibly moves it down; the user can fold it. Tapping an item
|
||||
* here un-buys it and it returns to the pending list.
|
||||
* Collapsible "Comprados (N)" section at the end of the list, folded by default so
|
||||
* the pending items stay in focus. Tapping an item here un-buys it and it returns
|
||||
* to the pending list.
|
||||
*/
|
||||
export function BoughtItemList({
|
||||
items,
|
||||
updateItem,
|
||||
savingIds,
|
||||
editingProps,
|
||||
onEdit,
|
||||
onMove,
|
||||
onDelete,
|
||||
}: BoughtItemListProps) {
|
||||
return (
|
||||
<Collapsible defaultOpen asChild>
|
||||
<Card className="gap-0 py-0">
|
||||
<CollapsibleTrigger className="group bg-muted text-muted-foreground hover:text-foreground flex w-full items-center gap-3 px-4 py-3 text-left transition-colors">
|
||||
<ChevronDownIcon className="size-5 transition-transform group-data-[state=closed]:-rotate-90" />
|
||||
<span className="text-base">Comprados · {items.length}</span>
|
||||
<Collapsible asChild>
|
||||
<section className="border-border overflow-hidden rounded-xl border border-dashed">
|
||||
<CollapsibleTrigger className="group text-muted-foreground hover:text-foreground focus-visible:ring-ring/50 flex min-h-12 w-full items-center gap-3 px-4 py-3 text-left transition-colors outline-none focus-visible:ring-3">
|
||||
<CheckIcon className="text-primary size-4" strokeWidth={2.5} aria-hidden />
|
||||
<span className="flex-1 text-base">Comprados ({items.length})</span>
|
||||
<ChevronDownIcon
|
||||
className="size-5 transition-transform group-data-[state=open]:rotate-180"
|
||||
aria-hidden
|
||||
/>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<ul className="divide-y">
|
||||
{items.map((item) => (
|
||||
<ItemRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
updateItem={updateItem}
|
||||
isSaving={savingIds.includes(item.id)}
|
||||
{...editingProps(item.id)}
|
||||
onMove={() => onMove(item)}
|
||||
onDelete={() => onDelete(item)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
<Card className="gap-0 rounded-none border-x-0 border-b-0 py-0 shadow-none">
|
||||
<ul className="divide-y">
|
||||
{items.map((item) => (
|
||||
<ItemRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
updateItem={updateItem}
|
||||
isSaving={savingIds.includes(item.id)}
|
||||
onEdit={() => onEdit(item)}
|
||||
onMove={() => onMove(item)}
|
||||
onDelete={() => onDelete(item)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
</Card>
|
||||
</CollapsibleContent>
|
||||
</Card>
|
||||
</section>
|
||||
</Collapsible>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { PlusIcon, SearchIcon } from 'lucide-react'
|
||||
import { type ClipboardEvent, useState } from 'react'
|
||||
import { Loader2Icon, MicIcon, PlusIcon } from 'lucide-react'
|
||||
import { type ClipboardEvent, useEffect, useRef, useState } from 'react'
|
||||
import { useForm, useWatch } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { z } from 'zod'
|
||||
@@ -14,10 +14,19 @@ import {
|
||||
InputGroupButton,
|
||||
InputGroupInput,
|
||||
} from '@/components/ui/input-group'
|
||||
import { isOptimisticItem, useCreateItem, useItems, useUpdateItem } from '@/hooks/use-items'
|
||||
import { useDictation } from '@/hooks/use-dictation'
|
||||
import {
|
||||
isOptimisticItem,
|
||||
useCreateItem,
|
||||
useItems,
|
||||
useRemoveItems,
|
||||
useUpdateItem,
|
||||
} from '@/hooks/use-items'
|
||||
import { useVoiceSplit } from '@/hooks/use-voice-split'
|
||||
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'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
// 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.
|
||||
@@ -33,6 +42,9 @@ type CreateItemFormProps = {
|
||||
autoFocus?: boolean
|
||||
}
|
||||
|
||||
/** How long the "Deshacer" of a dictation stays on screen. */
|
||||
const DICTATION_UNDO_MS = 8000
|
||||
|
||||
/** The input carries this id so it can be focused from outside the form (e.g. by the nav). */
|
||||
const NEW_ITEM_INPUT_ID = 'new-item-input'
|
||||
|
||||
@@ -64,15 +76,28 @@ function itemLimitError(item: PreviewItem): string | null {
|
||||
return null
|
||||
}
|
||||
|
||||
/** What adding a batch of items did, so a dictation can be undone. */
|
||||
type AddedItems = {
|
||||
/** Ids of the items created (failed ones are left out). */
|
||||
created: Promise<string[]>
|
||||
/** The previous quantity/notes of the pending items that were added to. */
|
||||
merged: { itemId: string; quantity: string | null; notes: string | null }[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Input to add items to a list. Submits with Enter or the button. The text is read
|
||||
* 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.
|
||||
*
|
||||
* The microphone dictates instead: the transcript is split into items by the API (with
|
||||
* AI) and each one goes through this same flow. "Deshacer" removes the whole dictation.
|
||||
*/
|
||||
export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProps) {
|
||||
const createItem = useCreateItem(listId)
|
||||
const updateItem = useUpdateItem(listId)
|
||||
const removeItems = useRemoveItems(listId)
|
||||
const voiceSplit = useVoiceSplit()
|
||||
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)
|
||||
@@ -86,8 +111,22 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
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))
|
||||
// A dictation finishes after a request: by then the list may have changed.
|
||||
const existingRef = useRef(existing)
|
||||
existingRef.current = existing
|
||||
|
||||
const dictation = useDictation({ onTranscript: (transcript) => void addDictation(transcript) })
|
||||
const processing = voiceSplit.isPending
|
||||
const dictating = dictation.listening || processing
|
||||
|
||||
// The partial transcript is shown in the input while the user talks.
|
||||
useEffect(() => {
|
||||
if (dictation.listening) form.setValue('name', dictation.interim)
|
||||
}, [dictation.listening, dictation.interim, form])
|
||||
|
||||
const preview = readItems(text, literal, existing)
|
||||
const showPreview =
|
||||
!dictating &&
|
||||
text.trim() !== '' &&
|
||||
(literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate))
|
||||
|
||||
@@ -97,6 +136,58 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
form.setError('name', { message })
|
||||
}
|
||||
|
||||
/** Adds the items, or adds to the pending ones they repeat. A failed one comes back to the input. */
|
||||
const addItems = (toAdd: PreviewItem[]): AddedItems => {
|
||||
const created: Promise<string | null>[] = []
|
||||
const merged: AddedItems['merged'] = []
|
||||
|
||||
for (const item of toAdd) {
|
||||
if (item.duplicate) {
|
||||
const patch = mergeInto(item.duplicate, item)
|
||||
if (patch.quantity !== undefined || patch.notes !== undefined) {
|
||||
updateItem.mutate({ itemId: item.duplicate.id, ...patch })
|
||||
merged.push({
|
||||
itemId: item.duplicate.id,
|
||||
quantity: item.duplicate.quantity,
|
||||
notes: item.duplicate.notes,
|
||||
})
|
||||
}
|
||||
toast(
|
||||
patch.quantity
|
||||
? `Se sumó a «${item.duplicate.name}» (${patch.quantity})`
|
||||
: `«${item.duplicate.name}» ya está en la lista`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
created.push(
|
||||
createItem
|
||||
.mutateAsync({
|
||||
name: item.name,
|
||||
quantity: item.quantity ?? undefined,
|
||||
notes: item.notes ?? undefined,
|
||||
})
|
||||
.then(
|
||||
(createdItem) => createdItem.id,
|
||||
(error) => {
|
||||
restoreText(
|
||||
item.source,
|
||||
error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos añadir el artículo.',
|
||||
)
|
||||
return null
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
created: Promise.all(created).then((ids) => ids.filter((id): id is string => id !== null)),
|
||||
merged,
|
||||
}
|
||||
}
|
||||
|
||||
// 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) => {
|
||||
@@ -112,35 +203,52 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
setLiteralText(null)
|
||||
form.setFocus('name')
|
||||
|
||||
for (const item of toAdd) {
|
||||
if (item.duplicate) {
|
||||
const patch = mergeInto(item.duplicate, item)
|
||||
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.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos añadir el artículo.',
|
||||
),
|
||||
},
|
||||
)
|
||||
}
|
||||
addItems(toAdd)
|
||||
})
|
||||
|
||||
/**
|
||||
* The API splits the transcript into one string per item and each one is read by the
|
||||
* usual parser. If the request fails, the whole transcript is added as a single item.
|
||||
*/
|
||||
const addDictation = async (transcript: string) => {
|
||||
form.reset()
|
||||
setLiteralText(null)
|
||||
|
||||
let toAdd: PreviewItem[]
|
||||
try {
|
||||
const { items: spoken } = await voiceSplit.mutateAsync({ text: transcript })
|
||||
toAdd = readItems(spoken.join('; '), false, existingRef.current)
|
||||
} catch {
|
||||
toAdd = readItems(transcript, true, existingRef.current)
|
||||
}
|
||||
|
||||
if (toAdd.length === 0) return
|
||||
|
||||
const limitError = toAdd.map(itemLimitError).find(Boolean)
|
||||
if (limitError) {
|
||||
form.setValue('name', transcript)
|
||||
form.setError('name', { message: limitError })
|
||||
return
|
||||
}
|
||||
|
||||
const { created, merged } = addItems(toAdd)
|
||||
const createdIds = await created
|
||||
const count = createdIds.length + merged.length
|
||||
if (count === 0) return
|
||||
|
||||
toast(`Se ${count === 1 ? 'agregó 1 producto' : `agregaron ${count} productos`}`, {
|
||||
// Longer than a plain toast: the user has to check what was understood first.
|
||||
duration: DICTATION_UNDO_MS,
|
||||
action: {
|
||||
label: 'Deshacer',
|
||||
onClick: () => {
|
||||
void removeItems(createdIds)
|
||||
for (const previous of merged) updateItem.mutate(previous)
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// 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')
|
||||
@@ -161,31 +269,24 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
})
|
||||
}
|
||||
|
||||
const micLabel = processing
|
||||
? 'Procesando el dictado'
|
||||
: dictation.listening
|
||||
? 'Dejar de escuchar'
|
||||
: 'Dictar productos'
|
||||
|
||||
return (
|
||||
<form onSubmit={onSubmit}>
|
||||
<Field data-invalid={!!form.formState.errors.name}>
|
||||
<InputGroup className="bg-card h-14 rounded-full shadow-xs dark:bg-card">
|
||||
<InputGroupAddon className="pl-5">
|
||||
<SearchIcon className="size-5" />
|
||||
</InputGroupAddon>
|
||||
<InputGroupInput
|
||||
id={NEW_ITEM_INPUT_ID}
|
||||
aria-label="Nuevo artículo"
|
||||
aria-invalid={!!form.formState.errors.name}
|
||||
autoComplete="off"
|
||||
placeholder="Ej: 400 g de jamón. Feteado fino"
|
||||
autoFocus={autoFocus}
|
||||
className="text-base"
|
||||
onPaste={onPaste}
|
||||
{...form.register('name')}
|
||||
/>
|
||||
<InputGroupAddon align="inline-end" className="pr-2">
|
||||
<InputGroupAddon className="pl-1.5">
|
||||
<InputGroupButton
|
||||
type="submit"
|
||||
variant="default"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="Agregar"
|
||||
className="size-10 rounded-full"
|
||||
disabled={dictating}
|
||||
className="text-muted-foreground hover:text-foreground size-11 rounded-full"
|
||||
// Tapping the button must not steal the focus from the input: on mobile that
|
||||
// would close the keyboard between one item and the next.
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
@@ -193,8 +294,52 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
<PlusIcon className="size-5" strokeWidth={2.5} />
|
||||
</InputGroupButton>
|
||||
</InputGroupAddon>
|
||||
<InputGroupInput
|
||||
id={NEW_ITEM_INPUT_ID}
|
||||
aria-label="Nuevo artículo"
|
||||
aria-invalid={!!form.formState.errors.name}
|
||||
aria-describedby={dictation.error ? 'dictation-error' : undefined}
|
||||
autoComplete="off"
|
||||
placeholder={
|
||||
dictation.listening ? 'Escuchando…' : 'Agregar… ej: 400 g de jamón. Feteado fino'
|
||||
}
|
||||
autoFocus={autoFocus}
|
||||
readOnly={dictating}
|
||||
className="text-base"
|
||||
onPaste={onPaste}
|
||||
{...form.register('name', { onChange: dictation.clearError })}
|
||||
/>
|
||||
{dictation.supported && (
|
||||
<InputGroupAddon align="inline-end" className="pr-1.5">
|
||||
<InputGroupButton
|
||||
type="button"
|
||||
variant={dictation.listening ? 'default' : 'secondary'}
|
||||
size="icon-sm"
|
||||
aria-label={micLabel}
|
||||
aria-pressed={dictation.listening}
|
||||
disabled={processing}
|
||||
className={cn(
|
||||
'relative size-11 rounded-full',
|
||||
dictation.listening &&
|
||||
'after:bg-primary/30 after:absolute after:inset-0 after:-z-10 after:rounded-full motion-safe:after:animate-ping',
|
||||
)}
|
||||
onClick={dictation.listening ? dictation.stop : dictation.start}
|
||||
>
|
||||
{processing ? (
|
||||
<Loader2Icon className="size-5 animate-spin" />
|
||||
) : (
|
||||
<MicIcon className="size-5" />
|
||||
)}
|
||||
</InputGroupButton>
|
||||
</InputGroupAddon>
|
||||
)}
|
||||
</InputGroup>
|
||||
<FieldError errors={[form.formState.errors.name]} className="px-5" />
|
||||
{dictation.error && (
|
||||
<p id="dictation-error" className="text-muted-foreground px-5 text-sm" aria-live="polite">
|
||||
{dictation.error}
|
||||
</p>
|
||||
)}
|
||||
{showPreview && (
|
||||
<ItemInputPreview
|
||||
items={preview}
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import type { Ref } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Field, FieldError } from '@/components/ui/field'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import type { useUpdateItem } from '@/hooks/use-items'
|
||||
|
||||
const itemDetailsSchema = z.object({
|
||||
// Free text so "2 kg" works; the API trims it and an empty value clears it.
|
||||
quantity: z.string().trim().max(40, 'Máximo 40 caracteres'),
|
||||
notes: z.string().trim().max(280, 'Máximo 280 caracteres'),
|
||||
})
|
||||
|
||||
type ItemDetailsValues = z.infer<typeof itemDetailsSchema>
|
||||
|
||||
type ItemEditorProps = {
|
||||
item: ListItem
|
||||
updateItem: ReturnType<typeof useUpdateItem>
|
||||
onClose: () => void
|
||||
/**
|
||||
* Receives the quantity input, so the row can focus it synchronously from the
|
||||
* gesture that opened the editor (iOS only shows the keyboard that way).
|
||||
*/
|
||||
quantityInputRef?: Ref<HTMLInputElement>
|
||||
}
|
||||
|
||||
/**
|
||||
* Inline editor for an item's quantity and notes, shown right below its row.
|
||||
* Opened by swiping the row to the left or right-clicking it.
|
||||
*/
|
||||
export function ItemEditor({ item, updateItem, onClose, quantityInputRef }: ItemEditorProps) {
|
||||
// The editor only exists while open, so it always starts from the current
|
||||
// values (including another member's edit received over SSE).
|
||||
const form = useForm<ItemDetailsValues>({
|
||||
resolver: zodResolver(itemDetailsSchema),
|
||||
defaultValues: { quantity: item.quantity ?? '', notes: item.notes ?? '' },
|
||||
})
|
||||
|
||||
const { ref: registerQuantityRef, ...quantityField } = form.register('quantity')
|
||||
|
||||
const onSubmit = form.handleSubmit((values) => {
|
||||
updateItem.mutate(
|
||||
{ itemId: item.id, quantity: values.quantity || null, notes: values.notes || null },
|
||||
{
|
||||
// The row already shows the new values optimistically, so on success
|
||||
// nothing else is left to do. On error the hook reports the problem
|
||||
// details and the editor stays open, keeping the typed text for a retry.
|
||||
onSuccess: onClose,
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={onSubmit}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== 'Escape') return
|
||||
event.preventDefault()
|
||||
onClose()
|
||||
}}
|
||||
className="bg-muted/40 flex flex-col gap-3 border-t px-4 py-3"
|
||||
>
|
||||
<Field data-invalid={!!form.formState.errors.quantity}>
|
||||
<Input
|
||||
aria-label="Cantidad"
|
||||
placeholder="Cantidad (ej. 2)"
|
||||
autoComplete="off"
|
||||
autoFocus
|
||||
aria-invalid={!!form.formState.errors.quantity}
|
||||
className="bg-card"
|
||||
{...quantityField}
|
||||
ref={(element) => {
|
||||
registerQuantityRef(element)
|
||||
if (typeof quantityInputRef === 'function') quantityInputRef(element)
|
||||
else if (quantityInputRef) quantityInputRef.current = element
|
||||
}}
|
||||
/>
|
||||
<FieldError errors={[form.formState.errors.quantity]} />
|
||||
</Field>
|
||||
<Field data-invalid={!!form.formState.errors.notes}>
|
||||
<Textarea
|
||||
aria-label="Notas"
|
||||
placeholder="Notas (opcional)"
|
||||
rows={2}
|
||||
aria-invalid={!!form.formState.errors.notes}
|
||||
className="bg-card min-h-12"
|
||||
{...form.register('notes')}
|
||||
/>
|
||||
<FieldError errors={[form.formState.errors.notes]} />
|
||||
</Field>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button type="submit" disabled={updateItem.isPending}>
|
||||
Guardar
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import { splitItems } from '@/lib/items'
|
||||
|
||||
import { BoughtItemList } from './bought-item-list'
|
||||
import { ItemRow } from './item-row'
|
||||
import { ItemSheet } from './item-sheet'
|
||||
import { MoveItemDialog } from './move-item-dialog'
|
||||
|
||||
type ItemListProps = {
|
||||
@@ -27,7 +28,7 @@ type ItemListProps = {
|
||||
|
||||
/**
|
||||
* Items loaded from the API, pending ones first. Tapping an item marks it as
|
||||
* bought; bought items move to a collapsible "Comprados" card below
|
||||
* bought; bought items move to a collapsible "Comprados (N)" section at the end
|
||||
* and are only shown on the day they were bought.
|
||||
*/
|
||||
export function ItemList({ listId }: ItemListProps) {
|
||||
@@ -38,7 +39,7 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
// Just-deleted items stay hidden while they can still be restored.
|
||||
const deletingIds = usePendingDeletions()
|
||||
const today = useToday()
|
||||
// Only one row shows its inline editor at a time: opening another closes it.
|
||||
// The item whose edit sheet is open, by id so the sheet shows its live values.
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
// The item whose "move to another list" dialog is open.
|
||||
const [movingItem, setMovingItem] = useState<ListItem | null>(null)
|
||||
@@ -53,12 +54,6 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
setMovingItem(item)
|
||||
}
|
||||
|
||||
const editingProps = (itemId: string) => ({
|
||||
editing: editingId === itemId,
|
||||
onEditingChange: (editing: boolean) =>
|
||||
setEditingId((current) => (editing ? itemId : current === itemId ? null : current)),
|
||||
})
|
||||
|
||||
// Live updates: another member adds or buys an item and this list refreshes.
|
||||
useListEvents(listId)
|
||||
|
||||
@@ -90,6 +85,9 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
today,
|
||||
)
|
||||
|
||||
const editingItem =
|
||||
items.find((item) => item.id === editingId && !deletingIds.has(item.id)) ?? null
|
||||
|
||||
if (pending.length === 0 && boughtToday.length === 0) {
|
||||
return (
|
||||
<Card>
|
||||
@@ -119,7 +117,7 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
item={item}
|
||||
updateItem={updateItem}
|
||||
isSaving={savingIds.includes(item.id)}
|
||||
{...editingProps(item.id)}
|
||||
onEdit={() => setEditingId(item.id)}
|
||||
onMove={() => openMoveDialog(item)}
|
||||
onDelete={() => handleDelete(item)}
|
||||
/>
|
||||
@@ -133,12 +131,18 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
items={boughtToday}
|
||||
updateItem={updateItem}
|
||||
savingIds={savingIds}
|
||||
editingProps={editingProps}
|
||||
onEdit={(item) => setEditingId(item.id)}
|
||||
onMove={openMoveDialog}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
)}
|
||||
|
||||
<ItemSheet
|
||||
item={editingItem}
|
||||
updateItem={updateItem}
|
||||
onClose={() => setEditingId(null)}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
<MoveItemDialog listId={listId} item={movingItem} onClose={() => setMovingItem(null)} />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { CheckIcon, FolderInputIcon, PencilIcon, Trash2Icon } from 'lucide-react'
|
||||
import { type PointerEvent, useRef, useState } from 'react'
|
||||
import { flushSync } from 'react-dom'
|
||||
|
||||
import { ItemEditor } from '@/components/items/item-editor'
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
@@ -20,9 +18,8 @@ export type ItemRowProps = {
|
||||
updateItem: ReturnType<typeof useUpdateItem>
|
||||
/** This item's bought state is being saved; only this row waits for it. */
|
||||
isSaving: boolean
|
||||
/** The inline editor of this row is open (only one row edits at a time). */
|
||||
editing: boolean
|
||||
onEditingChange: (editing: boolean) => void
|
||||
/** Opens the edit sheet for this item. */
|
||||
onEdit: () => void
|
||||
/** Opens the "move to another list" dialog for this item. */
|
||||
onMove: () => void
|
||||
/** Deletes the item (it can be undone for a few seconds). */
|
||||
@@ -65,40 +62,18 @@ function swipeAction(dx: number): SwipeAction | null {
|
||||
}
|
||||
|
||||
/** A single item row inside a grouped card: tapping it toggles its bought state. */
|
||||
export function ItemRow({
|
||||
item,
|
||||
updateItem,
|
||||
isSaving,
|
||||
editing,
|
||||
onEditingChange,
|
||||
onMove,
|
||||
onDelete,
|
||||
}: ItemRowProps) {
|
||||
export function ItemRow({ item, updateItem, isSaving, onEdit, onMove, onDelete }: ItemRowProps) {
|
||||
const [dragX, setDragX] = useState(0)
|
||||
const swipeStart = useRef<{ x: number; y: number } | null>(null)
|
||||
// Set once a drag passes a threshold: releasing the finger then runs that
|
||||
// action, and the click that the touch may fire right after is ignored.
|
||||
const swiped = useRef<SwipeAction | null>(null)
|
||||
const [action, setAction] = useState<SwipeAction | null>(null)
|
||||
const quantityInputRef = useRef<HTMLInputElement>(null)
|
||||
// "Editar" was picked in the context menu: the editor's input takes the focus
|
||||
// once the menu closes, since the menu keeps it while it is open.
|
||||
const focusEditorOnMenuClose = useRef(false)
|
||||
|
||||
// A placeholder has no server id yet, so it cannot be toggled or edited.
|
||||
const editable = !isSaving && !isOptimisticItem(item)
|
||||
const quantity = quantityLabel(item.quantity)
|
||||
|
||||
/**
|
||||
* Opens the editor and focuses its first input in the same event handler:
|
||||
* iOS only shows the keyboard for a focus made synchronously inside a user
|
||||
* gesture, so the editor is rendered with `flushSync` first.
|
||||
*/
|
||||
const openEditor = () => {
|
||||
flushSync(() => onEditingChange(true))
|
||||
quantityInputRef.current?.focus()
|
||||
}
|
||||
|
||||
const handlePointerDown = (event: PointerEvent<HTMLButtonElement>) => {
|
||||
// Mice use the right-click menu; only touch drags are tracked here.
|
||||
swiped.current = null
|
||||
@@ -126,7 +101,7 @@ export function ItemRow({
|
||||
swipeStart.current = null
|
||||
setDragX(0)
|
||||
setAction(null)
|
||||
if (released === 'edit') openEditor()
|
||||
if (released === 'edit') onEdit()
|
||||
if (released === 'move') onMove()
|
||||
if (released === 'delete') onDelete()
|
||||
}
|
||||
@@ -183,7 +158,6 @@ export function ItemRow({
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={item.completed}
|
||||
aria-expanded={editing}
|
||||
disabled={!editable}
|
||||
onClick={() => {
|
||||
if (swiped.current) {
|
||||
@@ -231,25 +205,15 @@ export function ItemRow({
|
||||
)}
|
||||
</span>
|
||||
{quantity && (
|
||||
<span className="text-muted-foreground shrink-0 text-sm">{quantity}</span>
|
||||
<span className="bg-accent text-accent-foreground shrink-0 rounded-md px-2 py-0.5 text-sm font-semibold">
|
||||
{quantity}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</ContextMenuTrigger>
|
||||
{/* Right-click is the desktop equivalent of the swipes. */}
|
||||
<ContextMenuContent
|
||||
onCloseAutoFocus={(event) => {
|
||||
if (!focusEditorOnMenuClose.current) return
|
||||
focusEditorOnMenuClose.current = false
|
||||
event.preventDefault()
|
||||
quantityInputRef.current?.focus()
|
||||
}}
|
||||
>
|
||||
<ContextMenuItem
|
||||
onSelect={() => {
|
||||
focusEditorOnMenuClose.current = true
|
||||
onEditingChange(true)
|
||||
}}
|
||||
>
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onSelect={onEdit}>
|
||||
<PencilIcon />
|
||||
Editar
|
||||
</ContextMenuItem>
|
||||
@@ -265,14 +229,6 @@ export function ItemRow({
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
</div>
|
||||
{editing && (
|
||||
<ItemEditor
|
||||
item={item}
|
||||
updateItem={updateItem}
|
||||
onClose={() => onEditingChange(false)}
|
||||
quantityInputRef={quantityInputRef}
|
||||
/>
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
245
apps/web/src/components/items/item-sheet.tsx
Normal file
245
apps/web/src/components/items/item-sheet.tsx
Normal file
@@ -0,0 +1,245 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { MinusIcon, PlusIcon, Trash2Icon, XIcon } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { useForm, useWatch } from 'react-hook-form'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Field, FieldError, FieldLabel } from '@/components/ui/field'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
Sheet,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetTitle,
|
||||
} from '@/components/ui/sheet'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import type { useUpdateItem } from '@/hooks/use-items'
|
||||
import {
|
||||
amountValue,
|
||||
EDITOR_UNITS,
|
||||
fromEditableQuantity,
|
||||
stepAmount,
|
||||
toEditableQuantity,
|
||||
} from '@/lib/item-quantity'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const itemSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1, 'Escribe un nombre').max(120, 'Máximo 120 caracteres'),
|
||||
amount: z.string().trim().max(30, 'Máximo 30 caracteres'),
|
||||
unit: z.string(),
|
||||
notes: z.string().trim().max(280, 'Máximo 280 caracteres'),
|
||||
})
|
||||
.refine((value) => (fromEditableQuantity(value)?.length ?? 0) <= 40, {
|
||||
path: ['amount'],
|
||||
message: 'La cantidad es demasiado larga',
|
||||
})
|
||||
|
||||
type ItemValues = z.infer<typeof itemSchema>
|
||||
|
||||
type ItemSheetProps = {
|
||||
/** The item being edited; `null` keeps the sheet closed. */
|
||||
item: ListItem | null
|
||||
updateItem: ReturnType<typeof useUpdateItem>
|
||||
onClose: () => void
|
||||
/** Deletes the item (undoable for a few seconds) and closes the sheet. */
|
||||
onDelete: (item: ListItem) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Bottom sheet to edit an item: name, quantity (− / + and a unit), note, delete and
|
||||
* save. Opened by swiping the row to the left or with "Editar" in its right-click menu.
|
||||
*/
|
||||
export function ItemSheet({ item, updateItem, onClose, onDelete }: ItemSheetProps) {
|
||||
// While the sheet slides out `item` is already `null`: keep showing the last one.
|
||||
const [shown, setShown] = useState(item)
|
||||
if (item && item !== shown) setShown(item)
|
||||
|
||||
return (
|
||||
<Sheet open={item !== null} onOpenChange={(open) => !open && onClose()}>
|
||||
<SheetContent
|
||||
side="bottom"
|
||||
showCloseButton={false}
|
||||
className="max-h-[90dvh] gap-0 overflow-y-auto rounded-t-3xl px-5 pt-3 pb-[calc(1.25rem+env(safe-area-inset-bottom))] sm:mx-auto sm:max-w-lg"
|
||||
>
|
||||
<div className="bg-muted-foreground/30 mx-auto mb-3 h-1 w-10 rounded-full" aria-hidden />
|
||||
{/* Mounted per item so the form always starts from its current values. */}
|
||||
{shown && (
|
||||
<ItemForm
|
||||
key={shown.id}
|
||||
item={shown}
|
||||
updateItem={updateItem}
|
||||
onClose={onClose}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
)}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemForm({ item, updateItem, onClose, onDelete }: ItemSheetProps & { item: ListItem }) {
|
||||
const form = useForm<ItemValues>({
|
||||
resolver: zodResolver(itemSchema),
|
||||
defaultValues: {
|
||||
name: item.name,
|
||||
...toEditableQuantity(item.quantity),
|
||||
notes: item.notes ?? '',
|
||||
},
|
||||
})
|
||||
|
||||
const [amount, unit] = useWatch({ control: form.control, name: ['amount', 'unit'] })
|
||||
const numeric = amountValue(amount) !== null
|
||||
// A unit the selector does not offer ("paquete") stays available, so it is not lost.
|
||||
const units = EDITOR_UNITS.some((option) => option.value === unit)
|
||||
? EDITOR_UNITS
|
||||
: [...EDITOR_UNITS, { value: unit, label: unit }]
|
||||
|
||||
const step = (direction: 1 | -1) =>
|
||||
form.setValue('amount', stepAmount(amount, unit, direction), { shouldDirty: true })
|
||||
|
||||
const onSubmit = form.handleSubmit((values) => {
|
||||
updateItem.mutate(
|
||||
{
|
||||
itemId: item.id,
|
||||
name: values.name,
|
||||
quantity: fromEditableQuantity(values),
|
||||
notes: values.notes || null,
|
||||
},
|
||||
// The list already shows the new values optimistically; on error the hook reports
|
||||
// the problem and the sheet stays open with what was typed.
|
||||
{ onSuccess: onClose },
|
||||
)
|
||||
})
|
||||
|
||||
const errors = form.formState.errors
|
||||
|
||||
return (
|
||||
<form onSubmit={onSubmit} className="flex flex-col gap-5">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<SheetTitle className="text-lg font-semibold">Editar producto</SheetTitle>
|
||||
<SheetClose asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="icon"
|
||||
className="size-11 rounded-full"
|
||||
aria-label="Cerrar"
|
||||
>
|
||||
<XIcon className="size-5" />
|
||||
</Button>
|
||||
</SheetClose>
|
||||
</div>
|
||||
<SheetDescription className="sr-only">
|
||||
Cambia el nombre, la cantidad o la nota de «{item.name}».
|
||||
</SheetDescription>
|
||||
|
||||
<Field data-invalid={!!errors.name}>
|
||||
<FieldLabel htmlFor="item-name">Producto</FieldLabel>
|
||||
<Input
|
||||
id="item-name"
|
||||
autoComplete="off"
|
||||
aria-invalid={!!errors.name}
|
||||
className="bg-card h-12 rounded-xl px-4"
|
||||
{...form.register('name')}
|
||||
/>
|
||||
<FieldError errors={[errors.name]} />
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!errors.amount}>
|
||||
<FieldLabel htmlFor="item-amount">Cantidad</FieldLabel>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="bg-card flex h-12 items-center overflow-hidden rounded-xl border">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="h-full w-12 rounded-none"
|
||||
aria-label="Restar"
|
||||
disabled={!numeric || amount === stepAmount(amount, unit, -1)}
|
||||
onClick={() => step(-1)}
|
||||
>
|
||||
<MinusIcon className="size-5" />
|
||||
</Button>
|
||||
<input
|
||||
id="item-amount"
|
||||
inputMode="decimal"
|
||||
autoComplete="off"
|
||||
aria-invalid={!!errors.amount}
|
||||
className="h-full w-16 border-x bg-transparent text-center text-base outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
|
||||
{...form.register('amount')}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="h-full w-12 rounded-none"
|
||||
aria-label="Sumar"
|
||||
onClick={() => step(1)}
|
||||
>
|
||||
<PlusIcon className="size-5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<fieldset className="flex flex-wrap gap-2">
|
||||
<legend className="sr-only">Unidad</legend>
|
||||
{units.map((option) => {
|
||||
const selected = option.value === unit
|
||||
|
||||
return (
|
||||
<button
|
||||
key={option.value || 'count'}
|
||||
type="button"
|
||||
aria-pressed={selected}
|
||||
onClick={() => form.setValue('unit', option.value, { shouldDirty: true })}
|
||||
className={cn(
|
||||
'focus-visible:ring-ring/50 h-11 min-w-11 rounded-xl border px-3 text-base transition-colors outline-none focus-visible:ring-3',
|
||||
selected
|
||||
? 'bg-accent text-accent-foreground border-transparent font-semibold'
|
||||
: 'bg-card hover:bg-muted',
|
||||
)}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</fieldset>
|
||||
</div>
|
||||
<FieldError errors={[errors.amount]} />
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!errors.notes}>
|
||||
<FieldLabel htmlFor="item-notes">Nota</FieldLabel>
|
||||
<Textarea
|
||||
id="item-notes"
|
||||
rows={2}
|
||||
placeholder="Marca, tipo, corte…"
|
||||
aria-invalid={!!errors.notes}
|
||||
className="bg-card min-h-16 rounded-xl px-4 py-3"
|
||||
{...form.register('notes')}
|
||||
/>
|
||||
<FieldError errors={[errors.notes]} />
|
||||
</Field>
|
||||
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="text-destructive hover:text-destructive size-12 rounded-xl"
|
||||
aria-label={`Eliminar «${item.name}»`}
|
||||
onClick={() => onDelete(item)}
|
||||
>
|
||||
<Trash2Icon className="size-5" />
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
className="h-12 flex-1 rounded-xl text-base font-semibold"
|
||||
disabled={updateItem.isPending}
|
||||
>
|
||||
Guardar
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -8,9 +8,10 @@ type ListProgressProps = {
|
||||
}
|
||||
|
||||
/**
|
||||
* "4 pendientes · 7 comprados" plus a bar for today's progress. Reads the items
|
||||
* query the list already loads, so it adds no request; renders nothing until
|
||||
* the items are in or when the list is empty.
|
||||
* A bar for today's progress: items bought today over the items shown (pending plus
|
||||
* bought today). The "X pendientes · Y comprados" count lives in the header. Reads
|
||||
* the items query the list already loads, so it adds no request; renders nothing
|
||||
* until the items are in or when the list is empty.
|
||||
*/
|
||||
export function ListProgress({ listId }: ListProgressProps) {
|
||||
const { data: items } = useItems(listId)
|
||||
@@ -24,16 +25,10 @@ export function ListProgress({ listId }: ListProgressProps) {
|
||||
if (total === 0) return null
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<p className="text-muted-foreground">
|
||||
{pending.length} {pending.length === 1 ? 'pendiente' : 'pendientes'} · {boughtToday.length}{' '}
|
||||
{boughtToday.length === 1 ? 'comprado' : 'comprados'}
|
||||
</p>
|
||||
<Progress
|
||||
value={(boughtToday.length / total) * 100}
|
||||
aria-label="Progreso de la compra"
|
||||
className="h-2"
|
||||
/>
|
||||
</div>
|
||||
<Progress
|
||||
value={(boughtToday.length / total) * 100}
|
||||
aria-label={`Comprados ${boughtToday.length} de ${total}`}
|
||||
className="h-1.5"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query'
|
||||
import { Link, useMatch, useRouterState } from '@tanstack/react-router'
|
||||
import { ArrowLeftIcon, SettingsIcon } from 'lucide-react'
|
||||
|
||||
import { ListSwitcher } from '@/components/layout/list-switcher'
|
||||
import { sectionTitle } from '@/components/layout/nav-items'
|
||||
import { ThemeToggle } from '@/components/theme-toggle'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
@@ -45,8 +46,12 @@ export function AppHeader() {
|
||||
)}
|
||||
<div className="ml-auto flex shrink-0 items-center gap-1">
|
||||
{list && (
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<Link to="/lists/$listId/settings" params={{ listId: list.id }}>
|
||||
<Button variant="outline" size="sm" className="h-11 min-w-11" asChild>
|
||||
<Link
|
||||
to="/lists/$listId/settings"
|
||||
params={{ listId: list.id }}
|
||||
aria-label="Gestionar la lista"
|
||||
>
|
||||
<SettingsIcon className="size-4" />
|
||||
<span className="hidden sm:inline">Gestionar</span>
|
||||
</Link>
|
||||
@@ -63,14 +68,13 @@ function ListHeading({ list, showBack }: { list: HeaderList; showBack: boolean }
|
||||
return (
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
{showBack && (
|
||||
<Button variant="ghost" size="icon" className="-ml-2 size-8 shrink-0" asChild>
|
||||
<Button variant="ghost" size="icon" className="-ml-2 size-11 shrink-0" asChild>
|
||||
<Link to="/lists" aria-label="Volver a listas">
|
||||
<ArrowLeftIcon className="size-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
<h1 className="truncate text-sm font-medium">{list.name}</h1>
|
||||
{list.isPrimary && <Badge className="shrink-0">Principal</Badge>}
|
||||
<ListSwitcher list={list} />
|
||||
<Badge variant="secondary" className="hidden shrink-0 sm:inline-flex">
|
||||
{list.role === 'owner' ? 'Propietario' : 'Colaborador'}
|
||||
</Badge>
|
||||
|
||||
95
apps/web/src/components/layout/list-switcher.tsx
Normal file
95
apps/web/src/components/layout/list-switcher.tsx
Normal file
@@ -0,0 +1,95 @@
|
||||
import type { ShoppingListSummary } from '@superlist/shared'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { CheckIcon, ChevronDownIcon, ListIcon, StarIcon } from 'lucide-react'
|
||||
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { itemsQueryOptions } from '@/hooks/use-items'
|
||||
import { useLists } from '@/hooks/use-lists'
|
||||
import { useToday } from '@/hooks/use-today'
|
||||
import { splitItems } from '@/lib/items'
|
||||
|
||||
type ListSwitcherProps = {
|
||||
list: Pick<ShoppingListSummary, 'id' | 'name'>
|
||||
}
|
||||
|
||||
/**
|
||||
* The open list's name with a "▾" that opens the user's lists (the same ones the
|
||||
* "Listas" tab shows), plus "X pendientes · Y comprados" below it. The primary list
|
||||
* opens on the home page, the others on their own page.
|
||||
*/
|
||||
export function ListSwitcher({ list }: ListSwitcherProps) {
|
||||
const { data: lists } = useLists()
|
||||
|
||||
return (
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<DropdownMenu>
|
||||
<h1 className="flex min-w-0">
|
||||
<DropdownMenuTrigger className="focus-visible:ring-ring/50 -ml-1 flex min-h-11 min-w-0 items-center gap-1 rounded-lg px-1 text-left text-xl leading-tight font-bold outline-none focus-visible:ring-3">
|
||||
<span className="truncate">{list.name}</span>
|
||||
<ChevronDownIcon className="size-5 shrink-0" aria-hidden />
|
||||
<span className="sr-only">: cambiar de lista</span>
|
||||
</DropdownMenuTrigger>
|
||||
</h1>
|
||||
<DropdownMenuContent align="start" className="w-64">
|
||||
<DropdownMenuLabel>Mis listas</DropdownMenuLabel>
|
||||
{lists?.map((option) => (
|
||||
<DropdownMenuItem key={option.id} asChild className="min-h-11">
|
||||
{option.isPrimary ? (
|
||||
<Link to="/">
|
||||
<ListOption list={option} current={option.id === list.id} />
|
||||
</Link>
|
||||
) : (
|
||||
<Link to="/lists/$listId" params={{ listId: option.id }}>
|
||||
<ListOption list={option} current={option.id === list.id} />
|
||||
</Link>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild className="min-h-11">
|
||||
<Link to="/lists">
|
||||
<ListIcon />
|
||||
Ver todas las listas
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<ListCounts listId={list.id} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ListOption({ list, current }: { list: ShoppingListSummary; current: boolean }) {
|
||||
return (
|
||||
<>
|
||||
<span className="min-w-0 flex-1 truncate">{list.name}</span>
|
||||
{list.isPrimary && <StarIcon aria-label="Principal" className="text-muted-foreground" />}
|
||||
{current && <CheckIcon aria-label="Lista actual" className="text-primary" />}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** "6 pendientes · 2 comprados", from the items query the page already loads. */
|
||||
function ListCounts({ listId }: { listId: string }) {
|
||||
const { data: items } = useQuery(itemsQueryOptions(listId))
|
||||
const today = useToday()
|
||||
|
||||
if (!items) return null
|
||||
|
||||
const { pending, boughtToday } = splitItems(items, today)
|
||||
|
||||
return (
|
||||
<p className="text-muted-foreground truncate text-sm leading-tight">
|
||||
{pending.length} {pending.length === 1 ? 'pendiente' : 'pendientes'} · {boughtToday.length}{' '}
|
||||
{boughtToday.length === 1 ? 'comprado' : 'comprados'}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
@@ -27,7 +27,7 @@ export function ThemeToggle() {
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="relative"
|
||||
className="relative size-11"
|
||||
aria-label={`Tema: ${current.label} — cambiar a ${next.label}`}
|
||||
onClick={() => setTheme(next.value)}
|
||||
>
|
||||
|
||||
131
apps/web/src/hooks/use-dictation.ts
Normal file
131
apps/web/src/hooks/use-dictation.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
/** The slice of the Web Speech API this hook uses (TypeScript's DOM lib does not ship it). */
|
||||
type SpeechRecognitionResultLike = { isFinal: boolean; 0: { transcript: string } }
|
||||
|
||||
type SpeechRecognitionLike = {
|
||||
lang: string
|
||||
interimResults: boolean
|
||||
continuous: boolean
|
||||
maxAlternatives: number
|
||||
onresult: ((event: { results: ArrayLike<SpeechRecognitionResultLike> }) => void) | null
|
||||
onerror: ((event: { error: string }) => void) | null
|
||||
onend: (() => void) | null
|
||||
start: () => void
|
||||
stop: () => void
|
||||
abort: () => void
|
||||
}
|
||||
|
||||
type SpeechRecognitionConstructor = new () => SpeechRecognitionLike
|
||||
|
||||
/** Errors that only mean "nothing was said" or "we stopped it": not worth telling. */
|
||||
const IGNORED_ERRORS = new Set(['no-speech', 'aborted'])
|
||||
|
||||
const ERROR_MESSAGES: Record<string, string> = {
|
||||
'not-allowed': 'Permite el acceso al micrófono para dictar.',
|
||||
'service-not-allowed': 'El dictado no está disponible en este navegador.',
|
||||
'audio-capture': 'No encontramos un micrófono.',
|
||||
network: 'Sin conexión para reconocer la voz.',
|
||||
}
|
||||
|
||||
/**
|
||||
* The browser's speech recognition, or `null` when there is none. An iOS home-screen
|
||||
* app exposes `webkitSpeechRecognition` but it does not work there, so it counts as
|
||||
* unsupported (the keyboard's own dictation still works).
|
||||
*/
|
||||
function getSpeechRecognition(): SpeechRecognitionConstructor | null {
|
||||
if (typeof window === 'undefined') return null
|
||||
|
||||
const iosStandalone = (navigator as Navigator & { standalone?: boolean }).standalone === true
|
||||
if (iosStandalone) return null
|
||||
|
||||
const speechWindow = window as Window & {
|
||||
SpeechRecognition?: SpeechRecognitionConstructor
|
||||
webkitSpeechRecognition?: SpeechRecognitionConstructor
|
||||
}
|
||||
|
||||
return speechWindow.SpeechRecognition ?? speechWindow.webkitSpeechRecognition ?? null
|
||||
}
|
||||
|
||||
type UseDictationOptions = {
|
||||
/** Called once with the whole transcript when the user stops talking. */
|
||||
onTranscript: (transcript: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Dictation with the Web Speech API in Argentine Spanish: one phrase per `start()`
|
||||
* (`continuous = false`), with the partial transcript in `interim` while the user
|
||||
* talks. `no-speech` and `aborted` are ignored; any other error is in `error`.
|
||||
*/
|
||||
export function useDictation({ onTranscript }: UseDictationOptions) {
|
||||
const [supported] = useState(() => getSpeechRecognition() !== null)
|
||||
const [listening, setListening] = useState(false)
|
||||
const [interim, setInterim] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const recognitionRef = useRef<SpeechRecognitionLike | null>(null)
|
||||
const onTranscriptRef = useRef(onTranscript)
|
||||
|
||||
useEffect(() => {
|
||||
onTranscriptRef.current = onTranscript
|
||||
})
|
||||
|
||||
// Leaving the page stops listening, without delivering a transcript.
|
||||
useEffect(() => () => recognitionRef.current?.abort(), [])
|
||||
|
||||
const start = useCallback(() => {
|
||||
const SpeechRecognition = getSpeechRecognition()
|
||||
if (!SpeechRecognition || recognitionRef.current) return
|
||||
|
||||
const recognition = new SpeechRecognition()
|
||||
recognition.lang = 'es-AR'
|
||||
recognition.interimResults = true
|
||||
recognition.continuous = false
|
||||
recognition.maxAlternatives = 1
|
||||
|
||||
let transcript = ''
|
||||
let failed = false
|
||||
|
||||
recognition.onresult = (event) => {
|
||||
// The results hold the whole phrase so far: final parts plus the guess in progress.
|
||||
transcript = Array.from(event.results, (result) => result[0].transcript)
|
||||
.join('')
|
||||
.trim()
|
||||
setInterim(transcript)
|
||||
}
|
||||
|
||||
recognition.onerror = (event) => {
|
||||
if (IGNORED_ERRORS.has(event.error)) return
|
||||
failed = true
|
||||
setError(ERROR_MESSAGES[event.error] ?? 'No pudimos reconocer la voz.')
|
||||
}
|
||||
|
||||
// Some browsers (iOS Safari) end without marking the last result as final, so
|
||||
// whatever was heard by then is the transcript.
|
||||
recognition.onend = () => {
|
||||
recognitionRef.current = null
|
||||
setListening(false)
|
||||
setInterim('')
|
||||
if (transcript && !failed) onTranscriptRef.current(transcript)
|
||||
}
|
||||
|
||||
setError(null)
|
||||
setInterim('')
|
||||
|
||||
try {
|
||||
recognition.start()
|
||||
} catch {
|
||||
setError('No pudimos empezar a escuchar.')
|
||||
return
|
||||
}
|
||||
|
||||
recognitionRef.current = recognition
|
||||
setListening(true)
|
||||
}, [])
|
||||
|
||||
/** Stops listening; what was heard so far is still delivered. */
|
||||
const stop = useCallback(() => recognitionRef.current?.stop(), [])
|
||||
|
||||
const clearError = useCallback(() => setError(null), [])
|
||||
|
||||
return { supported, listening, interim, error, start, stop, clearError }
|
||||
}
|
||||
@@ -86,6 +86,8 @@ export function useCreateItem(listId: string) {
|
||||
|
||||
type UpdateItemInput = {
|
||||
itemId: string
|
||||
/** New name; omitted to leave it untouched. */
|
||||
name?: string
|
||||
/** New bought state; omitted when only the details are being changed. */
|
||||
completed?: boolean
|
||||
/** New quantity (`null` clears it); omitted to leave it untouched. */
|
||||
@@ -104,7 +106,13 @@ export function useUpdateItem(listId: string) {
|
||||
return useMutation({
|
||||
mutationKey,
|
||||
mutationFn: (input: UpdateItemInput) => {
|
||||
const body: { completed?: boolean; quantity?: string | null; notes?: string | null } = {}
|
||||
const body: {
|
||||
name?: string
|
||||
completed?: boolean
|
||||
quantity?: string | null
|
||||
notes?: string | null
|
||||
} = {}
|
||||
if (input.name !== undefined) body.name = input.name
|
||||
if (input.completed !== undefined) body.completed = input.completed
|
||||
if (input.quantity !== undefined) body.quantity = input.quantity
|
||||
if (input.notes !== undefined) body.notes = input.notes
|
||||
@@ -114,7 +122,7 @@ export function useUpdateItem(listId: string) {
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
},
|
||||
onMutate: async ({ itemId, completed, quantity, notes }) => {
|
||||
onMutate: async ({ itemId, name, completed, quantity, notes }) => {
|
||||
// Cancel the outgoing refetch so it cannot overwrite our optimistic one.
|
||||
await queryClient.cancelQueries({ queryKey })
|
||||
|
||||
@@ -126,6 +134,7 @@ export function useUpdateItem(listId: string) {
|
||||
|
||||
return {
|
||||
...item,
|
||||
...(name !== undefined ? { name: name.trim() } : {}),
|
||||
...(completed !== undefined
|
||||
? { completed, boughtAt: completed ? new Date().toISOString() : null }
|
||||
: {}),
|
||||
@@ -260,3 +269,28 @@ export function useDeleteItem(listId: string) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes items right away, without the undo window of `useDeleteItem`: used to undo a
|
||||
* dictation, which is itself the undo. The rows leave the list at once.
|
||||
*/
|
||||
export function useRemoveItems(listId: string) {
|
||||
const queryClient = useQueryClient()
|
||||
const { queryKey } = itemsQueryOptions(listId)
|
||||
|
||||
return async (itemIds: string[]) => {
|
||||
const ids = new Set(itemIds)
|
||||
queryClient.setQueryData(queryKey, (items) => items?.filter((item) => !ids.has(item.id)))
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
itemIds.map((itemId) =>
|
||||
apiFetch<void>(`/lists/${listId}/items/${itemId}`, { method: 'DELETE' }),
|
||||
),
|
||||
)
|
||||
|
||||
if (results.some((result) => result.status === 'rejected')) {
|
||||
toast.error('No pudimos quitar todos los artículos.')
|
||||
await queryClient.invalidateQueries({ queryKey })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
20
apps/web/src/hooks/use-voice-split.ts
Normal file
20
apps/web/src/hooks/use-voice-split.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import type { VoiceSplitRequest, VoiceSplitResponse } from '@superlist/shared'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
|
||||
import { apiFetch } from '@/lib/api-client'
|
||||
|
||||
/**
|
||||
* Asks the API to split a dictated sentence into one string per item, each written the
|
||||
* way the item parser reads typed text. The API never fails because of the model (it
|
||||
* falls back to splitting on commas and "y"), so an error here means the request did not
|
||||
* get through.
|
||||
*/
|
||||
export function useVoiceSplit() {
|
||||
return useMutation({
|
||||
mutationFn: (input: VoiceSplitRequest) =>
|
||||
apiFetch<VoiceSplitResponse>('/voice/split', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
})
|
||||
}
|
||||
47
apps/web/src/lib/item-quantity.test.ts
Normal file
47
apps/web/src/lib/item-quantity.test.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { fromEditableQuantity, stepAmount, toEditableQuantity } from './item-quantity'
|
||||
|
||||
describe('toEditableQuantity', () => {
|
||||
it('splits a stored quantity into amount and unit', () => {
|
||||
expect(toEditableQuantity(null)).toEqual({ amount: '1', unit: '' })
|
||||
expect(toEditableQuantity('2')).toEqual({ amount: '2', unit: '' })
|
||||
expect(toEditableQuantity('1,5 l')).toEqual({ amount: '1,5', unit: 'l' })
|
||||
expect(toEditableQuantity('½ kg')).toEqual({ amount: '½', unit: 'kg' })
|
||||
expect(toEditableQuantity('2 paquetes')).toEqual({ amount: '2', unit: 'paquete' })
|
||||
})
|
||||
|
||||
it('keeps free text as the amount', () => {
|
||||
expect(toEditableQuantity('un par')).toEqual({ amount: 'un par', unit: '' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('stepAmount', () => {
|
||||
it('steps by one for counts and by bigger steps for measures', () => {
|
||||
expect(stepAmount('2', '', 1)).toBe('3')
|
||||
expect(stepAmount('2', '', -1)).toBe('1')
|
||||
expect(stepAmount('1', '', -1)).toBe('1')
|
||||
expect(stepAmount('400', 'g', 1)).toBe('500')
|
||||
expect(stepAmount('½', 'kg', 1)).toBe('1')
|
||||
expect(stepAmount('1', 'l', -1)).toBe('½')
|
||||
})
|
||||
|
||||
it('starts from one step when the amount is not a number', () => {
|
||||
expect(stepAmount('un par', '', 1)).toBe('1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('fromEditableQuantity', () => {
|
||||
it('stores the formatted quantity, and nothing for a plain one', () => {
|
||||
expect(fromEditableQuantity({ amount: '1', unit: '' })).toBeNull()
|
||||
expect(fromEditableQuantity({ amount: '', unit: 'kg' })).toBeNull()
|
||||
expect(fromEditableQuantity({ amount: '2', unit: '' })).toBe('2')
|
||||
expect(fromEditableQuantity({ amount: '1', unit: 'kg' })).toBe('1 kg')
|
||||
expect(fromEditableQuantity({ amount: '0.5', unit: 'kg' })).toBe('½ kg')
|
||||
expect(fromEditableQuantity({ amount: '2', unit: 'paquete' })).toBe('2 paquetes')
|
||||
})
|
||||
|
||||
it('keeps free text as typed', () => {
|
||||
expect(fromEditableQuantity({ amount: 'un par', unit: '' })).toBe('un par')
|
||||
})
|
||||
})
|
||||
64
apps/web/src/lib/item-quantity.ts
Normal file
64
apps/web/src/lib/item-quantity.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { formatQuantity, parseNumber, parseQuantity } from './natural-input/quantity'
|
||||
|
||||
/** Units offered by the item editor; `''` is a plain count ("un."). */
|
||||
export const EDITOR_UNITS = [
|
||||
{ value: '', label: 'un.' },
|
||||
{ value: 'g', label: 'g' },
|
||||
{ value: 'kg', label: 'kg' },
|
||||
{ value: 'ml', label: 'ml' },
|
||||
{ value: 'l', label: 'L' },
|
||||
] as const
|
||||
|
||||
/**
|
||||
* A quantity split into what the editor shows: the amount as text and the unit. A unit
|
||||
* the selector does not offer (`paquete`) is kept, so editing the amount does not lose it.
|
||||
* Free text that is not a quantity ("un par") goes into `amount` untouched.
|
||||
*/
|
||||
export type EditableQuantity = { amount: string; unit: string }
|
||||
|
||||
export function toEditableQuantity(quantity: string | null): EditableQuantity {
|
||||
if (!quantity?.trim()) return { amount: '1', unit: '' }
|
||||
|
||||
const parsed = parseQuantity(quantity)
|
||||
if (!parsed) return { amount: quantity.trim(), unit: '' }
|
||||
|
||||
return { amount: formatQuantity({ amount: parsed.amount, unit: null }), unit: parsed.unit ?? '' }
|
||||
}
|
||||
|
||||
/** The numeric value of the amount text, or `null` when it is free text. */
|
||||
export function amountValue(amount: string): number | null {
|
||||
return parseNumber(amount.trim())
|
||||
}
|
||||
|
||||
/** How much the − / + buttons change the amount for each unit. */
|
||||
export function amountStep(unit: string): number {
|
||||
if (unit === 'g' || unit === 'ml') return 100
|
||||
if (unit === 'kg' || unit === 'l') return 0.5
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
/** The amount after pressing − (`direction` −1) or + (1); never below one step. */
|
||||
export function stepAmount(amount: string, unit: string, direction: 1 | -1): string {
|
||||
const value = amountValue(amount) ?? 0
|
||||
const step = amountStep(unit)
|
||||
const next = Math.max(step, Math.round((value + direction * step) / step) * step)
|
||||
|
||||
return formatQuantity({ amount: next, unit: null })
|
||||
}
|
||||
|
||||
/**
|
||||
* The quantity to store for what the editor shows: `null` for a plain "1" (the same as no
|
||||
* quantity), the formatted quantity when the amount is a number ("2 paquetes", "½ kg") and
|
||||
* the text as typed otherwise.
|
||||
*/
|
||||
export function fromEditableQuantity({ amount, unit }: EditableQuantity): string | null {
|
||||
const text = amount.trim()
|
||||
if (!text) return null
|
||||
|
||||
const value = amountValue(text)
|
||||
if (value === null) return unit ? `${text} ${unit}` : text
|
||||
if (value === 1 && !unit) return null
|
||||
|
||||
return formatQuantity({ amount: value, unit: unit || null })
|
||||
}
|
||||
@@ -87,24 +87,36 @@ describe('splitItems', () => {
|
||||
})
|
||||
|
||||
describe('quantityLabel', () => {
|
||||
it('shows numeric quantities, with their unit when present', () => {
|
||||
expect(quantityLabel('2')).toBe('2')
|
||||
expect(quantityLabel('2 kg')).toBe('2 kg')
|
||||
expect(quantityLabel('1,5')).toBe('1,5')
|
||||
expect(quantityLabel(' 3 ')).toBe('3')
|
||||
it('shows quantities with a unit, litres in capitals', () => {
|
||||
expect(quantityLabel('2 l')).toBe('2 L')
|
||||
expect(quantityLabel('1,5 l')).toBe('1,5 L')
|
||||
expect(quantityLabel('1 kg')).toBe('1 kg')
|
||||
expect(quantityLabel('0,5')).toBe('0,5')
|
||||
expect(quantityLabel('½ kg')).toBe('½ kg')
|
||||
expect(quantityLabel('400 g')).toBe('400 g')
|
||||
expect(quantityLabel('1 lata')).toBe('1 lata')
|
||||
expect(quantityLabel('2 paquetes')).toBe('2 paquetes')
|
||||
})
|
||||
|
||||
it('hides empty, absent and plain-one quantities', () => {
|
||||
it('shows counts above one with a "×"', () => {
|
||||
expect(quantityLabel('2')).toBe('×2')
|
||||
expect(quantityLabel(' 12 ')).toBe('×12')
|
||||
expect(quantityLabel('1,5')).toBe('×1,5')
|
||||
})
|
||||
|
||||
it('shows a large bare amount as a weight, without "×"', () => {
|
||||
expect(quantityLabel('400')).toBe('400')
|
||||
})
|
||||
|
||||
it('hides empty quantities and counts up to one', () => {
|
||||
expect(quantityLabel(null)).toBeNull()
|
||||
expect(quantityLabel('')).toBeNull()
|
||||
expect(quantityLabel('1')).toBeNull()
|
||||
expect(quantityLabel(' 1 ')).toBeNull()
|
||||
expect(quantityLabel('0,5')).toBeNull()
|
||||
})
|
||||
|
||||
it('hides quantities whose text does not start with a number', () => {
|
||||
it('shows other free text only when it starts with a number', () => {
|
||||
expect(quantityLabel('2 + 200 g')).toBe('2 + 200 g')
|
||||
expect(quantityLabel('un par')).toBeNull()
|
||||
expect(quantityLabel('kg')).toBeNull()
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
|
||||
import { isSameLocalDay } from './dates'
|
||||
import { formatQuantity, parseQuantity } from './natural-input/quantity'
|
||||
|
||||
export type SplitItems = {
|
||||
/** Items still to buy, in the API's order (by `order`). */
|
||||
@@ -39,17 +40,32 @@ export function splitItems(items: ListItem[], now: Date): SplitItems {
|
||||
return { pending, boughtToday }
|
||||
}
|
||||
|
||||
/** Bare amounts from here up are weights ("400 de jamón"), not counts: no "×". */
|
||||
const BARE_WEIGHT_FROM = 50
|
||||
|
||||
/**
|
||||
* The quantity to show at the right of an item's name, or `null` when it must
|
||||
* stay hidden. A plain "1" adds no information, so it is hidden, as is anything
|
||||
* that does not start with a number ("un par"); every other quantity is shown,
|
||||
* including fractions and quantities with a unit ("½ kg", "1 kg", "0,5").
|
||||
* The quantity tag shown at the right of an item's name ("2 L", "×12", "1 kg"), or
|
||||
* `null` when it must stay hidden. It is shown when the quantity has a unit or is a
|
||||
* count above one; a plain "1" (or any count up to one) adds nothing. Free text that
|
||||
* does not start with a number ("un par") stays hidden, other free text ("2 + 200 g")
|
||||
* is shown as typed.
|
||||
*/
|
||||
export function quantityLabel(quantity: string | null): string | null {
|
||||
if (!quantity) return null
|
||||
|
||||
const trimmed = quantity.trim()
|
||||
if (!/^(\d|[½¼¾])/.test(trimmed)) return null
|
||||
const parsed = parseQuantity(trimmed)
|
||||
|
||||
return trimmed === '1' ? null : trimmed
|
||||
if (parsed) {
|
||||
if (parsed.unit) {
|
||||
const label = formatQuantity(parsed)
|
||||
return parsed.unit === 'l' ? label.replace(/ l$/, ' L') : label
|
||||
}
|
||||
if (parsed.amount <= 1) return null
|
||||
|
||||
const amount = formatQuantity(parsed)
|
||||
return parsed.amount >= BARE_WEIGHT_FROM ? amount : `×${amount}`
|
||||
}
|
||||
|
||||
return /^(\d|[½¼¾])/.test(trimmed) ? trimmed : null
|
||||
}
|
||||
|
||||
53
apps/web/src/lib/natural-input/voice-examples.test.ts
Normal file
53
apps/web/src/lib/natural-input/voice-examples.test.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { VOICE_SPLIT_EXAMPLES } from '@superlist/shared'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { parseItemInput } from './parse-item'
|
||||
import { parseQuantity } from './quantity'
|
||||
|
||||
/**
|
||||
* The dictation examples the API shows the model (`@superlist/shared` → voice.ts) must be
|
||||
* written exactly the way this parser reads them: each string is one item with the
|
||||
* expected quantity, unit and note.
|
||||
*/
|
||||
const EXPECTED: Record<
|
||||
string,
|
||||
{ name: string; amount: number | null; unit: string | null; notes: string | null }
|
||||
> = {
|
||||
'2 pascualinas': { name: 'Pascualinas', amount: 2, unit: null, notes: null },
|
||||
'1,5 kg de papas': { name: 'Papas', amount: 1.5, unit: 'kg', notes: null },
|
||||
'400 de jamon. Feteado fino': { name: 'Jamón', amount: 400, unit: null, notes: 'Feteado fino' },
|
||||
'1 lata de atun': { name: 'Atún', amount: 1, unit: 'lata', notes: null },
|
||||
'Queso crema. Solo si hay marca Tregar': {
|
||||
name: 'Queso crema',
|
||||
amount: null,
|
||||
unit: null,
|
||||
notes: 'Solo si hay marca Tregar',
|
||||
},
|
||||
'6 unidades de yogur': { name: 'Yogur', amount: 6, unit: null, notes: null },
|
||||
'400g de queso': { name: 'Queso', amount: 400, unit: 'g', notes: null },
|
||||
'Leche (descremada)': { name: 'Leche', amount: null, unit: null, notes: 'Descremada' },
|
||||
}
|
||||
|
||||
describe('dictation few-shot examples', () => {
|
||||
const items = VOICE_SPLIT_EXAMPLES.flatMap((example) => example.items)
|
||||
|
||||
it('has an expectation for every example item', () => {
|
||||
expect([...items].sort()).toEqual(Object.keys(EXPECTED).sort())
|
||||
})
|
||||
|
||||
it.each(items)('parses "%s" as one item with the expected quantity and note', (text) => {
|
||||
const parsed = parseItemInput(text)
|
||||
expect(parsed).toHaveLength(1)
|
||||
|
||||
const [item] = parsed
|
||||
const quantity = item.quantity ? parseQuantity(item.quantity) : null
|
||||
const expected = EXPECTED[text]
|
||||
|
||||
expect({
|
||||
name: item.name,
|
||||
amount: quantity?.amount ?? null,
|
||||
unit: quantity?.unit ?? null,
|
||||
notes: item.notes,
|
||||
}).toEqual(expected)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user