Compare commits
8 Commits
86d4796d88
...
feat/passw
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1964d3e08b | ||
|
|
2117188bf9 | ||
|
|
9bd2cc9089 | ||
|
|
9d4388ed8c | ||
|
|
48c0c83424 | ||
|
|
a814b34036 | ||
|
|
eb1f6cb2a9 | ||
|
|
feb8df14c0 |
17
.claude/launch.json
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"version": "0.0.1",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "web",
|
||||
"runtimeExecutable": "bun",
|
||||
"runtimeArgs": ["run", "dev", "--filter=@superlist/web"],
|
||||
"port": 7153
|
||||
},
|
||||
{
|
||||
"name": "api",
|
||||
"runtimeExecutable": "bun",
|
||||
"runtimeArgs": ["run", "dev", "--filter=@superlist/api"],
|
||||
"port": 4100
|
||||
}
|
||||
]
|
||||
}
|
||||
10
.env.example
@@ -13,12 +13,20 @@ BETTER_AUTH_URL="http://localhost:4100"
|
||||
NODE_ENV="development"
|
||||
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
|
||||
# LOG_LEVEL="info"
|
||||
# Resend API key used to send invitation emails. Without it, emails are logged instead.
|
||||
# Resend API key used to send invitation and password reset emails. Without it, emails are logged instead.
|
||||
# RESEND_API_KEY="re_xxxxxxxx"
|
||||
# From address for outgoing email (must be a verified Resend sender)
|
||||
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
||||
# Public URL of the web app, used to build the accept-invitation links
|
||||
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 ---
|
||||
# Optional. In dev, Vite proxies /api/* to the API (http://localhost:4100), so
|
||||
|
||||
15
AGENTS.md
@@ -6,8 +6,9 @@ Scaffold is in place and verified: Turborepo monorepo with `apps/api`, `apps/web
|
||||
Biome as the only JS/TS tool and the text Bun lockfile committed. It is deployed with Docker Compose on
|
||||
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;
|
||||
there is no Google login and no email verification). The `health` module is the reference example.
|
||||
Not done yet: product features are just starting (sign-up, password recovery with an emailed OTP, shopping lists, list items and invitations exist;
|
||||
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`)
|
||||
|
||||
@@ -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
|
||||
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
|
||||
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`,
|
||||
`apps/api/src/generated/`.
|
||||
- Tests live next to the code as `*.test.ts`. The API uses `bun test` (`src/lib/result-json.test.ts`,
|
||||
@@ -201,7 +203,10 @@ export class CreateAlert {
|
||||
→ `requestId` → request logger → BetterAuth → modules.
|
||||
- **Auth**: BetterAuth is configured in `apps/api/src/lib/auth.ts` (Prisma adapter, `baseURL` from
|
||||
`BETTER_AUTH_URL`, `secret` from `BETTER_AUTH_SECRET`, `trustedOrigins` from `CORS_ORIGIN`,
|
||||
email+password enabled) and owns every route under `/api/auth/*`.
|
||||
email+password enabled) and owns every route under `/api/auth/*`. Password recovery uses the `emailOTP`
|
||||
plugin (6-digit code, 10 minutes, hashed in `verifications`): the web `/forgot-password` route calls
|
||||
`emailOtp.requestPasswordReset` / `emailOtp.resetPassword`, and the code is sent with `sendEmail`
|
||||
(`lib/mailer.ts`, template in `lib/emails/password-reset.ts`). Without `RESEND_API_KEY` the code is logged.
|
||||
- **Prisma 7**: the generator is `prisma-client` and writes to `apps/api/src/generated/prisma` (gitignored), so
|
||||
import it as `@/generated/prisma/client` — never `@prisma/client` directly. The client uses the
|
||||
`@prisma/adapter-pg` adapter with `DATABASE_URL` and is exported as `prisma` (plus the `Database` type) from
|
||||
@@ -239,7 +244,7 @@ apps/web/src/
|
||||
- **Routing: TanStack Router with file-based routes.** Add a file under `src/routes` and the route tree is
|
||||
regenerated (`bun run routes:generate`, also run by `dev`, `build` and `typecheck`; the Vite plugin watches
|
||||
the directory in dev). Never edit `routeTree.gen.ts`; `tsr.config.json` holds the generator config.
|
||||
- `(auth)/sign-in.tsx` — public routes.
|
||||
- `(auth)/sign-in.tsx`, `sign-up.tsx`, `forgot-password.tsx` — public routes.
|
||||
- `_authenticated/route.tsx` — pathless layout for signed-in pages; it guards on the BetterAuth session
|
||||
(`authClient.useSession()`) and redirects to `/sign-in` when there is none. Add authenticated pages inside
|
||||
`_authenticated/`.
|
||||
|
||||
@@ -6,9 +6,17 @@ BETTER_AUTH_URL="http://localhost:4100"
|
||||
NODE_ENV="development"
|
||||
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
|
||||
# LOG_LEVEL="info"
|
||||
# Resend API key used to send invitation emails. Without it, emails are logged instead.
|
||||
# Resend API key used to send invitation and password reset emails. Without it, emails are logged instead.
|
||||
# RESEND_API_KEY="re_xxxxxxxx"
|
||||
# From address for outgoing email (must be a verified Resend sender)
|
||||
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
||||
# Public URL of the web app, used to build the accept-invitation links
|
||||
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"
|
||||
|
||||
@@ -9,6 +9,7 @@ import { errorHandler, notFoundHandler } from '@/lib/problem-details'
|
||||
import { healthModule } from '@/modules/health'
|
||||
import { invitationsModule } from '@/modules/invitations'
|
||||
import { listsModule } from '@/modules/lists'
|
||||
import { voiceModule } from '@/modules/voice'
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
const allowedOrigins = (process.env.CORS_ORIGIN ?? 'http://localhost:7153')
|
||||
@@ -47,6 +48,7 @@ export function createApp() {
|
||||
app.route('/api/health', healthModule)
|
||||
app.route('/api/lists', listsModule)
|
||||
app.route('/api/invitations', invitationsModule)
|
||||
app.route('/api/voice', voiceModule)
|
||||
|
||||
app.notFound(notFoundHandler)
|
||||
app.onError(errorHandler)
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { betterAuth } from 'better-auth'
|
||||
import { prismaAdapter } from 'better-auth/adapters/prisma'
|
||||
import { emailOTP } from 'better-auth/plugins'
|
||||
|
||||
import { passwordResetEmail } from '@/lib/emails/password-reset'
|
||||
import { acceptPendingInvitations, ensurePrimaryList } from '@/lib/list-membership'
|
||||
import { logger } from '@/lib/logger'
|
||||
import { sendEmail } from '@/lib/mailer'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
|
||||
@@ -9,6 +13,8 @@ const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
|
||||
.map((origin) => origin.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const OTP_EXPIRES_IN_SECONDS = 10 * 60
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: prismaAdapter(prisma, { provider: 'postgresql' }),
|
||||
baseURL: process.env.BETTER_AUTH_URL,
|
||||
@@ -27,7 +33,31 @@ export const auth = betterAuth({
|
||||
enabled: true,
|
||||
minPasswordLength: 8,
|
||||
requireEmailVerification: false,
|
||||
revokeSessionsOnPasswordReset: true,
|
||||
},
|
||||
plugins: [
|
||||
// Password recovery: a 6-digit code sent by email, checked by
|
||||
// /api/auth/email-otp/reset-password. Codes live (hashed) in `verifications`.
|
||||
emailOTP({
|
||||
otpLength: 6,
|
||||
expiresIn: OTP_EXPIRES_IN_SECONDS,
|
||||
allowedAttempts: 3,
|
||||
storeOTP: 'hashed',
|
||||
disableSignUp: true,
|
||||
sendVerificationOTP: async ({ email, otp, type }) => {
|
||||
if (type !== 'forget-password') return
|
||||
|
||||
// Not awaited on purpose: answering at the same speed whether or not the
|
||||
// email exists avoids leaking which addresses have an account.
|
||||
void sendEmail({
|
||||
to: email,
|
||||
...passwordResetEmail({ otp, expiresInMinutes: OTP_EXPIRES_IN_SECONDS / 60 }),
|
||||
}).catch((error: unknown) => {
|
||||
logger.error({ err: error, to: email }, 'failed to send the password reset email')
|
||||
})
|
||||
},
|
||||
}),
|
||||
],
|
||||
databaseHooks: {
|
||||
user: {
|
||||
create: {
|
||||
|
||||
47
apps/api/src/lib/emails/password-reset.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import type { Email } from '@/lib/mailer'
|
||||
|
||||
type PasswordResetEmailInput = {
|
||||
otp: string
|
||||
expiresInMinutes: number
|
||||
}
|
||||
|
||||
/** Builds the "your password reset code" email (in Spanish). */
|
||||
export function passwordResetEmail({
|
||||
otp,
|
||||
expiresInMinutes,
|
||||
}: PasswordResetEmailInput): Omit<Email, 'to'> {
|
||||
const subject = `Tu código para restablecer la contraseña: ${otp}`
|
||||
|
||||
const text = [
|
||||
'Recibimos una solicitud para restablecer la contraseña de tu cuenta de Superlist.',
|
||||
'',
|
||||
`Tu código es: ${otp}`,
|
||||
'',
|
||||
`Vence en ${expiresInMinutes} minutos.`,
|
||||
'Si no lo pediste, ignora este correo: tu contraseña no cambiará.',
|
||||
].join('\n')
|
||||
|
||||
const html = `<!doctype html>
|
||||
<html lang="es">
|
||||
<body style="font-family: ui-sans-serif, system-ui, sans-serif; background:#f4f4f5; padding:32px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:480px; margin:0 auto; background:#ffffff; border-radius:12px; padding:32px;">
|
||||
<tr><td>
|
||||
<h1 style="font-size:20px; margin:0 0 16px;">Restablece tu contraseña</h1>
|
||||
<p style="font-size:15px; line-height:1.5; color:#3f3f46; margin:0 0 24px;">
|
||||
Recibimos una solicitud para restablecer la contraseña de tu cuenta de Superlist.
|
||||
Usa este código para elegir una nueva:
|
||||
</p>
|
||||
<p style="font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size:32px; font-weight:700; letter-spacing:8px; text-align:center; background:#f4f4f5; border-radius:8px; padding:16px; margin:0 0 24px; color:#18181b;">
|
||||
${otp}
|
||||
</p>
|
||||
<p style="font-size:13px; line-height:1.5; color:#71717a; margin:0;">
|
||||
El código vence en ${expiresInMinutes} minutos. Si no lo pediste, ignora este correo:
|
||||
tu contraseña no cambiará.
|
||||
</p>
|
||||
</td></tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>`
|
||||
|
||||
return { subject, html, text }
|
||||
}
|
||||
123
apps/api/src/lib/gemini.ts
Normal 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
|
||||
}
|
||||
}
|
||||
27
apps/api/src/modules/lists/items/delete/route.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { Hono } from 'hono'
|
||||
|
||||
import { requireSession } from '@/lib/auth-session'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { resultJson } from '@/lib/result-json'
|
||||
import { validate } from '@/lib/validate'
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
import { ItemParamsSchema } from '../update/schema'
|
||||
import { DeleteItem } from './use-case'
|
||||
|
||||
/** DELETE /lists/:listId/items/:itemId — deletes an item from a list the user belongs to. */
|
||||
export const deleteItemRoute = new Hono<AppEnv>().delete(
|
||||
'/:itemId',
|
||||
requireSession,
|
||||
validate.param(ItemParamsSchema),
|
||||
async (c) => {
|
||||
const { listId, itemId } = c.req.valid('param')
|
||||
const result = await new DeleteItem(prisma).execute({
|
||||
listId,
|
||||
itemId,
|
||||
userId: c.get('user').id,
|
||||
})
|
||||
|
||||
return resultJson(c, result, { status: 204 })
|
||||
},
|
||||
)
|
||||
75
apps/api/src/modules/lists/items/delete/use-case.test.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
import type { ListEvent } from '@superlist/shared'
|
||||
|
||||
import { ListEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
import { DeleteItem } from './use-case'
|
||||
|
||||
function createDb(options: { membership: unknown; item: { id: string } | null }) {
|
||||
const deletes: unknown[] = []
|
||||
|
||||
const db = {
|
||||
shoppingListMember: {
|
||||
findUnique: async () => options.membership,
|
||||
},
|
||||
listItem: {
|
||||
findFirst: async () => options.item,
|
||||
delete: async (args: unknown) => {
|
||||
deletes.push(args)
|
||||
return options.item
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return { db: db as unknown as Database, deletes }
|
||||
}
|
||||
|
||||
function createBus() {
|
||||
const events = new ListEvents()
|
||||
const published: ListEvent[] = []
|
||||
events.subscribe('list-1', (event) => published.push(event))
|
||||
|
||||
return { events, published }
|
||||
}
|
||||
|
||||
const input = { listId: 'list-1', itemId: 'item-1', userId: 'user-1' }
|
||||
|
||||
describe('DeleteItem', () => {
|
||||
it('answers 404 when the user does not belong to the list', async () => {
|
||||
const { db, deletes } = createDb({ membership: null, item: { id: 'item-1' } })
|
||||
const { events, published } = createBus()
|
||||
const result = await new DeleteItem(db, events).execute(input)
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(404)
|
||||
expect(deletes).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('answers 404 when the item does not belong to the list', async () => {
|
||||
const { db, deletes } = createDb({ membership: { role: 'owner' }, item: null })
|
||||
const { events, published } = createBus()
|
||||
const result = await new DeleteItem(db, events).execute(input)
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(404)
|
||||
expect(deletes).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('deletes the item and publishes item.removed', async () => {
|
||||
const { db, deletes } = createDb({
|
||||
membership: { role: 'collaborator' },
|
||||
item: { id: 'item-1' },
|
||||
})
|
||||
const { events, published } = createBus()
|
||||
const result = await new DeleteItem(db, events).execute(input)
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(deletes).toEqual([{ where: { id: 'item-1' } }])
|
||||
expect(published).toEqual([{ type: 'item.removed', listId: 'list-1', itemId: 'item-1' }])
|
||||
})
|
||||
})
|
||||
42
apps/api/src/modules/lists/items/delete/use-case.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { Failure, Ok, type ProblemDetails, problems, type Result } from '@superlist/shared'
|
||||
|
||||
import { type ListEvents, listEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
type DeleteItemFields = {
|
||||
listId: string
|
||||
itemId: string
|
||||
userId: string
|
||||
}
|
||||
|
||||
/** Deletes an item from a list. Only members can do it. */
|
||||
export class DeleteItem {
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly events: ListEvents = listEvents,
|
||||
) {}
|
||||
|
||||
async execute(input: DeleteItemFields): Promise<Result<void, ProblemDetails>> {
|
||||
const membership = await this.db.shoppingListMember.findUnique({
|
||||
where: { listId_userId: { listId: input.listId, userId: input.userId } },
|
||||
})
|
||||
|
||||
if (!membership) {
|
||||
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
|
||||
}
|
||||
|
||||
const item = await this.db.listItem.findFirst({
|
||||
where: { id: input.itemId, shoppingListId: input.listId },
|
||||
})
|
||||
|
||||
if (!item) {
|
||||
return Failure(problems.notFound('El artículo no existe en esta lista.'))
|
||||
}
|
||||
|
||||
await this.db.listItem.delete({ where: { id: item.id } })
|
||||
|
||||
this.events.publish({ type: 'item.removed', listId: input.listId, itemId: item.id })
|
||||
|
||||
return Ok(undefined)
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,9 @@ import { Hono } from 'hono'
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
import { createItemRoute } from './create/route'
|
||||
import { deleteItemRoute } from './delete/route'
|
||||
import { listItemsRoute } from './list/route'
|
||||
import { moveItemRoute } from './move/route'
|
||||
import { updateItemRoute } from './update/route'
|
||||
|
||||
/** `items` sub-module of `lists`: mounted at `/lists/:listId/items`. */
|
||||
@@ -11,3 +13,5 @@ export const listItemsModule = new Hono<AppEnv>()
|
||||
.route('/', listItemsRoute)
|
||||
.route('/', createItemRoute)
|
||||
.route('/', updateItemRoute)
|
||||
.route('/', moveItemRoute)
|
||||
.route('/', deleteItemRoute)
|
||||
|
||||
31
apps/api/src/modules/lists/items/move/route.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { Hono } from 'hono'
|
||||
|
||||
import { requireSession } from '@/lib/auth-session'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { resultJson } from '@/lib/result-json'
|
||||
import { validate } from '@/lib/validate'
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
import { ItemParamsSchema } from '../update/schema'
|
||||
import { MoveItemSchema } from './schema'
|
||||
import { MoveItem } from './use-case'
|
||||
|
||||
/** POST /lists/:listId/items/:itemId/move — moves an item to another list of the user. */
|
||||
export const moveItemRoute = new Hono<AppEnv>().post(
|
||||
'/:itemId/move',
|
||||
requireSession,
|
||||
validate.param(ItemParamsSchema),
|
||||
validate.json(MoveItemSchema),
|
||||
async (c) => {
|
||||
const { listId, itemId } = c.req.valid('param')
|
||||
const { targetListId } = c.req.valid('json')
|
||||
const result = await new MoveItem(prisma).execute({
|
||||
listId,
|
||||
itemId,
|
||||
userId: c.get('user').id,
|
||||
targetListId,
|
||||
})
|
||||
|
||||
return resultJson(c, result)
|
||||
},
|
||||
)
|
||||
8
apps/api/src/modules/lists/items/move/schema.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
/** Body of `POST /lists/:listId/items/:itemId/move`. */
|
||||
export const MoveItemSchema = z.object({
|
||||
targetListId: z.uuid('El identificador de la lista de destino no es válido'),
|
||||
})
|
||||
|
||||
export type MoveItemInput = z.infer<typeof MoveItemSchema>
|
||||
141
apps/api/src/modules/lists/items/move/use-case.test.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
import type { ListEvent } from '@superlist/shared'
|
||||
|
||||
import { ListEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
import { MoveItem } from './use-case'
|
||||
|
||||
type ItemRow = {
|
||||
id: string
|
||||
shoppingListId: string
|
||||
name: string
|
||||
completed: boolean
|
||||
boughtAt: Date | null
|
||||
quantity: string | null
|
||||
notes: string | null
|
||||
order: number
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
const now = new Date('2026-10-20T10:00:00.000Z')
|
||||
|
||||
const item: ItemRow = {
|
||||
id: 'item-1',
|
||||
shoppingListId: 'list-1',
|
||||
name: 'Leche',
|
||||
completed: false,
|
||||
boughtAt: null,
|
||||
quantity: '1 L',
|
||||
notes: 'sin lactosa',
|
||||
order: 0,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
|
||||
function createDb(options: { memberOf: string[]; item: ItemRow | null }) {
|
||||
const updates: unknown[] = []
|
||||
|
||||
const db = {
|
||||
shoppingListMember: {
|
||||
findUnique: async (args: { where: { listId_userId: { listId: string } } }) =>
|
||||
options.memberOf.includes(args.where.listId_userId.listId) ? { role: 'owner' } : null,
|
||||
},
|
||||
listItem: {
|
||||
findFirst: async () => options.item,
|
||||
update: async (args: { data: Partial<ItemRow> }) => {
|
||||
updates.push(args)
|
||||
return { ...options.item, ...args.data } as ItemRow
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return { db: db as unknown as Database, updates }
|
||||
}
|
||||
|
||||
function createBus() {
|
||||
const events = new ListEvents()
|
||||
const published: ListEvent[] = []
|
||||
events.subscribe('list-1', (event) => published.push(event))
|
||||
events.subscribe('list-2', (event) => published.push(event))
|
||||
|
||||
return { events, published }
|
||||
}
|
||||
|
||||
const input = { listId: 'list-1', itemId: 'item-1', userId: 'user-1', targetListId: 'list-2' }
|
||||
|
||||
describe('MoveItem', () => {
|
||||
it('answers 400 when the target is the same list', async () => {
|
||||
const { db, updates } = createDb({ memberOf: ['list-1'], item })
|
||||
const { events, published } = createBus()
|
||||
const result = await new MoveItem(db, events).execute({ ...input, targetListId: 'list-1' })
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(400)
|
||||
expect(updates).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('answers 404 when the user does not belong to the source list', async () => {
|
||||
const { db, updates } = createDb({ memberOf: ['list-2'], item })
|
||||
const { events, published } = createBus()
|
||||
const result = await new MoveItem(db, events).execute(input)
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(404)
|
||||
expect(updates).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('answers 404 when the user does not belong to the target list', async () => {
|
||||
const { db, updates } = createDb({ memberOf: ['list-1'], item })
|
||||
const { events, published } = createBus()
|
||||
const result = await new MoveItem(db, events).execute(input)
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(404)
|
||||
expect(result.error.detail).toBe('La lista de destino no existe o no tienes acceso.')
|
||||
expect(updates).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('answers 404 when the item does not belong to the source list', async () => {
|
||||
const { db, updates } = createDb({ memberOf: ['list-1', 'list-2'], item: null })
|
||||
const { events, published } = createBus()
|
||||
const result = await new MoveItem(db, events).execute(input)
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(404)
|
||||
expect(updates).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('moves the item, keeping its details, and notifies both lists', async () => {
|
||||
const { db, updates } = createDb({ memberOf: ['list-1', 'list-2'], item })
|
||||
const { events, published } = createBus()
|
||||
const result = await new MoveItem(db, events).execute(input)
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||
|
||||
expect(updates).toEqual([{ where: { id: 'item-1' }, data: { shoppingListId: 'list-2' } }])
|
||||
expect(result.value).toMatchObject({
|
||||
id: 'item-1',
|
||||
listId: 'list-2',
|
||||
name: 'Leche',
|
||||
quantity: '1 L',
|
||||
notes: 'sin lactosa',
|
||||
completed: false,
|
||||
})
|
||||
|
||||
expect(published).toEqual([
|
||||
{ type: 'item.removed', listId: 'list-1', itemId: 'item-1' },
|
||||
{ type: 'item.created', listId: 'list-2', item: result.value },
|
||||
])
|
||||
})
|
||||
})
|
||||
72
apps/api/src/modules/lists/items/move/use-case.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import {
|
||||
Failure,
|
||||
type ListItem,
|
||||
Ok,
|
||||
type ProblemDetails,
|
||||
problems,
|
||||
type Result,
|
||||
} from '@superlist/shared'
|
||||
|
||||
import { type ListEvents, listEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
import { toListItem } from '../serialize'
|
||||
|
||||
type MoveItemFields = {
|
||||
listId: string
|
||||
itemId: string
|
||||
userId: string
|
||||
targetListId: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves an item to another list, keeping its name, quantity, notes and bought
|
||||
* state. The user has to be a member of both lists.
|
||||
*/
|
||||
export class MoveItem {
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly events: ListEvents = listEvents,
|
||||
) {}
|
||||
|
||||
async execute(input: MoveItemFields): Promise<Result<ListItem, ProblemDetails>> {
|
||||
if (input.targetListId === input.listId) {
|
||||
return Failure(problems.badRequest('El artículo ya está en esa lista.'))
|
||||
}
|
||||
|
||||
const membership = await this.db.shoppingListMember.findUnique({
|
||||
where: { listId_userId: { listId: input.listId, userId: input.userId } },
|
||||
})
|
||||
|
||||
if (!membership) {
|
||||
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
|
||||
}
|
||||
|
||||
const targetMembership = await this.db.shoppingListMember.findUnique({
|
||||
where: { listId_userId: { listId: input.targetListId, userId: input.userId } },
|
||||
})
|
||||
|
||||
if (!targetMembership) {
|
||||
return Failure(problems.notFound('La lista de destino no existe o no tienes acceso.'))
|
||||
}
|
||||
|
||||
const item = await this.db.listItem.findFirst({
|
||||
where: { id: input.itemId, shoppingListId: input.listId },
|
||||
})
|
||||
|
||||
if (!item) {
|
||||
return Failure(problems.notFound('El artículo no existe en esta lista.'))
|
||||
}
|
||||
|
||||
const moved = await this.db.listItem.update({
|
||||
where: { id: item.id },
|
||||
data: { shoppingListId: input.targetListId },
|
||||
})
|
||||
|
||||
const dto = toListItem(moved)
|
||||
this.events.publish({ type: 'item.removed', listId: input.listId, itemId: item.id })
|
||||
this.events.publish({ type: 'item.created', listId: input.targetListId, item: dto })
|
||||
|
||||
return Ok(dto)
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import type { AppEnv } from '@/types'
|
||||
import { ItemParamsSchema, UpdateItemSchema } from './schema'
|
||||
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(
|
||||
'/:itemId',
|
||||
requireSession,
|
||||
@@ -17,11 +17,12 @@ export const updateItemRoute = new Hono<AppEnv>().patch(
|
||||
validate.json(UpdateItemSchema),
|
||||
async (c) => {
|
||||
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({
|
||||
listId,
|
||||
itemId,
|
||||
userId: c.get('user').id,
|
||||
name,
|
||||
completed,
|
||||
quantity,
|
||||
notes,
|
||||
|
||||
@@ -11,13 +11,22 @@ export type ItemParams = z.infer<typeof ItemParamsSchema>
|
||||
/** Body of `PATCH /lists/:listId/items/:itemId` — at least one field is required. */
|
||||
export const UpdateItemSchema = z
|
||||
.object({
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, 'El nombre es obligatorio')
|
||||
.max(120, 'Máximo 120 caracteres')
|
||||
.optional(),
|
||||
completed: z.boolean().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(),
|
||||
})
|
||||
.refine(
|
||||
(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.',
|
||||
},
|
||||
|
||||
@@ -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
|
||||
// simulated by merging those fields into the row the query returned.
|
||||
update: async (args: {
|
||||
data: Partial<Pick<ItemRow, 'completed' | 'boughtAt' | 'quantity' | 'notes'>>
|
||||
data: Partial<Pick<ItemRow, 'name' | 'completed' | 'boughtAt' | 'quantity' | 'notes'>>
|
||||
}) => {
|
||||
updates.push(args)
|
||||
return { ...options.item, ...args.data } as ItemRow
|
||||
@@ -170,6 +170,25 @@ describe('UpdateItem', () => {
|
||||
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 () => {
|
||||
const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) })
|
||||
const { events, published } = createBus()
|
||||
|
||||
@@ -16,6 +16,8 @@ type UpdateItemFields = {
|
||||
listId: string
|
||||
itemId: 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. */
|
||||
completed?: boolean
|
||||
/** 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
|
||||
* statistics, and is cleared when the item goes back to pending.
|
||||
*/
|
||||
@@ -53,12 +55,17 @@ export class UpdateItem {
|
||||
}
|
||||
|
||||
const data: {
|
||||
name?: string
|
||||
completed?: boolean
|
||||
boughtAt?: Date | null
|
||||
quantity?: string | null
|
||||
notes?: string | null
|
||||
} = {}
|
||||
|
||||
if (input.name !== undefined) {
|
||||
data.name = input.name.trim()
|
||||
}
|
||||
|
||||
if (input.completed !== undefined) {
|
||||
data.completed = input.completed
|
||||
data.boughtAt = input.completed ? new Date() : null
|
||||
|
||||
8
apps/api/src/modules/voice/index.ts
Normal 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)
|
||||
60
apps/api/src/modules/voice/split/items.test.ts
Normal 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)
|
||||
})
|
||||
})
|
||||
91
apps/api/src/modules/voice/split/items.ts
Normal 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)
|
||||
}
|
||||
30
apps/api/src/modules/voice/split/prompt.ts
Normal 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 }],
|
||||
}
|
||||
}
|
||||
151
apps/api/src/modules/voice/split/route.test.ts
Normal 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)
|
||||
})
|
||||
})
|
||||
23
apps/api/src/modules/voice/split/route.ts
Normal 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)
|
||||
},
|
||||
)
|
||||
13
apps/api/src/modules/voice/split/schema.ts
Normal 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>
|
||||
54
apps/api/src/modules/voice/split/use-case.ts
Normal 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) })
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 2.9 KiB After Width: | Height: | Size: 5.1 KiB |
@@ -1,14 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32" height="32" role="img" aria-label="Superlist">
|
||||
<rect width="32" height="32" rx="7" fill="#0a0a0a" />
|
||||
<text
|
||||
x="16"
|
||||
y="17"
|
||||
text-anchor="middle"
|
||||
dominant-baseline="middle"
|
||||
font-family="'Geist Variable', Helvetica, Arial, sans-serif"
|
||||
font-size="15"
|
||||
font-weight="600"
|
||||
letter-spacing="-0.6"
|
||||
fill="#fafafa"
|
||||
>SL</text>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-label="Superlist">
|
||||
<rect width="512" height="512" rx="116" fill="#287c39"/>
|
||||
<path d="M190 206c0-58 26-86 66-86s66 28 66 86" fill="none" stroke="#faf9f6" stroke-width="26" stroke-linecap="round"/>
|
||||
<path d="M150 196h212l20 196H130z" fill="#faf9f6" stroke="#faf9f6" stroke-width="44" stroke-linejoin="round"/>
|
||||
<path d="M198 300l42 42 78-80" fill="none" stroke="#287c39" stroke-width="34" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 431 B After Width: | Height: | Size: 552 B |
|
Before Width: | Height: | Size: 8.9 KiB After Width: | Height: | Size: 13 KiB |
@@ -1,14 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-label="Superlist">
|
||||
<rect width="512" height="512" fill="#0a0a0a" />
|
||||
<text
|
||||
x="256"
|
||||
y="270"
|
||||
text-anchor="middle"
|
||||
dominant-baseline="middle"
|
||||
font-family="'Geist Variable', Helvetica, Arial, sans-serif"
|
||||
font-size="216"
|
||||
font-weight="600"
|
||||
letter-spacing="-9"
|
||||
fill="#fafafa"
|
||||
>SL</text>
|
||||
<rect width="512" height="512" fill="#287c39"/>
|
||||
<g transform="translate(256 262) scale(0.78) translate(-256 -262)">
|
||||
<path d="M190 206c0-58 26-86 66-86s66 28 66 86" fill="none" stroke="#faf9f6" stroke-width="26" stroke-linecap="round"/>
|
||||
<path d="M150 196h212l20 196H130z" fill="#faf9f6" stroke="#faf9f6" stroke-width="44" stroke-linejoin="round"/>
|
||||
<path d="M198 300l42 42 78-80" fill="none" stroke="#287c39" stroke-width="34" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 431 B After Width: | Height: | Size: 620 B |
|
Before Width: | Height: | Size: 5.0 KiB After Width: | Height: | Size: 7.4 KiB |
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 22 KiB |
50
apps/web/src/components/app-logo.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
/**
|
||||
* Superlist's mark: a shopping bag with a check, on the app's green. It is the same
|
||||
* drawing as `public/favicon.svg` and the PWA icons, so keep them in sync.
|
||||
*/
|
||||
export function AppLogo({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 512 512"
|
||||
className={cn('size-8 shrink-0', className)}
|
||||
role="img"
|
||||
aria-label="Superlist"
|
||||
>
|
||||
<rect width="512" height="512" rx="116" fill="#287c39" />
|
||||
<path
|
||||
d="M190 206c0-58 26-86 66-86s66 28 66 86"
|
||||
fill="none"
|
||||
stroke="#faf9f6"
|
||||
strokeWidth="26"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<path
|
||||
d="M150 196h212l20 196H130z"
|
||||
fill="#faf9f6"
|
||||
stroke="#faf9f6"
|
||||
strokeWidth="44"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M198 300l42 42 78-80"
|
||||
fill="none"
|
||||
stroke="#287c39"
|
||||
strokeWidth="34"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
/** The mark next to the "Superlist" name, for the sign-in and sign-up pages. */
|
||||
export function AppBrand({ className }: { className?: string }) {
|
||||
return (
|
||||
<div className={cn('flex items-center justify-center gap-2.5', className)}>
|
||||
<AppLogo className="size-10" />
|
||||
<span className="text-2xl font-bold tracking-tight">Superlist</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,39 +1,47 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { ChevronDownIcon } from 'lucide-react'
|
||||
import { CheckIcon, ChevronDownIcon } from 'lucide-react'
|
||||
|
||||
import { Card } from '@/components/ui/card'
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
|
||||
import type { useUpdateItem } from '@/hooks/use-items'
|
||||
|
||||
import { ItemRow, type ItemRowProps } from './item-row'
|
||||
import { ItemRow } from './item-row'
|
||||
|
||||
type BoughtItemListProps = {
|
||||
items: ListItem[]
|
||||
updateItem: ReturnType<typeof useUpdateItem>
|
||||
savingIds: string[]
|
||||
/** The editing state of each row, owned by the parent so only one row edits at a time. */
|
||||
editingProps: (itemId: string) => Pick<ItemRowProps, 'editing' | 'onEditingChange'>
|
||||
onEdit: (item: ListItem) => void
|
||||
onMove: (item: ListItem) => void
|
||||
onDelete: (item: ListItem) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapsible "Comprados" card below the pending items. Expanded by default so
|
||||
* marking an item visibly moves it down; the user can fold it. Tapping an item
|
||||
* here un-buys it and it returns to the pending list.
|
||||
* Collapsible "Comprados (N)" section at the end of the list, folded by default so
|
||||
* the pending items stay in focus. Tapping an item here un-buys it and it returns
|
||||
* to the pending list.
|
||||
*/
|
||||
export function BoughtItemList({
|
||||
items,
|
||||
updateItem,
|
||||
savingIds,
|
||||
editingProps,
|
||||
onEdit,
|
||||
onMove,
|
||||
onDelete,
|
||||
}: BoughtItemListProps) {
|
||||
return (
|
||||
<Collapsible defaultOpen asChild>
|
||||
<Card className="gap-0 py-0">
|
||||
<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">
|
||||
<ChevronDownIcon className="size-5 transition-transform group-data-[state=closed]:-rotate-90" />
|
||||
<span className="text-base">Comprados · {items.length}</span>
|
||||
<Collapsible asChild>
|
||||
<section className="border-border overflow-hidden rounded-xl border border-dashed">
|
||||
<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">
|
||||
<CheckIcon className="text-primary size-4" strokeWidth={2.5} aria-hidden />
|
||||
<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>
|
||||
<CollapsibleContent>
|
||||
<Card className="gap-0 rounded-none border-x-0 border-b-0 py-0 shadow-none">
|
||||
<ul className="divide-y">
|
||||
{items.map((item) => (
|
||||
<ItemRow
|
||||
@@ -41,12 +49,15 @@ export function BoughtItemList({
|
||||
item={item}
|
||||
updateItem={updateItem}
|
||||
isSaving={savingIds.includes(item.id)}
|
||||
{...editingProps(item.id)}
|
||||
onEdit={() => onEdit(item)}
|
||||
onMove={() => onMove(item)}
|
||||
onDelete={() => onDelete(item)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
</CollapsibleContent>
|
||||
</Card>
|
||||
</CollapsibleContent>
|
||||
</section>
|
||||
</Collapsible>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { PlusIcon, SearchIcon } from 'lucide-react'
|
||||
import { type ClipboardEvent, useState } from 'react'
|
||||
import { Loader2Icon, MicIcon, PlusIcon } from 'lucide-react'
|
||||
import { type ClipboardEvent, useEffect, useState } from 'react'
|
||||
import { useForm, useWatch } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { ItemInputPreview, type PreviewItem } from '@/components/items/item-input-preview'
|
||||
import { ItemInputPreview } from '@/components/items/item-input-preview'
|
||||
import { Field, FieldError } from '@/components/ui/field'
|
||||
import {
|
||||
InputGroup,
|
||||
@@ -14,15 +12,17 @@ import {
|
||||
InputGroupButton,
|
||||
InputGroupInput,
|
||||
} from '@/components/ui/input-group'
|
||||
import { isOptimisticItem, useCreateItem, useItems, useUpdateItem } from '@/hooks/use-items'
|
||||
import { ApiError } from '@/lib/api-client'
|
||||
import { findDuplicate, mergeBatch, mergeInto } from '@/lib/natural-input/merge'
|
||||
import { isPlainItem, literalItem, parseItemInput } from '@/lib/natural-input/parse-item'
|
||||
import { itemLimitError, readItems, useAddItems } from '@/hooks/use-add-items'
|
||||
import { useDictation } from '@/hooks/use-dictation'
|
||||
import { useKeyboardDictation } from '@/hooks/use-keyboard-dictation'
|
||||
import { isPlainItem } from '@/lib/natural-input/parse-item'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
// The input may hold several items ("leche, pan y 2 pascualinas" or a pasted list);
|
||||
// each one is checked against the API limits once the text is read.
|
||||
const createItemSchema = z.object({
|
||||
name: z.string().trim().min(1, 'Escribe un artículo').max(2000, 'Máximo 2000 caracteres'),
|
||||
// Not called `name`: iOS offers to autofill a contact into an input named that way.
|
||||
entry: z.string().trim().min(1, 'Escribe un artículo').max(2000, 'Máximo 2000 caracteres'),
|
||||
})
|
||||
|
||||
type CreateItemValues = z.infer<typeof createItemSchema>
|
||||
@@ -55,92 +55,91 @@ export function refocusNewItemInput(): void {
|
||||
document.getElementById(NEW_ITEM_INPUT_ID)?.focus()
|
||||
}
|
||||
|
||||
/** Why a read item cannot be sent as is, mirroring the API limits, or `null`. */
|
||||
function itemLimitError(item: PreviewItem): string | null {
|
||||
if (item.name.length > 120) return `«${item.name.slice(0, 20)}…»: máximo 120 caracteres`
|
||||
if ((item.quantity?.length ?? 0) > 40) return `«${item.name}»: la cantidad es demasiado larga`
|
||||
if ((item.notes?.length ?? 0) > 280) return `«${item.name}»: la nota es demasiado larga`
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* 2 pascualinas"), previewed while typing, and an item already pending is added to
|
||||
* 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) {
|
||||
const createItem = useCreateItem(listId)
|
||||
const updateItem = useUpdateItem(listId)
|
||||
const { data: items } = useItems(listId)
|
||||
// The text the user asked to add as typed; editing it brings the reading back.
|
||||
const [literalText, setLiteralText] = useState<string | null>(null)
|
||||
|
||||
const form = useForm<CreateItemValues>({
|
||||
resolver: zodResolver(createItemSchema),
|
||||
defaultValues: { name: '' },
|
||||
defaultValues: { entry: '' },
|
||||
})
|
||||
|
||||
const text = useWatch({ control: form.control, name: 'name' })
|
||||
const text = useWatch({ control: form.control, name: 'entry' })
|
||||
const literal = literalText !== null && literalText === text
|
||||
// Placeholders have no server id yet, so they cannot be added to.
|
||||
const existing = (items ?? []).filter((item) => !isOptimisticItem(item))
|
||||
const preview = readItems(text, literal, existing)
|
||||
const showPreview =
|
||||
text.trim() !== '' &&
|
||||
(literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate))
|
||||
|
||||
const restoreText = (source: string, message: string) => {
|
||||
const current = form.getValues('name').trim()
|
||||
form.setValue('name', current ? `${current}; ${source}` : source)
|
||||
form.setError('name', { message })
|
||||
const current = form.getValues('entry').trim()
|
||||
form.setValue('entry', current ? `${current}; ${source}` : source)
|
||||
form.setError('entry', { message })
|
||||
}
|
||||
|
||||
// A failed item comes back to the input, and so does a dictation that breaks the limits.
|
||||
const { existing, addItems, addDictation, processing } = useAddItems(listId, {
|
||||
onItemFailed: restoreText,
|
||||
onDictationRejected: (transcript, message) => {
|
||||
form.setValue('entry', transcript)
|
||||
form.setError('entry', { message })
|
||||
},
|
||||
})
|
||||
|
||||
const dictation = useDictation({ onTranscript: (transcript) => onTranscript(transcript) })
|
||||
// The keyboard's own microphone (the only one in the installed iOS app) just writes
|
||||
// text: once it has been quiet for a few seconds, that text is added as a dictation.
|
||||
const keyboardDictation = useKeyboardDictation({
|
||||
onIdle: () => {
|
||||
const dictated = form.getValues('entry').trim()
|
||||
if (dictated && !dictation.listening && !processing) onTranscript(dictated)
|
||||
},
|
||||
})
|
||||
const dictating = dictation.listening || processing
|
||||
|
||||
// The partial transcript is shown in the input while the user talks.
|
||||
useEffect(() => {
|
||||
if (dictation.listening) form.setValue('entry', dictation.interim)
|
||||
}, [dictation.listening, dictation.interim, form])
|
||||
|
||||
const preview = readItems(text, literal, existing)
|
||||
const showPreview =
|
||||
!dictating &&
|
||||
text.trim() !== '' &&
|
||||
(literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate))
|
||||
|
||||
// The input clears at once (items are added optimistically) so several items can be
|
||||
// typed in a row; if a request fails its text comes back with the error.
|
||||
const onSubmit = form.handleSubmit((values) => {
|
||||
const toAdd = readItems(values.name, literal, existing)
|
||||
keyboardDictation.cancel()
|
||||
const toAdd = readItems(values.entry, literal, existing)
|
||||
|
||||
const limitError = toAdd.map(itemLimitError).find(Boolean)
|
||||
if (limitError) {
|
||||
form.setError('name', { message: limitError })
|
||||
form.setError('entry', { message: limitError })
|
||||
return
|
||||
}
|
||||
|
||||
form.reset()
|
||||
setLiteralText(null)
|
||||
form.setFocus('name')
|
||||
form.setFocus('entry')
|
||||
|
||||
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 })
|
||||
}
|
||||
toast(
|
||||
patch.quantity
|
||||
? `Se sumó a «${item.duplicate.name}» (${patch.quantity})`
|
||||
: `«${item.duplicate.name}» ya está en la lista`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
createItem.mutate(
|
||||
{ name: item.name, quantity: item.quantity ?? undefined, notes: item.notes ?? undefined },
|
||||
{
|
||||
onError: (error) =>
|
||||
restoreText(
|
||||
item.source,
|
||||
error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos añadir el artículo.',
|
||||
),
|
||||
},
|
||||
)
|
||||
}
|
||||
addItems(toAdd)
|
||||
})
|
||||
|
||||
/** A dictation clears the input and goes through `addDictation`. */
|
||||
const onTranscript = (transcript: string) => {
|
||||
keyboardDictation.cancel()
|
||||
form.reset()
|
||||
setLiteralText(null)
|
||||
void addDictation(transcript)
|
||||
}
|
||||
|
||||
// An <input> drops line breaks, so a pasted list keeps one item per line as "; ".
|
||||
const onPaste = (event: ClipboardEvent<HTMLInputElement>) => {
|
||||
const pasted = event.clipboardData.getData('text')
|
||||
@@ -156,36 +155,36 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
.filter(Boolean)
|
||||
.join('; ')
|
||||
|
||||
form.setValue('name', input.value.slice(0, start) + lines + input.value.slice(end), {
|
||||
form.setValue('entry', input.value.slice(0, start) + lines + input.value.slice(end), {
|
||||
shouldDirty: true,
|
||||
})
|
||||
}
|
||||
|
||||
const micLabel = processing
|
||||
? 'Procesando el dictado'
|
||||
: dictation.listening
|
||||
? 'Dejar de escuchar'
|
||||
: 'Dictar productos'
|
||||
|
||||
return (
|
||||
<form onSubmit={onSubmit}>
|
||||
<Field data-invalid={!!form.formState.errors.name}>
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
// Enter while dictating ends the dictation: what was heard goes through its flow.
|
||||
if (!dictation.listening) return onSubmit(event)
|
||||
event.preventDefault()
|
||||
dictation.stop()
|
||||
}}
|
||||
>
|
||||
<Field data-invalid={!!form.formState.errors.entry}>
|
||||
<InputGroup className="bg-card h-14 rounded-full shadow-xs dark:bg-card">
|
||||
<InputGroupAddon className="pl-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">
|
||||
<InputGroupAddon className="pl-1.5">
|
||||
<InputGroupButton
|
||||
type="submit"
|
||||
variant="default"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
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
|
||||
// would close the keyboard between one item and the next.
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
@@ -193,8 +192,58 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
<PlusIcon className="size-5" strokeWidth={2.5} />
|
||||
</InputGroupButton>
|
||||
</InputGroupAddon>
|
||||
<InputGroupInput
|
||||
id={NEW_ITEM_INPUT_ID}
|
||||
aria-label="Nuevo artículo"
|
||||
aria-invalid={!!form.formState.errors.entry}
|
||||
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}
|
||||
onKeyDown={keyboardDictation.onKeyDown}
|
||||
onInput={keyboardDictation.onInput}
|
||||
{...form.register('entry', { 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={() => {
|
||||
keyboardDictation.cancel()
|
||||
if (dictation.listening) dictation.stop()
|
||||
else dictation.start()
|
||||
}}
|
||||
>
|
||||
{processing ? (
|
||||
<Loader2Icon className="size-5 animate-spin" />
|
||||
) : (
|
||||
<MicIcon className="size-5" />
|
||||
)}
|
||||
</InputGroupButton>
|
||||
</InputGroupAddon>
|
||||
)}
|
||||
</InputGroup>
|
||||
<FieldError errors={[form.formState.errors.name]} className="px-5" />
|
||||
<FieldError errors={[form.formState.errors.entry]} className="px-5" />
|
||||
{dictation.error && (
|
||||
<p id="dictation-error" className="text-muted-foreground px-5 text-sm" aria-live="polite">
|
||||
{dictation.error}
|
||||
</p>
|
||||
)}
|
||||
{showPreview && (
|
||||
<ItemInputPreview
|
||||
items={preview}
|
||||
@@ -206,12 +255,3 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
/** The items `text` adds, each with the pending item it repeats, if any. */
|
||||
function readItems(text: string, literal: boolean, existing: ListItem[]): PreviewItem[] {
|
||||
if (!text.trim()) return []
|
||||
|
||||
const items = literal ? [literalItem(text)] : mergeBatch(parseItemInput(text))
|
||||
|
||||
return items.map((item) => ({ ...item, duplicate: findDuplicate(existing, item.name) }))
|
||||
}
|
||||
|
||||
88
apps/web/src/components/items/dictate-items-button.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import { Loader2Icon, MicIcon, SquareIcon } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useAddItems } from '@/hooks/use-add-items'
|
||||
import { DICTATION_MESSAGES, useMicrophoneDictation } from '@/hooks/use-microphone-dictation'
|
||||
|
||||
type DictateItemsButtonProps = {
|
||||
listId: string
|
||||
}
|
||||
|
||||
/**
|
||||
* "Dictar ítems" for an empty list: listens until the user stops it and adds what was
|
||||
* said through the same flow as the input's microphone (split by the API, undoable).
|
||||
*/
|
||||
export function DictateItemsButton({ listId }: DictateItemsButtonProps) {
|
||||
const [message, setMessage] = useState<string | null>(null)
|
||||
const { addDictation, processing } = useAddItems(listId, {
|
||||
onItemFailed: (source, detail) => toast.error(`No pudimos añadir «${source}»: ${detail}`),
|
||||
onDictationRejected: (_, detail) => setMessage(detail),
|
||||
})
|
||||
|
||||
const dictation = useMicrophoneDictation({
|
||||
onPhrases: async (phrases) => {
|
||||
const understood = await addDictation(phrases.join('\n'))
|
||||
if (understood === 0) setMessage(DICTATION_MESSAGES.empty)
|
||||
},
|
||||
onError: setMessage,
|
||||
})
|
||||
|
||||
const listening = dictation.status === 'listening'
|
||||
const busy = dictation.status === 'requesting' || processing
|
||||
|
||||
const label = processing
|
||||
? 'Procesando el dictado'
|
||||
: dictation.status === 'requesting'
|
||||
? 'Pidiendo acceso al micrófono'
|
||||
: listening
|
||||
? 'Detener dictado'
|
||||
: 'Dictar ítems'
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant={listening ? 'default' : 'secondary'}
|
||||
aria-label={label}
|
||||
aria-pressed={listening}
|
||||
disabled={busy}
|
||||
className="relative rounded-full"
|
||||
onClick={() => {
|
||||
setMessage(null)
|
||||
if (listening) dictation.stop()
|
||||
else dictation.start()
|
||||
}}
|
||||
>
|
||||
{busy ? (
|
||||
<Loader2Icon className="animate-spin" />
|
||||
) : listening ? (
|
||||
<SquareIcon className="fill-current" />
|
||||
) : (
|
||||
<MicIcon />
|
||||
)}
|
||||
{listening ? 'Detener dictado' : 'Dictar ítems'}
|
||||
</Button>
|
||||
|
||||
<div aria-live="polite" className="flex flex-col items-center gap-1 text-sm">
|
||||
{listening && (
|
||||
<p className="text-primary flex items-center gap-2 font-medium">
|
||||
<span className="relative flex size-2.5" aria-hidden="true">
|
||||
<span className="bg-primary absolute inline-flex size-full rounded-full opacity-75 motion-safe:animate-ping" />
|
||||
<span className="bg-primary relative inline-flex size-2.5 rounded-full" />
|
||||
</span>
|
||||
Micrófono activo, te escuchamos
|
||||
</p>
|
||||
)}
|
||||
{listening && dictation.heard && (
|
||||
<p className="text-muted-foreground max-w-xs">{dictation.heard}</p>
|
||||
)}
|
||||
{listening && !dictation.heard && (
|
||||
<p className="text-muted-foreground">Di «nuevo ítem» o haz una pausa entre artículos.</p>
|
||||
)}
|
||||
{message && !listening && <p className="text-destructive max-w-xs">{message}</p>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -1,17 +1,27 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { ShoppingBasketIcon } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useItems, usePendingItemUpdates, useUpdateItem } from '@/hooks/use-items'
|
||||
import {
|
||||
useDeleteItem,
|
||||
useItems,
|
||||
usePendingDeletions,
|
||||
usePendingItemUpdates,
|
||||
useUpdateItem,
|
||||
} from '@/hooks/use-items'
|
||||
import { useListEvents } from '@/hooks/use-list-events'
|
||||
import { useToday } from '@/hooks/use-today'
|
||||
import { ApiError } from '@/lib/api-client'
|
||||
import { splitItems } from '@/lib/items'
|
||||
|
||||
import { BoughtItemList } from './bought-item-list'
|
||||
import { DictateItemsButton } from './dictate-items-button'
|
||||
import { ItemRow } from './item-row'
|
||||
import { ItemSheet } from './item-sheet'
|
||||
import { MoveItemDialog } from './move-item-dialog'
|
||||
|
||||
type ItemListProps = {
|
||||
listId: string
|
||||
@@ -19,22 +29,31 @@ type ItemListProps = {
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function ItemList({ listId }: ItemListProps) {
|
||||
const { data: items, isPending, error } = useItems(listId)
|
||||
const updateItem = useUpdateItem(listId)
|
||||
const savingIds = usePendingItemUpdates(listId)
|
||||
const deleteItem = useDeleteItem(listId)
|
||||
// Just-deleted items stay hidden while they can still be restored.
|
||||
const deletingIds = usePendingDeletions()
|
||||
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)
|
||||
// The item whose "move to another list" dialog is open.
|
||||
const [movingItem, setMovingItem] = useState<ListItem | null>(null)
|
||||
|
||||
const editingProps = (itemId: string) => ({
|
||||
editing: editingId === itemId,
|
||||
onEditingChange: (editing: boolean) =>
|
||||
setEditingId((current) => (editing ? itemId : current === itemId ? null : current)),
|
||||
})
|
||||
const handleDelete = (item: ListItem) => {
|
||||
setEditingId((current) => (current === item.id ? null : current))
|
||||
deleteItem(item)
|
||||
}
|
||||
|
||||
const openMoveDialog = (item: ListItem) => {
|
||||
setEditingId((current) => (current === item.id ? null : current))
|
||||
setMovingItem(item)
|
||||
}
|
||||
|
||||
// Live updates: another member adds or buys an item and this list refreshes.
|
||||
useListEvents(listId)
|
||||
@@ -62,7 +81,13 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
)
|
||||
}
|
||||
|
||||
const { pending, boughtToday } = splitItems(items, today)
|
||||
const { pending, boughtToday } = splitItems(
|
||||
items.filter((item) => !deletingIds.has(item.id)),
|
||||
today,
|
||||
)
|
||||
|
||||
const editingItem =
|
||||
items.find((item) => item.id === editingId && !deletingIds.has(item.id)) ?? null
|
||||
|
||||
if (pending.length === 0 && boughtToday.length === 0) {
|
||||
return (
|
||||
@@ -77,6 +102,7 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
Usa el campo de arriba para añadir tu primer artículo.
|
||||
</p>
|
||||
</div>
|
||||
<DictateItemsButton listId={listId} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
@@ -93,7 +119,9 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
item={item}
|
||||
updateItem={updateItem}
|
||||
isSaving={savingIds.includes(item.id)}
|
||||
{...editingProps(item.id)}
|
||||
onEdit={() => setEditingId(item.id)}
|
||||
onMove={() => openMoveDialog(item)}
|
||||
onDelete={() => handleDelete(item)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
@@ -105,9 +133,19 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
items={boughtToday}
|
||||
updateItem={updateItem}
|
||||
savingIds={savingIds}
|
||||
editingProps={editingProps}
|
||||
onEdit={(item) => setEditingId(item.id)}
|
||||
onMove={openMoveDialog}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
)}
|
||||
|
||||
<ItemSheet
|
||||
item={editingItem}
|
||||
updateItem={updateItem}
|
||||
onClose={() => setEditingId(null)}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
<MoveItemDialog listId={listId} item={movingItem} onClose={() => setMovingItem(null)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { CheckIcon, PencilIcon } from 'lucide-react'
|
||||
import { CheckIcon, FolderInputIcon, PencilIcon, Trash2Icon } from 'lucide-react'
|
||||
import { type PointerEvent, useRef, useState } from 'react'
|
||||
import { flushSync } from 'react-dom'
|
||||
|
||||
import { ItemEditor } from '@/components/items/item-editor'
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuTrigger,
|
||||
} from '@/components/ui/context-menu'
|
||||
import { isOptimisticItem, type useUpdateItem } from '@/hooks/use-items'
|
||||
import { quantityLabel } from '@/lib/items'
|
||||
import { cn } from '@/lib/utils'
|
||||
@@ -13,56 +18,65 @@ export type ItemRowProps = {
|
||||
updateItem: ReturnType<typeof useUpdateItem>
|
||||
/** This item's bought state is being saved; only this row waits for it. */
|
||||
isSaving: boolean
|
||||
/** The inline editor of this row is open (only one row edits at a time). */
|
||||
editing: boolean
|
||||
onEditingChange: (editing: boolean) => void
|
||||
/** Opens the edit sheet for this item. */
|
||||
onEdit: () => void
|
||||
/** Opens the "move to another list" dialog for this item. */
|
||||
onMove: () => void
|
||||
/** Deletes the item (it can be undone for a few seconds). */
|
||||
onDelete: () => void
|
||||
}
|
||||
|
||||
/** Horizontal drag (px) that turns a touch on the row into "edit the item". */
|
||||
const SWIPE_THRESHOLD = 48
|
||||
const EDIT_THRESHOLD = 48
|
||||
|
||||
/** Furthest the row slides while dragged, so it never leaves the card. */
|
||||
const MAX_DRAG = SWIPE_THRESHOLD * 1.5
|
||||
/** A longer drag (px) that turns it into "move the item to another list". */
|
||||
const MOVE_THRESHOLD = 120
|
||||
|
||||
/**
|
||||
* How far the row is drawn for a finger `dx` px to the left: it follows the
|
||||
* finger up to the threshold and then resists, capped at `MAX_DRAG`.
|
||||
* Drag (px) to the right that turns a touch into "delete the item". Longer than
|
||||
* the edit swipe because it is destructive (even if it can be undone).
|
||||
*/
|
||||
const DELETE_THRESHOLD = 96
|
||||
|
||||
/** What releasing the finger does, decided by how far the row was dragged. */
|
||||
type SwipeAction = 'edit' | 'move' | 'delete'
|
||||
|
||||
/**
|
||||
* How far the row is drawn for a finger `dx` px away: it follows the finger up
|
||||
* to the furthest threshold on that side and then resists, capped a bit past it
|
||||
* so the row never leaves the card. Negative is to the left.
|
||||
*/
|
||||
function dragOffset(dx: number): number {
|
||||
if (dx >= 0) return 0
|
||||
const distance = -dx
|
||||
const resisted =
|
||||
distance <= SWIPE_THRESHOLD ? distance : SWIPE_THRESHOLD + (distance - SWIPE_THRESHOLD) / 3
|
||||
const limit = dx < 0 ? MOVE_THRESHOLD : DELETE_THRESHOLD
|
||||
const distance = Math.abs(dx)
|
||||
const resisted = distance <= limit ? distance : limit + (distance - limit) / 3
|
||||
|
||||
return -Math.min(resisted, MAX_DRAG)
|
||||
return Math.sign(dx) * Math.min(resisted, limit * 1.25)
|
||||
}
|
||||
|
||||
function swipeAction(dx: number): SwipeAction | null {
|
||||
if (dx < -MOVE_THRESHOLD) return 'move'
|
||||
if (dx < -EDIT_THRESHOLD) return 'edit'
|
||||
if (dx > DELETE_THRESHOLD) return 'delete'
|
||||
return null
|
||||
}
|
||||
|
||||
/** A single item row inside a grouped card: tapping it toggles its bought state. */
|
||||
export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }: ItemRowProps) {
|
||||
export function ItemRow({ item, updateItem, isSaving, onEdit, onMove, onDelete }: ItemRowProps) {
|
||||
const [dragX, setDragX] = useState(0)
|
||||
const swipeStart = useRef<{ x: number; y: number } | null>(null)
|
||||
// Set once a drag passes the threshold: releasing the finger then opens the
|
||||
// editor, and the click that the touch may fire right after is ignored.
|
||||
const swiped = useRef(false)
|
||||
const quantityInputRef = useRef<HTMLInputElement>(null)
|
||||
// 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.
|
||||
const swiped = useRef<SwipeAction | null>(null)
|
||||
const [action, setAction] = useState<SwipeAction | null>(null)
|
||||
|
||||
// A placeholder has no server id yet, so it cannot be toggled or edited.
|
||||
const editable = !isSaving && !isOptimisticItem(item)
|
||||
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>) => {
|
||||
// Mice edit through right-click; only touch drags are tracked here.
|
||||
swiped.current = false
|
||||
// Mice use the right-click menu; only touch drags are tracked here.
|
||||
swiped.current = null
|
||||
if (!editable || event.pointerType === 'mouse') return
|
||||
swipeStart.current = { x: event.clientX, y: event.clientY }
|
||||
}
|
||||
@@ -78,20 +92,25 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }
|
||||
if (!swiped.current && Math.abs(dx) <= Math.abs(dy)) return
|
||||
|
||||
setDragX(dragOffset(dx))
|
||||
swiped.current = dx < -SWIPE_THRESHOLD
|
||||
swiped.current = swipeAction(dx)
|
||||
setAction(swiped.current)
|
||||
}
|
||||
|
||||
const handlePointerUp = () => {
|
||||
const shouldOpen = swipeStart.current !== null && swiped.current
|
||||
const released = swipeStart.current !== null ? swiped.current : null
|
||||
swipeStart.current = null
|
||||
setDragX(0)
|
||||
if (shouldOpen) openEditor()
|
||||
setAction(null)
|
||||
if (released === 'edit') onEdit()
|
||||
if (released === 'move') onMove()
|
||||
if (released === 'delete') onDelete()
|
||||
}
|
||||
|
||||
const handlePointerCancel = () => {
|
||||
swipeStart.current = null
|
||||
swiped.current = false
|
||||
swiped.current = null
|
||||
setDragX(0)
|
||||
setAction(null)
|
||||
}
|
||||
|
||||
const dragging = swipeStart.current !== null && dragX !== 0
|
||||
@@ -99,23 +118,50 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }
|
||||
return (
|
||||
<li>
|
||||
<div className="relative overflow-hidden">
|
||||
{dragX !== 0 && (
|
||||
{dragX > 0 && (
|
||||
<div
|
||||
className="bg-primary/15 text-primary absolute inset-y-0 right-0 flex items-center justify-center"
|
||||
className={cn(
|
||||
'absolute inset-y-0 left-0 flex items-center justify-center transition-colors',
|
||||
// Past the threshold the background turns solid: releasing deletes.
|
||||
action === 'delete'
|
||||
? 'bg-destructive text-white'
|
||||
: 'bg-destructive/15 text-destructive',
|
||||
)}
|
||||
style={{ width: dragX }}
|
||||
aria-hidden
|
||||
>
|
||||
<Trash2Icon className="size-5" />
|
||||
</div>
|
||||
)}
|
||||
{dragX < 0 && (
|
||||
<div
|
||||
className={cn(
|
||||
'absolute inset-y-0 right-0 flex items-center justify-center transition-colors',
|
||||
// Past the move threshold the background changes, so the user
|
||||
// knows releasing now moves the item instead of editing it.
|
||||
action === 'move'
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-primary/15 text-primary',
|
||||
)}
|
||||
style={{ width: -dragX }}
|
||||
aria-hidden
|
||||
>
|
||||
{action === 'move' ? (
|
||||
<FolderInputIcon className="size-5" />
|
||||
) : (
|
||||
<PencilIcon className="size-5" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild disabled={!editable}>
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={item.completed}
|
||||
aria-expanded={editing}
|
||||
disabled={!editable}
|
||||
onClick={() => {
|
||||
if (swiped.current) {
|
||||
swiped.current = false
|
||||
swiped.current = null
|
||||
return
|
||||
}
|
||||
|
||||
@@ -125,12 +171,6 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerUp}
|
||||
onPointerCancel={handlePointerCancel}
|
||||
// Right-click is the desktop equivalent of the swipe: edit the item.
|
||||
onContextMenu={(event) => {
|
||||
if (!editable) return
|
||||
event.preventDefault()
|
||||
openEditor()
|
||||
}}
|
||||
style={dragX !== 0 ? { transform: `translateX(${dragX}px)` } : undefined}
|
||||
className={cn(
|
||||
'bg-card hover:bg-muted/50 focus-visible:bg-muted/50 relative flex w-full cursor-pointer touch-pan-y items-center gap-4 px-4 py-3.5 text-left outline-none disabled:cursor-default disabled:opacity-60',
|
||||
@@ -164,17 +204,31 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }
|
||||
<span className="text-muted-foreground truncate text-sm">{item.notes}</span>
|
||||
)}
|
||||
</span>
|
||||
{quantity && <span className="text-muted-foreground shrink-0 text-sm">{quantity}</span>}
|
||||
</button>
|
||||
</div>
|
||||
{editing && (
|
||||
<ItemEditor
|
||||
item={item}
|
||||
updateItem={updateItem}
|
||||
onClose={() => onEditingChange(false)}
|
||||
quantityInputRef={quantityInputRef}
|
||||
/>
|
||||
{quantity && (
|
||||
<span className="bg-accent text-accent-foreground shrink-0 rounded-md px-2 py-0.5 text-sm font-semibold">
|
||||
{quantity}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</ContextMenuTrigger>
|
||||
{/* Right-click is the desktop equivalent of the swipes. */}
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onSelect={onEdit}>
|
||||
<PencilIcon />
|
||||
Editar
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={onMove}>
|
||||
<FolderInputIcon />
|
||||
Mover a otra lista…
|
||||
</ContextMenuItem>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem variant="destructive" onSelect={onDelete}>
|
||||
<Trash2Icon />
|
||||
Eliminar
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
245
apps/web/src/components/items/item-sheet.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@@ -8,9 +8,10 @@ type ListProgressProps = {
|
||||
}
|
||||
|
||||
/**
|
||||
* "4 pendientes · 7 comprados" plus a bar for today's progress. Reads 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.
|
||||
* A bar for today's progress: items bought today over the items shown (pending plus
|
||||
* bought today). The "X pendientes · Y comprados" count lives in the header. Reads
|
||||
* 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) {
|
||||
const { data: items } = useItems(listId)
|
||||
@@ -24,16 +25,10 @@ export function ListProgress({ listId }: ListProgressProps) {
|
||||
if (total === 0) return null
|
||||
|
||||
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
|
||||
value={(boughtToday.length / total) * 100}
|
||||
aria-label="Progreso de la compra"
|
||||
className="h-2"
|
||||
aria-label={`Comprados ${boughtToday.length} de ${total}`}
|
||||
className="h-1.5"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
94
apps/web/src/components/items/move-item-dialog.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { ChevronRightIcon, ListIcon } from 'lucide-react'
|
||||
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useMoveItem } from '@/hooks/use-items'
|
||||
import { useLists } from '@/hooks/use-lists'
|
||||
import { ApiError } from '@/lib/api-client'
|
||||
|
||||
type MoveItemDialogProps = {
|
||||
listId: string
|
||||
/** The item being moved; `null` keeps the dialog closed. */
|
||||
item: ListItem | null
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets the user pick another of their lists for an item. Picking one moves the
|
||||
* item there and closes the dialog; the user stays on the current list.
|
||||
*/
|
||||
export function MoveItemDialog({ listId, item, onClose }: MoveItemDialogProps) {
|
||||
const { data: lists, isPending, error } = useLists()
|
||||
const moveItem = useMoveItem(listId)
|
||||
|
||||
const targets = lists?.filter((list) => list.id !== listId) ?? []
|
||||
|
||||
return (
|
||||
<Dialog open={item !== null} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Mover a otra lista</DialogTitle>
|
||||
<DialogDescription>
|
||||
{item ? `Elige a qué lista quieres mover «${item.name}».` : null}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{error ? (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>
|
||||
{error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos cargar tus listas.'}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : isPending ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Skeleton className="h-11 w-full" />
|
||||
<Skeleton className="h-11 w-full" />
|
||||
</div>
|
||||
) : targets.length === 0 ? (
|
||||
<p className="text-muted-foreground text-sm">
|
||||
No tienes otras listas.{' '}
|
||||
<Link to="/lists" className="text-primary underline-offset-4 hover:underline">
|
||||
Crea una
|
||||
</Link>{' '}
|
||||
para poder mover artículos.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="-mx-2 flex flex-col">
|
||||
{targets.map((list) => (
|
||||
<li key={list.id}>
|
||||
<button
|
||||
type="button"
|
||||
className="hover:bg-muted focus-visible:bg-muted flex w-full items-center gap-3 rounded-md px-2 py-3 text-left outline-none transition-colors"
|
||||
onClick={() => {
|
||||
if (!item) return
|
||||
moveItem.mutate({
|
||||
itemId: item.id,
|
||||
targetListId: list.id,
|
||||
targetListName: list.name,
|
||||
})
|
||||
onClose()
|
||||
}}
|
||||
>
|
||||
<ListIcon className="text-muted-foreground size-5 shrink-0" />
|
||||
<span className="min-w-0 flex-1 truncate text-base">{list.name}</span>
|
||||
<ChevronRightIcon className="text-muted-foreground size-4 shrink-0" />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query'
|
||||
import { Link, useMatch, useRouterState } from '@tanstack/react-router'
|
||||
import { ArrowLeftIcon, SettingsIcon } from 'lucide-react'
|
||||
|
||||
import { ListSwitcher } from '@/components/layout/list-switcher'
|
||||
import { sectionTitle } from '@/components/layout/nav-items'
|
||||
import { ThemeToggle } from '@/components/theme-toggle'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
@@ -45,8 +46,12 @@ export function AppHeader() {
|
||||
)}
|
||||
<div className="ml-auto flex shrink-0 items-center gap-1">
|
||||
{list && (
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<Link to="/lists/$listId/settings" params={{ listId: list.id }}>
|
||||
<Button variant="outline" size="sm" className="h-11 min-w-11" asChild>
|
||||
<Link
|
||||
to="/lists/$listId/settings"
|
||||
params={{ listId: list.id }}
|
||||
aria-label="Gestionar la lista"
|
||||
>
|
||||
<SettingsIcon className="size-4" />
|
||||
<span className="hidden sm:inline">Gestionar</span>
|
||||
</Link>
|
||||
@@ -63,14 +68,13 @@ function ListHeading({ list, showBack }: { list: HeaderList; showBack: boolean }
|
||||
return (
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
{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">
|
||||
<ArrowLeftIcon className="size-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
<h1 className="truncate text-sm font-medium">{list.name}</h1>
|
||||
{list.isPrimary && <Badge className="shrink-0">Principal</Badge>}
|
||||
<ListSwitcher list={list} />
|
||||
<Badge variant="secondary" className="hidden shrink-0 sm:inline-flex">
|
||||
{list.role === 'owner' ? 'Propietario' : 'Colaborador'}
|
||||
</Badge>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Link, useRouterState } from '@tanstack/react-router'
|
||||
import { AppLogo } from '@/components/app-logo'
|
||||
import { focusNewItemInput } from '@/components/items/create-item-form'
|
||||
import { isNavItemActive, NAV_ITEMS } from '@/components/layout/nav-items'
|
||||
import { NavUser } from '@/components/layout/nav-user'
|
||||
@@ -25,9 +26,7 @@ export function AppSidebar() {
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton size="lg" asChild>
|
||||
<Link to="/" onClick={() => focusNewItemInput(pathname)}>
|
||||
<div className="bg-primary text-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg text-sm font-semibold">
|
||||
SL
|
||||
</div>
|
||||
<AppLogo className="size-8 rounded-lg" />
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<span className="truncate font-medium">Superlist</span>
|
||||
<span className="text-muted-foreground truncate text-xs">Listas compartidas</span>
|
||||
|
||||
95
apps/web/src/components/layout/list-switcher.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@@ -27,7 +27,7 @@ export function ThemeToggle() {
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="relative"
|
||||
className="relative size-11"
|
||||
aria-label={`Tema: ${current.label} — cambiar a ${next.label}`}
|
||||
onClick={() => setTheme(next.value)}
|
||||
>
|
||||
|
||||
244
apps/web/src/components/ui/context-menu.tsx
Normal file
@@ -0,0 +1,244 @@
|
||||
import { cn } from 'cn'
|
||||
import { CheckIcon, ChevronRightIcon } from 'lucide-react'
|
||||
import { ContextMenu as ContextMenuPrimitive } from 'radix-ui'
|
||||
import * as React from 'react'
|
||||
|
||||
function ContextMenu({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
||||
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuTrigger({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Trigger
|
||||
data-slot="context-menu-trigger"
|
||||
className={cn('select-none', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
||||
return <ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuPortal({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
||||
return <ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuSub({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
||||
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
||||
return <ContextMenuPrimitive.RadioGroup data-slot="context-menu-radio-group" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Content> & {
|
||||
side?: 'top' | 'right' | 'bottom' | 'left'
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal>
|
||||
<ContextMenuPrimitive.Content
|
||||
data-slot="context-menu-content"
|
||||
className={cn(
|
||||
'z-50 max-h-(--radix-context-menu-content-available-height) min-w-36 origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</ContextMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = 'default',
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: 'default' | 'destructive'
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Item
|
||||
data-slot="context-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"group/context-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 focus:*:[svg]:text-accent-foreground data-[variant=destructive]:*:[svg]:text-destructive",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubTrigger
|
||||
data-slot="context-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto" />
|
||||
</ContextMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubContent
|
||||
data-slot="context-menu-sub-content"
|
||||
className={cn(
|
||||
'z-50 min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-lg border bg-popover p-1 text-popover-foreground shadow-lg duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.CheckboxItem
|
||||
data-slot="context-menu-checkbox-item"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute right-2">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioItem
|
||||
data-slot="context-menu-radio-item"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute right-2">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Label
|
||||
data-slot="context-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
'px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Separator
|
||||
data-slot="context-menu-separator"
|
||||
className={cn('-mx-1 my-1 h-px bg-border', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) {
|
||||
return (
|
||||
<span
|
||||
data-slot="context-menu-shortcut"
|
||||
className={cn(
|
||||
'ml-auto text-xs tracking-widest text-muted-foreground group-focus/context-menu-item:text-accent-foreground',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
ContextMenu,
|
||||
ContextMenuCheckboxItem,
|
||||
ContextMenuContent,
|
||||
ContextMenuGroup,
|
||||
ContextMenuItem,
|
||||
ContextMenuLabel,
|
||||
ContextMenuPortal,
|
||||
ContextMenuRadioGroup,
|
||||
ContextMenuRadioItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuShortcut,
|
||||
ContextMenuSub,
|
||||
ContextMenuSubContent,
|
||||
ContextMenuSubTrigger,
|
||||
ContextMenuTrigger,
|
||||
}
|
||||
171
apps/web/src/hooks/use-add-items.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { useRef } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import type { PreviewItem } from '@/components/items/item-input-preview'
|
||||
import {
|
||||
isOptimisticItem,
|
||||
useCreateItem,
|
||||
useItems,
|
||||
useRemoveItems,
|
||||
useUpdateItem,
|
||||
} from '@/hooks/use-items'
|
||||
import { useVoiceSplit } from '@/hooks/use-voice-split'
|
||||
import { ApiError } from '@/lib/api-client'
|
||||
import { findDuplicate, mergeBatch, mergeInto } from '@/lib/natural-input/merge'
|
||||
import { literalItem, parseItemInput } from '@/lib/natural-input/parse-item'
|
||||
|
||||
/** How long the "Deshacer" of a dictation stays on screen. */
|
||||
const DICTATION_UNDO_MS = 8000
|
||||
|
||||
/** Why a read item cannot be sent as is, mirroring the API limits, or `null`. */
|
||||
export function itemLimitError(item: PreviewItem): string | null {
|
||||
if (item.name.length > 120) return `«${item.name.slice(0, 20)}…»: máximo 120 caracteres`
|
||||
if ((item.quantity?.length ?? 0) > 40) return `«${item.name}»: la cantidad es demasiado larga`
|
||||
if ((item.notes?.length ?? 0) > 280) return `«${item.name}»: la nota es demasiado larga`
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** The items `text` adds, each with the pending item it repeats, if any. */
|
||||
export function readItems(text: string, literal: boolean, existing: ListItem[]): PreviewItem[] {
|
||||
if (!text.trim()) return []
|
||||
|
||||
const items = literal ? [literalItem(text)] : mergeBatch(parseItemInput(text))
|
||||
|
||||
return items.map((item) => ({ ...item, duplicate: findDuplicate(existing, item.name) }))
|
||||
}
|
||||
|
||||
/** What adding a batch of items did, so a dictation can be undone. */
|
||||
type AddedItems = {
|
||||
/** Ids of the items created (failed ones are left out). */
|
||||
created: Promise<string[]>
|
||||
/** The previous quantity/notes of the pending items that were added to. */
|
||||
merged: { itemId: string; quantity: string | null; notes: string | null }[]
|
||||
}
|
||||
|
||||
type UseAddItemsOptions = {
|
||||
/** An item could not be created: `source` is the text it was read from. */
|
||||
onItemFailed: (source: string, message: string) => void
|
||||
/** A dictation was not added because an item breaks the API limits. */
|
||||
onDictationRejected: (transcript: string, message: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds items to a list the way the "add an item" input does: an item already pending is
|
||||
* added to instead of repeated, and a dictation is split into items by the API (with AI)
|
||||
* and can be undone as a whole.
|
||||
*/
|
||||
export function useAddItems(
|
||||
listId: string,
|
||||
{ onItemFailed, onDictationRejected }: UseAddItemsOptions,
|
||||
) {
|
||||
const createItem = useCreateItem(listId)
|
||||
const updateItem = useUpdateItem(listId)
|
||||
const removeItems = useRemoveItems(listId)
|
||||
const voiceSplit = useVoiceSplit()
|
||||
const { data: items } = useItems(listId)
|
||||
// Placeholders have no server id yet, so they cannot be added to.
|
||||
const existing = (items ?? []).filter((item) => !isOptimisticItem(item))
|
||||
// A dictation finishes after a request: by then the list may have changed.
|
||||
const existingRef = useRef(existing)
|
||||
existingRef.current = existing
|
||||
|
||||
/** Adds the items, or adds to the pending ones they repeat. */
|
||||
const addItems = (toAdd: PreviewItem[]): AddedItems => {
|
||||
const created: Promise<string | null>[] = []
|
||||
const merged: AddedItems['merged'] = []
|
||||
|
||||
for (const item of toAdd) {
|
||||
if (item.duplicate) {
|
||||
const patch = mergeInto(item.duplicate, item)
|
||||
if (patch.quantity !== undefined || patch.notes !== undefined) {
|
||||
updateItem.mutate({ itemId: item.duplicate.id, ...patch })
|
||||
merged.push({
|
||||
itemId: item.duplicate.id,
|
||||
quantity: item.duplicate.quantity,
|
||||
notes: item.duplicate.notes,
|
||||
})
|
||||
}
|
||||
toast(
|
||||
patch.quantity
|
||||
? `Se sumó a «${item.duplicate.name}» (${patch.quantity})`
|
||||
: `«${item.duplicate.name}» ya está en la lista`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
created.push(
|
||||
createItem
|
||||
.mutateAsync({
|
||||
name: item.name,
|
||||
quantity: item.quantity ?? undefined,
|
||||
notes: item.notes ?? undefined,
|
||||
})
|
||||
.then(
|
||||
(createdItem) => createdItem.id,
|
||||
(error) => {
|
||||
onItemFailed(
|
||||
item.source,
|
||||
error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos añadir el artículo.',
|
||||
)
|
||||
return null
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
created: Promise.all(created).then((ids) => ids.filter((id): id is string => id !== null)),
|
||||
merged,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The API splits the transcript into one string per item and each one is read by the
|
||||
* usual parser. If the request fails, the transcript is read as typed text when it is
|
||||
* already split into lines, and added as a single item otherwise.
|
||||
*
|
||||
* @returns how many items were understood (0 when the dictation had none).
|
||||
*/
|
||||
const addDictation = async (transcript: string): Promise<number> => {
|
||||
let toAdd: PreviewItem[]
|
||||
try {
|
||||
const { items: spoken } = await voiceSplit.mutateAsync({ text: transcript })
|
||||
toAdd = readItems(spoken.join('; '), false, existingRef.current)
|
||||
} catch {
|
||||
toAdd = readItems(transcript, !/[;\n]/.test(transcript), existingRef.current)
|
||||
}
|
||||
|
||||
if (toAdd.length === 0) return 0
|
||||
|
||||
const limitError = toAdd.map(itemLimitError).find(Boolean)
|
||||
if (limitError) {
|
||||
onDictationRejected(transcript, limitError)
|
||||
return toAdd.length
|
||||
}
|
||||
|
||||
const { created, merged } = addItems(toAdd)
|
||||
const createdIds = await created
|
||||
const count = createdIds.length + merged.length
|
||||
if (count === 0) return toAdd.length
|
||||
|
||||
toast(`Se ${count === 1 ? 'agregó 1 producto' : `agregaron ${count} productos`}`, {
|
||||
// Longer than a plain toast: the user has to check what was understood first.
|
||||
duration: DICTATION_UNDO_MS,
|
||||
action: {
|
||||
label: 'Deshacer',
|
||||
onClick: () => {
|
||||
void removeItems(createdIds)
|
||||
for (const previous of merged) updateItem.mutate(previous)
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return toAdd.length
|
||||
}
|
||||
|
||||
return { existing, addItems, addDictation, processing: voiceSplit.isPending }
|
||||
}
|
||||
136
apps/web/src/hooks/use-dictation.ts
Normal file
@@ -0,0 +1,136 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
import {
|
||||
getSpeechRecognition as getBrowserSpeechRecognition,
|
||||
isIosStandalone,
|
||||
type SpeechRecognitionConstructor,
|
||||
} from '@/lib/speech-recognition'
|
||||
|
||||
/** 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' || isIosStandalone()) return null
|
||||
|
||||
return getBrowserSpeechRecognition()
|
||||
}
|
||||
|
||||
type UseDictationOptions = {
|
||||
/** Called once with the whole transcript when the user stops talking. */
|
||||
onTranscript: (transcript: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Quiet time after the last words heard that ends the dictation. Safari on iOS keeps
|
||||
* listening long after the user stops talking even with `continuous = false`, so the
|
||||
* phrase is delivered once nothing new has been heard for this long.
|
||||
*/
|
||||
export const DICTATION_SILENCE_MS = 3000
|
||||
|
||||
/** A recognition in progress: `finish` delivers what was heard, `cancel` drops it. */
|
||||
type DictationSession = { finish: () => void; cancel: () => 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. The phrase is delivered when the browser ends the recognition, when the user
|
||||
* stops it, or after `DICTATION_SILENCE_MS` without new words, whichever comes first.
|
||||
* `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 sessionRef = useRef<DictationSession | null>(null)
|
||||
const onTranscriptRef = useRef(onTranscript)
|
||||
|
||||
useEffect(() => {
|
||||
onTranscriptRef.current = onTranscript
|
||||
})
|
||||
|
||||
// Leaving the page stops listening, without delivering a transcript.
|
||||
useEffect(() => () => sessionRef.current?.cancel(), [])
|
||||
|
||||
const start = useCallback(() => {
|
||||
const SpeechRecognition = getSpeechRecognition()
|
||||
if (!SpeechRecognition || sessionRef.current) return
|
||||
|
||||
const recognition = new SpeechRecognition()
|
||||
recognition.lang = 'es-AR'
|
||||
recognition.interimResults = true
|
||||
recognition.continuous = false
|
||||
recognition.maxAlternatives = 1
|
||||
|
||||
let transcript = ''
|
||||
let failed = false
|
||||
let done = false
|
||||
let silenceTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
// Runs once, whatever ends the dictation first; aborting afterwards only fires an
|
||||
// ignored `aborted` error and an `onend` that finds the session already done.
|
||||
const end = (deliver: boolean) => {
|
||||
if (done) return
|
||||
done = true
|
||||
clearTimeout(silenceTimer)
|
||||
sessionRef.current = null
|
||||
setListening(false)
|
||||
setInterim('')
|
||||
recognition.abort()
|
||||
if (deliver && transcript && !failed) onTranscriptRef.current(transcript)
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
clearTimeout(silenceTimer)
|
||||
silenceTimer = setTimeout(() => end(true), DICTATION_SILENCE_MS)
|
||||
}
|
||||
|
||||
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 = () => end(true)
|
||||
|
||||
setError(null)
|
||||
setInterim('')
|
||||
|
||||
try {
|
||||
recognition.start()
|
||||
} catch {
|
||||
setError('No pudimos empezar a escuchar.')
|
||||
return
|
||||
}
|
||||
|
||||
sessionRef.current = { finish: () => end(true), cancel: () => end(false) }
|
||||
setListening(true)
|
||||
}, [])
|
||||
|
||||
/** Stops listening right away; what was heard so far is still delivered. */
|
||||
const stop = useCallback(() => sessionRef.current?.finish(), [])
|
||||
|
||||
const clearError = useCallback(() => setError(null), [])
|
||||
|
||||
return { supported, listening, interim, error, start, stop, clearError }
|
||||
}
|
||||
@@ -6,10 +6,17 @@ import {
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
} from '@tanstack/react-query'
|
||||
import { useSyncExternalStore } from 'react'
|
||||
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { ApiError, apiFetch } from '@/lib/api-client'
|
||||
import {
|
||||
DELETE_UNDO_MS,
|
||||
getPendingDeletions,
|
||||
scheduleDeletion,
|
||||
subscribePendingDeletions,
|
||||
} from '@/lib/pending-deletions'
|
||||
|
||||
export const itemsQueryOptions = (listId: string) =>
|
||||
queryOptions({
|
||||
@@ -79,6 +86,8 @@ export function useCreateItem(listId: string) {
|
||||
|
||||
type UpdateItemInput = {
|
||||
itemId: string
|
||||
/** New name; omitted to leave it untouched. */
|
||||
name?: string
|
||||
/** New bought state; omitted when only the details are being changed. */
|
||||
completed?: boolean
|
||||
/** New quantity (`null` clears it); omitted to leave it untouched. */
|
||||
@@ -97,7 +106,13 @@ export function useUpdateItem(listId: string) {
|
||||
return useMutation({
|
||||
mutationKey,
|
||||
mutationFn: (input: UpdateItemInput) => {
|
||||
const body: { completed?: boolean; quantity?: string | null; notes?: string | null } = {}
|
||||
const body: {
|
||||
name?: string
|
||||
completed?: boolean
|
||||
quantity?: string | null
|
||||
notes?: string | null
|
||||
} = {}
|
||||
if (input.name !== undefined) body.name = input.name
|
||||
if (input.completed !== undefined) body.completed = input.completed
|
||||
if (input.quantity !== undefined) body.quantity = input.quantity
|
||||
if (input.notes !== undefined) body.notes = input.notes
|
||||
@@ -107,7 +122,7 @@ export function useUpdateItem(listId: string) {
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
},
|
||||
onMutate: async ({ itemId, completed, quantity, notes }) => {
|
||||
onMutate: async ({ itemId, name, completed, quantity, notes }) => {
|
||||
// Cancel the outgoing refetch so it cannot overwrite our optimistic one.
|
||||
await queryClient.cancelQueries({ queryKey })
|
||||
|
||||
@@ -119,6 +134,7 @@ export function useUpdateItem(listId: string) {
|
||||
|
||||
return {
|
||||
...item,
|
||||
...(name !== undefined ? { name: name.trim() } : {}),
|
||||
...(completed !== undefined
|
||||
? { completed, boughtAt: completed ? new Date().toISOString() : null }
|
||||
: {}),
|
||||
@@ -162,3 +178,119 @@ export function usePendingItemUpdates(listId: string): string[] {
|
||||
select: (mutation) => (mutation.state.variables as UpdateItemInput).itemId,
|
||||
})
|
||||
}
|
||||
|
||||
type MoveItemInput = {
|
||||
itemId: string
|
||||
targetListId: string
|
||||
/** Name of the target list, only used for the confirmation toast. */
|
||||
targetListName: string
|
||||
}
|
||||
|
||||
export function useMoveItem(listId: string) {
|
||||
const queryClient = useQueryClient()
|
||||
const { queryKey } = itemsQueryOptions(listId)
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ itemId, targetListId }: MoveItemInput) =>
|
||||
apiFetch<ListItem>(`/lists/${listId}/items/${itemId}/move`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ targetListId }),
|
||||
}),
|
||||
// The item leaves this list right away; the user stays on it.
|
||||
onMutate: async ({ itemId }) => {
|
||||
await queryClient.cancelQueries({ queryKey })
|
||||
|
||||
const items = queryClient.getQueryData(queryKey)
|
||||
const index = items?.findIndex((item) => item.id === itemId) ?? -1
|
||||
const previous = index >= 0 ? items?.[index] : undefined
|
||||
|
||||
queryClient.setQueryData(queryKey, (current) => current?.filter((item) => item.id !== itemId))
|
||||
|
||||
return { previous, index }
|
||||
},
|
||||
onSuccess: (_moved, { targetListId, targetListName }) => {
|
||||
toast.success(`Movido a «${targetListName}»`)
|
||||
return queryClient.invalidateQueries({ queryKey: itemsQueryOptions(targetListId).queryKey })
|
||||
},
|
||||
// The item goes back to where it was, so the list does not jump around.
|
||||
onError: (error, _variables, context) => {
|
||||
toast.error(
|
||||
error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos mover el artículo.',
|
||||
)
|
||||
|
||||
const previous = context?.previous
|
||||
if (!previous) return
|
||||
|
||||
queryClient.setQueryData(queryKey, (items) => {
|
||||
if (!items || items.some((item) => item.id === previous.id)) return items
|
||||
const next = [...items]
|
||||
next.splice(Math.min(context.index, next.length), 0, previous)
|
||||
return next
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** Ids of the items hidden because they were just deleted (they can still come back). */
|
||||
export function usePendingDeletions(): ReadonlySet<string> {
|
||||
return useSyncExternalStore(subscribePendingDeletions, getPendingDeletions)
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an item with a few seconds to undo it: the row disappears at once,
|
||||
* a toast offers "Deshacer" and the `DELETE` is only sent once that time is
|
||||
* over, so undoing never has to recreate anything.
|
||||
*/
|
||||
export function useDeleteItem(listId: string) {
|
||||
const queryClient = useQueryClient()
|
||||
const { queryKey } = itemsQueryOptions(listId)
|
||||
|
||||
return (item: ListItem) => {
|
||||
const undo = scheduleDeletion(item.id, async ({ keepalive }) => {
|
||||
try {
|
||||
await apiFetch<void>(`/lists/${listId}/items/${item.id}`, { method: 'DELETE', keepalive })
|
||||
queryClient.setQueryData(queryKey, (items) =>
|
||||
items?.filter((current) => current.id !== item.id),
|
||||
)
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos eliminar el artículo.',
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
toast(`«${item.name}» eliminado`, {
|
||||
duration: DELETE_UNDO_MS,
|
||||
action: { label: 'Deshacer', onClick: undo },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
29
apps/web/src/hooks/use-keyboard-dictation.test.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { isDictatedInput } from './use-keyboard-dictation'
|
||||
|
||||
describe('isDictatedInput', () => {
|
||||
it('takes words or phrases written without a key press as dictation', () => {
|
||||
expect(isDictatedInput({ inputType: 'insertText', data: 'Yogur', msSinceKeydown: 5000 })).toBe(
|
||||
true,
|
||||
)
|
||||
expect(
|
||||
isDictatedInput({ inputType: 'insertReplacementText', data: null, msSinceKeydown: 5000 }),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('does not take typing as dictation', () => {
|
||||
expect(isDictatedInput({ inputType: 'insertText', data: 'Yogur', msSinceKeydown: 10 })).toBe(
|
||||
false,
|
||||
)
|
||||
expect(isDictatedInput({ inputType: 'insertText', data: 'y', msSinceKeydown: 5000 })).toBe(
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
it('never takes pastes, drops or deletions as dictation', () => {
|
||||
for (const inputType of ['insertFromPaste', 'insertFromDrop', 'deleteContentBackward']) {
|
||||
expect(isDictatedInput({ inputType, data: 'leche y pan', msSinceKeydown: 5000 })).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
92
apps/web/src/hooks/use-keyboard-dictation.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import { type FormEvent, type KeyboardEvent, useCallback, useEffect, useRef } from 'react'
|
||||
|
||||
/** Quiet time after the keyboard's dictation last wrote into the input before it is added. */
|
||||
export const KEYBOARD_DICTATION_IDLE_MS = 3000
|
||||
|
||||
/** How close to a key press an input event must be to count as typed. */
|
||||
const KEYDOWN_WINDOW_MS = 100
|
||||
|
||||
/** Insertions that are never dictation (pasting or dropping text, deleting). */
|
||||
const NOT_DICTATION = /^(insertFromPaste|insertFromDrop|delete)/
|
||||
|
||||
/**
|
||||
* Whether an input event looks like the system keyboard's dictation writing into the
|
||||
* field: text that arrives without a key press, several characters at once (dictation
|
||||
* writes word by word or a whole phrase) or as a replacement of what it wrote before.
|
||||
* Tapping a keyboard suggestion looks the same, which is the price of the guess.
|
||||
*/
|
||||
export function isDictatedInput(event: {
|
||||
inputType: string
|
||||
data: string | null
|
||||
msSinceKeydown: number
|
||||
}): boolean {
|
||||
if (NOT_DICTATION.test(event.inputType)) return false
|
||||
if (event.msSinceKeydown < KEYDOWN_WINDOW_MS) return false
|
||||
if (event.inputType === 'insertReplacementText') return true
|
||||
|
||||
return event.inputType === 'insertText' && (event.data?.trim().length ?? 0) > 1
|
||||
}
|
||||
|
||||
type UseKeyboardDictationOptions = {
|
||||
/** Called with the input's text once the dictation has been quiet for a while. */
|
||||
onIdle: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* The installed iOS app has no speech recognition, so people dictate with the
|
||||
* keyboard's microphone, which only writes text into the input. This notices text that
|
||||
* arrives that way and calls `onIdle` once nothing new has arrived for
|
||||
* `KEYBOARD_DICTATION_IDLE_MS`, so it is added without pressing Enter. Typing a key
|
||||
* cancels it: from then on the text is the user's to submit.
|
||||
*/
|
||||
export function useKeyboardDictation({ onIdle }: UseKeyboardDictationOptions) {
|
||||
const lastKeydown = useRef(0)
|
||||
const dictated = useRef(false)
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
|
||||
const onIdleRef = useRef(onIdle)
|
||||
|
||||
useEffect(() => {
|
||||
onIdleRef.current = onIdle
|
||||
})
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
clearTimeout(timer.current)
|
||||
dictated.current = false
|
||||
}, [])
|
||||
|
||||
useEffect(() => cancel, [cancel])
|
||||
|
||||
const onKeyDown = useCallback(
|
||||
(_event: KeyboardEvent<HTMLInputElement>) => {
|
||||
lastKeydown.current = performance.now()
|
||||
cancel()
|
||||
},
|
||||
[cancel],
|
||||
)
|
||||
|
||||
const onInput = useCallback((event: FormEvent<HTMLInputElement>) => {
|
||||
const native = event.nativeEvent as InputEvent
|
||||
const inputType = native.inputType ?? ''
|
||||
|
||||
const looksDictated = isDictatedInput({
|
||||
inputType,
|
||||
data: native.data ?? null,
|
||||
msSinceKeydown: performance.now() - lastKeydown.current,
|
||||
})
|
||||
|
||||
// Once dictation started, any later update without a key press (corrections,
|
||||
// composition) keeps it going; a paste or a deletion stops it.
|
||||
if (looksDictated) dictated.current = true
|
||||
else if (NOT_DICTATION.test(inputType)) dictated.current = false
|
||||
|
||||
clearTimeout(timer.current)
|
||||
if (!dictated.current) return
|
||||
|
||||
timer.current = setTimeout(() => {
|
||||
dictated.current = false
|
||||
onIdleRef.current()
|
||||
}, KEYBOARD_DICTATION_IDLE_MS)
|
||||
}, [])
|
||||
|
||||
return { onKeyDown, onInput, cancel }
|
||||
}
|
||||
154
apps/web/src/hooks/use-microphone-dictation.ts
Normal file
@@ -0,0 +1,154 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { splitDictation } from '@/lib/natural-input/dictation'
|
||||
import { getSpeechRecognition, type SpeechRecognitionLike } from '@/lib/speech-recognition'
|
||||
|
||||
export const DICTATION_MESSAGES = {
|
||||
denied: 'No tenemos permiso para usar el micrófono. Habilítalo en los ajustes del navegador.',
|
||||
unavailable: 'No encontramos un micrófono disponible.',
|
||||
unsupported:
|
||||
'Este navegador no permite dictar. Puedes usar el micrófono del teclado en el campo de arriba.',
|
||||
empty: 'No escuchamos ningún artículo. Inténtalo de nuevo.',
|
||||
failed: 'Ocurrió un error al reconocer la voz. Inténtalo de nuevo.',
|
||||
} as const
|
||||
|
||||
/** Recognition errors with a message of their own; any other one is `failed`. */
|
||||
const RECOGNITION_ERRORS: Record<string, string | null> = {
|
||||
'not-allowed': DICTATION_MESSAGES.denied,
|
||||
'service-not-allowed': DICTATION_MESSAGES.unsupported,
|
||||
'audio-capture': DICTATION_MESSAGES.unavailable,
|
||||
// Silence just ends with no phrases; a stop of ours is not an error.
|
||||
'no-speech': null,
|
||||
aborted: null,
|
||||
}
|
||||
|
||||
/** What `getUserMedia` rejects with, as one of the messages. */
|
||||
function microphoneError(error: unknown): string {
|
||||
const name = error instanceof DOMException ? error.name : ''
|
||||
if (name === 'NotAllowedError' || name === 'SecurityError') return DICTATION_MESSAGES.denied
|
||||
|
||||
return DICTATION_MESSAGES.unavailable
|
||||
}
|
||||
|
||||
type DictationStatus = 'idle' | 'requesting' | 'listening'
|
||||
|
||||
type UseMicrophoneDictationOptions = {
|
||||
/** The phrases dictated, one per item said, when the dictation ends with some. */
|
||||
onPhrases: (phrases: string[]) => void
|
||||
/** Why the dictation did not deliver anything, in Spanish. */
|
||||
onError: (message: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Dictation of several items in a row with the Web Speech API (`webkitSpeechRecognition`
|
||||
* in Safari), in Argentine Spanish. `start()` must run inside a click handler: it asks
|
||||
* for the microphone right there, then listens until the user calls `stop()` or the
|
||||
* browser ends the recognition. Pauses, line breaks and "nuevo ítem" separate phrases
|
||||
* (`splitDictation`).
|
||||
*
|
||||
* The microphone stream is only used to ask for the permission: its tracks are stopped
|
||||
* as soon as it arrives (even after an unmount), before the recognition opens its own
|
||||
* capture. Unmounting aborts the recognition.
|
||||
*/
|
||||
export function useMicrophoneDictation({ onPhrases, onError }: UseMicrophoneDictationOptions) {
|
||||
const [status, setStatus] = useState<DictationStatus>('idle')
|
||||
// What has been heard so far, shown while listening.
|
||||
const [heard, setHeard] = useState('')
|
||||
const callbacksRef = useRef({ onPhrases, onError })
|
||||
// Ends the dictation in progress: `true` delivers what was heard, `false` drops it.
|
||||
const endRef = useRef<((deliver: boolean) => void) | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
callbacksRef.current = { onPhrases, onError }
|
||||
})
|
||||
|
||||
useEffect(() => () => endRef.current?.(false), [])
|
||||
|
||||
const start = useCallback(() => {
|
||||
if (endRef.current) return
|
||||
|
||||
const SpeechRecognition = getSpeechRecognition()
|
||||
if (!SpeechRecognition) {
|
||||
callbacksRef.current.onError(DICTATION_MESSAGES.unsupported)
|
||||
return
|
||||
}
|
||||
|
||||
let recognition: SpeechRecognitionLike | null = null
|
||||
let segments: string[] = []
|
||||
let failure: string | null = null
|
||||
let done = false
|
||||
|
||||
const end = (deliver: boolean) => {
|
||||
if (done) return
|
||||
done = true
|
||||
endRef.current = null
|
||||
// Aborting afterwards only fires an ignored `aborted` and an `onend` that finds it done.
|
||||
recognition?.abort()
|
||||
setStatus('idle')
|
||||
setHeard('')
|
||||
// Stopped while the permission was being asked: there is nothing to tell.
|
||||
if (!deliver || (!recognition && !failure)) return
|
||||
|
||||
const phrases = splitDictation(segments)
|
||||
if (failure) callbacksRef.current.onError(failure)
|
||||
else if (phrases.length === 0) callbacksRef.current.onError(DICTATION_MESSAGES.empty)
|
||||
else callbacksRef.current.onPhrases(phrases)
|
||||
}
|
||||
|
||||
const listen = () => {
|
||||
recognition = new SpeechRecognition()
|
||||
recognition.lang = 'es-AR'
|
||||
recognition.interimResults = true
|
||||
recognition.continuous = true
|
||||
recognition.maxAlternatives = 1
|
||||
|
||||
// Each result is a stretch of speech between pauses; the last one may still change.
|
||||
recognition.onresult = (event) => {
|
||||
segments = Array.from(event.results, (result) => result[0].transcript)
|
||||
setHeard(splitDictation(segments).join(' · '))
|
||||
}
|
||||
|
||||
recognition.onerror = (event) => {
|
||||
const message = RECOGNITION_ERRORS[event.error]
|
||||
if (message === null) return
|
||||
failure = message ?? DICTATION_MESSAGES.failed
|
||||
}
|
||||
|
||||
recognition.onend = () => end(true)
|
||||
|
||||
try {
|
||||
recognition.start()
|
||||
setStatus('listening')
|
||||
} catch {
|
||||
failure = DICTATION_MESSAGES.failed
|
||||
end(true)
|
||||
}
|
||||
}
|
||||
|
||||
endRef.current = end
|
||||
setStatus('requesting')
|
||||
|
||||
// Without `getUserMedia` (e.g. outside HTTPS) the recognition asks for the microphone itself.
|
||||
if (!navigator.mediaDevices?.getUserMedia) {
|
||||
listen()
|
||||
return
|
||||
}
|
||||
|
||||
// Called right in the click, before any `await`, so Safari treats it as the user's.
|
||||
navigator.mediaDevices.getUserMedia({ audio: true }).then(
|
||||
(stream) => {
|
||||
for (const track of stream.getTracks()) track.stop()
|
||||
if (!done) listen()
|
||||
},
|
||||
(error: unknown) => {
|
||||
failure = microphoneError(error)
|
||||
end(true)
|
||||
},
|
||||
)
|
||||
}, [])
|
||||
|
||||
/** Stops listening; what was heard so far is delivered. */
|
||||
const stop = useCallback(() => endRef.current?.(true), [])
|
||||
|
||||
return { status, heard, start, stop }
|
||||
}
|
||||
20
apps/web/src/hooks/use-voice-split.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import type { VoiceSplitRequest, VoiceSplitResponse } from '@superlist/shared'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
|
||||
import { apiFetch } from '@/lib/api-client'
|
||||
|
||||
/**
|
||||
* Asks the API to split a dictated sentence into one string per item, each written the
|
||||
* way the item parser reads typed text. The API never fails because of the model (it
|
||||
* falls back to splitting on commas and "y"), so an error here means the request did not
|
||||
* get through.
|
||||
*/
|
||||
export function useVoiceSplit() {
|
||||
return useMutation({
|
||||
mutationFn: (input: VoiceSplitRequest) =>
|
||||
apiFetch<VoiceSplitResponse>('/voice/split', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
})
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { emailOTPClient } from 'better-auth/client/plugins'
|
||||
import { createAuthClient } from 'better-auth/react'
|
||||
|
||||
/**
|
||||
@@ -7,6 +8,7 @@ import { createAuthClient } from 'better-auth/react'
|
||||
*/
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: import.meta.env.VITE_API_URL || window.location.origin,
|
||||
plugins: [emailOTPClient()],
|
||||
})
|
||||
|
||||
export const { signIn, signUp, signOut, useSession } = authClient
|
||||
export const { signIn, signUp, signOut, useSession, emailOtp } = authClient
|
||||
|
||||
47
apps/web/src/lib/item-quantity.test.ts
Normal 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')
|
||||
})
|
||||
})
|
||||
64
apps/web/src/lib/item-quantity.ts
Normal 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 })
|
||||
}
|
||||
@@ -87,24 +87,36 @@ describe('splitItems', () => {
|
||||
})
|
||||
|
||||
describe('quantityLabel', () => {
|
||||
it('shows numeric quantities, with their unit when present', () => {
|
||||
expect(quantityLabel('2')).toBe('2')
|
||||
expect(quantityLabel('2 kg')).toBe('2 kg')
|
||||
expect(quantityLabel('1,5')).toBe('1,5')
|
||||
expect(quantityLabel(' 3 ')).toBe('3')
|
||||
it('shows quantities with a unit, litres in capitals', () => {
|
||||
expect(quantityLabel('2 l')).toBe('2 L')
|
||||
expect(quantityLabel('1,5 l')).toBe('1,5 L')
|
||||
expect(quantityLabel('1 kg')).toBe('1 kg')
|
||||
expect(quantityLabel('0,5')).toBe('0,5')
|
||||
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('')).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('kg')).toBeNull()
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
|
||||
import { isSameLocalDay } from './dates'
|
||||
import { formatQuantity, parseQuantity } from './natural-input/quantity'
|
||||
|
||||
export type SplitItems = {
|
||||
/** 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 }
|
||||
}
|
||||
|
||||
/** 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
|
||||
* stay hidden. A plain "1" adds no information, so it is hidden, as is anything
|
||||
* that does not start with a number ("un par"); every other quantity is shown,
|
||||
* including fractions and quantities with a unit ("½ kg", "1 kg", "0,5").
|
||||
* The quantity tag shown at the right of an item's name ("2 L", "×12", "1 kg"), or
|
||||
* `null` when it must stay hidden. It is shown when the quantity has a unit or is a
|
||||
* count above one; a plain "1" (or any count up to one) adds nothing. Free text that
|
||||
* 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 {
|
||||
if (!quantity) return null
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { QueryKey } from '@tanstack/react-query'
|
||||
export const LIST_EVENT_TYPES: readonly ListEventType[] = [
|
||||
'item.created',
|
||||
'item.updated',
|
||||
'item.removed',
|
||||
'invitation.created',
|
||||
'member.added',
|
||||
'list.updated',
|
||||
@@ -19,6 +20,7 @@ export function queryKeysForListEvent(type: ListEventType, listId: string): Quer
|
||||
switch (type) {
|
||||
case 'item.created':
|
||||
case 'item.updated':
|
||||
case 'item.removed':
|
||||
return [['lists', listId, 'items']]
|
||||
case 'invitation.created':
|
||||
case 'member.added':
|
||||
|
||||
37
apps/web/src/lib/natural-input/dictation.test.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { splitDictation } from './dictation'
|
||||
|
||||
describe('splitDictation', () => {
|
||||
it('splits on "nuevo ítem" and its variants', () => {
|
||||
expect(
|
||||
splitDictation([
|
||||
'leche descremada nuevo ítem pan Nuevo item 2 kilos de papa, otro artículo yerba',
|
||||
]),
|
||||
).toEqual(['leche descremada', 'pan', '2 kilos de papa', 'yerba'])
|
||||
})
|
||||
|
||||
it('takes every segment and line as a separate phrase', () => {
|
||||
expect(splitDictation(['Leche.', ' pan\nqueso rallado '])).toEqual([
|
||||
'Leche',
|
||||
'pan',
|
||||
'queso rallado',
|
||||
])
|
||||
})
|
||||
|
||||
it('collapses spaces and drops empty phrases', () => {
|
||||
expect(splitDictation([' dulce de leche ', '', 'nuevo ítem', '...'])).toEqual([
|
||||
'dulce de leche',
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps a repeated phrase once, ignoring case and accents', () => {
|
||||
expect(splitDictation(['jamón', 'Jamon nuevo ítem pan', 'pan'])).toEqual(['jamón', 'pan'])
|
||||
})
|
||||
|
||||
it('does not split words that only contain the keywords', () => {
|
||||
expect(splitDictation(['productos nuevos de limpieza'])).toEqual([
|
||||
'productos nuevos de limpieza',
|
||||
])
|
||||
})
|
||||
})
|
||||
35
apps/web/src/lib/natural-input/dictation.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { normalizeWord } from './text'
|
||||
|
||||
/**
|
||||
* What the user says to start another item: "nuevo ítem", "otro artículo", "nuevo
|
||||
* producto". The punctuation the recognizer puts around it goes with it.
|
||||
*/
|
||||
const NEXT_ITEM =
|
||||
/[\s,.;:]*(?<!\p{L})(?:nuevo|otro)\s+(?:[íi]tem|art[íi]culo|producto)(?!\p{L})[\s,.;:]*/giu
|
||||
|
||||
/** Punctuation the recognizer adds around a phrase ("Leche."), not part of the item. */
|
||||
const EDGE_PUNCTUATION = /^[\s,.;:]+|[\s,.;:]+$/g
|
||||
|
||||
/**
|
||||
* The phrases of a dictation, one per item said: each segment (a pause or a line break,
|
||||
* as the recognizer delivers them) is also split on "nuevo ítem". Spaces are collapsed,
|
||||
* empty phrases dropped and a phrase repeated in the same dictation kept once (ignoring
|
||||
* case and accents); the words themselves are left as heard.
|
||||
*/
|
||||
export function splitDictation(segments: string[]): string[] {
|
||||
const phrases: string[] = []
|
||||
const seen = new Set<string>()
|
||||
|
||||
for (const segment of segments) {
|
||||
for (const part of segment.split(/\r?\n/).flatMap((line) => line.split(NEXT_ITEM))) {
|
||||
const phrase = part.replace(/\s+/g, ' ').replace(EDGE_PUNCTUATION, '')
|
||||
const key = normalizeWord(phrase)
|
||||
if (!phrase || seen.has(key)) continue
|
||||
|
||||
seen.add(key)
|
||||
phrases.push(phrase)
|
||||
}
|
||||
}
|
||||
|
||||
return phrases
|
||||
}
|
||||
53
apps/web/src/lib/natural-input/voice-examples.test.ts
Normal 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)
|
||||
})
|
||||
})
|
||||
67
apps/web/src/lib/pending-deletions.test.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import {
|
||||
DELETE_UNDO_MS,
|
||||
flushPendingDeletions,
|
||||
getPendingDeletions,
|
||||
scheduleDeletion,
|
||||
} from './pending-deletions'
|
||||
|
||||
describe('pending deletions', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('hides the item and sends the delete once the undo window is over', async () => {
|
||||
const commit = vi.fn(async () => {})
|
||||
scheduleDeletion('item-1', commit)
|
||||
|
||||
expect(getPendingDeletions().has('item-1')).toBe(true)
|
||||
await vi.advanceTimersByTimeAsync(DELETE_UNDO_MS - 1)
|
||||
expect(commit).not.toHaveBeenCalled()
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(commit).toHaveBeenCalledWith({ keepalive: false })
|
||||
expect(getPendingDeletions().has('item-1')).toBe(false)
|
||||
})
|
||||
|
||||
it('undo restores the item and never sends the delete', async () => {
|
||||
const commit = vi.fn(async () => {})
|
||||
const undo = scheduleDeletion('item-2', commit)
|
||||
|
||||
undo()
|
||||
expect(getPendingDeletions().has('item-2')).toBe(false)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(DELETE_UNDO_MS)
|
||||
expect(commit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows the item again when the delete fails', async () => {
|
||||
const commit = vi.fn(async (_init: { keepalive: boolean }) => {
|
||||
throw new Error('offline')
|
||||
})
|
||||
scheduleDeletion('item-3', (init) => commit(init).catch(() => {}))
|
||||
|
||||
await vi.advanceTimersByTimeAsync(DELETE_UNDO_MS)
|
||||
expect(commit).toHaveBeenCalledOnce()
|
||||
expect(getPendingDeletions().has('item-3')).toBe(false)
|
||||
})
|
||||
|
||||
it('flushes waiting deletions right away with keepalive', async () => {
|
||||
const commit = vi.fn(async () => {})
|
||||
scheduleDeletion('item-4', commit)
|
||||
|
||||
flushPendingDeletions()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(commit).toHaveBeenCalledWith({ keepalive: true })
|
||||
expect(getPendingDeletions().has('item-4')).toBe(false)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(DELETE_UNDO_MS)
|
||||
expect(commit).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
90
apps/web/src/lib/pending-deletions.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
/** How long a deleted item can still be restored before its `DELETE` is sent. */
|
||||
export const DELETE_UNDO_MS = 3000
|
||||
|
||||
/** Sends the `DELETE`; `keepalive` is set when the page is going away. */
|
||||
type Commit = (init: { keepalive: boolean }) => Promise<void>
|
||||
|
||||
type PendingDeletion = {
|
||||
/** Pending until the `DELETE` is sent; `undefined` once it is in flight. */
|
||||
timer: ReturnType<typeof setTimeout> | undefined
|
||||
commit: Commit
|
||||
}
|
||||
|
||||
/**
|
||||
* Items the user deleted, still hidden while they can be restored or while
|
||||
* their `DELETE` is in flight. It lives outside React so navigating away does
|
||||
* not cancel a deletion; rows are filtered out at render time, so a refetch
|
||||
* in the meantime cannot bring them back.
|
||||
*/
|
||||
const pending = new Map<string, PendingDeletion>()
|
||||
const listeners = new Set<() => void>()
|
||||
let snapshot: ReadonlySet<string> = new Set()
|
||||
|
||||
function emit() {
|
||||
snapshot = new Set(pending.keys())
|
||||
for (const listener of listeners) listener()
|
||||
}
|
||||
|
||||
/** `useSyncExternalStore` subscription. */
|
||||
export function subscribePendingDeletions(listener: () => void): () => void {
|
||||
listeners.add(listener)
|
||||
return () => listeners.delete(listener)
|
||||
}
|
||||
|
||||
/** Ids of the items hidden because they are being deleted (a stable snapshot). */
|
||||
export function getPendingDeletions(): ReadonlySet<string> {
|
||||
return snapshot
|
||||
}
|
||||
|
||||
async function run(itemId: string, keepalive: boolean) {
|
||||
const entry = pending.get(itemId)
|
||||
if (!entry) return
|
||||
|
||||
clearTimeout(entry.timer)
|
||||
entry.timer = undefined
|
||||
|
||||
try {
|
||||
await entry.commit({ keepalive })
|
||||
} finally {
|
||||
// On success the commit already dropped the item from the cache; on
|
||||
// failure the row comes back.
|
||||
pending.delete(itemId)
|
||||
emit()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hides the item and sends its `DELETE` after `DELETE_UNDO_MS`. Returns the
|
||||
* undo function, which only works while the `DELETE` has not been sent.
|
||||
*/
|
||||
export function scheduleDeletion(itemId: string, commit: Commit): () => void {
|
||||
if (!pending.has(itemId)) {
|
||||
pending.set(itemId, {
|
||||
timer: setTimeout(() => void run(itemId, false), DELETE_UNDO_MS),
|
||||
commit,
|
||||
})
|
||||
emit()
|
||||
}
|
||||
|
||||
return () => {
|
||||
const entry = pending.get(itemId)
|
||||
if (!entry?.timer) return
|
||||
|
||||
clearTimeout(entry.timer)
|
||||
pending.delete(itemId)
|
||||
emit()
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends every deletion still waiting, without waiting for the undo window. */
|
||||
export function flushPendingDeletions(): void {
|
||||
for (const [itemId, entry] of pending) {
|
||||
if (entry.timer) void run(itemId, true)
|
||||
}
|
||||
}
|
||||
|
||||
// Closing the tab or the installed app must not lose a deletion: `keepalive`
|
||||
// lets the request outlive the page.
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('pagehide', flushPendingDeletions)
|
||||
}
|
||||
34
apps/web/src/lib/speech-recognition.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
/** The slice of the Web Speech API the app uses (TypeScript's DOM lib does not ship it). */
|
||||
export type SpeechRecognitionResultLike = { isFinal: boolean; 0: { transcript: string } }
|
||||
|
||||
export type SpeechRecognitionLike = {
|
||||
lang: string
|
||||
interimResults: boolean
|
||||
continuous: boolean
|
||||
maxAlternatives: number
|
||||
onresult: ((event: { results: ArrayLike<SpeechRecognitionResultLike> }) => void) | null
|
||||
onerror: ((event: { error: string }) => void) | null
|
||||
onend: (() => void) | null
|
||||
start: () => void
|
||||
stop: () => void
|
||||
abort: () => void
|
||||
}
|
||||
|
||||
export type SpeechRecognitionConstructor = new () => SpeechRecognitionLike
|
||||
|
||||
/** `SpeechRecognition`, or Safari's `webkitSpeechRecognition`, or `null` when there is none. */
|
||||
export function getSpeechRecognition(): SpeechRecognitionConstructor | null {
|
||||
if (typeof window === 'undefined') return null
|
||||
|
||||
const speechWindow = window as Window & {
|
||||
SpeechRecognition?: SpeechRecognitionConstructor
|
||||
webkitSpeechRecognition?: SpeechRecognitionConstructor
|
||||
}
|
||||
|
||||
return speechWindow.SpeechRecognition ?? speechWindow.webkitSpeechRecognition ?? null
|
||||
}
|
||||
|
||||
/** Whether the page runs as an app installed on the iOS home screen. */
|
||||
export function isIosStandalone(): boolean {
|
||||
return (navigator as Navigator & { standalone?: boolean }).standalone === true
|
||||
}
|
||||
288
apps/web/src/routes/(auth)/forgot-password.tsx
Normal file
@@ -0,0 +1,288 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
|
||||
import { useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { AppBrand } from '@/components/app-logo'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { emailOtp } from '@/lib/auth-client'
|
||||
|
||||
type ForgotPasswordSearch = { redirect?: string; email?: string }
|
||||
|
||||
export const Route = createFileRoute('/(auth)/forgot-password')({
|
||||
validateSearch: (search: Record<string, unknown>): ForgotPasswordSearch => ({
|
||||
redirect: typeof search.redirect === 'string' ? search.redirect : undefined,
|
||||
email: typeof search.email === 'string' ? search.email : undefined,
|
||||
}),
|
||||
component: ForgotPasswordPage,
|
||||
})
|
||||
|
||||
const requestSchema = z.object({
|
||||
email: z.email('Introduce un correo electrónico válido'),
|
||||
})
|
||||
|
||||
const resetSchema = z
|
||||
.object({
|
||||
otp: z.string().regex(/^\d{6}$/, 'El código tiene 6 dígitos'),
|
||||
password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'),
|
||||
confirmPassword: z.string(),
|
||||
})
|
||||
.refine((values) => values.password === values.confirmPassword, {
|
||||
message: 'Las contraseñas no coinciden',
|
||||
path: ['confirmPassword'],
|
||||
})
|
||||
|
||||
// BetterAuth answers in English; an unknown email reads like a wrong code so the
|
||||
// form doesn't reveal which addresses have an account.
|
||||
const resetErrorMessages: Record<string, string> = {
|
||||
INVALID_OTP: 'El código no es correcto.',
|
||||
USER_NOT_FOUND: 'El código no es correcto.',
|
||||
OTP_EXPIRED: 'El código venció. Pide uno nuevo.',
|
||||
TOO_MANY_ATTEMPTS: 'Demasiados intentos fallidos. Pide un código nuevo.',
|
||||
}
|
||||
|
||||
type RequestValues = z.infer<typeof requestSchema>
|
||||
type ResetValues = z.infer<typeof resetSchema>
|
||||
|
||||
function ForgotPasswordPage() {
|
||||
const { redirect, email: initialEmail } = Route.useSearch()
|
||||
const [email, setEmail] = useState<string | null>(null)
|
||||
|
||||
return (
|
||||
<div className="flex min-h-svh flex-col items-center justify-center gap-6 p-6">
|
||||
<AppBrand />
|
||||
<Card className="w-full max-w-sm">
|
||||
{email ? (
|
||||
<ResetPasswordStep
|
||||
email={email}
|
||||
redirect={redirect}
|
||||
onChangeEmail={() => setEmail(null)}
|
||||
/>
|
||||
) : (
|
||||
<RequestCodeStep
|
||||
defaultEmail={initialEmail ?? ''}
|
||||
redirect={redirect}
|
||||
onSent={setEmail}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type RequestCodeStepProps = {
|
||||
defaultEmail: string
|
||||
redirect?: string
|
||||
onSent: (email: string) => void
|
||||
}
|
||||
|
||||
function RequestCodeStep({ defaultEmail, redirect, onSent }: RequestCodeStepProps) {
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const form = useForm<RequestValues>({
|
||||
resolver: zodResolver(requestSchema),
|
||||
defaultValues: { email: defaultEmail },
|
||||
})
|
||||
|
||||
const onSubmit = form.handleSubmit(async ({ email }) => {
|
||||
setError(null)
|
||||
|
||||
const { error: requestError } = await emailOtp.requestPasswordReset({ email })
|
||||
|
||||
if (requestError) {
|
||||
setError(requestError.message ?? 'No pudimos enviar el código')
|
||||
return
|
||||
}
|
||||
|
||||
onSent(email)
|
||||
})
|
||||
|
||||
return (
|
||||
<>
|
||||
<CardHeader>
|
||||
<CardTitle>Recuperar contraseña</CardTitle>
|
||||
<CardDescription>Te enviaremos un código por correo para elegir una nueva.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={onSubmit} className="flex flex-col gap-6">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>No pudimos enviar el código</AlertTitle>
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<Field data-invalid={!!form.formState.errors.email}>
|
||||
<FieldLabel htmlFor="email">Correo electrónico</FieldLabel>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
placeholder="ada@ejemplo.com"
|
||||
{...form.register('email')}
|
||||
/>
|
||||
<FieldError errors={[form.formState.errors.email]} />
|
||||
</Field>
|
||||
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
{form.formState.isSubmitting ? 'Enviando…' : 'Enviar código'}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
|
||||
<BackToSignIn redirect={redirect} />
|
||||
</form>
|
||||
</CardContent>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
type ResetPasswordStepProps = {
|
||||
email: string
|
||||
redirect?: string
|
||||
onChangeEmail: () => void
|
||||
}
|
||||
|
||||
function ResetPasswordStep({ email, redirect, onChangeEmail }: ResetPasswordStepProps) {
|
||||
const navigate = useNavigate()
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [resending, setResending] = useState(false)
|
||||
|
||||
const form = useForm<ResetValues>({
|
||||
resolver: zodResolver(resetSchema),
|
||||
defaultValues: { otp: '', password: '', confirmPassword: '' },
|
||||
})
|
||||
|
||||
const onSubmit = form.handleSubmit(async ({ otp, password }) => {
|
||||
setError(null)
|
||||
|
||||
const { error: resetError } = await emailOtp.resetPassword({ email, otp, password })
|
||||
|
||||
if (resetError) {
|
||||
setError(
|
||||
(resetError.code && resetErrorMessages[resetError.code]) ??
|
||||
resetError.message ??
|
||||
'No pudimos cambiar tu contraseña',
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
toast.success('Contraseña actualizada. Ya puedes iniciar sesión.')
|
||||
await navigate({ to: '/sign-in', search: redirect ? { redirect } : {} })
|
||||
})
|
||||
|
||||
const resend = async () => {
|
||||
setResending(true)
|
||||
const { error: requestError } = await emailOtp.requestPasswordReset({ email })
|
||||
setResending(false)
|
||||
|
||||
if (requestError) {
|
||||
toast.error(requestError.message ?? 'No pudimos reenviar el código')
|
||||
return
|
||||
}
|
||||
|
||||
toast.success('Te enviamos un código nuevo')
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<CardHeader>
|
||||
<CardTitle>Elige una nueva contraseña</CardTitle>
|
||||
<CardDescription>
|
||||
Si existe una cuenta con <span className="text-foreground font-medium">{email}</span>, te
|
||||
enviamos un código de 6 dígitos. Vence en 10 minutos.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={onSubmit} className="flex flex-col gap-6">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>No pudimos cambiar tu contraseña</AlertTitle>
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<Field data-invalid={!!form.formState.errors.otp}>
|
||||
<FieldLabel htmlFor="otp">Código</FieldLabel>
|
||||
<Input
|
||||
id="otp"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
maxLength={6}
|
||||
placeholder="123456"
|
||||
className="font-mono tracking-widest"
|
||||
{...form.register('otp')}
|
||||
/>
|
||||
<FieldError errors={[form.formState.errors.otp]} />
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!form.formState.errors.password}>
|
||||
<FieldLabel htmlFor="password">Nueva contraseña</FieldLabel>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
{...form.register('password')}
|
||||
/>
|
||||
<FieldError errors={[form.formState.errors.password]} />
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!form.formState.errors.confirmPassword}>
|
||||
<FieldLabel htmlFor="confirmPassword">Repite la contraseña</FieldLabel>
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
{...form.register('confirmPassword')}
|
||||
/>
|
||||
<FieldError errors={[form.formState.errors.confirmPassword]} />
|
||||
</Field>
|
||||
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
{form.formState.isSubmitting ? 'Guardando…' : 'Cambiar contraseña'}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<Button type="button" variant="link" className="h-auto p-0" onClick={onChangeEmail}>
|
||||
Usar otro correo
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
className="h-auto p-0"
|
||||
disabled={resending}
|
||||
onClick={resend}
|
||||
>
|
||||
{resending ? 'Reenviando…' : 'Reenviar código'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<BackToSignIn redirect={redirect} />
|
||||
</form>
|
||||
</CardContent>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function BackToSignIn({ redirect }: { redirect?: string }) {
|
||||
return (
|
||||
<p className="text-muted-foreground text-center text-sm">
|
||||
¿Recordaste tu contraseña?{' '}
|
||||
<Link
|
||||
to="/sign-in"
|
||||
search={redirect ? { redirect } : {}}
|
||||
className="text-foreground font-medium underline-offset-4 hover:underline"
|
||||
>
|
||||
Inicia sesión
|
||||
</Link>
|
||||
</p>
|
||||
)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { AppBrand } from '@/components/app-logo'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
@@ -54,7 +55,8 @@ function SignInPage() {
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="flex min-h-svh items-center justify-center p-6">
|
||||
<div className="flex min-h-svh flex-col items-center justify-center gap-6 p-6">
|
||||
<AppBrand />
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Iniciar sesión</CardTitle>
|
||||
@@ -83,7 +85,19 @@ function SignInPage() {
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!form.formState.errors.password}>
|
||||
<div className="flex items-center justify-between">
|
||||
<FieldLabel htmlFor="password">Contraseña</FieldLabel>
|
||||
<Link
|
||||
to="/forgot-password"
|
||||
search={() => {
|
||||
const email = form.getValues('email')
|
||||
return { redirect, email: email || undefined }
|
||||
}}
|
||||
className="text-muted-foreground text-sm underline-offset-4 hover:text-foreground hover:underline"
|
||||
>
|
||||
¿Olvidaste tu contraseña?
|
||||
</Link>
|
||||
</div>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { AppBrand } from '@/components/app-logo'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
@@ -55,7 +56,8 @@ function SignUpPage() {
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="flex min-h-svh items-center justify-center p-6">
|
||||
<div className="flex min-h-svh flex-col items-center justify-center gap-6 p-6">
|
||||
<AppBrand />
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Crear cuenta</CardTitle>
|
||||
|
||||
@@ -24,6 +24,10 @@ services:
|
||||
LOG_LEVEL: ${LOG_LEVEL:-}
|
||||
RESEND_API_KEY: ${RESEND_API_KEY:-}
|
||||
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:
|
||||
- "4100"
|
||||
networks:
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { ListItem } from './shopping-list'
|
||||
export type ListEventType =
|
||||
| 'item.created'
|
||||
| 'item.updated'
|
||||
| 'item.removed'
|
||||
| 'invitation.created'
|
||||
| 'member.added'
|
||||
| 'list.updated'
|
||||
@@ -15,6 +16,8 @@ export type ListEventType =
|
||||
*/
|
||||
export type ListEvent =
|
||||
| { type: 'item.created' | 'item.updated'; listId: string; item: ListItem }
|
||||
/** The item left this list (it was moved to another one). */
|
||||
| { type: 'item.removed'; listId: string; itemId: string }
|
||||
| { type: 'invitation.created'; listId: string; email: string }
|
||||
| { type: 'member.added'; listId: string; userId: string }
|
||||
| { type: 'list.updated'; listId: string; name: string }
|
||||
|
||||
@@ -2,3 +2,4 @@ export * from './events'
|
||||
export * from './problem-details'
|
||||
export * from './result'
|
||||
export * from './shopping-list'
|
||||
export * from './voice'
|
||||
|
||||
45
packages/shared/src/voice.ts
Normal 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)'],
|
||||
},
|
||||
]
|
||||
@@ -18,7 +18,10 @@
|
||||
"CORS_ORIGIN",
|
||||
"RESEND_API_KEY",
|
||||
"MAIL_FROM",
|
||||
"WEB_APP_URL"
|
||||
"WEB_APP_URL",
|
||||
"GEMINI_API_KEY",
|
||||
"GEMINI_MODEL",
|
||||
"GEMINI_TIMEOUT_MS"
|
||||
]
|
||||
},
|
||||
"dev": {
|
||||
@@ -34,6 +37,9 @@
|
||||
"RESEND_API_KEY",
|
||||
"MAIL_FROM",
|
||||
"WEB_APP_URL",
|
||||
"GEMINI_API_KEY",
|
||||
"GEMINI_MODEL",
|
||||
"GEMINI_TIMEOUT_MS",
|
||||
"VITE_API_URL"
|
||||
]
|
||||
},
|
||||
|
||||