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:
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),
|
||||
}),
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user