diff --git a/apps/web/src/components/items/create-item-form.tsx b/apps/web/src/components/items/create-item-form.tsx index 78d9890..b734fc8 100644 --- a/apps/web/src/components/items/create-item-form.tsx +++ b/apps/web/src/components/items/create-item-form.tsx @@ -22,6 +22,7 @@ import { 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' @@ -31,7 +32,8 @@ 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. const createItemSchema = z.object({ - name: z.string().trim().min(1, 'Escribe un artículo').max(2000, 'Máximo 2000 caracteres'), + // Not called `name`: iOS offers to autofill a contact into an input named that way. + entry: z.string().trim().min(1, 'Escribe un artículo').max(2000, 'Máximo 2000 caracteres'), }) type CreateItemValues = z.infer @@ -104,10 +106,10 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp const form = useForm({ resolver: zodResolver(createItemSchema), - defaultValues: { name: '' }, + defaultValues: { entry: '' }, }) - const text = useWatch({ control: form.control, name: 'name' }) + 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)) @@ -116,12 +118,20 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp existingRef.current = existing const dictation = useDictation({ onTranscript: (transcript) => void addDictation(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) + }, + }) 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) + if (dictation.listening) form.setValue('entry', dictation.interim) }, [dictation.listening, dictation.interim, form]) const preview = readItems(text, literal, existing) @@ -131,9 +141,9 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp (literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate)) const restoreText = (source: string, message: string) => { - const current = form.getValues('name').trim() - form.setValue('name', current ? `${current}; ${source}` : source) - form.setError('name', { message }) + 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. */ @@ -191,17 +201,18 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp // The input clears at once (items are added optimistically) so several items can be // typed in a row; if a request fails its text comes back with the error. const onSubmit = form.handleSubmit((values) => { - const toAdd = readItems(values.name, literal, existing) + keyboardDictation.cancel() + const toAdd = readItems(values.entry, literal, existing) const limitError = toAdd.map(itemLimitError).find(Boolean) if (limitError) { - form.setError('name', { message: limitError }) + form.setError('entry', { message: limitError }) return } form.reset() setLiteralText(null) - form.setFocus('name') + form.setFocus('entry') addItems(toAdd) }) @@ -211,6 +222,7 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp * usual parser. If the request fails, the whole transcript is added as a single item. */ const addDictation = async (transcript: string) => { + keyboardDictation.cancel() form.reset() setLiteralText(null) @@ -226,8 +238,8 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp const limitError = toAdd.map(itemLimitError).find(Boolean) if (limitError) { - form.setValue('name', transcript) - form.setError('name', { message: limitError }) + form.setValue('entry', transcript) + form.setError('entry', { message: limitError }) return } @@ -264,7 +276,7 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp .filter(Boolean) .join('; ') - form.setValue('name', input.value.slice(0, start) + lines + input.value.slice(end), { + form.setValue('entry', input.value.slice(0, start) + lines + input.value.slice(end), { shouldDirty: true, }) } @@ -284,7 +296,7 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp dictation.stop() }} > - + {dictation.supported && ( @@ -330,7 +344,11 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp 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} + onClick={() => { + keyboardDictation.cancel() + if (dictation.listening) dictation.stop() + else dictation.start() + }} > {processing ? ( @@ -341,7 +359,7 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp )} - + {dictation.error && (

{dictation.error} diff --git a/apps/web/src/hooks/use-keyboard-dictation.test.ts b/apps/web/src/hooks/use-keyboard-dictation.test.ts new file mode 100644 index 0000000..7d5c8a8 --- /dev/null +++ b/apps/web/src/hooks/use-keyboard-dictation.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest' + +import { isDictatedInput } from './use-keyboard-dictation' + +describe('isDictatedInput', () => { + it('takes words or phrases written without a key press as dictation', () => { + expect(isDictatedInput({ inputType: 'insertText', data: 'Yogur', msSinceKeydown: 5000 })).toBe( + true, + ) + expect( + isDictatedInput({ inputType: 'insertReplacementText', data: null, msSinceKeydown: 5000 }), + ).toBe(true) + }) + + it('does not take typing as dictation', () => { + expect(isDictatedInput({ inputType: 'insertText', data: 'Yogur', msSinceKeydown: 10 })).toBe( + false, + ) + expect(isDictatedInput({ inputType: 'insertText', data: 'y', msSinceKeydown: 5000 })).toBe( + false, + ) + }) + + it('never takes pastes, drops or deletions as dictation', () => { + for (const inputType of ['insertFromPaste', 'insertFromDrop', 'deleteContentBackward']) { + expect(isDictatedInput({ inputType, data: 'leche y pan', msSinceKeydown: 5000 })).toBe(false) + } + }) +}) diff --git a/apps/web/src/hooks/use-keyboard-dictation.ts b/apps/web/src/hooks/use-keyboard-dictation.ts new file mode 100644 index 0000000..a51474b --- /dev/null +++ b/apps/web/src/hooks/use-keyboard-dictation.ts @@ -0,0 +1,92 @@ +import { type FormEvent, type KeyboardEvent, useCallback, useEffect, useRef } from 'react' + +/** Quiet time after the keyboard's dictation last wrote into the input before it is added. */ +export const KEYBOARD_DICTATION_IDLE_MS = 3000 + +/** How close to a key press an input event must be to count as typed. */ +const KEYDOWN_WINDOW_MS = 100 + +/** Insertions that are never dictation (pasting or dropping text, deleting). */ +const NOT_DICTATION = /^(insertFromPaste|insertFromDrop|delete)/ + +/** + * Whether an input event looks like the system keyboard's dictation writing into the + * field: text that arrives without a key press, several characters at once (dictation + * writes word by word or a whole phrase) or as a replacement of what it wrote before. + * Tapping a keyboard suggestion looks the same, which is the price of the guess. + */ +export function isDictatedInput(event: { + inputType: string + data: string | null + msSinceKeydown: number +}): boolean { + if (NOT_DICTATION.test(event.inputType)) return false + if (event.msSinceKeydown < KEYDOWN_WINDOW_MS) return false + if (event.inputType === 'insertReplacementText') return true + + return event.inputType === 'insertText' && (event.data?.trim().length ?? 0) > 1 +} + +type UseKeyboardDictationOptions = { + /** Called with the input's text once the dictation has been quiet for a while. */ + onIdle: () => void +} + +/** + * The installed iOS app has no speech recognition, so people dictate with the + * keyboard's microphone, which only writes text into the input. This notices text that + * arrives that way and calls `onIdle` once nothing new has arrived for + * `KEYBOARD_DICTATION_IDLE_MS`, so it is added without pressing Enter. Typing a key + * cancels it: from then on the text is the user's to submit. + */ +export function useKeyboardDictation({ onIdle }: UseKeyboardDictationOptions) { + const lastKeydown = useRef(0) + const dictated = useRef(false) + const timer = useRef | undefined>(undefined) + const onIdleRef = useRef(onIdle) + + useEffect(() => { + onIdleRef.current = onIdle + }) + + const cancel = useCallback(() => { + clearTimeout(timer.current) + dictated.current = false + }, []) + + useEffect(() => cancel, [cancel]) + + const onKeyDown = useCallback( + (_event: KeyboardEvent) => { + lastKeydown.current = performance.now() + cancel() + }, + [cancel], + ) + + const onInput = useCallback((event: FormEvent) => { + const native = event.nativeEvent as InputEvent + const inputType = native.inputType ?? '' + + const looksDictated = isDictatedInput({ + inputType, + data: native.data ?? null, + msSinceKeydown: performance.now() - lastKeydown.current, + }) + + // Once dictation started, any later update without a key press (corrections, + // composition) keeps it going; a paste or a deletion stops it. + if (looksDictated) dictated.current = true + else if (NOT_DICTATION.test(inputType)) dictated.current = false + + clearTimeout(timer.current) + if (!dictated.current) return + + timer.current = setTimeout(() => { + dictated.current = false + onIdleRef.current() + }, KEYBOARD_DICTATION_IDLE_MS) + }, []) + + return { onKeyDown, onInput, cancel } +}