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:
Jose Selesan
2026-10-28 19:25:10 -03:00
parent eb1f6cb2a9
commit a814b34036
39 changed files with 1673 additions and 288 deletions

View File

@@ -19,6 +19,14 @@ NODE_ENV="development"
# MAIL_FROM="Superlist <invitaciones@superlist.app>" # MAIL_FROM="Superlist <invitaciones@superlist.app>"
# Public URL of the web app, used to build the accept-invitation links # Public URL of the web app, used to build the accept-invitation links
WEB_APP_URL="http://localhost:7153" WEB_APP_URL="http://localhost:7153"
# Dictation: AI Studio (Gemini API) key, backend only. NEVER prefix it with VITE_
# or Vite would put it in the browser bundle. Without it, dictated text is split
# on commas and "y" instead of by the model.
# GEMINI_API_KEY=""
# Optional: model id (defaults to Gemma 4's small variant)
# GEMINI_MODEL="gemma-4-26b-a4b-it"
# Optional: timeout of the model request, in milliseconds
# GEMINI_TIMEOUT_MS="8000"
# --- apps/web --- # --- apps/web ---
# Optional. In dev, Vite proxies /api/* to the API (http://localhost:4100), so # Optional. In dev, Vite proxies /api/* to the API (http://localhost:4100), so

View File

@@ -7,7 +7,8 @@ Biome as the only JS/TS tool and the text Bun lockfile committed. It is deployed
Dokploy (`docker-compose.yml`); there is no hosted CI. Dokploy (`docker-compose.yml`); there is no hosted CI.
Not done yet: product features are just starting (sign-up, shopping lists, list items and invitations exist; Not done yet: product features are just starting (sign-up, shopping lists, list items and invitations exist;
there is no Google login and no email verification). The `health` module is the reference example. there is no Google login and no email verification; the `voice` module splits dictated text with Gemma 4
through the Gemini API). The `health` module is the reference example.
## Stack (source of truth: `STACK.md`) ## Stack (source of truth: `STACK.md`)
@@ -99,7 +100,8 @@ Run from the repo root. Verification order is `build`, then `lint` → `typechec
`apps/web/nginx.conf`, which also proxies `/api/*` to `http://superlist-api:4100` (re-resolved through `apps/web/nginx.conf`, which also proxies `/api/*` to `http://superlist-api:4100` (re-resolved through
Docker's DNS, so API redeploys don't leave nginx on a stale IP). Required env vars are interpolated Docker's DNS, so API redeploys don't leave nginx on a stale IP). Required env vars are interpolated
by Compose (`DATABASE_URL`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `CORS_ORIGIN`, `WEB_APP_URL`); set them by Compose (`DATABASE_URL`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `CORS_ORIGIN`, `WEB_APP_URL`); set them
in Dokploy. There is no hosted CI. in Dokploy. The dictation variables (`GEMINI_API_KEY`, `GEMINI_MODEL`, `GEMINI_TIMEOUT_MS`) are optional and
backend-only — never give them a `VITE_` prefix, or Vite would ship the key in the browser bundle. There is no hosted CI.
- Generated files are gitignored and must never be edited by hand: `apps/web/src/routeTree.gen.ts`, - Generated files are gitignored and must never be edited by hand: `apps/web/src/routeTree.gen.ts`,
`apps/api/src/generated/`. `apps/api/src/generated/`.
- Tests live next to the code as `*.test.ts`. The API uses `bun test` (`src/lib/result-json.test.ts`, - Tests live next to the code as `*.test.ts`. The API uses `bun test` (`src/lib/result-json.test.ts`,

View File

@@ -12,3 +12,11 @@ NODE_ENV="development"
# MAIL_FROM="Superlist <invitaciones@superlist.app>" # MAIL_FROM="Superlist <invitaciones@superlist.app>"
# Public URL of the web app, used to build the accept-invitation links # Public URL of the web app, used to build the accept-invitation links
WEB_APP_URL="http://localhost:7153" WEB_APP_URL="http://localhost:7153"
# Dictation: AI Studio (Gemini API) key, backend only. NEVER prefix it with VITE_
# or Vite would put it in the browser bundle. Without it, dictated text is split
# on commas and "y" instead of by the model.
# GEMINI_API_KEY=""
# Optional: model id (defaults to Gemma 4's small variant)
# GEMINI_MODEL="gemma-4-26b-a4b-it"
# Optional: timeout of the model request, in milliseconds
# GEMINI_TIMEOUT_MS="8000"

View File

@@ -9,6 +9,7 @@ import { errorHandler, notFoundHandler } from '@/lib/problem-details'
import { healthModule } from '@/modules/health' import { healthModule } from '@/modules/health'
import { invitationsModule } from '@/modules/invitations' import { invitationsModule } from '@/modules/invitations'
import { listsModule } from '@/modules/lists' import { listsModule } from '@/modules/lists'
import { voiceModule } from '@/modules/voice'
import type { AppEnv } from '@/types' import type { AppEnv } from '@/types'
const allowedOrigins = (process.env.CORS_ORIGIN ?? 'http://localhost:7153') const allowedOrigins = (process.env.CORS_ORIGIN ?? 'http://localhost:7153')
@@ -47,6 +48,7 @@ export function createApp() {
app.route('/api/health', healthModule) app.route('/api/health', healthModule)
app.route('/api/lists', listsModule) app.route('/api/lists', listsModule)
app.route('/api/invitations', invitationsModule) app.route('/api/invitations', invitationsModule)
app.route('/api/voice', voiceModule)
app.notFound(notFoundHandler) app.notFound(notFoundHandler)
app.onError(errorHandler) app.onError(errorHandler)

123
apps/api/src/lib/gemini.ts Normal file
View File

@@ -0,0 +1,123 @@
/**
* Minimal client for the Gemini API `generateContent` REST endpoint (Google AI Studio),
* called with `fetch` — no SDK. It serves Gemma models too, which is what the API uses.
*
* Configuration (backend only — never prefix these with `VITE_`, or Vite would put the
* key in the browser bundle):
* - `GEMINI_API_KEY`: AI Studio API key. Without it every call fails with `missing-key`.
* - `GEMINI_MODEL`: model id, `gemma-4-26b-a4b-it` by default.
* - `GEMINI_TIMEOUT_MS`: request timeout, 8000 ms by default.
*/
const GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models'
/** Gemma 4's small, fast variant (a mixture of experts with ~4B active parameters). */
export const DEFAULT_GEMINI_MODEL = 'gemma-4-26b-a4b-it'
export const DEFAULT_GEMINI_TIMEOUT_MS = 8000
export type GeminiConfig = {
apiKey: string | undefined
model: string
timeoutMs: number
}
/** Reads the configuration from the environment, with the defaults above. */
export function geminiConfigFromEnv(env: Record<string, string | undefined> = process.env) {
const timeout = Number.parseInt(env.GEMINI_TIMEOUT_MS ?? '', 10)
return {
apiKey: env.GEMINI_API_KEY?.trim() || undefined,
model: env.GEMINI_MODEL?.trim() || DEFAULT_GEMINI_MODEL,
timeoutMs: Number.isFinite(timeout) && timeout > 0 ? timeout : DEFAULT_GEMINI_TIMEOUT_MS,
} satisfies GeminiConfig
}
/** Why a call failed, short enough to log (it never includes the prompt). */
export type GeminiFailureReason =
| 'missing-key'
| 'timeout'
| 'rate-limited'
| `http-${number}`
| 'network'
| 'empty-response'
export class GeminiError extends Error {
constructor(readonly reason: GeminiFailureReason) {
super(`Gemini request failed: ${reason}`)
this.name = 'GeminiError'
}
}
/** One turn of the conversation: `user` for the input, `model` for an example answer. */
export type GeminiTurn = { role: 'user' | 'model'; text: string }
export type GenerateInput = {
systemInstruction: string
turns: GeminiTurn[]
}
type GenerateContentResponse = {
candidates?: { content?: { parts?: { text?: string; thought?: boolean }[] } }[]
}
/** Something that answers a prompt with text: the Gemini client, or a fake in tests. */
export type TextGenerator = { generate(input: GenerateInput): Promise<string> }
export class GeminiClient implements TextGenerator {
constructor(
private readonly config: GeminiConfig = geminiConfigFromEnv(),
private readonly fetchFn: typeof fetch = fetch,
) {}
/** The model's text answer. Throws `GeminiError` on any failure. */
async generate({ systemInstruction, turns }: GenerateInput): Promise<string> {
if (!this.config.apiKey) throw new GeminiError('missing-key')
let response: Response
try {
response = await this.fetchFn(
`${GEMINI_API_URL}/${encodeURIComponent(this.config.model)}:generateContent`,
{
method: 'POST',
headers: { 'content-type': 'application/json', 'x-goog-api-key': this.config.apiKey },
body: JSON.stringify({
systemInstruction: { parts: [{ text: systemInstruction }] },
contents: turns.map(({ role, text }) => ({ role, parts: [{ text }] })),
generationConfig: { temperature: 0 },
}),
signal: AbortSignal.timeout(this.config.timeoutMs),
},
)
} catch (error) {
const name = error instanceof Error ? error.name : ''
throw new GeminiError(
name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'network',
)
}
if (response.status === 429) throw new GeminiError('rate-limited')
if (!response.ok) throw new GeminiError(`http-${response.status}`)
let body: GenerateContentResponse
try {
body = (await response.json()) as GenerateContentResponse
} catch (error) {
const name = error instanceof Error ? error.name : ''
throw new GeminiError(
name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'empty-response',
)
}
// Thinking models may send their reasoning as `thought` parts: only the answer counts.
const text = (body.candidates?.[0]?.content?.parts ?? [])
.filter((part) => !part.thought && typeof part.text === 'string')
.map((part) => part.text)
.join('')
.trim()
if (!text) throw new GeminiError('empty-response')
return text
}
}

