feat: add dictation
This commit is contained in:
@@ -1,12 +1,10 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
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 { toast } from 'sonner'
|
||||
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 {
|
||||
InputGroup,
|
||||
@@ -14,19 +12,10 @@ import {
|
||||
InputGroupButton,
|
||||
InputGroupInput,
|
||||
} from '@/components/ui/input-group'
|
||||
import { itemLimitError, readItems, useAddItems } from '@/hooks/use-add-items'
|
||||
import { useDictation } from '@/hooks/use-dictation'
|
||||
import {
|
||||
isOptimisticItem,
|
||||
useCreateItem,
|
||||
useItems,
|
||||
useRemoveItems,
|
||||
useUpdateItem,
|
||||
} from '@/hooks/use-items'
|
||||
import { useKeyboardDictation } from '@/hooks/use-keyboard-dictation'
|
||||
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 { isPlainItem } 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);
|
||||
@@ -44,9 +33,6 @@ 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'
|
||||
|
||||
@@ -69,23 +55,6 @@ export function refocusNewItemInput(): void {
|
||||
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
|
||||
* 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.
|
||||
*/
|
||||
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)
|
||||
|
||||
@@ -111,22 +75,31 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
|
||||
const text = useWatch({ control: form.control, name: 'entry' })
|
||||
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
|
||||
// text: once it has been quiet for a few seconds, that text is added as a dictation.
|
||||
const keyboardDictation = useKeyboardDictation({
|
||||
onIdle: () => {
|
||||
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
|
||||
|
||||
// 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() !== '' &&
|
||||
(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
|
||||
// typed in a row; if a request fails its text comes back with the error.
|
||||
const onSubmit = form.handleSubmit((values) => {
|
||||
@@ -217,48 +132,12 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
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) => {
|
||||
/** A dictation clears the input and goes through `addDictation`. */
|
||||
const onTranscript = (transcript: string) => {
|
||||
keyboardDictation.cancel()
|
||||
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('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)
|
||||
},
|
||||
},
|
||||
})
|
||||
void addDictation(transcript)
|
||||
}
|
||||
|
||||
// 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>
|
||||
)
|
||||
}
|
||||
|
||||
/** 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) }))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user