feat: add dictation
This commit is contained in:
17
.claude/launch.json
Normal file
17
.claude/launch.json
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"version": "0.0.1",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "web",
|
||||||
|
"runtimeExecutable": "bun",
|
||||||
|
"runtimeArgs": ["run", "dev", "--filter=@superlist/web"],
|
||||||
|
"port": 7153
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "api",
|
||||||
|
"runtimeExecutable": "bun",
|
||||||
|
"runtimeArgs": ["run", "dev", "--filter=@superlist/api"],
|
||||||
|
"port": 4100
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,12 +1,10 @@
|
|||||||
import { zodResolver } from '@hookform/resolvers/zod'
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
import type { ListItem } from '@superlist/shared'
|
|
||||||
import { Loader2Icon, MicIcon, PlusIcon } from 'lucide-react'
|
import { Loader2Icon, MicIcon, PlusIcon } from 'lucide-react'
|
||||||
import { type ClipboardEvent, useEffect, useRef, useState } from 'react'
|
import { type ClipboardEvent, useEffect, useState } from 'react'
|
||||||
import { useForm, useWatch } from 'react-hook-form'
|
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 { ItemInputPreview } from '@/components/items/item-input-preview'
|
||||||
import { Field, FieldError } from '@/components/ui/field'
|
import { Field, FieldError } from '@/components/ui/field'
|
||||||
import {
|
import {
|
||||||
InputGroup,
|
InputGroup,
|
||||||
@@ -14,19 +12,10 @@ import {
|
|||||||
InputGroupButton,
|
InputGroupButton,
|
||||||
InputGroupInput,
|
InputGroupInput,
|
||||||
} from '@/components/ui/input-group'
|
} from '@/components/ui/input-group'
|
||||||
|
import { itemLimitError, readItems, useAddItems } from '@/hooks/use-add-items'
|
||||||
import { useDictation } from '@/hooks/use-dictation'
|
import { useDictation } from '@/hooks/use-dictation'
|
||||||
import {
|
|
||||||
isOptimisticItem,
|
|
||||||
useCreateItem,
|
|
||||||
useItems,
|
|
||||||
useRemoveItems,
|
|
||||||
useUpdateItem,
|
|
||||||
} from '@/hooks/use-items'
|
|
||||||
import { useKeyboardDictation } from '@/hooks/use-keyboard-dictation'
|
import { useKeyboardDictation } from '@/hooks/use-keyboard-dictation'
|
||||||
import { useVoiceSplit } from '@/hooks/use-voice-split'
|
import { isPlainItem } from '@/lib/natural-input/parse-item'
|
||||||
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'
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
// The input may hold several items ("leche, pan y 2 pascualinas" or a pasted list);
|
// The input may hold several items ("leche, pan y 2 pascualinas" or a pasted list);
|
||||||
@@ -44,9 +33,6 @@ type CreateItemFormProps = {
|
|||||||
autoFocus?: boolean
|
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). */
|
/** 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'
|
const NEW_ITEM_INPUT_ID = 'new-item-input'
|
||||||
|
|
||||||
@@ -69,23 +55,6 @@ export function refocusNewItemInput(): void {
|
|||||||
document.getElementById(NEW_ITEM_INPUT_ID)?.focus()
|
document.getElementById(NEW_ITEM_INPUT_ID)?.focus()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 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
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 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
|
* as natural language ("400 de jamon", "Queso crema. Solo Tregar", "leche, pan y
|
||||||
@@ -96,11 +65,6 @@ type AddedItems = {
|
|||||||
* AI) and each one goes through this same flow. "Deshacer" removes the whole dictation.
|
* AI) and each one goes through this same flow. "Deshacer" removes the whole dictation.
|
||||||
*/
|
*/
|
||||||
export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProps) {
|
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.
|
// The text the user asked to add as typed; editing it brings the reading back.
|
||||||
const [literalText, setLiteralText] = useState<string | null>(null)
|
const [literalText, setLiteralText] = useState<string | null>(null)
|
||||||
|
|
||||||
@@ -111,22 +75,31 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
|
|
||||||
const text = useWatch({ control: form.control, name: 'entry' })
|
const text = useWatch({ control: form.control, name: 'entry' })
|
||||||
const literal = literalText !== null && literalText === text
|
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 restoreText = (source: string, message: string) => {
|
||||||
|
const current = form.getValues('entry').trim()
|
||||||
|
form.setValue('entry', current ? `${current}; ${source}` : source)
|
||||||
|
form.setError('entry', { message })
|
||||||
|
}
|
||||||
|
|
||||||
|
// A failed item comes back to the input, and so does a dictation that breaks the limits.
|
||||||
|
const { existing, addItems, addDictation, processing } = useAddItems(listId, {
|
||||||
|
onItemFailed: restoreText,
|
||||||
|
onDictationRejected: (transcript, message) => {
|
||||||
|
form.setValue('entry', transcript)
|
||||||
|
form.setError('entry', { message })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const dictation = useDictation({ onTranscript: (transcript) => onTranscript(transcript) })
|
||||||
// The keyboard's own microphone (the only one in the installed iOS app) just writes
|
// The keyboard's own microphone (the only one in the installed iOS app) just writes
|
||||||
// text: once it has been quiet for a few seconds, that text is added as a dictation.
|
// text: once it has been quiet for a few seconds, that text is added as a dictation.
|
||||||
const keyboardDictation = useKeyboardDictation({
|
const keyboardDictation = useKeyboardDictation({
|
||||||
onIdle: () => {
|
onIdle: () => {
|
||||||
const dictated = form.getValues('entry').trim()
|
const dictated = form.getValues('entry').trim()
|
||||||
if (dictated && !dictation.listening && !voiceSplit.isPending) void addDictation(dictated)
|
if (dictated && !dictation.listening && !processing) onTranscript(dictated)
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
const processing = voiceSplit.isPending
|
|
||||||
const dictating = dictation.listening || processing
|
const dictating = dictation.listening || processing
|
||||||
|
|
||||||
// The partial transcript is shown in the input while the user talks.
|
// The partial transcript is shown in the input while the user talks.
|
||||||
@@ -140,64 +113,6 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
text.trim() !== '' &&
|
text.trim() !== '' &&
|
||||||
(literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate))
|
(literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate))
|
||||||
|
|
||||||
const restoreText = (source: string, message: string) => {
|
|
||||||
const current = form.getValues('entry').trim()
|
|
||||||
form.setValue('entry', current ? `${current}; ${source}` : source)
|
|
||||||
form.setError('entry', { 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
|
// 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.
|
// 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) => {
|
||||||
@@ -217,48 +132,12 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
addItems(toAdd)
|
addItems(toAdd)
|
||||||
})
|
})
|
||||||
|
|
||||||
/**
|
/** A dictation clears the input and goes through `addDictation`. */
|
||||||
* The API splits the transcript into one string per item and each one is read by the
|
const onTranscript = (transcript: string) => {
|
||||||
* usual parser. If the request fails, the whole transcript is added as a single item.
|
|
||||||
*/
|
|
||||||
const addDictation = async (transcript: string) => {
|
|
||||||
keyboardDictation.cancel()
|
keyboardDictation.cancel()
|
||||||
form.reset()
|
form.reset()
|
||||||
setLiteralText(null)
|
setLiteralText(null)
|
||||||
|
void addDictation(transcript)
|
||||||
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('entry', transcript)
|
|
||||||
form.setError('entry', { 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 "; ".
|
// An <input> drops line breaks, so a pasted list keeps one item per line as "; ".
|
||||||
@@ -376,12 +255,3 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
</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) }))
|
|
||||||
}
|
|
||||||
|
|||||||
88
apps/web/src/components/items/dictate-items-button.tsx
Normal file
88
apps/web/src/components/items/dictate-items-button.tsx
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
import { Loader2Icon, MicIcon, SquareIcon } from 'lucide-react'
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { useAddItems } from '@/hooks/use-add-items'
|
||||||
|
import { DICTATION_MESSAGES, useMicrophoneDictation } from '@/hooks/use-microphone-dictation'
|
||||||
|
|
||||||
|
type DictateItemsButtonProps = {
|
||||||
|
listId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "Dictar ítems" for an empty list: listens until the user stops it and adds what was
|
||||||
|
* said through the same flow as the input's microphone (split by the API, undoable).
|
||||||
|
*/
|
||||||
|
export function DictateItemsButton({ listId }: DictateItemsButtonProps) {
|
||||||
|
const [message, setMessage] = useState<string | null>(null)
|
||||||
|
const { addDictation, processing } = useAddItems(listId, {
|
||||||
|
onItemFailed: (source, detail) => toast.error(`No pudimos añadir «${source}»: ${detail}`),
|
||||||
|
onDictationRejected: (_, detail) => setMessage(detail),
|
||||||
|
})
|
||||||
|
|
||||||
|
const dictation = useMicrophoneDictation({
|
||||||
|
onPhrases: async (phrases) => {
|
||||||
|
const understood = await addDictation(phrases.join('\n'))
|
||||||
|
if (understood === 0) setMessage(DICTATION_MESSAGES.empty)
|
||||||
|
},
|
||||||
|
onError: setMessage,
|
||||||
|
})
|
||||||
|
|
||||||
|
const listening = dictation.status === 'listening'
|
||||||
|
const busy = dictation.status === 'requesting' || processing
|
||||||
|
|
||||||
|
const label = processing
|
||||||
|
? 'Procesando el dictado'
|
||||||
|
: dictation.status === 'requesting'
|
||||||
|
? 'Pidiendo acceso al micrófono'
|
||||||
|
: listening
|
||||||
|
? 'Detener dictado'
|
||||||
|
: 'Dictar ítems'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={listening ? 'default' : 'secondary'}
|
||||||
|
aria-label={label}
|
||||||
|
aria-pressed={listening}
|
||||||
|
disabled={busy}
|
||||||
|
className="relative rounded-full"
|
||||||
|
onClick={() => {
|
||||||
|
setMessage(null)
|
||||||
|
if (listening) dictation.stop()
|
||||||
|
else dictation.start()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{busy ? (
|
||||||
|
<Loader2Icon className="animate-spin" />
|
||||||
|
) : listening ? (
|
||||||
|
<SquareIcon className="fill-current" />
|
||||||
|
) : (
|
||||||
|
<MicIcon />
|
||||||
|
)}
|
||||||
|
{listening ? 'Detener dictado' : 'Dictar ítems'}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<div aria-live="polite" className="flex flex-col items-center gap-1 text-sm">
|
||||||
|
{listening && (
|
||||||
|
<p className="text-primary flex items-center gap-2 font-medium">
|
||||||
|
<span className="relative flex size-2.5" aria-hidden="true">
|
||||||
|
<span className="bg-primary absolute inline-flex size-full rounded-full opacity-75 motion-safe:animate-ping" />
|
||||||
|
<span className="bg-primary relative inline-flex size-2.5 rounded-full" />
|
||||||
|
</span>
|
||||||
|
Micrófono activo, te escuchamos
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{listening && dictation.heard && (
|
||||||
|
<p className="text-muted-foreground max-w-xs">{dictation.heard}</p>
|
||||||
|
)}
|
||||||
|
{listening && !dictation.heard && (
|
||||||
|
<p className="text-muted-foreground">Di «nuevo ítem» o haz una pausa entre artículos.</p>
|
||||||
|
)}
|
||||||
|
{message && !listening && <p className="text-destructive max-w-xs">{message}</p>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ import { ApiError } from '@/lib/api-client'
|
|||||||
import { splitItems } from '@/lib/items'
|
import { splitItems } from '@/lib/items'
|
||||||
|
|
||||||
import { BoughtItemList } from './bought-item-list'
|
import { BoughtItemList } from './bought-item-list'
|
||||||
|
import { DictateItemsButton } from './dictate-items-button'
|
||||||
import { ItemRow } from './item-row'
|
import { ItemRow } from './item-row'
|
||||||
import { ItemSheet } from './item-sheet'
|
import { ItemSheet } from './item-sheet'
|
||||||
import { MoveItemDialog } from './move-item-dialog'
|
import { MoveItemDialog } from './move-item-dialog'
|
||||||
@@ -101,6 +102,7 @@ export function ItemList({ listId }: ItemListProps) {
|
|||||||
Usa el campo de arriba para añadir tu primer artículo.
|
Usa el campo de arriba para añadir tu primer artículo.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<DictateItemsButton listId={listId} />
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
)
|
)
|
||||||
|
|||||||
171
apps/web/src/hooks/use-add-items.ts
Normal file
171
apps/web/src/hooks/use-add-items.ts
Normal file
@@ -0,0 +1,171 @@
|
|||||||
|
import type { ListItem } from '@superlist/shared'
|
||||||
|
import { useRef } from 'react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
import type { PreviewItem } from '@/components/items/item-input-preview'
|
||||||
|
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 { literalItem, parseItemInput } from '@/lib/natural-input/parse-item'
|
||||||
|
|
||||||
|
/** How long the "Deshacer" of a dictation stays on screen. */
|
||||||
|
const DICTATION_UNDO_MS = 8000
|
||||||
|
|
||||||
|
/** Why a read item cannot be sent as is, mirroring the API limits, or `null`. */
|
||||||
|
export 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
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The items `text` adds, each with the pending item it repeats, if any. */
|
||||||
|
export 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) }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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 }[]
|
||||||
|
}
|
||||||
|
|
||||||
|
type UseAddItemsOptions = {
|
||||||
|
/** An item could not be created: `source` is the text it was read from. */
|
||||||
|
onItemFailed: (source: string, message: string) => void
|
||||||
|
/** A dictation was not added because an item breaks the API limits. */
|
||||||
|
onDictationRejected: (transcript: string, message: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds items to a list the way the "add an item" input does: an item already pending is
|
||||||
|
* added to instead of repeated, and a dictation is split into items by the API (with AI)
|
||||||
|
* and can be undone as a whole.
|
||||||
|
*/
|
||||||
|
export function useAddItems(
|
||||||
|
listId: string,
|
||||||
|
{ onItemFailed, onDictationRejected }: UseAddItemsOptions,
|
||||||
|
) {
|
||||||
|
const createItem = useCreateItem(listId)
|
||||||
|
const updateItem = useUpdateItem(listId)
|
||||||
|
const removeItems = useRemoveItems(listId)
|
||||||
|
const voiceSplit = useVoiceSplit()
|
||||||
|
const { data: items } = useItems(listId)
|
||||||
|
// 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
|
||||||
|
|
||||||
|
/** Adds the items, or adds to the pending ones they repeat. */
|
||||||
|
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) => {
|
||||||
|
onItemFailed(
|
||||||
|
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 API splits the transcript into one string per item and each one is read by the
|
||||||
|
* usual parser. If the request fails, the transcript is read as typed text when it is
|
||||||
|
* already split into lines, and added as a single item otherwise.
|
||||||
|
*
|
||||||
|
* @returns how many items were understood (0 when the dictation had none).
|
||||||
|
*/
|
||||||
|
const addDictation = async (transcript: string): Promise<number> => {
|
||||||
|
let toAdd: PreviewItem[]
|
||||||
|
try {
|
||||||
|
const { items: spoken } = await voiceSplit.mutateAsync({ text: transcript })
|
||||||
|
toAdd = readItems(spoken.join('; '), false, existingRef.current)
|
||||||
|
} catch {
|
||||||
|
toAdd = readItems(transcript, !/[;\n]/.test(transcript), existingRef.current)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (toAdd.length === 0) return 0
|
||||||
|
|
||||||
|
const limitError = toAdd.map(itemLimitError).find(Boolean)
|
||||||
|
if (limitError) {
|
||||||
|
onDictationRejected(transcript, limitError)
|
||||||
|
return toAdd.length
|
||||||
|
}
|
||||||
|
|
||||||
|
const { created, merged } = addItems(toAdd)
|
||||||
|
const createdIds = await created
|
||||||
|
const count = createdIds.length + merged.length
|
||||||
|
if (count === 0) return toAdd.length
|
||||||
|
|
||||||
|
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)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return toAdd.length
|
||||||
|
}
|
||||||
|
|
||||||
|
return { existing, addItems, addDictation, processing: voiceSplit.isPending }
|
||||||
|
}
|
||||||
@@ -1,22 +1,10 @@
|
|||||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
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). */
|
import {
|
||||||
type SpeechRecognitionResultLike = { isFinal: boolean; 0: { transcript: string } }
|
getSpeechRecognition as getBrowserSpeechRecognition,
|
||||||
|
isIosStandalone,
|
||||||
type SpeechRecognitionLike = {
|
type SpeechRecognitionConstructor,
|
||||||
lang: string
|
} from '@/lib/speech-recognition'
|
||||||
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. */
|
/** Errors that only mean "nothing was said" or "we stopped it": not worth telling. */
|
||||||
const IGNORED_ERRORS = new Set(['no-speech', 'aborted'])
|
const IGNORED_ERRORS = new Set(['no-speech', 'aborted'])
|
||||||
@@ -34,17 +22,9 @@ const ERROR_MESSAGES: Record<string, string> = {
|
|||||||
* unsupported (the keyboard's own dictation still works).
|
* unsupported (the keyboard's own dictation still works).
|
||||||
*/
|
*/
|
||||||
function getSpeechRecognition(): SpeechRecognitionConstructor | null {
|
function getSpeechRecognition(): SpeechRecognitionConstructor | null {
|
||||||
if (typeof window === 'undefined') return null
|
if (typeof window === 'undefined' || isIosStandalone()) return null
|
||||||
|
|
||||||
const iosStandalone = (navigator as Navigator & { standalone?: boolean }).standalone === true
|
return getBrowserSpeechRecognition()
|
||||||
if (iosStandalone) return null
|
|
||||||
|
|
||||||
const speechWindow = window as Window & {
|
|
||||||
SpeechRecognition?: SpeechRecognitionConstructor
|
|
||||||
webkitSpeechRecognition?: SpeechRecognitionConstructor
|
|
||||||
}
|
|
||||||
|
|
||||||
return speechWindow.SpeechRecognition ?? speechWindow.webkitSpeechRecognition ?? null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type UseDictationOptions = {
|
type UseDictationOptions = {
|
||||||
|
|||||||
154
apps/web/src/hooks/use-microphone-dictation.ts
Normal file
154
apps/web/src/hooks/use-microphone-dictation.ts
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
|
|
||||||
|
import { splitDictation } from '@/lib/natural-input/dictation'
|
||||||
|
import { getSpeechRecognition, type SpeechRecognitionLike } from '@/lib/speech-recognition'
|
||||||
|
|
||||||
|
export const DICTATION_MESSAGES = {
|
||||||
|
denied: 'No tenemos permiso para usar el micrófono. Habilítalo en los ajustes del navegador.',
|
||||||
|
unavailable: 'No encontramos un micrófono disponible.',
|
||||||
|
unsupported:
|
||||||
|
'Este navegador no permite dictar. Puedes usar el micrófono del teclado en el campo de arriba.',
|
||||||
|
empty: 'No escuchamos ningún artículo. Inténtalo de nuevo.',
|
||||||
|
failed: 'Ocurrió un error al reconocer la voz. Inténtalo de nuevo.',
|
||||||
|
} as const
|
||||||
|
|
||||||
|
/** Recognition errors with a message of their own; any other one is `failed`. */
|
||||||
|
const RECOGNITION_ERRORS: Record<string, string | null> = {
|
||||||
|
'not-allowed': DICTATION_MESSAGES.denied,
|
||||||
|
'service-not-allowed': DICTATION_MESSAGES.unsupported,
|
||||||
|
'audio-capture': DICTATION_MESSAGES.unavailable,
|
||||||
|
// Silence just ends with no phrases; a stop of ours is not an error.
|
||||||
|
'no-speech': null,
|
||||||
|
aborted: null,
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What `getUserMedia` rejects with, as one of the messages. */
|
||||||
|
function microphoneError(error: unknown): string {
|
||||||
|
const name = error instanceof DOMException ? error.name : ''
|
||||||
|
if (name === 'NotAllowedError' || name === 'SecurityError') return DICTATION_MESSAGES.denied
|
||||||
|
|
||||||
|
return DICTATION_MESSAGES.unavailable
|
||||||
|
}
|
||||||
|
|
||||||
|
type DictationStatus = 'idle' | 'requesting' | 'listening'
|
||||||
|
|
||||||
|
type UseMicrophoneDictationOptions = {
|
||||||
|
/** The phrases dictated, one per item said, when the dictation ends with some. */
|
||||||
|
onPhrases: (phrases: string[]) => void
|
||||||
|
/** Why the dictation did not deliver anything, in Spanish. */
|
||||||
|
onError: (message: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dictation of several items in a row with the Web Speech API (`webkitSpeechRecognition`
|
||||||
|
* in Safari), in Argentine Spanish. `start()` must run inside a click handler: it asks
|
||||||
|
* for the microphone right there, then listens until the user calls `stop()` or the
|
||||||
|
* browser ends the recognition. Pauses, line breaks and "nuevo ítem" separate phrases
|
||||||
|
* (`splitDictation`).
|
||||||
|
*
|
||||||
|
* The microphone stream is only used to ask for the permission: its tracks are stopped
|
||||||
|
* as soon as it arrives (even after an unmount), before the recognition opens its own
|
||||||
|
* capture. Unmounting aborts the recognition.
|
||||||
|
*/
|
||||||
|
export function useMicrophoneDictation({ onPhrases, onError }: UseMicrophoneDictationOptions) {
|
||||||
|
const [status, setStatus] = useState<DictationStatus>('idle')
|
||||||
|
// What has been heard so far, shown while listening.
|
||||||
|
const [heard, setHeard] = useState('')
|
||||||
|
const callbacksRef = useRef({ onPhrases, onError })
|
||||||
|
// Ends the dictation in progress: `true` delivers what was heard, `false` drops it.
|
||||||
|
const endRef = useRef<((deliver: boolean) => void) | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
callbacksRef.current = { onPhrases, onError }
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => () => endRef.current?.(false), [])
|
||||||
|
|
||||||
|
const start = useCallback(() => {
|
||||||
|
if (endRef.current) return
|
||||||
|
|
||||||
|
const SpeechRecognition = getSpeechRecognition()
|
||||||
|
if (!SpeechRecognition) {
|
||||||
|
callbacksRef.current.onError(DICTATION_MESSAGES.unsupported)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let recognition: SpeechRecognitionLike | null = null
|
||||||
|
let segments: string[] = []
|
||||||
|
let failure: string | null = null
|
||||||
|
let done = false
|
||||||
|
|
||||||
|
const end = (deliver: boolean) => {
|
||||||
|
if (done) return
|
||||||
|
done = true
|
||||||
|
endRef.current = null
|
||||||
|
// Aborting afterwards only fires an ignored `aborted` and an `onend` that finds it done.
|
||||||
|
recognition?.abort()
|
||||||
|
setStatus('idle')
|
||||||
|
setHeard('')
|
||||||
|
// Stopped while the permission was being asked: there is nothing to tell.
|
||||||
|
if (!deliver || (!recognition && !failure)) return
|
||||||
|
|
||||||
|
const phrases = splitDictation(segments)
|
||||||
|
if (failure) callbacksRef.current.onError(failure)
|
||||||
|
else if (phrases.length === 0) callbacksRef.current.onError(DICTATION_MESSAGES.empty)
|
||||||
|
else callbacksRef.current.onPhrases(phrases)
|
||||||
|
}
|
||||||
|
|
||||||
|
const listen = () => {
|
||||||
|
recognition = new SpeechRecognition()
|
||||||
|
recognition.lang = 'es-AR'
|
||||||
|
recognition.interimResults = true
|
||||||
|
recognition.continuous = true
|
||||||
|
recognition.maxAlternatives = 1
|
||||||
|
|
||||||
|
// Each result is a stretch of speech between pauses; the last one may still change.
|
||||||
|
recognition.onresult = (event) => {
|
||||||
|
segments = Array.from(event.results, (result) => result[0].transcript)
|
||||||
|
setHeard(splitDictation(segments).join(' · '))
|
||||||
|
}
|
||||||
|
|
||||||
|
recognition.onerror = (event) => {
|
||||||
|
const message = RECOGNITION_ERRORS[event.error]
|
||||||
|
if (message === null) return
|
||||||
|
failure = message ?? DICTATION_MESSAGES.failed
|
||||||
|
}
|
||||||
|
|
||||||
|
recognition.onend = () => end(true)
|
||||||
|
|
||||||
|
try {
|
||||||
|
recognition.start()
|
||||||
|
setStatus('listening')
|
||||||
|
} catch {
|
||||||
|
failure = DICTATION_MESSAGES.failed
|
||||||
|
end(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
endRef.current = end
|
||||||
|
setStatus('requesting')
|
||||||
|
|
||||||
|
// Without `getUserMedia` (e.g. outside HTTPS) the recognition asks for the microphone itself.
|
||||||
|
if (!navigator.mediaDevices?.getUserMedia) {
|
||||||
|
listen()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Called right in the click, before any `await`, so Safari treats it as the user's.
|
||||||
|
navigator.mediaDevices.getUserMedia({ audio: true }).then(
|
||||||
|
(stream) => {
|
||||||
|
for (const track of stream.getTracks()) track.stop()
|
||||||
|
if (!done) listen()
|
||||||
|
},
|
||||||
|
(error: unknown) => {
|
||||||
|
failure = microphoneError(error)
|
||||||
|
end(true)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
/** Stops listening; what was heard so far is delivered. */
|
||||||
|
const stop = useCallback(() => endRef.current?.(true), [])
|
||||||
|
|
||||||
|
return { status, heard, start, stop }
|
||||||
|
}
|
||||||
37
apps/web/src/lib/natural-input/dictation.test.ts
Normal file
37
apps/web/src/lib/natural-input/dictation.test.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import { splitDictation } from './dictation'
|
||||||
|
|
||||||
|
describe('splitDictation', () => {
|
||||||
|
it('splits on "nuevo ítem" and its variants', () => {
|
||||||
|
expect(
|
||||||
|
splitDictation([
|
||||||
|
'leche descremada nuevo ítem pan Nuevo item 2 kilos de papa, otro artículo yerba',
|
||||||
|
]),
|
||||||
|
).toEqual(['leche descremada', 'pan', '2 kilos de papa', 'yerba'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('takes every segment and line as a separate phrase', () => {
|
||||||
|
expect(splitDictation(['Leche.', ' pan\nqueso rallado '])).toEqual([
|
||||||
|
'Leche',
|
||||||
|
'pan',
|
||||||
|
'queso rallado',
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('collapses spaces and drops empty phrases', () => {
|
||||||
|
expect(splitDictation([' dulce de leche ', '', 'nuevo ítem', '...'])).toEqual([
|
||||||
|
'dulce de leche',
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps a repeated phrase once, ignoring case and accents', () => {
|
||||||
|
expect(splitDictation(['jamón', 'Jamon nuevo ítem pan', 'pan'])).toEqual(['jamón', 'pan'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not split words that only contain the keywords', () => {
|
||||||
|
expect(splitDictation(['productos nuevos de limpieza'])).toEqual([
|
||||||
|
'productos nuevos de limpieza',
|
||||||
|
])
|
||||||
|
})
|
||||||
|
})
|
||||||
35
apps/web/src/lib/natural-input/dictation.ts
Normal file
35
apps/web/src/lib/natural-input/dictation.ts
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import { normalizeWord } from './text'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the user says to start another item: "nuevo ítem", "otro artículo", "nuevo
|
||||||
|
* producto". The punctuation the recognizer puts around it goes with it.
|
||||||
|
*/
|
||||||
|
const NEXT_ITEM =
|
||||||
|
/[\s,.;:]*(?<!\p{L})(?:nuevo|otro)\s+(?:[íi]tem|art[íi]culo|producto)(?!\p{L})[\s,.;:]*/giu
|
||||||
|
|
||||||
|
/** Punctuation the recognizer adds around a phrase ("Leche."), not part of the item. */
|
||||||
|
const EDGE_PUNCTUATION = /^[\s,.;:]+|[\s,.;:]+$/g
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The phrases of a dictation, one per item said: each segment (a pause or a line break,
|
||||||
|
* as the recognizer delivers them) is also split on "nuevo ítem". Spaces are collapsed,
|
||||||
|
* empty phrases dropped and a phrase repeated in the same dictation kept once (ignoring
|
||||||
|
* case and accents); the words themselves are left as heard.
|
||||||
|
*/
|
||||||
|
export function splitDictation(segments: string[]): string[] {
|
||||||
|
const phrases: string[] = []
|
||||||
|
const seen = new Set<string>()
|
||||||
|
|
||||||
|
for (const segment of segments) {
|
||||||
|
for (const part of segment.split(/\r?\n/).flatMap((line) => line.split(NEXT_ITEM))) {
|
||||||
|
const phrase = part.replace(/\s+/g, ' ').replace(EDGE_PUNCTUATION, '')
|
||||||
|
const key = normalizeWord(phrase)
|
||||||
|
if (!phrase || seen.has(key)) continue
|
||||||
|
|
||||||
|
seen.add(key)
|
||||||
|
phrases.push(phrase)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return phrases
|
||||||
|
}
|
||||||
34
apps/web/src/lib/speech-recognition.ts
Normal file
34
apps/web/src/lib/speech-recognition.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
/** The slice of the Web Speech API the app uses (TypeScript's DOM lib does not ship it). */
|
||||||
|
export type SpeechRecognitionResultLike = { isFinal: boolean; 0: { transcript: string } }
|
||||||
|
|
||||||
|
export 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
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SpeechRecognitionConstructor = new () => SpeechRecognitionLike
|
||||||
|
|
||||||
|
/** `SpeechRecognition`, or Safari's `webkitSpeechRecognition`, or `null` when there is none. */
|
||||||
|
export function getSpeechRecognition(): SpeechRecognitionConstructor | null {
|
||||||
|
if (typeof window === 'undefined') return null
|
||||||
|
|
||||||
|
const speechWindow = window as Window & {
|
||||||
|
SpeechRecognition?: SpeechRecognitionConstructor
|
||||||
|
webkitSpeechRecognition?: SpeechRecognitionConstructor
|
||||||
|
}
|
||||||
|
|
||||||
|
return speechWindow.SpeechRecognition ?? speechWindow.webkitSpeechRecognition ?? null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the page runs as an app installed on the iOS home screen. */
|
||||||
|
export function isIosStandalone(): boolean {
|
||||||
|
return (navigator as Navigator & { standalone?: boolean }).standalone === true
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user