View File

@@ -9,7 +9,7 @@ import type { AppEnv } from '@/types'
import { ItemParamsSchema, UpdateItemSchema } from './schema' import { ItemParamsSchema, UpdateItemSchema } from './schema'
import { UpdateItem } from './use-case' import { UpdateItem } from './use-case'
/** PATCH /lists/:listId/items/:itemId — updates an item's bought state, quantity and/or notes. */ /** PATCH /lists/:listId/items/:itemId — updates an item's name, bought state, quantity and/or notes. */
export const updateItemRoute = new Hono<AppEnv>().patch( export const updateItemRoute = new Hono<AppEnv>().patch(
'/:itemId', '/:itemId',
requireSession, requireSession,
@@ -17,11 +17,12 @@ export const updateItemRoute = new Hono<AppEnv>().patch(
validate.json(UpdateItemSchema), validate.json(UpdateItemSchema),
async (c) => { async (c) => {
const { listId, itemId } = c.req.valid('param') const { listId, itemId } = c.req.valid('param')
const { completed, quantity, notes } = c.req.valid('json') const { name, completed, quantity, notes } = c.req.valid('json')
const result = await new UpdateItem(prisma).execute({ const result = await new UpdateItem(prisma).execute({
listId, listId,
itemId, itemId,
userId: c.get('user').id, userId: c.get('user').id,
name,
completed, completed,
quantity, quantity,
notes, notes,

View File

@@ -11,13 +11,22 @@ export type ItemParams = z.infer<typeof ItemParamsSchema>
/** Body of `PATCH /lists/:listId/items/:itemId` — at least one field is required. */ /** Body of `PATCH /lists/:listId/items/:itemId` — at least one field is required. */
export const UpdateItemSchema = z export const UpdateItemSchema = z
.object({ .object({
name: z
.string()
.trim()
.min(1, 'El nombre es obligatorio')
.max(120, 'Máximo 120 caracteres')
.optional(),
completed: z.boolean().optional(), completed: z.boolean().optional(),
quantity: z.string().trim().max(40, 'Máximo 40 caracteres').nullable().optional(), quantity: z.string().trim().max(40, 'Máximo 40 caracteres').nullable().optional(),
notes: z.string().trim().max(280, 'Máximo 280 caracteres').nullable().optional(), notes: z.string().trim().max(280, 'Máximo 280 caracteres').nullable().optional(),
}) })
.refine( .refine(
(value) => (value) =>
value.completed !== undefined || value.quantity !== undefined || value.notes !== undefined, value.name !== undefined ||
value.completed !== undefined ||
value.quantity !== undefined ||
value.notes !== undefined,
{ {
message: 'Indica al menos un campo para actualizar.', message: 'Indica al menos un campo para actualizar.',
}, },

View File

@@ -48,7 +48,7 @@ function createDb(options: { membership: unknown; item: ItemRow | null }) {
// The use case only sends the fields it changes, so the stored row is // The use case only sends the fields it changes, so the stored row is
// simulated by merging those fields into the row the query returned. // simulated by merging those fields into the row the query returned.
update: async (args: { update: async (args: {
data: Partial<Pick<ItemRow, 'completed' | 'boughtAt' | 'quantity' | 'notes'>> data: Partial<Pick<ItemRow, 'name' | 'completed' | 'boughtAt' | 'quantity' | 'notes'>>
}) => { }) => {
updates.push(args) updates.push(args)
return { ...options.item, ...args.data } as ItemRow return { ...options.item, ...args.data } as ItemRow
@@ -170,6 +170,25 @@ describe('UpdateItem', () => {
expect(result.value.quantity).toBeNull() expect(result.value.quantity).toBeNull()
}) })
it('renames the item, leaving the rest untouched', async () => {
const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) })
const { events } = createBus()
const result = await new UpdateItem(db, events).execute({
listId: 'list-1',
itemId: 'item-1',
userId: 'user-1',
name: ' Leche descremada ',
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
const data = updates[0] as { data: { name?: string } }
expect(data.data).toEqual({ name: 'Leche descremada' })
expect(result.value.name).toBe('Leche descremada')
expect(result.value.quantity).toBe('1 L')
})
it('updates only the notes, leaving the rest untouched', async () => { it('updates only the notes, leaving the rest untouched', async () => {
const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) }) const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) })
const { events, published } = createBus() const { events, published } = createBus()

View File

@@ -16,6 +16,8 @@ type UpdateItemFields = {
listId: string listId: string
itemId: string itemId: string
userId: string userId: string
/** New name (already trimmed and non-empty); when omitted it stays untouched. */
name?: string
/** New bought state; when omitted the state stays untouched. */ /** New bought state; when omitted the state stays untouched. */
completed?: boolean completed?: boolean
/** New quantity (`null` or an empty string clears it); when omitted it stays untouched. */ /** New quantity (`null` or an empty string clears it); when omitted it stays untouched. */
@@ -25,7 +27,7 @@ type UpdateItemFields = {
} }
/** /**
* Updates an item's bought state, its quantity and/or its notes. Only members can do it. * Updates an item's name, its bought state, its quantity and/or its notes. Only members can do it.
* `boughtAt` records the moment an item was marked as bought, for future * `boughtAt` records the moment an item was marked as bought, for future
* statistics, and is cleared when the item goes back to pending. * statistics, and is cleared when the item goes back to pending.
*/ */
@@ -53,12 +55,17 @@ export class UpdateItem {
} }
const data: { const data: {
name?: string
completed?: boolean completed?: boolean
boughtAt?: Date | null boughtAt?: Date | null
quantity?: string | null quantity?: string | null
notes?: string | null notes?: string | null
} = {} } = {}
if (input.name !== undefined) {
data.name = input.name.trim()
}
if (input.completed !== undefined) { if (input.completed !== undefined) {
data.completed = input.completed data.completed = input.completed
data.boughtAt = input.completed ? new Date() : null data.boughtAt = input.completed ? new Date() : null

View File

@@ -0,0 +1,8 @@
import { Hono } from 'hono'
import type { AppEnv } from '@/types'
import { splitVoiceRoute } from './split/route'
/** `voice` module: every feature of the module is mounted here. */
export const voiceModule = new Hono<AppEnv>().route('/', splitVoiceRoute)

View File

@@ -0,0 +1,60 @@
import { describe, expect, it } from 'bun:test'
import { fallbackSplit, parseModelItems } from './items'
describe('fallbackSplit', () => {
it('splits on commas, semicolons, " y " and " e "', () => {
expect(fallbackSplit('dos litros de leche, una docena de huevos y bolsas; pan e hilo')).toEqual(
['dos litros de leche', 'una docena de huevos', 'bolsas', 'pan', 'hilo'],
)
})
it('keeps decimal commas and drops empty segments', () => {
expect(fallbackSplit('1,5 kg de papas, , cebolla ;')).toEqual(['1,5 kg de papas', 'cebolla'])
})
it('does not split inside words', () => {
expect(fallbackSplit('yerba y yogur')).toEqual(['yerba', 'yogur'])
expect(fallbackSplit('mayonesa')).toEqual(['mayonesa'])
})
it('caps the number and the length of the items', () => {
const many = Array.from({ length: 40 }, (_, index) => `item ${index}`).join(', ')
expect(fallbackSplit(many)).toHaveLength(30)
expect(fallbackSplit('a'.repeat(150))[0]).toHaveLength(100)
})
})
describe('parseModelItems', () => {
it('reads a valid array, trimming and dropping empty items', () => {
expect(parseModelItems('["2 l de leche", " 12 huevos ", ""]')).toEqual([
'2 l de leche',
'12 huevos',
])
})
it('reads JSON inside a code fence or surrounded by prose', () => {
expect(parseModelItems('```json\n["pan", "queso"]\n```')).toEqual(['pan', 'queso'])
expect(parseModelItems('Claro, acá va: ["pan", "queso [rallado]"] ¡Listo!')).toEqual([
'pan',
'queso [rallado]',
])
expect(parseModelItems('{"items": ["pan"]}')).toEqual(['pan'])
})
it('rejects invalid JSON and anything that is not an array of strings', () => {
expect(parseModelItems('no sé')).toBeNull()
expect(parseModelItems('["pan", ')).toBeNull()
expect(parseModelItems('[1, 2]')).toBeNull()
expect(parseModelItems('{"producto": "pan"}')).toBeNull()
})
it('keeps at most 30 items of at most 100 characters', () => {
const items = parseModelItems(
JSON.stringify([...Array.from({ length: 35 }, (_, i) => `item ${i}`), 'x']),
)
expect(items).toHaveLength(30)
expect(items?.at(-1)).toBe('item 29')
expect(parseModelItems(JSON.stringify(['b'.repeat(120)]))?.[0]).toHaveLength(100)
})
})

View File

@@ -0,0 +1,91 @@
import { VOICE_ITEM_MAX_LENGTH, VOICE_MAX_ITEMS } from '@superlist/shared'
/**
* Trims every item, drops empty ones and caps the result: at most `VOICE_MAX_ITEMS`
* items of at most `VOICE_ITEM_MAX_LENGTH` characters each.
*/
export function cleanItems(items: string[]): string[] {
return items
.map((item) => item.trim().slice(0, VOICE_ITEM_MAX_LENGTH).trim())
.filter(Boolean)
.slice(0, VOICE_MAX_ITEMS)
}
/**
* Plan B when the model cannot be used: splits on commas, semicolons, " y " and " e ".
* A comma between digits is a decimal ("1,5 kg") and stays.
*/
export function fallbackSplit(text: string): string[] {
return cleanItems(text.split(/\s*[;\n]\s*|\s*,\s*(?!\d)|\s+[ye]\s+/i))
}
/** Removes a Markdown code fence around the answer (```json … ```), if any. */
function stripCodeFences(text: string): string {
const fenced = /```(?:json|JSON)?\s*([\s\S]*?)```/.exec(text)
return (fenced?.[1] ?? text).trim()
}
/**
* The first balanced JSON array or object in `text`, skipping brackets inside strings.
* Returns `null` when there is none.
*/
function firstJsonValue(text: string): string | null {
const start = text.search(/[[{]/)
if (start === -1) return null
let depth = 0
let inString = false
let escaped = false
for (let index = start; index < text.length; index++) {
const char = text[index]
if (inString) {
if (escaped) escaped = false
else if (char === '\\') escaped = true
else if (char === '"') inString = false
continue
}
if (char === '"') inString = true
else if (char === '[' || char === '{') depth++
else if (char === ']' || char === '}') {
depth--
if (depth === 0) return text.slice(start, index + 1)
}
}
return null
}
function tryParse(text: string): unknown {
try {
return JSON.parse(text)
} catch {
return undefined
}
}
/**
* Reads the model's answer: a JSON array of strings, possibly inside a code fence,
* surrounded by prose or wrapped as `{ "items": [...] }`. Returns the cleaned items,
* or `null` when the answer is not an array of strings.
*/
export function parseModelItems(answer: string): string[] | null {
const unfenced = stripCodeFences(answer)
let value = tryParse(unfenced)
if (value === undefined) {
const json = firstJsonValue(unfenced)
value = json ? tryParse(json) : undefined
}
if (value && typeof value === 'object' && !Array.isArray(value) && 'items' in value) {
value = value.items
}
if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) return null
return cleanItems(value)
}

View File

@@ -0,0 +1,30 @@
import { VOICE_SPLIT_EXAMPLES } from '@superlist/shared'
import type { GeminiTurn, GenerateInput } from '@/lib/gemini'
/** What the model is told to do. Gemma accepts it as `systemInstruction`. */
export const SPLIT_INSTRUCTION = `Sos un asistente que arma listas de compras en español rioplatense.
Recibís la transcripción de lo que alguien dictó y respondés SOLO con un array JSON de strings, sin texto antes ni después.
Reglas:
- Un elemento por producto.
- Números en dígitos: "dos" → 2, "media docena" → 6, "una docena" → 12, "un kilo" → 1 kg, "un kilo y medio" → 1,5 kg.
- Unidades abreviadas: g, kg, ml, l. Los envases quedan como palabra: "1 lata", "2 paquetes".
- La cantidad va al principio: "2 l de leche", "400 g de queso", "12 huevos".
- Detalles como marca, color, tipo o corte van como nota, después de un punto: "Bolsas de residuos. Negras y verdes".
- No inventes productos ni cantidades: si no se dijo una cantidad, no pongas ninguna.
- Corregí errores obvios de la transcripción (palabras mal reconocidas, mayúsculas).
- Si no hay ningún producto, respondé [].`
/** The conversation sent to the model: the few-shot examples, then the transcript. */
export function buildSplitPrompt(text: string): GenerateInput {
const examples: GeminiTurn[] = VOICE_SPLIT_EXAMPLES.flatMap(({ said, items }) => [
{ role: 'user' as const, text: said },
{ role: 'model' as const, text: JSON.stringify(items) },
])
return {
systemInstruction: SPLIT_INSTRUCTION,
turns: [...examples, { role: 'user', text }],
}
}

View File

@@ -0,0 +1,151 @@
import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test'
import type { MiddlewareHandler } from 'hono'
import { Hono } from 'hono'
import type { AppEnv } from '@/types'
// The session is BetterAuth's (and its database's) business: here every request is signed in.
mock.module('@/lib/auth-session', () => ({
requireSession: (async (c, next) => {
c.set('user', { id: 'user-1', name: 'Ana', email: 'ana@example.com' })
await next()
}) satisfies MiddlewareHandler<AppEnv>,
}))
const { voiceModule } = await import('@/modules/voice')
const warnings: unknown[] = []
const originalFetch = globalThis.fetch
const originalEnv = { ...process.env }
function createTestApp() {
return new Hono<AppEnv>()
.use(async (c, next) => {
c.set('logger', { warn: (...args: unknown[]) => warnings.push(args) } as never)
await next()
})
.route('/api/voice', voiceModule)
}
function split(body: unknown) {
return createTestApp().request('/api/voice/split', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
})
}
function mockFetch(handler: (url: string, init: RequestInit) => Promise<Response>) {
const fn = mock(handler)
globalThis.fetch = fn as unknown as typeof fetch
return fn
}
function modelAnswer(text: string) {
return Response.json({ candidates: [{ content: { parts: [{ text }] } }] })
}
const TEXT = 'dos litros de leche descremada, una docena de huevos y bolsas de residuos'
beforeEach(() => {
warnings.length = 0
process.env.GEMINI_API_KEY = 'test-key'
process.env.GEMINI_MODEL = 'gemma-test'
process.env.GEMINI_TIMEOUT_MS = '50'
})
afterEach(() => {
globalThis.fetch = originalFetch
process.env = { ...originalEnv }
})
describe('POST /api/voice/split', () => {
it('returns the items the model answers with', async () => {
const fetchMock = mockFetch(async () =>
modelAnswer('["2 l de leche descremada", "12 huevos", "Bolsas de residuos"]'),
)
const response = await split({ text: TEXT })
expect(response.status).toBe(200)
expect(await response.json()).toEqual({
items: ['2 l de leche descremada', '12 huevos', 'Bolsas de residuos'],
})
expect(warnings).toHaveLength(0)
const [url, init] = fetchMock.mock.calls[0] ?? []
expect(url).toContain('/models/gemma-test:generateContent')
expect(new Headers(init?.headers).get('x-goog-api-key')).toBe('test-key')
const sent = JSON.parse(String(init?.body))
expect(sent.generationConfig.temperature).toBe(0)
expect(sent.systemInstruction.parts[0].text).toContain('array JSON')
expect(sent.contents.at(-1)).toEqual({ role: 'user', parts: [{ text: TEXT }] })
})
it('falls back to splitting the text when the model times out', async () => {
mockFetch(
(_url, init) =>
new Promise((_resolve, reject) => {
init.signal?.addEventListener('abort', () => reject(init.signal?.reason))
}),
)
const response = await split({ text: TEXT })
expect(response.status).toBe(200)
expect(await response.json()).toEqual({
items: ['dos litros de leche descremada', 'una docena de huevos', 'bolsas de residuos'],
})
expect(JSON.stringify(warnings)).toContain('timeout')
// The transcript itself is never logged.
expect(JSON.stringify(warnings)).not.toContain('leche')
})
it('falls back when the model is rate limited (429)', async () => {
mockFetch(async () => new Response('quota', { status: 429 }))
const response = await split({ text: 'pan y queso' })
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ items: ['pan', 'queso'] })
expect(JSON.stringify(warnings)).toContain('rate-limited')
})
it('falls back when the model answers invalid JSON', async () => {
mockFetch(async () => modelAnswer('Perdón, no entendí.'))
const response = await split({ text: 'pan, queso' })
expect(await response.json()).toEqual({ items: ['pan', 'queso'] })
expect(JSON.stringify(warnings)).toContain('invalid-json')
})
it('falls back without calling the model when there is no API key', async () => {
delete process.env.GEMINI_API_KEY
const fetchMock = mockFetch(async () => modelAnswer('[]'))
const response = await split({ text: 'pan' })
expect(await response.json()).toEqual({ items: ['pan'] })
expect(fetchMock).not.toHaveBeenCalled()
})
it('rejects an empty text with a 422', async () => {
const fetchMock = mockFetch(async () => modelAnswer('[]'))
const response = await split({ text: ' ' })
expect(response.status).toBe(422)
expect(response.headers.get('content-type')).toContain('application/problem+json')
expect(fetchMock).not.toHaveBeenCalled()
})
it('truncates the text to 500 characters', async () => {
const fetchMock = mockFetch(async () => modelAnswer('["pan"]'))
await split({ text: 'a'.repeat(800) })
const sent = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))
expect(sent.contents.at(-1).parts[0].text).toHaveLength(500)
})
})

View File

@@ -0,0 +1,23 @@
import { Hono } from 'hono'
import { requireSession } from '@/lib/auth-session'
import { GeminiClient } from '@/lib/gemini'
import { resultJson } from '@/lib/result-json'
import { validate } from '@/lib/validate'
import type { AppEnv } from '@/types'
import { SplitVoiceSchema } from './schema'
import { SplitVoiceText } from './use-case'
/** POST /voice/split — splits a dictated sentence into one string per item. */
export const splitVoiceRoute = new Hono<AppEnv>().post(
'/split',
requireSession,
validate.json(SplitVoiceSchema),
async (c) => {
const { text } = c.req.valid('json')
const result = await new SplitVoiceText(new GeminiClient(), c.get('logger')).execute({ text })
return resultJson(c, result)
},
)

View File

@@ -0,0 +1,13 @@
import { VOICE_TEXT_MAX_LENGTH } from '@superlist/shared'
import { z } from 'zod'
/** Body of `POST /voice/split`. Longer transcripts are cut to `VOICE_TEXT_MAX_LENGTH`. */
export const SplitVoiceSchema = z.object({
text: z
.string()
.trim()
.min(1, 'El texto no puede estar vacío')
.transform((text) => text.slice(0, VOICE_TEXT_MAX_LENGTH)),
})
export type SplitVoiceInput = z.infer<typeof SplitVoiceSchema>

View File

@@ -0,0 +1,54 @@
import {
Ok,
type ProblemDetails,
type Result,
VOICE_TEXT_MAX_LENGTH,
type VoiceSplitResponse,
} from '@superlist/shared'
import { GeminiError, type TextGenerator } from '@/lib/gemini'
import type { Logger } from '@/lib/logger'
import { cleanItems, fallbackSplit, parseModelItems } from './items'
import { buildSplitPrompt } from './prompt'
/**
* Splits a dictated sentence into one string per item ("dos litros de leche y doce
* huevos" → ["2 l de leche", "12 huevos"]), asking the model first. The model only
* splits and normalizes; the web app reads each string with its usual parser.
*
* It never fails because of the model: when the model is not configured, times out,
* is rate limited or answers something that is not an array of strings, the text is
* split on commas, semicolons, " y " and " e " instead, and the reason is logged
* (never the transcript).
*/
export class SplitVoiceText {
constructor(
private readonly model: TextGenerator,
private readonly logger: Pick<Logger, 'warn'>,
) {}
async execute(input: { text: string }): Promise<Result<VoiceSplitResponse, ProblemDetails>> {
const text = input.text.trim().slice(0, VOICE_TEXT_MAX_LENGTH)
if (!text) return Ok({ items: [] })
let answer: string
try {
answer = await this.model.generate(buildSplitPrompt(text))
} catch (error) {
return this.fallback(text, error instanceof GeminiError ? error.reason : 'unexpected-error')
}
const items = parseModelItems(answer)
if (items === null) return this.fallback(text, 'invalid-json')
if (items.length === 0) return this.fallback(text, 'no-items')
return Ok({ items: cleanItems(items) })
}
private fallback(text: string, reason: string): Result<VoiceSplitResponse, ProblemDetails> {
this.logger.warn({ reason, textLength: text.length }, 'voice split: using the fallback split')
return Ok({ items: fallbackSplit(text) })
}
}

View File

@@ -1,43 +1,47 @@
import type { ListItem } from '@superlist/shared' import type { ListItem } from '@superlist/shared'
import { ChevronDownIcon } from 'lucide-react' import { CheckIcon, ChevronDownIcon } from 'lucide-react'
import { Card } from '@/components/ui/card' import { Card } from '@/components/ui/card'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible' import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
import type { useUpdateItem } from '@/hooks/use-items' import type { useUpdateItem } from '@/hooks/use-items'
import { ItemRow, type ItemRowProps } from './item-row' import { ItemRow } from './item-row'
type BoughtItemListProps = { type BoughtItemListProps = {
items: ListItem[] items: ListItem[]
updateItem: ReturnType<typeof useUpdateItem> updateItem: ReturnType<typeof useUpdateItem>
savingIds: string[] savingIds: string[]
/** The editing state of each row, owned by the parent so only one row edits at a time. */ onEdit: (item: ListItem) => void
editingProps: (itemId: string) => Pick<ItemRowProps, 'editing' | 'onEditingChange'>
onMove: (item: ListItem) => void onMove: (item: ListItem) => void
onDelete: (item: ListItem) => void onDelete: (item: ListItem) => void
} }
/** /**
* Collapsible "Comprados" card below the pending items. Expanded by default so * Collapsible "Comprados (N)" section at the end of the list, folded by default so
* marking an item visibly moves it down; the user can fold it. Tapping an item * the pending items stay in focus. Tapping an item here un-buys it and it returns
* here un-buys it and it returns to the pending list. * to the pending list.
*/ */
export function BoughtItemList({ export function BoughtItemList({
items, items,
updateItem, updateItem,
savingIds, savingIds,
editingProps, onEdit,
onMove, onMove,
onDelete, onDelete,
}: BoughtItemListProps) { }: BoughtItemListProps) {
return ( return (
<Collapsible defaultOpen asChild> <Collapsible asChild>
<Card className="gap-0 py-0"> <section className="border-border overflow-hidden rounded-xl border border-dashed">
<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"> <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">
<ChevronDownIcon className="size-5 transition-transform group-data-[state=closed]:-rotate-90" /> <CheckIcon className="text-primary size-4" strokeWidth={2.5} aria-hidden />
<span className="text-base">Comprados · {items.length}</span> <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> </CollapsibleTrigger>
<CollapsibleContent> <CollapsibleContent>
<Card className="gap-0 rounded-none border-x-0 border-b-0 py-0 shadow-none">
<ul className="divide-y"> <ul className="divide-y">
{items.map((item) => ( {items.map((item) => (
<ItemRow <ItemRow
@@ -45,14 +49,15 @@ export function BoughtItemList({
item={item} item={item}
updateItem={updateItem} updateItem={updateItem}
isSaving={savingIds.includes(item.id)} isSaving={savingIds.includes(item.id)}
{...editingProps(item.id)} onEdit={() => onEdit(item)}
onMove={() => onMove(item)} onMove={() => onMove(item)}
onDelete={() => onDelete(item)} onDelete={() => onDelete(item)}
/> />
))} ))}
</ul> </ul>
</CollapsibleContent>
</Card> </Card>
</CollapsibleContent>
</section>
</Collapsible> </Collapsible>
) )
} }

View File

@@ -1,7 +1,7 @@
import { zodResolver } from '@hookform/resolvers/zod' import { zodResolver } from '@hookform/resolvers/zod'
import type { ListItem } from '@superlist/shared' import type { ListItem } from '@superlist/shared'
import { PlusIcon, SearchIcon } from 'lucide-react' import { Loader2Icon, MicIcon, PlusIcon } from 'lucide-react'
import { type ClipboardEvent, useState } from 'react' import { type ClipboardEvent, useEffect, useRef, useState } from 'react'
import { useForm, useWatch } from 'react-hook-form' import { useForm, useWatch } from 'react-hook-form'
import { toast } from 'sonner' import { toast } from 'sonner'
import { z } from 'zod' import { z } from 'zod'
@@ -14,10 +14,19 @@ import {
InputGroupButton, InputGroupButton,
InputGroupInput, InputGroupInput,
} from '@/components/ui/input-group' } 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 { ApiError } from '@/lib/api-client'
import { findDuplicate, mergeBatch, mergeInto } from '@/lib/natural-input/merge' import { findDuplicate, mergeBatch, mergeInto } from '@/lib/natural-input/merge'
import { isPlainItem, literalItem, parseItemInput } from '@/lib/natural-input/parse-item' 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); // 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. // each one is checked against the API limits once the text is read.
@@ -33,6 +42,9 @@ 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'
@@ -64,15 +76,28 @@ function itemLimitError(item: PreviewItem): string | null {
return 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 * 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 * 2 pascualinas"), previewed while typing, and an item already pending is added to
* instead of repeated. * 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) { export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProps) {
const createItem = useCreateItem(listId) const createItem = useCreateItem(listId)
const updateItem = useUpdateItem(listId) const updateItem = useUpdateItem(listId)
const removeItems = useRemoveItems(listId)
const voiceSplit = useVoiceSplit()
const { data: items } = useItems(listId) 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)
@@ -86,8 +111,22 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
const literal = literalText !== null && literalText === text const literal = literalText !== null && literalText === text
// Placeholders have no server id yet, so they cannot be added to. // Placeholders have no server id yet, so they cannot be added to.
const existing = (items ?? []).filter((item) => !isOptimisticItem(item)) 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 preview = readItems(text, literal, existing)
const showPreview = const showPreview =
!dictating &&
text.trim() !== '' && text.trim() !== '' &&
(literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate)) (literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate))
@@ -97,6 +136,58 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
form.setError('name', { message }) 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 // 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) => {
@@ -112,34 +203,51 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
setLiteralText(null) setLiteralText(null)
form.setFocus('name') form.setFocus('name')
for (const item of toAdd) { addItems(toAdd)
if (item.duplicate) { })
const patch = mergeInto(item.duplicate, item)
if (patch.quantity !== undefined || patch.notes !== undefined) { /**
updateItem.mutate({ itemId: item.duplicate.id, ...patch }) * 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.
toast( */
patch.quantity const addDictation = async (transcript: string) => {
? `Se sumó a «${item.duplicate.name}» (${patch.quantity})` form.reset()
: `«${item.duplicate.name}» ya está en la lista`, setLiteralText(null)
)
continue 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)
} }
createItem.mutate( if (toAdd.length === 0) return
{ name: item.name, quantity: item.quantity ?? undefined, notes: item.notes ?? undefined },
{ const limitError = toAdd.map(itemLimitError).find(Boolean)
onError: (error) => if (limitError) {
restoreText( form.setValue('name', transcript)
item.source, form.setError('name', { message: limitError })
error instanceof ApiError return
? (error.problem.detail ?? error.problem.title)
: 'No pudimos añadir el artículo.',
),
},
)
} }
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 "; ".
const onPaste = (event: ClipboardEvent<HTMLInputElement>) => { const onPaste = (event: ClipboardEvent<HTMLInputElement>) => {
@@ -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 ( return (
<form onSubmit={onSubmit}> <form onSubmit={onSubmit}>
<Field data-invalid={!!form.formState.errors.name}> <Field data-invalid={!!form.formState.errors.name}>
<InputGroup className="bg-card h-14 rounded-full shadow-xs dark:bg-card"> <InputGroup className="bg-card h-14 rounded-full shadow-xs dark:bg-card">
<InputGroupAddon className="pl-5"> <InputGroupAddon className="pl-1.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">
<InputGroupButton <InputGroupButton
type="submit" type="submit"
variant="default" variant="ghost"
size="icon-sm" size="icon-sm"
aria-label="Agregar" 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 // Tapping the button must not steal the focus from the input: on mobile that
// would close the keyboard between one item and the next. // would close the keyboard between one item and the next.
onMouseDown={(event) => event.preventDefault()} onMouseDown={(event) => event.preventDefault()}
@@ -193,8 +294,52 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
<PlusIcon className="size-5" strokeWidth={2.5} /> <PlusIcon className="size-5" strokeWidth={2.5} />
</InputGroupButton> </InputGroupButton>
</InputGroupAddon> </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> </InputGroup>
<FieldError errors={[form.formState.errors.name]} className="px-5" /> <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 && ( {showPreview && (
<ItemInputPreview <ItemInputPreview
items={preview} items={preview}

View File

@@ -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>
)
}

View File

@@ -19,6 +19,7 @@ import { splitItems } from '@/lib/items'
import { BoughtItemList } from './bought-item-list' import { BoughtItemList } from './bought-item-list'
import { ItemRow } from './item-row' import { ItemRow } from './item-row'
import { ItemSheet } from './item-sheet'
import { MoveItemDialog } from './move-item-dialog' import { MoveItemDialog } from './move-item-dialog'
type ItemListProps = { type ItemListProps = {
@@ -27,7 +28,7 @@ type ItemListProps = {
/** /**
* Items loaded from the API, pending ones first. Tapping an item marks it as * 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. * and are only shown on the day they were bought.
*/ */
export function ItemList({ listId }: ItemListProps) { 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. // Just-deleted items stay hidden while they can still be restored.
const deletingIds = usePendingDeletions() const deletingIds = usePendingDeletions()
const today = useToday() 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) const [editingId, setEditingId] = useState<string | null>(null)
// The item whose "move to another list" dialog is open. // The item whose "move to another list" dialog is open.
const [movingItem, setMovingItem] = useState<ListItem | null>(null) const [movingItem, setMovingItem] = useState<ListItem | null>(null)
@@ -53,12 +54,6 @@ export function ItemList({ listId }: ItemListProps) {
setMovingItem(item) 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. // Live updates: another member adds or buys an item and this list refreshes.
useListEvents(listId) useListEvents(listId)
@@ -90,6 +85,9 @@ export function ItemList({ listId }: ItemListProps) {
today, today,
) )
const editingItem =
items.find((item) => item.id === editingId && !deletingIds.has(item.id)) ?? null
if (pending.length === 0 && boughtToday.length === 0) { if (pending.length === 0 && boughtToday.length === 0) {
return ( return (
<Card> <Card>
@@ -119,7 +117,7 @@ export function ItemList({ listId }: ItemListProps) {
item={item} item={item}
updateItem={updateItem} updateItem={updateItem}
isSaving={savingIds.includes(item.id)} isSaving={savingIds.includes(item.id)}
{...editingProps(item.id)} onEdit={() => setEditingId(item.id)}
onMove={() => openMoveDialog(item)} onMove={() => openMoveDialog(item)}
onDelete={() => handleDelete(item)} onDelete={() => handleDelete(item)}
/> />
@@ -133,12 +131,18 @@ export function ItemList({ listId }: ItemListProps) {
items={boughtToday} items={boughtToday}
updateItem={updateItem} updateItem={updateItem}
savingIds={savingIds} savingIds={savingIds}
editingProps={editingProps} onEdit={(item) => setEditingId(item.id)}
onMove={openMoveDialog} onMove={openMoveDialog}
onDelete={handleDelete} onDelete={handleDelete}
/> />
)} )}
<ItemSheet
item={editingItem}
updateItem={updateItem}
onClose={() => setEditingId(null)}
onDelete={handleDelete}
/>
<MoveItemDialog listId={listId} item={movingItem} onClose={() => setMovingItem(null)} /> <MoveItemDialog listId={listId} item={movingItem} onClose={() => setMovingItem(null)} />
</div> </div>
) )

View File

@@ -1,9 +1,7 @@
import type { ListItem } from '@superlist/shared' import type { ListItem } from '@superlist/shared'
import { CheckIcon, FolderInputIcon, PencilIcon, Trash2Icon } from 'lucide-react' import { CheckIcon, FolderInputIcon, PencilIcon, Trash2Icon } from 'lucide-react'
import { type PointerEvent, useRef, useState } from 'react' import { type PointerEvent, useRef, useState } from 'react'
import { flushSync } from 'react-dom'
import { ItemEditor } from '@/components/items/item-editor'
import { import {
ContextMenu, ContextMenu,
ContextMenuContent, ContextMenuContent,
@@ -20,9 +18,8 @@ export type ItemRowProps = {
updateItem: ReturnType<typeof useUpdateItem> updateItem: ReturnType<typeof useUpdateItem>
/** This item's bought state is being saved; only this row waits for it. */ /** This item's bought state is being saved; only this row waits for it. */
isSaving: boolean isSaving: boolean
/** The inline editor of this row is open (only one row edits at a time). */ /** Opens the edit sheet for this item. */
editing: boolean onEdit: () => void
onEditingChange: (editing: boolean) => void
/** Opens the "move to another list" dialog for this item. */ /** Opens the "move to another list" dialog for this item. */
onMove: () => void onMove: () => void
/** Deletes the item (it can be undone for a few seconds). */ /** 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. */ /** A single item row inside a grouped card: tapping it toggles its bought state. */
export function ItemRow({ export function ItemRow({ item, updateItem, isSaving, onEdit, onMove, onDelete }: ItemRowProps) {
item,
updateItem,
isSaving,
editing,
onEditingChange,
onMove,
onDelete,
}: ItemRowProps) {
const [dragX, setDragX] = useState(0) const [dragX, setDragX] = useState(0)
const swipeStart = useRef<{ x: number; y: number } | null>(null) const swipeStart = useRef<{ x: number; y: number } | null>(null)
// Set once a drag passes a threshold: releasing the finger then runs that // 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. // action, and the click that the touch may fire right after is ignored.
const swiped = useRef<SwipeAction | null>(null) const swiped = useRef<SwipeAction | null>(null)
const [action, setAction] = useState<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. // A placeholder has no server id yet, so it cannot be toggled or edited.
const editable = !isSaving && !isOptimisticItem(item) const editable = !isSaving && !isOptimisticItem(item)
const quantity = quantityLabel(item.quantity) 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>) => { const handlePointerDown = (event: PointerEvent<HTMLButtonElement>) => {
// Mice use the right-click menu; only touch drags are tracked here. // Mice use the right-click menu; only touch drags are tracked here.
swiped.current = null swiped.current = null
@@ -126,7 +101,7 @@ export function ItemRow({
swipeStart.current = null swipeStart.current = null
setDragX(0) setDragX(0)
setAction(null) setAction(null)
if (released === 'edit') openEditor() if (released === 'edit') onEdit()
if (released === 'move') onMove() if (released === 'move') onMove()
if (released === 'delete') onDelete() if (released === 'delete') onDelete()
} }
@@ -183,7 +158,6 @@ export function ItemRow({
<button <button
type="button" type="button"
aria-pressed={item.completed} aria-pressed={item.completed}
aria-expanded={editing}
disabled={!editable} disabled={!editable}
onClick={() => { onClick={() => {
if (swiped.current) { if (swiped.current) {
@@ -231,25 +205,15 @@ export function ItemRow({
)} )}
</span> </span>
{quantity && ( {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> </button>
</ContextMenuTrigger> </ContextMenuTrigger>
{/* Right-click is the desktop equivalent of the swipes. */} {/* Right-click is the desktop equivalent of the swipes. */}
<ContextMenuContent <ContextMenuContent>
onCloseAutoFocus={(event) => { <ContextMenuItem onSelect={onEdit}>
if (!focusEditorOnMenuClose.current) return
focusEditorOnMenuClose.current = false
event.preventDefault()
quantityInputRef.current?.focus()
}}
>
<ContextMenuItem
onSelect={() => {
focusEditorOnMenuClose.current = true
onEditingChange(true)
}}
>
<PencilIcon /> <PencilIcon />
Editar Editar
</ContextMenuItem> </ContextMenuItem>
@@ -265,14 +229,6 @@ export function ItemRow({
</ContextMenuContent> </ContextMenuContent>
</ContextMenu> </ContextMenu>
</div> </div>
{editing && (
<ItemEditor
item={item}
updateItem={updateItem}
onClose={() => onEditingChange(false)}
quantityInputRef={quantityInputRef}
/>
)}
</li> </li>
) )
} }

View 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>
)
}

View File

@@ -8,9 +8,10 @@ type ListProgressProps = {
} }
/** /**
* "4 pendientes · 7 comprados" plus a bar for today's progress. Reads the items * A bar for today's progress: items bought today over the items shown (pending plus
* query the list already loads, so it adds no request; renders nothing until * bought today). The "X pendientes · Y comprados" count lives in the header. Reads
* the items are in or when the list is empty. * 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) { export function ListProgress({ listId }: ListProgressProps) {
const { data: items } = useItems(listId) const { data: items } = useItems(listId)
@@ -24,16 +25,10 @@ export function ListProgress({ listId }: ListProgressProps) {
if (total === 0) return null if (total === 0) return null
return ( 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 <Progress
value={(boughtToday.length / total) * 100} value={(boughtToday.length / total) * 100}
aria-label="Progreso de la compra" aria-label={`Comprados ${boughtToday.length} de ${total}`}
className="h-2" className="h-1.5"
/> />
</div>
) )
} }

View File

@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query'
import { Link, useMatch, useRouterState } from '@tanstack/react-router' import { Link, useMatch, useRouterState } from '@tanstack/react-router'
import { ArrowLeftIcon, SettingsIcon } from 'lucide-react' import { ArrowLeftIcon, SettingsIcon } from 'lucide-react'
import { ListSwitcher } from '@/components/layout/list-switcher'
import { sectionTitle } from '@/components/layout/nav-items' import { sectionTitle } from '@/components/layout/nav-items'
import { ThemeToggle } from '@/components/theme-toggle' import { ThemeToggle } from '@/components/theme-toggle'
import { Badge } from '@/components/ui/badge' import { Badge } from '@/components/ui/badge'
@@ -45,8 +46,12 @@ export function AppHeader() {
)} )}
<div className="ml-auto flex shrink-0 items-center gap-1"> <div className="ml-auto flex shrink-0 items-center gap-1">
{list && ( {list && (
<Button variant="outline" size="sm" asChild> <Button variant="outline" size="sm" className="h-11 min-w-11" asChild>
<Link to="/lists/$listId/settings" params={{ listId: list.id }}> <Link
to="/lists/$listId/settings"
params={{ listId: list.id }}
aria-label="Gestionar la lista"
>
<SettingsIcon className="size-4" /> <SettingsIcon className="size-4" />
<span className="hidden sm:inline">Gestionar</span> <span className="hidden sm:inline">Gestionar</span>
</Link> </Link>
@@ -63,14 +68,13 @@ function ListHeading({ list, showBack }: { list: HeaderList; showBack: boolean }
return ( return (
<div className="flex min-w-0 items-center gap-2"> <div className="flex min-w-0 items-center gap-2">
{showBack && ( {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"> <Link to="/lists" aria-label="Volver a listas">
<ArrowLeftIcon className="size-4" /> <ArrowLeftIcon className="size-4" />
</Link> </Link>
</Button> </Button>
)} )}
<h1 className="truncate text-sm font-medium">{list.name}</h1> <ListSwitcher list={list} />
{list.isPrimary && <Badge className="shrink-0">Principal</Badge>}
<Badge variant="secondary" className="hidden shrink-0 sm:inline-flex"> <Badge variant="secondary" className="hidden shrink-0 sm:inline-flex">
{list.role === 'owner' ? 'Propietario' : 'Colaborador'} {list.role === 'owner' ? 'Propietario' : 'Colaborador'}
</Badge> </Badge>

View 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>
)
}

View File

@@ -27,7 +27,7 @@ export function ThemeToggle() {
<Button <Button
variant="ghost" variant="ghost"
size="icon" size="icon"
className="relative" className="relative size-11"
aria-label={`Tema: ${current.label} — cambiar a ${next.label}`} aria-label={`Tema: ${current.label} — cambiar a ${next.label}`}
onClick={() => setTheme(next.value)} onClick={() => setTheme(next.value)}
> >

View 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 }
}

View File

@@ -86,6 +86,8 @@ export function useCreateItem(listId: string) {
type UpdateItemInput = { type UpdateItemInput = {
itemId: string itemId: string
/** New name; omitted to leave it untouched. */
name?: string
/** New bought state; omitted when only the details are being changed. */ /** New bought state; omitted when only the details are being changed. */
completed?: boolean completed?: boolean
/** New quantity (`null` clears it); omitted to leave it untouched. */ /** New quantity (`null` clears it); omitted to leave it untouched. */
@@ -104,7 +106,13 @@ export function useUpdateItem(listId: string) {
return useMutation({ return useMutation({
mutationKey, mutationKey,
mutationFn: (input: UpdateItemInput) => { 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.completed !== undefined) body.completed = input.completed
if (input.quantity !== undefined) body.quantity = input.quantity if (input.quantity !== undefined) body.quantity = input.quantity
if (input.notes !== undefined) body.notes = input.notes if (input.notes !== undefined) body.notes = input.notes
@@ -114,7 +122,7 @@ export function useUpdateItem(listId: string) {
body: JSON.stringify(body), 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. // Cancel the outgoing refetch so it cannot overwrite our optimistic one.
await queryClient.cancelQueries({ queryKey }) await queryClient.cancelQueries({ queryKey })
@@ -126,6 +134,7 @@ export function useUpdateItem(listId: string) {
return { return {
...item, ...item,
...(name !== undefined ? { name: name.trim() } : {}),
...(completed !== undefined ...(completed !== undefined
? { completed, boughtAt: completed ? new Date().toISOString() : null } ? { 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 })
}
}
}

View 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),
}),
})
}

View 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')
})
})

View 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 })
}

View File

@@ -87,24 +87,36 @@ describe('splitItems', () => {
}) })
describe('quantityLabel', () => { describe('quantityLabel', () => {
it('shows numeric quantities, with their unit when present', () => { it('shows quantities with a unit, litres in capitals', () => {
expect(quantityLabel('2')).toBe('2') expect(quantityLabel('2 l')).toBe('2 L')
expect(quantityLabel('2 kg')).toBe('2 kg') expect(quantityLabel('1,5 l')).toBe('1,5 L')
expect(quantityLabel('1,5')).toBe('1,5')
expect(quantityLabel(' 3 ')).toBe('3')
expect(quantityLabel('1 kg')).toBe('1 kg') expect(quantityLabel('1 kg')).toBe('1 kg')
expect(quantityLabel('0,5')).toBe('0,5')
expect(quantityLabel('½ kg')).toBe('½ kg') 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(null)).toBeNull()
expect(quantityLabel('')).toBeNull() expect(quantityLabel('')).toBeNull()
expect(quantityLabel('1')).toBeNull() expect(quantityLabel('1')).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('un par')).toBeNull()
expect(quantityLabel('kg')).toBeNull() expect(quantityLabel('kg')).toBeNull()
}) })

View File

@@ -1,6 +1,7 @@
import type { ListItem } from '@superlist/shared' import type { ListItem } from '@superlist/shared'
import { isSameLocalDay } from './dates' import { isSameLocalDay } from './dates'
import { formatQuantity, parseQuantity } from './natural-input/quantity'
export type SplitItems = { export type SplitItems = {
/** Items still to buy, in the API's order (by `order`). */ /** 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 } 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 * The quantity tag shown at the right of an item's name ("2 L", "×12", "1 kg"), or
* stay hidden. A plain "1" adds no information, so it is hidden, as is anything * `null` when it must stay hidden. It is shown when the quantity has a unit or is a
* that does not start with a number ("un par"); every other quantity is shown, * count above one; a plain "1" (or any count up to one) adds nothing. Free text that
* including fractions and quantities with a unit ("½ kg", "1 kg", "0,5"). * 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 { export function quantityLabel(quantity: string | null): string | null {
if (!quantity) return null if (!quantity) return null
const trimmed = quantity.trim() 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
} }

View 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)
})
})

View File

@@ -24,6 +24,10 @@ services:
LOG_LEVEL: ${LOG_LEVEL:-} LOG_LEVEL: ${LOG_LEVEL:-}
RESEND_API_KEY: ${RESEND_API_KEY:-} RESEND_API_KEY: ${RESEND_API_KEY:-}
MAIL_FROM: ${MAIL_FROM:-} MAIL_FROM: ${MAIL_FROM:-}
# Dictation (optional): without the key, dictated text is split without AI.
GEMINI_API_KEY: ${GEMINI_API_KEY:-}
GEMINI_MODEL: ${GEMINI_MODEL:-gemma-4-26b-a4b-it}
GEMINI_TIMEOUT_MS: ${GEMINI_TIMEOUT_MS:-8000}
expose: expose:
- "4100" - "4100"
networks: networks:

View File

@@ -2,3 +2,4 @@ export * from './events'
export * from './problem-details' export * from './problem-details'
export * from './result' export * from './result'
export * from './shopping-list' export * from './shopping-list'
export * from './voice'

View File

@@ -0,0 +1,45 @@
/**
* Dictation: `POST /api/voice/split` turns a spoken sentence into one string per item,
* each written the way the web app's item parser (`apps/web/src/lib/natural-input`)
* reads typed text. The API only splits and normalizes; quantities are read by that
* parser, so these examples live here, where both workspaces can reach them: the API
* shows them to the model and the web tests check the parser reads them as expected.
*/
/** Body of `POST /api/voice/split`. */
export type VoiceSplitRequest = { text: string }
/** Response of `POST /api/voice/split`. */
export type VoiceSplitResponse = { items: string[] }
/** Longest transcript the API reads; the rest is cut off. */
export const VOICE_TEXT_MAX_LENGTH = 500
/** Most items one dictation can add. */
export const VOICE_MAX_ITEMS = 30
/** Longest item string kept from one dictation. */
export const VOICE_ITEM_MAX_LENGTH = 100
/**
* Few-shot examples for the model: what was said and the items it should answer with.
* Every item string is copied verbatim from the parser's tests (`parse-item.test.ts`).
*/
export const VOICE_SPLIT_EXAMPLES: { said: string; items: string[] }[] = [
{
said: 'dos pascualinas y un kilo y medio de papas',
items: ['2 pascualinas', '1,5 kg de papas'],
},
{
said: 'cuatrocientos de jamón feteado fino y una lata de atún',
items: ['400 de jamon. Feteado fino', '1 lata de atun'],
},
{
said: 'queso crema solo si hay marca tregar y seis yogures',
items: ['Queso crema. Solo si hay marca Tregar', '6 unidades de yogur'],
},
{
said: 'cuatrocientos gramos de queso y leche descremada',
items: ['400g de queso', 'Leche (descremada)'],
},
]

View File

@@ -18,7 +18,10 @@
"CORS_ORIGIN", "CORS_ORIGIN",
"RESEND_API_KEY", "RESEND_API_KEY",
"MAIL_FROM", "MAIL_FROM",
"WEB_APP_URL" "WEB_APP_URL",
"GEMINI_API_KEY",
"GEMINI_MODEL",
"GEMINI_TIMEOUT_MS"
] ]
}, },
"dev": { "dev": {
@@ -34,6 +37,9 @@
"RESEND_API_KEY", "RESEND_API_KEY",
"MAIL_FROM", "MAIL_FROM",
"WEB_APP_URL", "WEB_APP_URL",
"GEMINI_API_KEY",
"GEMINI_MODEL",
"GEMINI_TIMEOUT_MS",
"VITE_API_URL" "VITE_API_URL"
] ]
}, },