29 Commits

Author SHA1 Message Date
Jose Selesan
1964d3e08b feat: add dictation 2026-10-29 10:29:57 -03:00
Jose Selesan
2117188bf9 feat(auth): recover a password with a code sent by email
Enable BetterAuth's emailOTP plugin for password resets: a 6-digit code,
valid for 10 minutes with 3 attempts, stored hashed in `verifications`
(no migration). The code goes out through the existing Resend mailer with
a new Spanish template, and other sessions are revoked after the reset.

The web app gets a two-step /forgot-password route (request the code,
then set the new password) linked from sign-in. Unknown emails get the
same responses as known ones so the form doesn't reveal accounts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 10:13:15 -03:00
Jose Selesan
9bd2cc9089 feat(web): add the Superlist icon and logo
A cream shopping bag with a check on the app's green replaces the black
"SL" placeholder: favicon, iOS home-screen icon, PWA icons (with a maskable
version that keeps the bag inside the safe zone) and an AppLogo component
shown in the sidebar and above the sign-in and sign-up forms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 09:46:13 -03:00
Jose Selesan
9d4388ed8c feat(web): add text dictated with the iOS keyboard after 3 seconds
The installed iOS app has no speech recognition, so people dictate with the
keyboard's microphone, which only writes text into the input and never
ended it. Text that arrives without key presses (words or phrases at once,
or replacements) is now treated as a dictation: 3 seconds after the last
change it goes through the voice flow (AI split, "Deshacer"). Typing a key
cancels it; pastes and deletions never trigger it.

The form field is no longer called `name`, which made iOS offer to
autofill a contact into the add field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 19:41:39 -03:00
Jose Selesan
48c0c83424 feat(web): finish a dictation after 3 seconds of silence
Safari on iOS keeps listening long after the user stops talking, so the
phrase only got added by pressing Enter (which added the raw transcript,
skipping the AI split). Now the dictation ends 3 seconds after the last words
heard and goes through the usual voice flow; Enter while listening ends it
the same way instead of adding the text as typed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 19:34:20 -03:00
Jose Selesan
a814b34036 feat(items): voice dictation with Gemma 4 and a reworked list UI
Dictation: a mic button in the add field uses the Web Speech API (es-AR) and
shows the partial transcript in the input. POST /api/voice/split asks Gemma 4
(Gemini API, plain fetch) to split the sentence into one string per item,
written the way the existing parser reads typed text; each string then goes
through the usual add flow. The endpoint never fails because of the model:
missing key, timeout, 429 or invalid JSON fall back to splitting on commas,
semicolons, " y " and " e ". A toast offers "Deshacer" for the whole dictation;
if the request fails, the transcript is added as a single item.

UI: "+" instead of the search icon, quantity tags ("2 L", "×12", "1 kg"), the
list name with a list switcher and the pending/bought count in the header,
"Comprados (N)" folded by default, and a bottom sheet to edit name, quantity
(− / + and unit), note and delete. PATCH items now accepts a name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 19:25:10 -03:00
Jose Selesan
eb1f6cb2a9 feat(items): delete an item with a swipe right, undoable for 3 seconds
A long swipe right on an item (or "Eliminar" in the desktop context menu)
hides it and shows a toast with "Deshacer". The DELETE is only sent once
the 3 seconds are over, so undoing just cancels it; pending deletions are
flushed with keepalive if the page is closed in the meantime.

The API gets DELETE /api/lists/:listId/items/:itemId, members only, which
publishes item.removed so other members see the item disappear.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:40:56 -03:00
Jose Selesan
feb8df14c0 feat(items): move an item to another list with a long swipe
A longer swipe left on an item (past the edit threshold) opens a dialog
with the user's other lists; picking one moves the item there while the
user stays on the current list. On desktop, right-click now opens a
context menu with "Editar" and "Mover a otra lista…".

The API gets POST /api/lists/:listId/items/:itemId/move, which requires
membership in both lists and publishes item.removed on the source list
and item.created on the target, so other members see the change live.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:24:38 -03:00
Jose Selesan
86d4796d88 fix(web): reload the installed iOS app when the theme changes
An iOS home-screen app only reads theme-color on page load, so updating
the meta in place left the status bar with the previous theme's color.
Reload when the resolved theme changes; the pre-paint script applies the
stored theme before the first paint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:10:03 -03:00
Jose Selesan
d5feb65d62 feat(web): show the build's commit and date in settings
Lets you tell whether an installed PWA picked up a new release. The
commit is read from .git at build time (the Docker build stage has no
git binary), so .dockerignore now lets HEAD and the refs through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:00:33 -03:00
Jose Selesan
71793dbd3a fix(web): match the iOS status bar to the theme picked in the app
The theme-color metas used prefers-color-scheme media queries, so they
followed the OS theme and ignored the in-app choice. Use a single meta
that the pre-paint script and ThemeProvider update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:24:38 -03:00
Jose Selesan
5abdb08204 feat(items): read quantity, unit and notes from natural-language input
"400 de jamon" adds Jamón · 400, "Queso crema. Solo Tregar" adds a note,
"leche, pan y 2 pascualinas" adds three items and a pasted list adds one per
line. Units are normalized (½ kg, 1,5 l, 2 paquetes), common accents are
restored, and a pending duplicate gets its quantity summed instead of a new
row. A preview under the input shows the reading, with a way to add the text
as typed. quantityLabel now shows any quantity except a plain "1".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:10:23 -03:00
Jose Selesan
d02ab28fc5 feat(items): edit quantity and notes inline, with swipe feedback
The PATCH endpoint now also accepts notes. Swiping an item to the left (or
right-clicking it) opens an inline editor below the row for its quantity and
notes, focused on the quantity input, instead of the quantity dialog. The row
slides with the finger during the swipe and snaps back on release, and only
one row edits at a time. Toggling an item no longer moves the focus to the
add-item input, and notes show under the item's name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 18:30:04 -03:00
Jose Selesan
db7cdd5585 feat(items): edit an item's quantity by swiping or right-clicking it
The PATCH endpoint now accepts quantity alongside completed (at least one
field is required), and the row shows the quantity only when its leading
number is above one. A small dialog edits it, opened by a left swipe on
touch or by right-clicking the row on desktop.
2026-10-20 15:02:41 -03:00
Jose Selesan
247ea903a9 fix(web): clear the bottom nav's safe-area inset on scrollable pages 2026-10-19 20:34:56 -03:00
Jose Selesan
b913fe3299 Add sticky header 2026-10-19 18:57:47 -03:00
Jose Selesan
b7fa930831 fix(web): keep focus on the item input when adding with the + button
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:05:41 -03:00
Jose Selesan
812d4b7170 feat(web): green, warm-paper theme with a matching dark mode
- New light palette (warm off-white background, white cards, grocery green
  primary) and a green-tinted charcoal dark mode; larger radius.
- Items render as one grouped card; bought items live in a collapsible
  "Comprados · N" card with a muted header.
- Pill-shaped add-item input (shadcn input-group) with a round add button.
- Progress summary ("N pendientes · M comprados" + bar) above the input.
- Active bottom-nav item uses the primary color with a dot.
- theme-color metas and PWA manifest follow the new background.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:55:48 -03:00
Jose Selesan
123601939c fix(web): declare workbox-window so the Docker build resolves it
virtual:pwa-register imports workbox-window, a transitive dependency of
vite-plugin-pwa. It resolved locally only because the global bunfig uses the
hoisted linker; the Docker image installs with Bun's isolated linker, where
undeclared packages are not reachable from apps/web.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:18:16 -03:00
Jose Selesan
686325d8a4 feat(web): auto-update the PWA when a new release is deployed
Register the service worker from the app (virtual:pwa-register) instead of
the injected script, so an installed PWA that stays open also checks for a
new worker every 30 minutes, when it returns to the foreground and when the
connection comes back. The new worker skips waiting, claims every tab and the
page reloads into it, deferring the reload until the app is backgrounded if
the user is typing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:15:10 -03:00
Jose Selesan
56853bbdeb fix(deploy): let the API reach Dokploy's database again
Since 815dcc3 the api service only joined the stack-private `internal`
network, so it could no longer resolve the database host on
`dokploy-network` and `prisma migrate deploy` failed with P1001.

api joins `dokploy-network` again, only to reach the database. nginx
still proxies to the `superlist-api` alias, which is declared only on
`internal`, so the shared network never routes our traffic elsewhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:08:19 -03:00
Jose Selesan
debf3b2728 feat(web): UI quick wins for items, navigation and settings
- Toggling an item only disables that row, so several items can be
  marked in a row; failures roll back just that item and show a toast,
  and the list refetches once the last toggle settles.
- Sidebar, bottom nav and header share one set of sections
  (Inicio / Listas / Ajustes); the bottom nav drops the duplicated
  "Cuenta" link and the header drops the non-functional search button.
- Settings: the name is saved through BetterAuth, the email is shown
  read-only, and the fake notification switches are replaced by a real
  theme picker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:52:08 -03:00
Jose Selesan
bba10361f0 feat: show list name on header 2026-10-19 12:46:40 -03:00
Jose Selesan
c374db1616 feat: Enahnce add item delay 2026-10-19 12:26:21 -03:00
Jose Selesan
815dcc300d fix(deploy): isolate web→api traffic on a private network
nginx proxied to `api:4100` over the shared `dokploy-network`, where the
generic name `api` resolved to more than one container (a stale one from a
previous deploy, or another project's service). nginx pinned those IPs at
startup and round-robined across them, so requests hit a refused upstream
and could reach a foreign container.

- api now lives only on a stack-private `internal` network, aliased as
  `superlist-api`; only web joins `dokploy-network` for Traefik.
- nginx proxies via a variable with Docker's resolver (127.0.0.11,
  valid=10s), so API redeploys never leave it on a stale IP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:05:20 -03:00
Jose Selesan
371e59de92 fix: redirect to login on first load without session 2026-10-19 11:43:55 -03:00
Jose Selesan
5a8604298e fix(api): fall back to defaults when LOG_LEVEL or MAIL_FROM are empty
Compose defines unset optional variables as empty strings, so `??` kept
"" and Pino crashed on startup with an empty level, leaving the api
container unhealthy on Dokploy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 09:41:53 -03:00
Jose Selesan
e0003490b3 Updated healthcheck 2026-10-19 09:32:13 -03:00
Jose Selesan
9e16dc1c81 Remove healthcheck 2026-10-19 09:30:28 -03:00
111 changed files with 6164 additions and 531 deletions

17
.claude/launch.json Normal file
View 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
}
]
}

View File

@@ -1,4 +1,8 @@
.git
# Just enough of the repository for the web build to read the commit hash.
!.git/HEAD
!.git/refs
!.git/packed-refs
.github
**/node_modules
**/.turbo

View File

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

View File

@@ -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`)
@@ -90,12 +91,17 @@ Run from the repo root. Verification order is `build`, then `lint` → `typechec
rename never changes the TypeScript API. Default constraint/index names follow the mapped names, so do not
set `map:` unless you have a reason to.
- **Deployment: Docker Compose on Dokploy** (`docker-compose.yml` at the repo root). Two services, `api` and
`web`; the database is external (Dokploy's), and both join the external `dokploy-network` for Traefik. The
`web`; the database is external (Dokploy's). Both join the external `dokploy-network` — `web` for Traefik,
`api` to reach the database (without it `prisma migrate deploy` fails with P1001). nginx reaches the API
over the stack-private `internal` network, where it has the alias `superlist-api`, declared only there
(never rely on a generic service name on the shared network: other projects can answer to it). The
`api` image (`apps/api/Dockerfile`) builds the Bun bundle and runs `prisma migrate deploy` before
`bun run start`; the `web` image (`apps/web/Dockerfile`) builds with Vite and serves `dist/` with
`apps/web/nginx.conf`, which also proxies `/api/*` to `http://api:4100`. Required env vars are interpolated
`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`,
@@ -197,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
@@ -235,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/`.

View File

@@ -53,9 +53,11 @@ same Biome check as `biome ci` would.
`docker-compose.yml` at the repo root defines the two runtime services — `api` (Bun + nginx-free Hono server)
and `web` (static build behind nginx, proxying `/api/*` to the API). The database is external (provided by
Dokploy), and both services join the external `dokploy-network` so Traefik can reach them.
Dokploy). Only `web` joins the external `dokploy-network` so Traefik can reach it; `web` and `api` talk over
the stack-private `internal` network, where the API answers to the unique alias `superlist-api` (a generic
name like `api` on the shared network could resolve to another project's container).
- One public domain: nginx serves the SPA and proxies `/api/*` → `http://api:4100`. All API routes are
- One public domain: nginx serves the SPA and proxies `/api/*` → `http://superlist-api:4100`. All API routes are
mounted under `/api` for that reason — never mount a route at the root of the API.
- Env vars are interpolated from the Dokploy service env (`docker-compose.yml` marks `DATABASE_URL`,
`BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `CORS_ORIGIN` and `WEB_APP_URL` as required). See `.env.example`.

View File

@@ -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"

View File

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

View File

@@ -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,16 +13,51 @@ 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,
secret: process.env.BETTER_AUTH_SECRET,
trustedOrigins,
session: {
// A signed copy of the session lives in a cookie for 5 minutes, so protected
// routes skip the session lookup in Postgres on every request. Trade-off: a
// session revoked elsewhere stays valid on other devices until the cache expires.
cookieCache: {
enabled: true,
maxAge: 5 * 60,
},
},
emailAndPassword: {
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: {

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

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

View File

@@ -7,7 +7,7 @@ const isProduction = process.env.NODE_ENV === 'production'
* never use `console.log` in the backend.
*/
export const logger = pino({
level: process.env.LOG_LEVEL ?? (isProduction ? 'info' : 'debug'),
level: process.env.LOG_LEVEL || (isProduction ? 'info' : 'debug'),
...(isProduction
? {}
: {

View File

@@ -11,7 +11,7 @@ export type Email = {
}
const apiKey = process.env.RESEND_API_KEY
const from = process.env.MAIL_FROM ?? 'Superlist <onboarding@resend.dev>'
const from = process.env.MAIL_FROM || 'Superlist <onboarding@resend.dev>'
let client: Resend | null = null

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

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

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

View File

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

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

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

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

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

View File

@@ -9,7 +9,7 @@ import type { AppEnv } from '@/types'
import { ItemParamsSchema, UpdateItemSchema } from './schema'
import { UpdateItem } from './use-case'
/** PATCH /lists/:listId/items/:itemId — marks an item as bought or pending. */
/** 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,12 +17,15 @@ export const updateItemRoute = new Hono<AppEnv>().patch(
validate.json(UpdateItemSchema),
async (c) => {
const { listId, itemId } = c.req.valid('param')
const { completed } = 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,
})
return resultJson(c, result)

View File

@@ -8,9 +8,28 @@ export const ItemParamsSchema = z.object({
export type ItemParams = z.infer<typeof ItemParamsSchema>
/** Body of `PATCH /lists/:listId/items/:itemId`. */
export const UpdateItemSchema = z.object({
completed: z.boolean(),
})
/** 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.name !== undefined ||
value.completed !== undefined ||
value.quantity !== undefined ||
value.notes !== undefined,
{
message: 'Indica al menos un campo para actualizar.',
},
)
export type UpdateItemInput = z.infer<typeof UpdateItemSchema>

View File

@@ -45,9 +45,13 @@ function createDb(options: { membership: unknown; item: ItemRow | null }) {
},
listItem: {
findFirst: async () => options.item,
update: async (args: { data: { completed: boolean; boughtAt: Date | 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, 'name' | 'completed' | 'boughtAt' | 'quantity' | 'notes'>>
}) => {
updates.push(args)
return itemRow(args.data.completed, args.data.boughtAt)
return { ...options.item, ...args.data } as ItemRow
},
},
}
@@ -122,6 +126,108 @@ describe('UpdateItem', () => {
expect(published).toEqual([{ type: 'item.updated', listId: 'list-1', item: result.value }])
})
it('updates only the quantity, leaving the bought state untouched', async () => {
const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) })
const { events, published } = createBus()
const result = await new UpdateItem(db, events).execute({
listId: 'list-1',
itemId: 'item-1',
userId: 'user-1',
quantity: ' 3 ',
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
expect(updates).toHaveLength(1)
const data = updates[0] as {
data: { completed?: boolean; boughtAt?: Date | null; quantity?: string | null }
}
expect(data.data).toEqual({ quantity: '3' })
expect(data.data.completed).toBeUndefined()
expect(result.value.completed).toBe(false)
expect(result.value.quantity).toBe('3')
expect(published).toEqual([{ type: 'item.updated', listId: 'list-1', item: result.value }])
})
it('clears the quantity when an empty value is sent', 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',
quantity: '',
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
const data = updates[0] as { data: { quantity?: string | null } }
expect(data.data).toEqual({ quantity: null })
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()
const result = await new UpdateItem(db, events).execute({
listId: 'list-1',
itemId: 'item-1',
userId: 'user-1',
notes: ' sin lactosa ',
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
const data = updates[0] as { data: { notes?: string | null } }
expect(data.data).toEqual({ notes: 'sin lactosa' })
expect(result.value.notes).toBe('sin lactosa')
expect(result.value.quantity).toBe('1 L')
expect(published).toEqual([{ type: 'item.updated', listId: 'list-1', item: result.value }])
})
it('clears the notes when an empty value is sent', 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',
notes: '',
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
const data = updates[0] as { data: { notes?: string | null } }
expect(data.data).toEqual({ notes: null })
expect(result.value.notes).toBeNull()
})
it('marks the item back to pending, clears boughtAt and publishes item.updated', async () => {
const { db, updates } = createDb({
membership: { role: 'collaborator' },

View File

@@ -12,9 +12,23 @@ import type { Database } from '@/lib/prisma'
import { toListItem } from '../serialize'
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. */
quantity?: string | null
/** New notes (`null` or an empty string clears them); when omitted they stay untouched. */
notes?: string | null
}
/**
* Marks an item as bought (or back to pending). Only members can do it.
* `boughtAt` records the moment it was marked as bought, for future
* 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.
*/
export class UpdateItem {
@@ -23,12 +37,7 @@ export class UpdateItem {
private readonly events: ListEvents = listEvents,
) {}
async execute(input: {
listId: string
itemId: string
userId: string
completed: boolean
}): Promise<Result<ListItem, ProblemDetails>> {
async execute(input: UpdateItemFields): Promise<Result<ListItem, ProblemDetails>> {
const membership = await this.db.shoppingListMember.findUnique({
where: { listId_userId: { listId: input.listId, userId: input.userId } },
})
@@ -45,12 +54,34 @@ export class UpdateItem {
return Failure(problems.notFound('El artículo no existe en esta lista.'))
}
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
}
if (input.quantity !== undefined) {
data.quantity = input.quantity?.trim() || null
}
if (input.notes !== undefined) {
data.notes = input.notes?.trim() || null
}
const updated = await this.db.listItem.update({
where: { id: item.id },
data: {
completed: input.completed,
boughtAt: input.completed ? new Date() : null,
},
data,
})
const dto = toListItem(updated)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -8,8 +8,9 @@
name="viewport"
content="width=device-width, initial-scale=1.0, viewport-fit=cover"
/>
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#ffffff" />
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#0a0a0a" />
<!-- Set from the resolved theme (script below and `theme-provider.tsx`), not with
`media` queries: those follow the OS and ignore the theme picked in the app. -->
<meta name="theme-color" content="#f9f8f5" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
@@ -28,6 +29,9 @@
stored === 'dark' || (stored !== 'light' && matchMedia('(prefers-color-scheme: dark)').matches)
document.documentElement.classList.toggle('dark', dark)
document.documentElement.style.colorScheme = dark ? 'dark' : 'light'
document
.querySelector('meta[name="theme-color"]')
.setAttribute('content', dark ? '#0f1411' : '#f9f8f5')
})()
</script>
</head>

View File

@@ -9,11 +9,19 @@ server {
gzip on;
gzip_types text/css application/javascript application/json image/svg+xml;
# API proxy: no path rewrite, /api/* reaches the API as-is. `proxy_buffering
# off` and the long read timeout keep the SSE streams (/lists/:id/events)
# flowing in realtime instead of being batched or cut off.
# Docker's embedded DNS. Proxying through a variable makes nginx re-resolve
# the API on every TTL instead of pinning the IPs it saw at startup, so a
# redeployed API container (new IP) is picked up without restarting nginx.
resolver 127.0.0.11 valid=10s ipv6=off;
# API proxy: no path rewrite, /api/* reaches the API as-is (proxy_pass with a
# variable and no URI forwards the original request URI). `superlist-api` is
# the API's alias on the stack-private network (see docker-compose.yml).
# `proxy_buffering off` and the long read timeout keep the SSE streams
# (/lists/:id/events) flowing in realtime instead of being batched or cut off.
location /api/ {
proxy_pass http://api:4100;
set $api_upstream http://superlist-api:4100;
proxy_pass $api_upstream;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;

View File

@@ -31,6 +31,7 @@
"recharts": "^3.10.1",
"sonner": "^2.0.8",
"tailwind-merge": "^3.7.0",
"workbox-window": "^7.4.1",
"zod": "^4.6.7"
},
"devDependencies": {

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

After

Width:  |  Height:  |  Size: 5.1 KiB

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.9 KiB

After

Width:  |  Height:  |  Size: 13 KiB

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.0 KiB

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 22 KiB

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

View File

@@ -1,6 +1,7 @@
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'
@@ -9,28 +10,54 @@ import { ItemRow } from './item-row'
type BoughtItemListProps = {
items: ListItem[]
updateItem: ReturnType<typeof useUpdateItem>
savingIds: string[]
onEdit: (item: ListItem) => void
onMove: (item: ListItem) => void
onDelete: (item: ListItem) => void
}
/**
* Collapsible "Comprados hoy" section 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 }: BoughtItemListProps) {
export function BoughtItemList({
items,
updateItem,
savingIds,
onEdit,
onMove,
onDelete,
}: BoughtItemListProps) {
return (
<Collapsible defaultOpen>
<CollapsibleTrigger className="group flex w-full items-center gap-1.5 py-1 text-left">
<ChevronDownIcon className="text-muted-foreground size-4 transition-transform group-data-[state=closed]:-rotate-90" />
<span className="text-muted-foreground text-sm font-medium">Comprados hoy</span>
<span className="text-muted-foreground text-sm">({items.length})</span>
</CollapsibleTrigger>
<CollapsibleContent>
<ul className="flex flex-col gap-2 pt-2">
{items.map((item) => (
<ItemRow key={item.id} item={item} updateItem={updateItem} />
))}
</ul>
</CollapsibleContent>
<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
key={item.id}
item={item}
updateItem={updateItem}
isSaving={savingIds.includes(item.id)}
onEdit={() => onEdit(item)}
onMove={() => onMove(item)}
onDelete={() => onDelete(item)}
/>
))}
</ul>
</Card>
</CollapsibleContent>
</section>
</Collapsible>
)
}

View File

@@ -1,15 +1,28 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { PlusIcon } from 'lucide-react'
import { useForm } from 'react-hook-form'
import { Loader2Icon, MicIcon, PlusIcon } from 'lucide-react'
import { type ClipboardEvent, useEffect, useState } from 'react'
import { useForm, useWatch } from 'react-hook-form'
import { z } from 'zod'
import { Button } from '@/components/ui/button'
import { ItemInputPreview } from '@/components/items/item-input-preview'
import { Field, FieldError } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { useCreateItem } from '@/hooks/use-items'
import {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupInput,
} from '@/components/ui/input-group'
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(120, 'Máximo 120 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>
@@ -34,40 +47,211 @@ const NEW_ITEM_INPUT_ID = 'new-item-input'
*/
export function focusNewItemInput(pathname: string): void {
if (pathname !== '/') return
refocusNewItemInput()
}
/** Puts the cursor back in the "add an item" input of the page on screen, if it has one. */
export function refocusNewItemInput(): void {
document.getElementById(NEW_ITEM_INPUT_ID)?.focus()
}
/** Input to add an item to a list. Submits with Enter or the button. */
/**
* 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)
// 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 onSubmit = form.handleSubmit((values) => {
createItem.mutate(values, { onSuccess: () => form.reset() })
const text = useWatch({ control: form.control, name: 'entry' })
const literal = literalText !== null && literalText === text
const restoreText = (source: string, message: string) => {
const current = form.getValues('entry').trim()
form.setValue('entry', current ? `${current}; ${source}` : source)
form.setError('entry', { message })
}
// A failed item comes back to the input, and so does a dictation that breaks the limits.
const { existing, addItems, addDictation, processing } = useAddItems(listId, {
onItemFailed: restoreText,
onDictationRejected: (transcript, message) => {
form.setValue('entry', transcript)
form.setError('entry', { message })
},
})
const dictation = useDictation({ onTranscript: (transcript) => onTranscript(transcript) })
// The keyboard's own microphone (the only one in the installed iOS app) just writes
// text: once it has been quiet for a few seconds, that text is added as a dictation.
const keyboardDictation = useKeyboardDictation({
onIdle: () => {
const dictated = form.getValues('entry').trim()
if (dictated && !dictation.listening && !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) => {
keyboardDictation.cancel()
const toAdd = readItems(values.entry, literal, existing)
const limitError = toAdd.map(itemLimitError).find(Boolean)
if (limitError) {
form.setError('entry', { message: limitError })
return
}
form.reset()
setLiteralText(null)
form.setFocus('entry')
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')
if (!/[\r\n]/.test(pasted)) return
event.preventDefault()
const input = event.currentTarget
const start = input.selectionStart ?? input.value.length
const end = input.selectionEnd ?? start
const lines = pasted
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean)
.join('; ')
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} className="flex items-start gap-2">
<Field className="flex-1" data-invalid={!!form.formState.errors.name}>
<Input
id={NEW_ITEM_INPUT_ID}
aria-label="Nuevo artículo"
autoComplete="off"
placeholder="Añade un artículo…"
autoFocus={autoFocus}
{...form.register('name')}
/>
<FieldError errors={[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-1.5">
<InputGroupButton
type="submit"
variant="ghost"
size="icon-sm"
aria-label="Agregar"
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()}
>
<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.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}
literal={literal}
onLiteralChange={(value) => setLiteralText(value ? text : null)}
/>
)}
</Field>
<Button type="submit" disabled={createItem.isPending}>
<PlusIcon />
{createItem.isPending ? 'Agregando…' : 'Agregar'}
</Button>
</form>
)
}

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

View File

@@ -0,0 +1,55 @@
import type { ListItem } from '@superlist/shared'
import { Button } from '@/components/ui/button'
import type { ParsedItem } from '@/lib/natural-input/parse-item'
export type PreviewItem = ParsedItem & {
/** The pending item this one will be added to instead of creating a new row. */
duplicate?: ListItem
}
type ItemInputPreviewProps = {
items: PreviewItem[]
/** The text will be added untouched, as a single item. */
literal: boolean
onLiteralChange: (literal: boolean) => void
}
/**
* Shows how the text in the "add an item" input will be read — name, quantity, note,
* and whether it adds to an item already on the list — with a way to add it as typed
* when the reading is wrong ("7 up").
*/
export function ItemInputPreview({ items, literal, onLiteralChange }: ItemInputPreviewProps) {
return (
<div className="flex flex-wrap items-center gap-1.5 px-5 text-sm" aria-live="polite">
{items.map((item) => (
<span
key={item.source}
className="bg-muted inline-flex max-w-full items-baseline gap-1.5 truncate rounded-full px-3 py-1"
>
<span className="truncate font-medium">{item.name}</span>
{item.quantity && <span className="text-muted-foreground">· {item.quantity}</span>}
{item.notes && (
<span className="text-muted-foreground truncate italic">· {item.notes}</span>
)}
{item.duplicate && (
<span className="text-primary text-xs">se suma a «{item.duplicate.name}»</span>
)}
</span>
))}
<Button
type="button"
variant="ghost"
size="xs"
className="text-muted-foreground"
// Keep the focus (and the mobile keyboard) in the input.
onMouseDown={(event) => event.preventDefault()}
onClick={() => onLiteralChange(!literal)}
>
{literal ? 'Interpretar' : 'Agregar tal cual'}
</Button>
</div>
)
}

View File

@@ -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 { Separator } from '@/components/ui/separator'
import { Skeleton } from '@/components/ui/skeleton'
import { useItems, 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,13 +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 hoy" section 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()
// 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 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)
@@ -53,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 (
@@ -68,27 +102,50 @@ export function ItemList({ listId }: ItemListProps) {
Usa el campo de arriba para añadir tu primer artículo.
</p>
</div>
<DictateItemsButton listId={listId} />
</CardContent>
</Card>
)
}
return (
<div className="flex flex-col gap-2">
<div className="flex flex-col gap-4">
{pending.length > 0 && (
<ul className="flex flex-col gap-2">
{pending.map((item) => (
<ItemRow key={item.id} item={item} updateItem={updateItem} />
))}
</ul>
<Card className="py-0">
<ul className="divide-y">
{pending.map((item) => (
<ItemRow
key={item.id}
item={item}
updateItem={updateItem}
isSaving={savingIds.includes(item.id)}
onEdit={() => setEditingId(item.id)}
onMove={() => openMoveDialog(item)}
onDelete={() => handleDelete(item)}
/>
))}
</ul>
</Card>
)}
{boughtToday.length > 0 && (
<>
{pending.length > 0 && <Separator className="mt-2" />}
<BoughtItemList items={boughtToday} updateItem={updateItem} />
</>
<BoughtItemList
items={boughtToday}
updateItem={updateItem}
savingIds={savingIds}
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>
)
}

View File

@@ -1,53 +1,234 @@
import type { ListItem } from '@superlist/shared'
import { CheckIcon } from 'lucide-react'
import { CheckIcon, FolderInputIcon, PencilIcon, Trash2Icon } from 'lucide-react'
import { type PointerEvent, useRef, useState } from 'react'
import { Card, CardContent } from '@/components/ui/card'
import type { useUpdateItem } from '@/hooks/use-items'
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'
type ItemRowProps = {
export type ItemRowProps = {
item: ListItem
updateItem: ReturnType<typeof useUpdateItem>
/** This item's bought state is being saved; only this row waits for it. */
isSaving: boolean
/** 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
}
/** A single item row: tapping it toggles its bought state. */
export function ItemRow({ item, updateItem }: ItemRowProps) {
/** Horizontal drag (px) that turns a touch on the row into "edit the item". */
const EDIT_THRESHOLD = 48
/** A longer drag (px) that turns it into "move the item to another list". */
const MOVE_THRESHOLD = 120
/**
* 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 {
const limit = dx < 0 ? MOVE_THRESHOLD : DELETE_THRESHOLD
const distance = Math.abs(dx)
const resisted = distance <= limit ? distance : limit + (distance - limit) / 3
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, onEdit, onMove, onDelete }: ItemRowProps) {
const [dragX, setDragX] = useState(0)
const swipeStart = useRef<{ x: number; y: number } | null>(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)
const handlePointerDown = (event: PointerEvent<HTMLButtonElement>) => {
// 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 }
}
const handlePointerMove = (event: PointerEvent<HTMLButtonElement>) => {
const start = swipeStart.current
if (!start) return
const dx = event.clientX - start.x
const dy = event.clientY - start.y
// While the movement is mostly vertical the user is scrolling the list,
// so no gesture is decided yet (and `touch-pan-y` lets the page scroll).
if (!swiped.current && Math.abs(dx) <= Math.abs(dy)) return
setDragX(dragOffset(dx))
swiped.current = swipeAction(dx)
setAction(swiped.current)
}
const handlePointerUp = () => {
const released = swipeStart.current !== null ? swiped.current : null
swipeStart.current = null
setDragX(0)
setAction(null)
if (released === 'edit') onEdit()
if (released === 'move') onMove()
if (released === 'delete') onDelete()
}
const handlePointerCancel = () => {
swipeStart.current = null
swiped.current = null
setDragX(0)
setAction(null)
}
const dragging = swipeStart.current !== null && dragX !== 0
return (
<li>
<Card>
<CardContent className="p-0">
<button
type="button"
aria-pressed={item.completed}
disabled={updateItem.isPending}
onClick={() => updateItem.mutate({ itemId: item.id, completed: !item.completed })}
className="flex w-full cursor-pointer items-center gap-3 p-3 text-left disabled:cursor-default disabled:opacity-60"
>
<span
className={cn(
'flex size-5 shrink-0 items-center justify-center rounded-full border',
item.completed
? 'bg-primary text-primary-foreground border-primary'
: 'border-muted-foreground/40 text-transparent',
)}
aria-hidden
>
<CheckIcon className="size-3" />
</span>
<span
className={cn(
'min-w-0 flex-1 truncate',
item.completed && 'text-muted-foreground line-through',
)}
>
{item.name}
</span>
{item.quantity && (
<span className="text-muted-foreground shrink-0 text-sm">{item.quantity}</span>
<div className="relative overflow-hidden">
{dragX > 0 && (
<div
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',
)}
</button>
</CardContent>
</Card>
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}
disabled={!editable}
onClick={() => {
if (swiped.current) {
swiped.current = null
return
}
updateItem.mutate({ itemId: item.id, completed: !item.completed })
}}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerCancel}
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',
// Follows the finger while dragged, then snaps back on release.
dragging
? 'transition-colors'
: 'transition-[background-color,transform] duration-200 motion-reduce:transition-colors',
)}
>
<span
className={cn(
'flex size-6 shrink-0 items-center justify-center rounded-full border-[1.5px] transition-colors',
item.completed
? 'bg-primary text-primary-foreground border-primary'
: 'border-muted-foreground/45 text-transparent',
)}
aria-hidden
>
<CheckIcon className="size-3.5" strokeWidth={3} />
</span>
<span className="flex min-w-0 flex-1 flex-col">
<span
className={cn(
'truncate text-base',
item.completed && 'text-muted-foreground line-through',
)}
>
{item.name}
</span>
{item.notes && (
<span className="text-muted-foreground truncate text-sm">{item.notes}</span>
)}
</span>
{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>
)
}

View File

@@ -0,0 +1,245 @@
import { zodResolver } from '@hookform/resolvers/zod'
import type { ListItem } from '@superlist/shared'
import { MinusIcon, PlusIcon, Trash2Icon, XIcon } from 'lucide-react'
import { useState } from 'react'
import { useForm, useWatch } from 'react-hook-form'
import { z } from 'zod'
import { Button } from '@/components/ui/button'
import { Field, FieldError, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import {
Sheet,
SheetClose,
SheetContent,
SheetDescription,
SheetTitle,
} from '@/components/ui/sheet'
import { Textarea } from '@/components/ui/textarea'
import type { useUpdateItem } from '@/hooks/use-items'
import {
amountValue,
EDITOR_UNITS,
fromEditableQuantity,
stepAmount,
toEditableQuantity,
} from '@/lib/item-quantity'
import { cn } from '@/lib/utils'
const itemSchema = z
.object({
name: z.string().trim().min(1, 'Escribe un nombre').max(120, 'Máximo 120 caracteres'),
amount: z.string().trim().max(30, 'Máximo 30 caracteres'),
unit: z.string(),
notes: z.string().trim().max(280, 'Máximo 280 caracteres'),
})
.refine((value) => (fromEditableQuantity(value)?.length ?? 0) <= 40, {
path: ['amount'],
message: 'La cantidad es demasiado larga',
})
type ItemValues = z.infer<typeof itemSchema>
type ItemSheetProps = {
/** The item being edited; `null` keeps the sheet closed. */
item: ListItem | null
updateItem: ReturnType<typeof useUpdateItem>
onClose: () => void
/** Deletes the item (undoable for a few seconds) and closes the sheet. */
onDelete: (item: ListItem) => void
}
/**
* Bottom sheet to edit an item: name, quantity (− / + and a unit), note, delete and
* save. Opened by swiping the row to the left or with "Editar" in its right-click menu.
*/
export function ItemSheet({ item, updateItem, onClose, onDelete }: ItemSheetProps) {
// While the sheet slides out `item` is already `null`: keep showing the last one.
const [shown, setShown] = useState(item)
if (item && item !== shown) setShown(item)
return (
<Sheet open={item !== null} onOpenChange={(open) => !open && onClose()}>
<SheetContent
side="bottom"
showCloseButton={false}
className="max-h-[90dvh] gap-0 overflow-y-auto rounded-t-3xl px-5 pt-3 pb-[calc(1.25rem+env(safe-area-inset-bottom))] sm:mx-auto sm:max-w-lg"
>
<div className="bg-muted-foreground/30 mx-auto mb-3 h-1 w-10 rounded-full" aria-hidden />
{/* Mounted per item so the form always starts from its current values. */}
{shown && (
<ItemForm
key={shown.id}
item={shown}
updateItem={updateItem}
onClose={onClose}
onDelete={onDelete}
/>
)}
</SheetContent>
</Sheet>
)
}
function ItemForm({ item, updateItem, onClose, onDelete }: ItemSheetProps & { item: ListItem }) {
const form = useForm<ItemValues>({
resolver: zodResolver(itemSchema),
defaultValues: {
name: item.name,
...toEditableQuantity(item.quantity),
notes: item.notes ?? '',
},
})
const [amount, unit] = useWatch({ control: form.control, name: ['amount', 'unit'] })
const numeric = amountValue(amount) !== null
// A unit the selector does not offer ("paquete") stays available, so it is not lost.
const units = EDITOR_UNITS.some((option) => option.value === unit)
? EDITOR_UNITS
: [...EDITOR_UNITS, { value: unit, label: unit }]
const step = (direction: 1 | -1) =>
form.setValue('amount', stepAmount(amount, unit, direction), { shouldDirty: true })
const onSubmit = form.handleSubmit((values) => {
updateItem.mutate(
{
itemId: item.id,
name: values.name,
quantity: fromEditableQuantity(values),
notes: values.notes || null,
},
// The list already shows the new values optimistically; on error the hook reports
// the problem and the sheet stays open with what was typed.
{ onSuccess: onClose },
)
})
const errors = form.formState.errors
return (
<form onSubmit={onSubmit} className="flex flex-col gap-5">
<div className="flex items-center justify-between gap-3">
<SheetTitle className="text-lg font-semibold">Editar producto</SheetTitle>
<SheetClose asChild>
<Button
type="button"
variant="secondary"
size="icon"
className="size-11 rounded-full"
aria-label="Cerrar"
>
<XIcon className="size-5" />
</Button>
</SheetClose>
</div>
<SheetDescription className="sr-only">
Cambia el nombre, la cantidad o la nota de «{item.name}».
</SheetDescription>
<Field data-invalid={!!errors.name}>
<FieldLabel htmlFor="item-name">Producto</FieldLabel>
<Input
id="item-name"
autoComplete="off"
aria-invalid={!!errors.name}
className="bg-card h-12 rounded-xl px-4"
{...form.register('name')}
/>
<FieldError errors={[errors.name]} />
</Field>
<Field data-invalid={!!errors.amount}>
<FieldLabel htmlFor="item-amount">Cantidad</FieldLabel>
<div className="flex flex-wrap items-center gap-3">
<div className="bg-card flex h-12 items-center overflow-hidden rounded-xl border">
<Button
type="button"
variant="ghost"
className="h-full w-12 rounded-none"
aria-label="Restar"
disabled={!numeric || amount === stepAmount(amount, unit, -1)}
onClick={() => step(-1)}
>
<MinusIcon className="size-5" />
</Button>
<input
id="item-amount"
inputMode="decimal"
autoComplete="off"
aria-invalid={!!errors.amount}
className="h-full w-16 border-x bg-transparent text-center text-base outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
{...form.register('amount')}
/>
<Button
type="button"
variant="ghost"
className="h-full w-12 rounded-none"
aria-label="Sumar"
onClick={() => step(1)}
>
<PlusIcon className="size-5" />
</Button>
</div>
<fieldset className="flex flex-wrap gap-2">
<legend className="sr-only">Unidad</legend>
{units.map((option) => {
const selected = option.value === unit
return (
<button
key={option.value || 'count'}
type="button"
aria-pressed={selected}
onClick={() => form.setValue('unit', option.value, { shouldDirty: true })}
className={cn(
'focus-visible:ring-ring/50 h-11 min-w-11 rounded-xl border px-3 text-base transition-colors outline-none focus-visible:ring-3',
selected
? 'bg-accent text-accent-foreground border-transparent font-semibold'
: 'bg-card hover:bg-muted',
)}
>
{option.label}
</button>
)
})}
</fieldset>
</div>
<FieldError errors={[errors.amount]} />
</Field>
<Field data-invalid={!!errors.notes}>
<FieldLabel htmlFor="item-notes">Nota</FieldLabel>
<Textarea
id="item-notes"
rows={2}
placeholder="Marca, tipo, corte…"
aria-invalid={!!errors.notes}
className="bg-card min-h-16 rounded-xl px-4 py-3"
{...form.register('notes')}
/>
<FieldError errors={[errors.notes]} />
</Field>
<div className="flex gap-3">
<Button
type="button"
variant="outline"
className="text-destructive hover:text-destructive size-12 rounded-xl"
aria-label={`Eliminar «${item.name}»`}
onClick={() => onDelete(item)}
>
<Trash2Icon className="size-5" />
</Button>
<Button
type="submit"
className="h-12 flex-1 rounded-xl text-base font-semibold"
disabled={updateItem.isPending}
>
Guardar
</Button>
</div>
</form>
)
}

View File

@@ -0,0 +1,21 @@
import { CreateItemForm } from '@/components/items/create-item-form'
import { ListProgress } from '@/components/items/list-progress'
type ListComposerProps = {
listId: string
}
/**
* Progress plus the "add an item" input, pinned right below the app header while
* the items scroll. `top-16` matches the header's `h-16`, and the negative margins
* undo the layout's padding so the solid background also covers the gap above.
*/
export function ListComposer({ listId }: ListComposerProps) {
return (
<div className="bg-background sticky top-16 z-[5] -mx-4 -mt-4 flex flex-col gap-4 px-4 pt-4 pb-3 md:-mx-6 md:-mt-6 md:gap-6 md:px-6 md:pt-6">
<ListProgress listId={listId} />
<CreateItemForm listId={listId} autoFocus />
</div>
)
}

View File

@@ -0,0 +1,34 @@
import { Progress } from '@/components/ui/progress'
import { useItems } from '@/hooks/use-items'
import { useToday } from '@/hooks/use-today'
import { splitItems } from '@/lib/items'
type ListProgressProps = {
listId: string
}
/**
* 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)
const today = useToday()
if (!items) return null
const { pending, boughtToday } = splitItems(items, today)
const total = pending.length + boughtToday.length
if (total === 0) return null
return (
<Progress
value={(boughtToday.length / total) * 100}
aria-label={`Comprados ${boughtToday.length} de ${total}`}
className="h-1.5"
/>
)
}

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

View File

@@ -1,41 +1,83 @@
import { useRouterState } from '@tanstack/react-router'
import { SearchIcon } from 'lucide-react'
import type { ShoppingListSummary } from '@superlist/shared'
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'
import { Button } from '@/components/ui/button'
import { Separator } from '@/components/ui/separator'
import { SidebarTrigger } from '@/components/ui/sidebar'
import { listQueryOptions } from '@/hooks/use-list'
import { listsQueryOptions, pickPrimaryList } from '@/hooks/use-lists'
function titleFor(pathname: string) {
if (pathname === '/') return 'Panel'
if (pathname.startsWith('/lists')) return 'Listas'
if (pathname.startsWith('/settings')) return 'Ajustes'
return 'Superlist'
}
type HeaderList = Pick<ShoppingListSummary, 'id' | 'name' | 'role' | 'isPrimary'>
export function AppHeader() {
const pathname = useRouterState({ select: (state) => state.location.pathname })
const title = titleFor(pathname)
const listMatch = useMatch({ from: '/_authenticated/lists/$listId/', shouldThrow: false })
const homeMatch = useMatch({ from: '/_authenticated/', shouldThrow: false })
const listId = listMatch?.params.listId
// The list pages carry their name, badges and actions here instead of in the body;
// both route loaders have already cached the data, so these don't add requests.
const { data: openList } = useQuery({
...listQueryOptions(listId ?? ''),
enabled: Boolean(listId),
})
const { data: lists } = useQuery({ ...listsQueryOptions(), enabled: Boolean(homeMatch) })
const list: HeaderList | undefined = listId
? openList
: homeMatch && lists
? pickPrimaryList(lists)
: undefined
return (
<header className="bg-background/95 supports-[backdrop-filter]:bg-background/60 sticky top-0 z-10 flex h-16 shrink-0 items-center gap-2 border-b backdrop-blur">
<div className="flex w-full items-center gap-2 px-4">
<div className="flex w-full min-w-0 items-center gap-2 px-4">
<SidebarTrigger className="-ml-1 hidden md:inline-flex" />
<Separator orientation="vertical" className="mr-2 h-4" />
<h1 className="truncate text-sm font-medium">{title}</h1>
<div className="ml-auto flex items-center gap-1">
<button
type="button"
className="text-muted-foreground hover:bg-accent hover:text-accent-foreground mr-1 hidden items-center gap-2 rounded-md border px-3 py-1.5 text-xs md:flex"
>
<SearchIcon className="size-3.5" />
Buscar
<kbd className="bg-muted text-muted-foreground rounded px-1.5 py-0.5 font-mono text-[10px]">
⌘K
</kbd>
</button>
<Separator orientation="vertical" className="mr-2 hidden h-4 md:block" />
{list ? (
<ListHeading list={list} showBack={Boolean(listId)} />
) : (
<h1 className="truncate text-sm font-medium">{sectionTitle(pathname)}</h1>
)}
<div className="ml-auto flex shrink-0 items-center gap-1">
{list && (
<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>
</Button>
)}
<ThemeToggle />
</div>
</div>
</header>
)
}
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-11 shrink-0" asChild>
<Link to="/lists" aria-label="Volver a listas">
<ArrowLeftIcon className="size-4" />
</Link>
</Button>
)}
<ListSwitcher list={list} />
<Badge variant="secondary" className="hidden shrink-0 sm:inline-flex">
{list.role === 'owner' ? 'Propietario' : 'Colaborador'}
</Badge>
</div>
)
}

View File

@@ -1,8 +1,7 @@
import { Link, useRouterState } from '@tanstack/react-router'
import type { LucideIcon } from 'lucide-react'
import { HomeIcon, SettingsIcon, ShoppingCartIcon } from 'lucide-react'
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'
import {
Sidebar,
@@ -17,23 +16,6 @@ import {
SidebarRail,
} from '@/components/ui/sidebar'
type NavItem = {
title: string
to: string
icon: LucideIcon
}
const NAV_ITEMS: NavItem[] = [
{ title: 'Principal', to: '/', icon: HomeIcon },
{ title: 'Listas', to: '/lists', icon: ShoppingCartIcon },
{ title: 'Ajustes', to: '/settings', icon: SettingsIcon },
]
function isActive(pathname: string, to: string) {
if (to === '/') return pathname === '/'
return pathname === to || pathname.startsWith(`${to}/`)
}
export function AppSidebar() {
const pathname = useRouterState({ select: (state) => state.location.pathname })
@@ -44,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>
@@ -59,13 +39,13 @@ export function AppSidebar() {
<SidebarContent>
<SidebarGroup>
<SidebarGroupLabel>Plataforma</SidebarGroupLabel>
<SidebarGroupLabel>Navegación</SidebarGroupLabel>
<SidebarMenu>
{NAV_ITEMS.map((item) => (
<SidebarMenuItem key={item.to}>
<SidebarMenuButton
asChild
isActive={isActive(pathname, item.to)}
isActive={isNavItemActive(pathname, item.to)}
tooltip={item.title}
>
<Link

View File

@@ -1,73 +1,37 @@
import { Link, useRouterState } from '@tanstack/react-router'
import { HomeIcon, SettingsIcon, ShoppingCartIcon, UserIcon } from 'lucide-react'
import { focusNewItemInput } from '@/components/items/create-item-form'
import { isNavItemActive, NAV_ITEMS } from '@/components/layout/nav-items'
import { cn } from '@/lib/utils'
function isActive(pathname: string, to: string) {
if (to === '/') return pathname === '/'
return pathname === to || pathname.startsWith(`${to}/`)
}
export function BottomNav() {
const pathname = useRouterState({ select: (state) => state.location.pathname })
return (
<footer className="fixed inset-x-0 bottom-0 z-30 border-t bg-background/95 supports-[backdrop-filter]:bg-background/60 backdrop-blur md:hidden pb-[env(safe-area-inset-bottom)]">
<nav className="mx-auto flex h-16 max-w-lg items-center justify-around px-2">
<Link
to="/"
onClick={() => focusNewItemInput(pathname)}
className={cn(
'flex flex-col items-center gap-1 rounded-md px-2 py-1.5 text-xs transition-colors',
isActive(pathname, '/')
? 'text-foreground'
: 'text-muted-foreground hover:text-foreground',
)}
>
<HomeIcon className="size-5" />
<span>Inicio</span>
</Link>
<nav className="mx-auto flex h-18 max-w-lg items-center justify-around px-2">
{NAV_ITEMS.map((item) => {
const active = isNavItemActive(pathname, item.to)
<Link
to="/lists"
className={cn(
'flex flex-col items-center gap-1 rounded-md px-2 py-1.5 text-xs transition-colors',
isActive(pathname, '/lists')
? 'text-foreground'
: 'text-muted-foreground hover:text-foreground',
)}
>
<ShoppingCartIcon className="size-5" />
<span>Listas</span>
</Link>
<Link
to="/settings"
className={cn(
'flex flex-col items-center gap-1 rounded-md px-2 py-1.5 text-xs transition-colors',
isActive(pathname, '/settings')
? 'text-foreground'
: 'text-muted-foreground hover:text-foreground',
)}
>
<SettingsIcon className="size-5" />
<span>Ajustes</span>
</Link>
<Link
to="/settings"
className={cn(
'flex flex-col items-center gap-1 rounded-md px-2 py-1.5 text-xs transition-colors',
isActive(pathname, '/settings')
? 'text-foreground'
: 'text-muted-foreground hover:text-foreground',
)}
aria-label="Cuenta"
>
<UserIcon className="size-5" />
<span>Cuenta</span>
</Link>
return (
<Link
key={item.to}
to={item.to}
onClick={item.to === '/' ? () => focusNewItemInput(pathname) : undefined}
aria-current={active ? 'page' : undefined}
className={cn(
'relative flex flex-col items-center gap-1 rounded-md px-3 py-1.5 text-xs transition-colors',
active ? 'text-primary font-medium' : 'text-muted-foreground hover:text-foreground',
)}
>
<item.icon className="size-5" />
<span>{item.title}</span>
{active && (
<span className="bg-primary absolute -bottom-1 size-1 rounded-full" aria-hidden />
)}
</Link>
)
})}
</nav>
</footer>
)

View File

@@ -0,0 +1,95 @@
import type { ShoppingListSummary } from '@superlist/shared'
import { useQuery } from '@tanstack/react-query'
import { Link } from '@tanstack/react-router'
import { CheckIcon, ChevronDownIcon, ListIcon, StarIcon } from 'lucide-react'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { itemsQueryOptions } from '@/hooks/use-items'
import { useLists } from '@/hooks/use-lists'
import { useToday } from '@/hooks/use-today'
import { splitItems } from '@/lib/items'
type ListSwitcherProps = {
list: Pick<ShoppingListSummary, 'id' | 'name'>
}
/**
* The open list's name with a "▾" that opens the user's lists (the same ones the
* "Listas" tab shows), plus "X pendientes · Y comprados" below it. The primary list
* opens on the home page, the others on their own page.
*/
export function ListSwitcher({ list }: ListSwitcherProps) {
const { data: lists } = useLists()
return (
<div className="flex min-w-0 flex-col">
<DropdownMenu>
<h1 className="flex min-w-0">
<DropdownMenuTrigger className="focus-visible:ring-ring/50 -ml-1 flex min-h-11 min-w-0 items-center gap-1 rounded-lg px-1 text-left text-xl leading-tight font-bold outline-none focus-visible:ring-3">
<span className="truncate">{list.name}</span>
<ChevronDownIcon className="size-5 shrink-0" aria-hidden />
<span className="sr-only">: cambiar de lista</span>
</DropdownMenuTrigger>
</h1>
<DropdownMenuContent align="start" className="w-64">
<DropdownMenuLabel>Mis listas</DropdownMenuLabel>
{lists?.map((option) => (
<DropdownMenuItem key={option.id} asChild className="min-h-11">
{option.isPrimary ? (
<Link to="/">
<ListOption list={option} current={option.id === list.id} />
</Link>
) : (
<Link to="/lists/$listId" params={{ listId: option.id }}>
<ListOption list={option} current={option.id === list.id} />
</Link>
)}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<DropdownMenuItem asChild className="min-h-11">
<Link to="/lists">
<ListIcon />
Ver todas las listas
</Link>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<ListCounts listId={list.id} />
</div>
)
}
function ListOption({ list, current }: { list: ShoppingListSummary; current: boolean }) {
return (
<>
<span className="min-w-0 flex-1 truncate">{list.name}</span>
{list.isPrimary && <StarIcon aria-label="Principal" className="text-muted-foreground" />}
{current && <CheckIcon aria-label="Lista actual" className="text-primary" />}
</>
)
}
/** "6 pendientes · 2 comprados", from the items query the page already loads. */
function ListCounts({ listId }: { listId: string }) {
const { data: items } = useQuery(itemsQueryOptions(listId))
const today = useToday()
if (!items) return null
const { pending, boughtToday } = splitItems(items, today)
return (
<p className="text-muted-foreground truncate text-sm leading-tight">
{pending.length} {pending.length === 1 ? 'pendiente' : 'pendientes'} · {boughtToday.length}{' '}
{boughtToday.length === 1 ? 'comprado' : 'comprados'}
</p>
)
}

View File

@@ -0,0 +1,25 @@
import type { LucideIcon } from 'lucide-react'
import { HomeIcon, SettingsIcon, ShoppingCartIcon } from 'lucide-react'
type NavItem = {
title: string
to: '/' | '/lists' | '/settings'
icon: LucideIcon
}
/** The app's sections, shared by the sidebar (desktop), the bottom nav (mobile) and the header. */
export const NAV_ITEMS: NavItem[] = [
{ title: 'Inicio', to: '/', icon: HomeIcon },
{ title: 'Listas', to: '/lists', icon: ShoppingCartIcon },
{ title: 'Ajustes', to: '/settings', icon: SettingsIcon },
]
export function isNavItemActive(pathname: string, to: NavItem['to']) {
if (to === '/') return pathname === '/'
return pathname === to || pathname.startsWith(`${to}/`)
}
/** Title of the section the pathname belongs to, for the header. */
export function sectionTitle(pathname: string) {
return NAV_ITEMS.find((item) => isNavItemActive(pathname, item.to))?.title ?? 'Superlist'
}

View File

@@ -1,5 +1,5 @@
import { useNavigate } from '@tanstack/react-router'
import { ChevronsUpDownIcon, LogOutIcon, UserIcon } from 'lucide-react'
import { ChevronsUpDownIcon, LogOutIcon, SettingsIcon } from 'lucide-react'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import {
@@ -78,8 +78,8 @@ export function NavUser() {
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem onClick={() => void navigate({ to: '/settings' })}>
<UserIcon />
Cuenta
<SettingsIcon />
Ajustes
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />

View File

@@ -16,6 +16,9 @@ type ThemeContextValue = {
const STORAGE_KEY = 'superlist-theme'
const DARK_QUERY = '(prefers-color-scheme: dark)'
/** Browser chrome color (the iOS status bar) per theme. Keep in sync with `index.html`. */
const THEME_COLORS: Record<ResolvedTheme, string> = { light: '#f9f8f5', dark: '#0f1411' }
/**
* This theme handling is hand-rolled on purpose. Libraries such as `next-themes`
* avoid the pre-paint flash by rendering a `<script>` from React, but React 19
@@ -44,6 +47,15 @@ function systemTheme(): ResolvedTheme {
return window.matchMedia(DARK_QUERY).matches ? 'dark' : 'light'
}
function resolveTheme(theme: Theme): ResolvedTheme {
return theme === 'system' ? systemTheme() : theme
}
/** iOS home-screen app (`navigator.standalone` only exists in iOS Safari). */
function isIosStandalone() {
return 'standalone' in navigator && navigator.standalone === true
}
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setThemeState] = useState<Theme>(readStoredTheme)
const [systemDark, setSystemDark] = useState(() => systemTheme() === 'dark')
@@ -60,16 +72,27 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
const root = document.documentElement
root.classList.toggle('dark', resolvedTheme === 'dark')
root.style.colorScheme = resolvedTheme
document
.querySelector('meta[name="theme-color"]')
?.setAttribute('content', THEME_COLORS[resolvedTheme])
}, [resolvedTheme])
const setTheme = useCallback((next: Theme) => {
setThemeState(next)
try {
window.localStorage.setItem(STORAGE_KEY, next)
} catch {
// Ignore storage failures: the theme still applies for this session.
}
}, [])
const setTheme = useCallback(
(next: Theme) => {
setThemeState(next)
try {
window.localStorage.setItem(STORAGE_KEY, next)
} catch {
// Ignore storage failures: the theme still applies for this session.
}
// An installed iOS app only reads `theme-color` when the page loads, so
// the status bar keeps the old color until a reload. The stored theme is
// applied again before the first paint by the script in `index.html`.
if (isIosStandalone() && resolveTheme(next) !== resolvedTheme) window.location.reload()
},
[resolvedTheme],
)
const value = useMemo(
() => ({ theme, resolvedTheme, setTheme }),

View File

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

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

View File

@@ -0,0 +1,142 @@
import { cn } from 'cn'
import { XIcon } from 'lucide-react'
import { Dialog as DialogPrimitive } from 'radix-ui'
import * as React from 'react'
import { Button } from '@/components/ui/button'
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
'fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0',
className,
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
'fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm 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}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close data-slot="dialog-close" asChild>
<Button variant="ghost" className="absolute top-2 right-2" size="icon-sm">
<XIcon />
<span className="sr-only">Close</span>
</Button>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div data-slot="dialog-header" className={cn('flex flex-col gap-2', className)} {...props} />
)
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<'div'> & {
showCloseButton?: boolean
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
'-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end',
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close asChild>
<Button variant="outline">Close</Button>
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn('font-heading text-base leading-none font-medium', className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn(
'text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground',
className,
)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View File

@@ -0,0 +1,142 @@
import { cva, type VariantProps } from 'class-variance-authority'
import { cn } from 'cn'
import * as React from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
function InputGroup({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="input-group"
role="group"
className={cn(
'group/input-group relative flex h-8 w-full min-w-0 items-center rounded-lg border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5',
className,
)}
{...props}
/>
)
}
const inputGroupAddonVariants = cva(
"flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4",
{
variants: {
align: {
'inline-start': 'order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]',
'inline-end': 'order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]',
'block-start':
'order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2',
'block-end':
'order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2',
},
},
defaultVariants: {
align: 'inline-start',
},
},
)
function InputGroupAddon({
className,
align = 'inline-start',
...props
}: React.ComponentProps<'div'> & VariantProps<typeof inputGroupAddonVariants>) {
return (
<div
role="group"
data-slot="input-group-addon"
data-align={align}
className={cn(inputGroupAddonVariants({ align }), className)}
onClick={(e) => {
if ((e.target as HTMLElement).closest('button')) {
return
}
e.currentTarget.parentElement?.querySelector('input')?.focus()
}}
{...props}
/>
)
}
const inputGroupButtonVariants = cva('flex items-center gap-2 text-sm shadow-none', {
variants: {
size: {
xs: "h-6 gap-1 rounded-[calc(var(--radius)-3px)] px-1.5 [&>svg:not([class*='size-'])]:size-3.5",
sm: '',
'icon-xs': 'size-6 rounded-[calc(var(--radius)-3px)] p-0 has-[>svg]:p-0',
'icon-sm': 'size-8 p-0 has-[>svg]:p-0',
},
},
defaultVariants: {
size: 'xs',
},
})
function InputGroupButton({
className,
type = 'button',
variant = 'ghost',
size = 'xs',
...props
}: Omit<React.ComponentProps<typeof Button>, 'size'> &
VariantProps<typeof inputGroupButtonVariants>) {
return (
<Button
type={type}
data-size={size}
variant={variant}
className={cn(inputGroupButtonVariants({ size }), className)}
{...props}
/>
)
}
function InputGroupText({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
className={cn(
"flex items-center gap-2 text-sm text-muted-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
)
}
function InputGroupInput({ className, ...props }: React.ComponentProps<'input'>) {
return (
<Input
data-slot="input-group-control"
className={cn(
'flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent',
className,
)}
{...props}
/>
)
}
function InputGroupTextarea({ className, ...props }: React.ComponentProps<'textarea'>) {
return (
<Textarea
data-slot="input-group-control"
className={cn(
'flex-1 resize-none rounded-none border-0 bg-transparent py-2 shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent',
className,
)}
{...props}
/>
)
}
export {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupInput,
InputGroupText,
InputGroupTextarea,
}

View File

@@ -0,0 +1,28 @@
import { cn } from 'cn'
import { Progress as ProgressPrimitive } from 'radix-ui'
import * as React from 'react'
function Progress({
className,
value,
...props
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
return (
<ProgressPrimitive.Root
data-slot="progress"
className={cn(
'relative flex h-1 w-full items-center overflow-x-hidden rounded-full bg-muted',
className,
)}
{...props}
>
<ProgressPrimitive.Indicator
data-slot="progress-indicator"
className="size-full flex-1 bg-primary transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
)
}
export { Progress }

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

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

View File

@@ -1,7 +1,22 @@
import type { ListItem } from '@superlist/shared'
import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
queryOptions,
useMutation,
useMutationState,
useQuery,
useQueryClient,
} from '@tanstack/react-query'
import { useSyncExternalStore } from 'react'
import { apiFetch } from '@/lib/api-client'
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({
@@ -13,8 +28,17 @@ export function useItems(listId: string) {
return useQuery(itemsQueryOptions(listId))
}
/** Prefix of the temporary ids given to items that are still being created. */
const OPTIMISTIC_ID_PREFIX = 'optimistic-'
/** Whether the item is a placeholder whose `POST` has not been answered yet. */
export function isOptimisticItem(item: ListItem): boolean {
return item.id.startsWith(OPTIMISTIC_ID_PREFIX)
}
export function useCreateItem(listId: string) {
const queryClient = useQueryClient()
const { queryKey } = itemsQueryOptions(listId)
return useMutation({
mutationFn: (input: { name: string; quantity?: string; notes?: string }) =>
@@ -22,41 +46,251 @@ export function useCreateItem(listId: string) {
method: 'POST',
body: JSON.stringify(input),
}),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] }),
// The item shows up right away; the POST response then swaps the placeholder
// for the real row, so no refetch of the whole list is needed (other members
// still get it through the SSE stream).
onMutate: async (input) => {
await queryClient.cancelQueries({ queryKey })
const now = new Date().toISOString()
const optimistic: ListItem = {
id: `${OPTIMISTIC_ID_PREFIX}${crypto.randomUUID()}`,
listId,
name: input.name.trim(),
completed: false,
boughtAt: null,
quantity: input.quantity?.trim() || null,
notes: input.notes?.trim() || null,
order: 0,
createdAt: now,
updatedAt: now,
}
queryClient.setQueryData(queryKey, (items) => items && [...items, optimistic])
return { optimisticId: optimistic.id }
},
onSuccess: (created, _input, context) => {
queryClient.setQueryData(queryKey, (items) =>
items?.map((item) => (item.id === context.optimisticId ? created : item)),
)
},
// Only this placeholder is removed, so other in-flight additions survive.
onError: (_error, _input, context) => {
queryClient.setQueryData(queryKey, (items) =>
items?.filter((item) => item.id !== context?.optimisticId),
)
},
})
}
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. */
quantity?: string | null
/** New notes (`null` clears them); omitted to leave them untouched. */
notes?: string | null
}
const updateItemMutationKey = (listId: string) => ['lists', listId, 'items', 'update']
export function useUpdateItem(listId: string) {
const queryClient = useQueryClient()
const queryKey = ['lists', listId, 'items']
const { queryKey } = itemsQueryOptions(listId)
const mutationKey = updateItemMutationKey(listId)
return useMutation({
mutationFn: (input: { itemId: string; completed: boolean }) =>
apiFetch<ListItem>(`/lists/${listId}/items/${input.itemId}`, {
mutationKey,
mutationFn: (input: UpdateItemInput) => {
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
return apiFetch<ListItem>(`/lists/${listId}/items/${input.itemId}`, {
method: 'PATCH',
body: JSON.stringify({ completed: input.completed }),
}),
onMutate: async ({ itemId, completed }) => {
body: JSON.stringify(body),
})
},
onMutate: async ({ itemId, name, completed, quantity, notes }) => {
// Cancel the outgoing refetch so it cannot overwrite our optimistic one.
await queryClient.cancelQueries({ queryKey })
const previous = queryClient.getQueriesData<ListItem[]>({ queryKey })
const previous = queryClient.getQueryData(queryKey)?.find((item) => item.id === itemId)
queryClient.setQueriesData<ListItem[]>({ queryKey }, (items) =>
items?.map((item) =>
item.id === itemId
? { ...item, completed, boughtAt: completed ? new Date().toISOString() : null }
: item,
),
queryClient.setQueryData(queryKey, (items) =>
items?.map((item) => {
if (item.id !== itemId) return item
return {
...item,
...(name !== undefined ? { name: name.trim() } : {}),
...(completed !== undefined
? { completed, boughtAt: completed ? new Date().toISOString() : null }
: {}),
...(quantity !== undefined ? { quantity: quantity?.trim() || null } : {}),
...(notes !== undefined ? { notes: notes?.trim() || null } : {}),
}
}),
)
return { previous }
},
onError: (_error, _variables, context) => {
context?.previous.forEach(([key, items]) => {
queryClient.setQueryData(key, items)
})
// Only this item is rolled back, so other toggles in flight keep their state.
onError: (error, _variables, context) => {
toast.error(
error instanceof ApiError
? (error.problem.detail ?? error.problem.title)
: 'No pudimos guardar el cambio.',
)
const previous = context?.previous
if (!previous) return
queryClient.setQueryData(queryKey, (items) =>
items?.map((item) => (item.id === previous.id ? previous : item)),
)
},
// Several items can be toggled in a row: refetch once the last one settles, so an
// early refetch cannot bring back the server state of a toggle still in flight.
onSettled: () => {
if (queryClient.isMutating({ mutationKey }) === 1) {
return queryClient.invalidateQueries({ queryKey })
}
},
onSettled: () => queryClient.invalidateQueries({ queryKey }),
})
}
/** Ids of the items of a list whose bought state is being saved right now. */
export function usePendingItemUpdates(listId: string): string[] {
return useMutationState({
filters: { mutationKey: updateItemMutationKey(listId), status: 'pending' },
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 })
}
}
}

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

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

View File

@@ -13,6 +13,11 @@ export function useLists() {
return useQuery(listsQueryOptions())
}
/** The list a user lands on: their primary one, falling back to the first. */
export function pickPrimaryList(lists: ShoppingListSummary[]): ShoppingListSummary | undefined {
return lists.find((list) => list.isPrimary) ?? lists[0]
}
export function useCreateList() {
const queryClient = useQueryClient()

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

View File

@@ -0,0 +1,20 @@
import type { VoiceSplitRequest, VoiceSplitResponse } from '@superlist/shared'
import { useMutation } from '@tanstack/react-query'
import { apiFetch } from '@/lib/api-client'
/**
* Asks the API to split a dictated sentence into one string per item, each written the
* way the item parser reads typed text. The API never fails because of the model (it
* falls back to splitting on commas and "y"), so an error here means the request did not
* get through.
*/
export function useVoiceSplit() {
return useMutation({
mutationFn: (input: VoiceSplitRequest) =>
apiFetch<VoiceSplitResponse>('/voice/split', {
method: 'POST',
body: JSON.stringify(input),
}),
})
}

View File

@@ -49,72 +49,74 @@
}
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--radius: 0.625rem;
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
/* Warm paper background, white cards and a grocery green as the accent. */
--background: oklch(0.982 0.004 91);
--foreground: oklch(0.17 0.005 90);
--card: oklch(0.997 0.002 91);
--card-foreground: oklch(0.17 0.005 90);
--popover: oklch(0.997 0.002 91);
--popover-foreground: oklch(0.17 0.005 90);
--primary: oklch(0.52 0.13 147);
--primary-foreground: oklch(0.99 0.01 147);
--secondary: oklch(0.95 0.007 91);
--secondary-foreground: oklch(0.24 0.005 90);
--muted: oklch(0.95 0.007 91);
--muted-foreground: oklch(0.52 0.008 90);
--accent: oklch(0.94 0.025 147);
--accent-foreground: oklch(0.36 0.09 147);
--destructive: oklch(0.577 0.215 27.325);
--border: oklch(0.915 0.007 91);
--input: oklch(0.9 0.008 91);
--ring: oklch(0.52 0.13 147);
--chart-1: oklch(0.52 0.13 147);
--chart-2: oklch(0.65 0.13 150);
--chart-3: oklch(0.75 0.12 85);
--chart-4: oklch(0.6 0.12 45);
--chart-5: oklch(0.45 0.05 200);
--radius: 0.875rem;
--sidebar: oklch(0.97 0.005 91);
--sidebar-foreground: oklch(0.17 0.005 90);
--sidebar-primary: oklch(0.52 0.13 147);
--sidebar-primary-foreground: oklch(0.99 0.01 147);
--sidebar-accent: oklch(0.94 0.025 147);
--sidebar-accent-foreground: oklch(0.36 0.09 147);
--sidebar-border: oklch(0.915 0.007 91);
--sidebar-ring: oklch(0.52 0.13 147);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
/* Deep green-tinted charcoal; the green is lifted so it reads on dark. */
--background: oklch(0.165 0.008 155);
--foreground: oklch(0.95 0.006 95);
--card: oklch(0.21 0.01 155);
--card-foreground: oklch(0.95 0.006 95);
--popover: oklch(0.23 0.01 155);
--popover-foreground: oklch(0.95 0.006 95);
--primary: oklch(0.72 0.16 148);
--primary-foreground: oklch(0.2 0.04 150);
--secondary: oklch(0.26 0.01 155);
--secondary-foreground: oklch(0.95 0.006 95);
--muted: oklch(0.255 0.01 155);
--muted-foreground: oklch(0.7 0.012 120);
--accent: oklch(0.3 0.045 150);
--accent-foreground: oklch(0.88 0.08 148);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
--border: oklch(1 0 0 / 9%);
--input: oklch(1 0 0 / 14%);
--ring: oklch(0.72 0.16 148);
--chart-1: oklch(0.72 0.16 148);
--chart-2: oklch(0.62 0.13 150);
--chart-3: oklch(0.8 0.12 85);
--chart-4: oklch(0.7 0.12 45);
--chart-5: oklch(0.65 0.06 200);
--sidebar: oklch(0.19 0.009 155);
--sidebar-foreground: oklch(0.95 0.006 95);
--sidebar-primary: oklch(0.72 0.16 148);
--sidebar-primary-foreground: oklch(0.2 0.04 150);
--sidebar-accent: oklch(0.3 0.045 150);
--sidebar-accent-foreground: oklch(0.88 0.08 148);
--sidebar-border: oklch(1 0 0 / 9%);
--sidebar-ring: oklch(0.72 0.16 148);
}
@layer base {

View File

@@ -0,0 +1,9 @@
// Replaced at build time by `define` in `vite.config.ts`.
declare const __APP_COMMIT__: string
declare const __APP_BUILT_AT__: string
/** The release this bundle was built from, to tell whether an installed PWA updated. */
export const appVersion = {
commit: __APP_COMMIT__,
builtAt: new Date(__APP_BUILT_AT__),
}

View File

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

View File

@@ -0,0 +1,47 @@
import { describe, expect, it } from 'vitest'
import { fromEditableQuantity, stepAmount, toEditableQuantity } from './item-quantity'
describe('toEditableQuantity', () => {
it('splits a stored quantity into amount and unit', () => {
expect(toEditableQuantity(null)).toEqual({ amount: '1', unit: '' })
expect(toEditableQuantity('2')).toEqual({ amount: '2', unit: '' })
expect(toEditableQuantity('1,5 l')).toEqual({ amount: '1,5', unit: 'l' })
expect(toEditableQuantity('½ kg')).toEqual({ amount: '½', unit: 'kg' })
expect(toEditableQuantity('2 paquetes')).toEqual({ amount: '2', unit: 'paquete' })
})
it('keeps free text as the amount', () => {
expect(toEditableQuantity('un par')).toEqual({ amount: 'un par', unit: '' })
})
})
describe('stepAmount', () => {
it('steps by one for counts and by bigger steps for measures', () => {
expect(stepAmount('2', '', 1)).toBe('3')
expect(stepAmount('2', '', -1)).toBe('1')
expect(stepAmount('1', '', -1)).toBe('1')
expect(stepAmount('400', 'g', 1)).toBe('500')
expect(stepAmount('½', 'kg', 1)).toBe('1')
expect(stepAmount('1', 'l', -1)).toBe('½')
})
it('starts from one step when the amount is not a number', () => {
expect(stepAmount('un par', '', 1)).toBe('1')
})
})
describe('fromEditableQuantity', () => {
it('stores the formatted quantity, and nothing for a plain one', () => {
expect(fromEditableQuantity({ amount: '1', unit: '' })).toBeNull()
expect(fromEditableQuantity({ amount: '', unit: 'kg' })).toBeNull()
expect(fromEditableQuantity({ amount: '2', unit: '' })).toBe('2')
expect(fromEditableQuantity({ amount: '1', unit: 'kg' })).toBe('1 kg')
expect(fromEditableQuantity({ amount: '0.5', unit: 'kg' })).toBe('½ kg')
expect(fromEditableQuantity({ amount: '2', unit: 'paquete' })).toBe('2 paquetes')
})
it('keeps free text as typed', () => {
expect(fromEditableQuantity({ amount: 'un par', unit: '' })).toBe('un par')
})
})

View File

@@ -0,0 +1,64 @@
import { formatQuantity, parseNumber, parseQuantity } from './natural-input/quantity'
/** Units offered by the item editor; `''` is a plain count ("un."). */
export const EDITOR_UNITS = [
{ value: '', label: 'un.' },
{ value: 'g', label: 'g' },
{ value: 'kg', label: 'kg' },
{ value: 'ml', label: 'ml' },
{ value: 'l', label: 'L' },
] as const
/**
* A quantity split into what the editor shows: the amount as text and the unit. A unit
* the selector does not offer (`paquete`) is kept, so editing the amount does not lose it.
* Free text that is not a quantity ("un par") goes into `amount` untouched.
*/
export type EditableQuantity = { amount: string; unit: string }
export function toEditableQuantity(quantity: string | null): EditableQuantity {
if (!quantity?.trim()) return { amount: '1', unit: '' }
const parsed = parseQuantity(quantity)
if (!parsed) return { amount: quantity.trim(), unit: '' }
return { amount: formatQuantity({ amount: parsed.amount, unit: null }), unit: parsed.unit ?? '' }
}
/** The numeric value of the amount text, or `null` when it is free text. */
export function amountValue(amount: string): number | null {
return parseNumber(amount.trim())
}
/** How much the − / + buttons change the amount for each unit. */
export function amountStep(unit: string): number {
if (unit === 'g' || unit === 'ml') return 100
if (unit === 'kg' || unit === 'l') return 0.5
return 1
}
/** The amount after pressing − (`direction` −1) or + (1); never below one step. */
export function stepAmount(amount: string, unit: string, direction: 1 | -1): string {
const value = amountValue(amount) ?? 0
const step = amountStep(unit)
const next = Math.max(step, Math.round((value + direction * step) / step) * step)
return formatQuantity({ amount: next, unit: null })
}
/**
* The quantity to store for what the editor shows: `null` for a plain "1" (the same as no
* quantity), the formatted quantity when the amount is a number ("2 paquetes", "½ kg") and
* the text as typed otherwise.
*/
export function fromEditableQuantity({ amount, unit }: EditableQuantity): string | null {
const text = amount.trim()
if (!text) return null
const value = amountValue(text)
if (value === null) return unit ? `${text} ${unit}` : text
if (value === 1 && !unit) return null
return formatQuantity({ amount: value, unit: unit || null })
}

View File

@@ -1,7 +1,7 @@
import type { ListItem } from '@superlist/shared'
import { describe, expect, it } from 'vitest'
import { splitItems } from './items'
import { quantityLabel, splitItems } from './items'
function item(overrides: Partial<ListItem>): ListItem {
return {
@@ -85,3 +85,39 @@ describe('splitItems', () => {
expect(boughtToday).toEqual([])
})
})
describe('quantityLabel', () => {
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('½ 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('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('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()
})
})

View File

@@ -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`). */
@@ -38,3 +39,33 @@ 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 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()
const parsed = parseQuantity(trimmed)
if (parsed) {
if (parsed.unit) {
const label = formatQuantity(parsed)
return parsed.unit === 'l' ? label.replace(/ l$/, ' L') : label
}
if (parsed.amount <= 1) return null
const amount = formatQuantity(parsed)
return parsed.amount >= BARE_WEIGHT_FROM ? amount : `×${amount}`
}
return /^(\d|[½¼¾])/.test(trimmed) ? trimmed : null
}

View File

@@ -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':

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

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

View File

@@ -0,0 +1,154 @@
import { normalizeWord } from './text'
/**
* Grocery words that are usually typed without their accent. The parser restores it
* (`jamon` → `jamón`), keyed by the word with accents stripped. Words that are spelled
* the same with or without an accent elsewhere (`papa`/`papá`) are deliberately left out.
*/
const ACCENTED_WORDS = [
// Almacén
'azúcar',
'café',
'té',
'puré',
'sémola',
'fécula',
'orégano',
'pimentón',
'cúrcuma',
'ají',
'maní',
'almíbar',
'dátiles',
'garrapiñada',
'ñoquis',
'ñoqui',
'budín',
'budines',
'turrón',
'bombón',
'bombones',
'sándwich',
'sándwiches',
'tónica',
// Frutas y verduras
'limón',
'melón',
'sandía',
'plátano',
'plátanos',
'ananá',
'maracuyá',
'arándano',
'arándanos',
'brócoli',
'rúcula',
'morrón',
'champiñón',
'espárrago',
'espárragos',
'rábano',
'rábanos',
'maíz',
// Carnes y pescados
'jamón',
'salchichón',
'salmón',
'atún',
'camarón',
'vacío',
'entraña',
'hígado',
'riñón',
// Limpieza y perfumería
'jabón',
'jabones',
'champú',
'algodón',
'fósforos',
'pañales',
'pañuelos',
'higiénico',
// Adjetivos frecuentes
'líquido',
'líquida',
'lácteo',
'árabe',
'francés',
'dietético',
'dietética',
'orgánico',
'orgánica',
'clásico',
'clásica',
'ácido',
'ácida',
]
export const ACCENTS: Record<string, string> = Object.fromEntries(
ACCENTED_WORDS.map((word) => [normalizeWord(word), word]),
)
/** Spanish number words, keyed without accents. */
export const NUMBER_WORDS: Record<string, number> = {
un: 1,
uno: 1,
una: 1,
dos: 2,
tres: 3,
cuatro: 4,
cinco: 5,
seis: 6,
siete: 7,
ocho: 8,
nueve: 9,
diez: 10,
once: 11,
doce: 12,
quince: 15,
veinte: 20,
}
/** Packaging units: kept as a word in the quantity and pluralized (`2 paquetes`). */
export const CONTAINER_UNITS = new Set([
'paquete',
'caja',
'lata',
'botella',
'bolsa',
'sobre',
'frasco',
'atado',
'maple',
'pack',
])
/** Unit spellings → canonical unit. `''` means "a unit that adds nothing" (`unidades`). */
export const UNIT_ALIASES: Record<string, string> = {
g: 'g',
gr: 'g',
grs: 'g',
gramo: 'g',
gramos: 'g',
kg: 'kg',
kgs: 'kg',
k: 'kg',
kilo: 'kg',
kilos: 'kg',
l: 'l',
lt: 'l',
lts: 'l',
litro: 'l',
litros: 'l',
ml: 'ml',
cc: 'ml',
u: '',
unidad: '',
unidades: '',
...Object.fromEntries(
[...CONTAINER_UNITS].flatMap((unit) => [
[unit, unit],
[`${unit}s`, unit],
]),
),
}

View File

@@ -0,0 +1,61 @@
import type { ListItem } from '@superlist/shared'
import { describe, expect, it } from 'vitest'
import { findDuplicate, mergeBatch, mergeInto } from './merge'
import { parseItemInput } from './parse-item'
function item(overrides: Partial<ListItem>): ListItem {
return {
id: 'item-1',
listId: 'list-1',
name: 'Jamón',
completed: false,
boughtAt: null,
quantity: null,
notes: null,
order: 0,
createdAt: '2026-10-15T10:00:00.000Z',
updatedAt: '2026-10-15T10:00:00.000Z',
...overrides,
}
}
describe('findDuplicate', () => {
it('matches pending items ignoring case, accents and a final "s"', () => {
const jamon = item({})
const pascualinas = item({ id: 'item-2', name: 'Pascualinas' })
expect(findDuplicate([jamon, pascualinas], 'jamon')).toBe(jamon)
expect(findDuplicate([jamon, pascualinas], 'Pascualina')).toBe(pascualinas)
expect(findDuplicate([jamon], 'Queso')).toBeUndefined()
})
it('ignores items already bought', () => {
expect(findDuplicate([item({ completed: true })], 'Jamón')).toBeUndefined()
})
})
describe('mergeInto', () => {
it('sums quantities and appends new notes', () => {
expect(
mergeInto({ quantity: '400 g', notes: 'Feteado' }, { quantity: '200 g', notes: 'Cocido' }),
).toEqual({ quantity: '600 g', notes: 'Feteado · Cocido' })
})
it('leaves out what does not change', () => {
expect(
mergeInto({ quantity: '400 g', notes: 'Feteado' }, { quantity: null, notes: 'feteado' }),
).toEqual({})
})
})
describe('mergeBatch', () => {
it('folds repeated items of one input', () => {
const merged = mergeBatch(parseItemInput('pan, leche, 2 panes'))
expect(merged.map(({ name, quantity }) => ({ name, quantity }))).toEqual([
{ name: 'Pan', quantity: '3' },
{ name: 'Leche', quantity: null },
])
})
})

View File

@@ -0,0 +1,73 @@
import type { ListItem } from '@superlist/shared'
import type { ParsedItem } from './parse-item'
import { addQuantities } from './quantity'
import { normalizeWord } from './text'
/** A name without case, accents or extra spaces. */
function itemKey(name: string): string {
return normalizeWord(name).replace(/\s+/g, ' ').trim()
}
/** Whether two names are the same item, singular or plural ("pan"/"panes", "leche"/"leches"). */
function sameItem(a: string, b: string): boolean {
const [short, long] = [itemKey(a), itemKey(b)].sort((x, y) => x.length - y.length)
return long === short || long === `${short}s` || long === `${short}es`
}
/** The pending item that `name` repeats ("jamon" matches "Jamón", "pascualina" "Pascualinas"). */
export function findDuplicate(items: ListItem[], name: string): ListItem | undefined {
return items.find((item) => !item.completed && sameItem(item.name, name))
}
/** Appends a note unless it is already there. */
function joinNotes(a: string | null, b: string | null): string | null {
if (!b) return a
if (!a) return b
if (normalizeWord(a).includes(normalizeWord(b))) return a
return `${a} · ${b}`.slice(0, 280)
}
/**
* The `PATCH` body that adds `incoming` to an item already on the list: quantities are
* summed and notes appended. Only changed fields are included, so it may be empty.
*/
export function mergeInto(
existing: Pick<ListItem, 'quantity' | 'notes'>,
incoming: Pick<ParsedItem, 'quantity' | 'notes'>,
): { quantity?: string | null; notes?: string | null } {
const patch: { quantity?: string | null; notes?: string | null } = {}
const quantity = addQuantities(existing.quantity, incoming.quantity)
if (quantity !== existing.quantity) patch.quantity = quantity
const notes = joinNotes(existing.notes, incoming.notes)
if (notes !== existing.notes) patch.notes = notes
return patch
}
/** Folds repeated items of one input into one ("pan, leche, pan" → Pan · 2, Leche). */
export function mergeBatch(items: ParsedItem[]): ParsedItem[] {
const merged: ParsedItem[] = []
for (const item of items) {
const index = merged.findIndex((previous) => sameItem(previous.name, item.name))
if (index === -1) {
merged.push(item)
continue
}
const previous = merged[index]
merged[index] = {
...previous,
...mergeInto(previous, item),
source: `${previous.source}; ${item.source}`,
}
}
return merged
}

View File

@@ -0,0 +1,110 @@
import { describe, expect, it } from 'vitest'
import { isPlainItem, literalItem, parseItemInput, parseSingleItem } from './parse-item'
function parsed(text: string) {
const { name, quantity, notes } = parseSingleItem(text)
return { name, quantity, notes }
}
describe('parseSingleItem', () => {
it.each([
['400 de jamon', 'Jamón', '400', null],
['2 pascualinas', 'Pascualinas', '2', null],
['Queso crema. Solo si hay marca Tregar', 'Queso crema', null, 'Solo si hay marca Tregar'],
['Pan - el integral', 'Pan', null, 'El integral'],
['Leche (descremada)', 'Leche', null, 'Descremada'],
['medio kilo de pan', 'Pan', '½ kg', null],
['un cuarto de jamon', 'Jamón', '¼ kg', null],
['medio de helado', 'Helado', '½ kg', null],
['una docena de huevos', 'Huevos', '12', null],
['media docena de facturas', 'Facturas', '6', null],
['dos paquetes de fideos', 'Fideos', '2 paquetes', null],
['1 lata de atun', 'Atún', '1 lata', null],
['1,5 kg de papas', 'Papas', '1,5 kg', null],
['1 kilo y medio de papas', 'Papas', '1,5 kg', null],
['1.5 kg de papas', 'Papas', '1,5 kg', null],
['400g de queso', 'Queso', '400 g', null],
['2 litros de leche', 'Leche', '2 l', null],
['6 unidades de yogur', 'Yogur', '6', null],
['leche x2', 'Leche', '2', null],
['pan x 3', 'Pan', '3', null],
['jamon 400 g', 'Jamón', '400 g', null],
['Coca 1,5l', 'Coca', '1,5 l', null],
['400 de jamon. Feteado fino', 'Jamón', '400', 'Feteado fino'],
])('reads "%s"', (text, name, quantity, notes) => {
expect(parsed(text)).toEqual({ name, quantity, notes })
})
it('keeps names that only look like quantities', () => {
expect(parsed('coca-cola')).toEqual({ name: 'Coca-cola', quantity: null, notes: null })
expect(parsed('Sprite 2.25')).toEqual({ name: 'Sprite 2.25', quantity: null, notes: null })
expect(parsed('Pilas AA 2')).toEqual({ name: 'Pilas AA 2', quantity: null, notes: null })
expect(parsed('medio pollo')).toEqual({ name: 'Medio pollo', quantity: null, notes: null })
})
it('takes the whole text as the name when nothing is left after the quantity', () => {
expect(parsed('400 g')).toEqual({ name: '400 g', quantity: null, notes: null })
expect(parsed('2')).toEqual({ name: '2', quantity: null, notes: null })
})
it('restores accents without touching brand names', () => {
expect(parsed('Jamon cocido').name).toBe('Jamón cocido')
expect(parsed('cafe LA VIRGINIA').name).toBe('Café LA VIRGINIA')
expect(parsed('pan frances').name).toBe('Pan francés')
})
it('ignores a trailing full stop', () => {
expect(parsed('Manteca.')).toEqual({ name: 'Manteca', quantity: null, notes: null })
})
})
describe('parseItemInput', () => {
const names = (text: string) => parseItemInput(text).map((item) => item.name)
it('splits on commas, a final "y", semicolons and line breaks', () => {
expect(names('leche, pan y 2 pascualinas')).toEqual(['Leche', 'Pan', 'Pascualinas'])
expect(names('leche; pan')).toEqual(['Leche', 'Pan'])
expect(names('- leche\n- pan\n\n1. queso')).toEqual(['Leche', 'Pan', 'Queso'])
})
it('keeps commas of a note and decimal commas', () => {
expect(parseItemInput('Queso. Si no hay, el otro')).toEqual([
{
name: 'Queso',
quantity: null,
notes: 'Si no hay, el otro',
source: 'Queso. Si no hay, el otro',
},
])
expect(names('1,5 kg de papas, cebolla')).toEqual(['Papas', 'Cebolla'])
})
it('does not split "y medio" off a quantity', () => {
expect(names('pan y medio kilo de queso')).toEqual(['Pan', 'Queso'])
expect(names('1 kilo y medio de papas, cebolla')).toEqual(['Papas', 'Cebolla'])
expect(names('1 kilo y medio')).toEqual(['1 kilo y medio'])
})
it('drops empty segments', () => {
expect(parseItemInput(' ; ,\n')).toEqual([])
})
})
describe('literalItem / isPlainItem', () => {
it('builds an untouched item', () => {
expect(literalItem(' 7 up ')).toEqual({
name: '7 up',
quantity: null,
notes: null,
source: '7 up',
})
})
it('tells when parsing adds nothing to the text', () => {
expect(isPlainItem(parseItemInput('leche'), 'leche')).toBe(true)
expect(isPlainItem(parseItemInput('jamon'), 'jamon')).toBe(false)
expect(isPlainItem(parseItemInput('2 panes'), '2 panes')).toBe(false)
})
})

View File

@@ -0,0 +1,136 @@
import { ACCENTS } from './lexicon'
import { formatQuantity, readLeadingQuantity, readTrailingQuantity, splitTokens } from './quantity'
import { capitalize, normalizeWord } from './text'
/** An item as read from free text, ready to be sent to `POST /lists/:listId/items`. */
export type ParsedItem = {
name: string
quantity: string | null
notes: string | null
/** The text this item was read from, given back to the input if adding it fails. */
source: string
}
/** What separates an item from its note: "Queso crema. Solo Tregar", "Pan - el integral". */
const NOTE_SEPARATORS = ['. ', ' - ', ' – ', ' — ']
/** A trailing parenthesis is a note too: "Leche (descremada)". */
const TRAILING_PARENTHESIS = /^(.*\S)\s*\(([^()]*)\)\s*$/
/**
* The "y"/"e" that separates two items. Before "medio"/"media" it is part of a quantity
* when it follows a unit or a number ("1 kilo y medio de papas") and a separator
* otherwise ("pan y medio kilo de queso").
*/
const AND =
/(?<!(?:kilos?|kgs?|litros?|lts?|docenas?|\d))\s+[ye]\s+(?=medi[oa]\b)|\s+[ye]\s+(?!medi[oa]\b)/i
/** List markers that pasted lists bring along: "- ", "• ", "1. ", "2) ", "[ ] ". */
const LIST_MARKER = /^(?:[-*•·]|\d+[.)]|\[[ xX]?\])\s+/
/**
* Reads every item in `text`. Semicolons and line breaks always separate items; commas
* and a final "y"/"e" do too ("leche, pan y 2 pascualinas"), except on a line that has a
* note, whose commas belong to the note ("Queso. Si no hay, el otro").
*/
export function parseItemInput(text: string): ParsedItem[] {
return text
.split(/[;\n]+/)
.map((line) => line.trim().replace(LIST_MARKER, ''))
.flatMap(splitLine)
.map(parseSingleItem)
.filter((item) => item.name)
}
/** The whole text as one item, untouched: the way out when the parser gets it wrong. */
export function literalItem(text: string): ParsedItem {
return { name: text.trim(), quantity: null, notes: null, source: text.trim() }
}
/** Whether the parsed items say nothing more than the text itself (so no preview is needed). */
export function isPlainItem(items: ParsedItem[], text: string): boolean {
if (items.length !== 1) return false
const [item] = items
return !item.quantity && !item.notes && item.name.toLowerCase() === text.trim().toLowerCase()
}
function hasNote(line: string): boolean {
return NOTE_SEPARATORS.some((separator) => line.includes(separator)) || /\)\s*$/.test(line)
}
function splitLine(line: string): string[] {
if (!line) return []
if (hasNote(line)) return [line]
// A comma between digits is a decimal ("1,5 kg").
return line
.split(/\s*,\s*(?!\d)/)
.flatMap((part) => part.split(AND))
.map((part) => part.trim())
.filter(Boolean)
}
/**
* Reads one item: "400 de jamon" → Jamón · 400, "2 pascualinas" → Pascualinas · 2,
* "Queso crema. Solo Tregar" → Queso crema + note, "leche x2" → Leche · 2.
*/
export function parseSingleItem(source: string): ParsedItem {
let text = source.trim()
let notes: string | null = null
const separator = NOTE_SEPARATORS.map((value) => ({ value, index: text.indexOf(value) }))
.filter(({ index }) => index > 0)
.sort((a, b) => a.index - b.index)[0]
if (separator) {
notes = text.slice(separator.index + separator.value.length)
text = text.slice(0, separator.index)
} else {
const parenthesis = TRAILING_PARENTHESIS.exec(text)
if (parenthesis) {
text = parenthesis[1]
notes = parenthesis[2]
}
}
text = text.replace(/\.+$/, '').trim()
notes = notes?.trim() ? capitalize(notes.trim()) : null
const tokens = splitTokens(text)
// A quantity with nothing left for the name ("400 g") is the name itself.
const leading = readLeadingQuantity(tokens)
const trailing = readTrailingQuantity(tokens)
let quantity: string | null = null
let nameWords = text.split(/\s+/)
if (leading && leading.consumed < tokens.length) {
quantity = formatQuantity(leading.quantity)
nameWords = tokens.slice(leading.consumed)
} else if (trailing && trailing.consumed < tokens.length) {
quantity = formatQuantity(trailing.quantity)
nameWords = tokens.slice(0, tokens.length - trailing.consumed)
}
return {
name: capitalize(nameWords.map(restoreAccent).join(' ')),
quantity,
notes,
source: source.trim(),
}
}
/**
* Restores the accent of a known grocery word typed without it, keeping a leading capital
* (`jamon` → `jamón`, `Jamon` → `Jamón`). Upper-case or mixed-case words are brand names
* and stay as typed.
*/
function restoreAccent(word: string): string {
const lower = word.toLowerCase()
if (word !== lower && word !== capitalize(lower)) return word
const accented = ACCENTS[normalizeWord(word)]
if (!accented) return word
return word === lower ? accented : capitalize(accented)
}

View File

@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest'
import { addQuantities, parseQuantity } from './quantity'
describe('parseQuantity', () => {
it('reads stored quantities', () => {
expect(parseQuantity('2')).toEqual({ amount: 2, unit: null })
expect(parseQuantity('400 g')).toEqual({ amount: 400, unit: 'g' })
expect(parseQuantity('½ kg')).toEqual({ amount: 0.5, unit: 'kg' })
expect(parseQuantity('2 paquetes')).toEqual({ amount: 2, unit: 'paquete' })
})
it('rejects free text', () => {
expect(parseQuantity('un par')).toBeNull()
expect(parseQuantity('')).toBeNull()
})
})
describe('addQuantities', () => {
it('sums compatible quantities', () => {
expect(addQuantities('2', '3')).toBe('5')
expect(addQuantities('400 g', '200 g')).toBe('600 g')
expect(addQuantities('400 g', '0,2 kg')).toBe('600 g')
expect(addQuantities('½ kg', '600 g')).toBe('1,1 kg')
expect(addQuantities('1 l', '500 ml')).toBe('1,5 l')
expect(addQuantities('1 paquete', '1 paquete')).toBe('2 paquetes')
})
it('reads a large bare number next to a weight as that weight', () => {
expect(addQuantities('400', '200 g')).toBe('600 g')
expect(addQuantities('400', '1 kg')).toBe('1,4 kg')
expect(addQuantities('2', '200 g')).toBe('2 + 200 g')
})
it('counts an empty quantity as one unit of a plain count', () => {
expect(addQuantities(null, null)).toBe('2')
expect(addQuantities(null, '3')).toBe('4')
expect(addQuantities(null, '400 g')).toBe('400 g')
expect(addQuantities('400 g', null)).toBe('400 g')
})
it('joins incompatible quantities', () => {
expect(addQuantities('2 paquetes', '1 kg')).toBe('2 paquetes + 1 kg')
expect(addQuantities('un par', '2')).toBe('un par + 2')
})
})

View File

@@ -0,0 +1,241 @@
import { CONTAINER_UNITS, NUMBER_WORDS, UNIT_ALIASES } from './lexicon'
import { normalizeWord } from './text'
/** A parsed quantity: an amount plus its canonical unit (`null` for a plain count). */
export type Quantity = { amount: number; unit: string | null }
/** Units that measure weight or volume, with their factor to the base unit (g / ml). */
const MEASURES: Record<string, { base: string; factor: number }> = {
g: { base: 'g', factor: 1 },
kg: { base: 'g', factor: 1000 },
ml: { base: 'ml', factor: 1 },
l: { base: 'ml', factor: 1000 },
}
const FRACTION_GLYPHS: Record<string, number> = { '½': 0.5, '¼': 0.25, '¾': 0.75 }
const GLYPH_FOR: [number, string][] = [
[0.5, '½'],
[0.25, '¼'],
[0.75, '¾'],
]
/** Parses a number token: `2`, `1,5`, `1.5`, `1/2`, `½`. */
export function parseNumber(token: string): number | null {
if (token in FRACTION_GLYPHS) return FRACTION_GLYPHS[token]
if (/^\d+(?:[.,]\d+)?$/.test(token)) return Number.parseFloat(token.replace(',', '.'))
const fraction = /^(\d+)\/(\d+)$/.exec(token)
if (fraction && Number(fraction[2]) > 0) return Number(fraction[1]) / Number(fraction[2])
return null
}
/** Parses a number written as a word (`dos`, `una`, `doce`). */
function parseNumberWord(token: string): number | null {
return NUMBER_WORDS[normalizeWord(token)] ?? null
}
/** The canonical unit for a token (`kilos` → `kg`), `''` for a unit to drop, `null` if none. */
export function parseUnit(token: string): string | null {
return UNIT_ALIASES[normalizeWord(token).replace(/\.$/, '')] ?? null
}
function formatAmount(amount: number): string {
const glyph = GLYPH_FOR.find(([value]) => Math.abs(value - amount) < 1e-9)
if (glyph) return glyph[1]
const rounded = Math.round(amount * 100) / 100
return String(rounded).replace('.', ',')
}
/** Renders a quantity the way it is stored: `400`, `½ kg`, `1,5 l`, `2 paquetes`. */
export function formatQuantity({ amount, unit }: Quantity): string {
const number = formatAmount(amount)
if (!unit) return number
const plural = CONTAINER_UNITS.has(unit) && amount > 1
return `${number} ${plural ? `${unit}s` : unit}`
}
/**
* Reads a quantity from the start of `tokens`, Spanish style: `2`, `400 g`, `400g`,
* `dos paquetes`, `medio kilo`, `un cuarto`, `una docena`, `media docena`, each optionally
* followed by `de`. Returns the quantity and how many tokens it used, or `null` when the
* tokens do not start with one.
*/
export function readLeadingQuantity(
tokens: string[],
): { quantity: Quantity; consumed: number } | null {
const words = tokens.map(normalizeWord)
let index = 0
let amount: number | null = null
let unit: string | null = null
// "medio"/"media"/"cuarto" (optionally after "un"/"una") only count as a quantity when a
// unit or "de" follows: "medio kilo de pan", "un cuarto de jamón", but not "medio pollo".
const fractionStart = words[0] === 'un' || words[0] === 'una' ? 1 : 0
const fractionWord = words[fractionStart]
if (fractionWord === 'medio' || fractionWord === 'media' || fractionWord === 'cuarto') {
const value = fractionWord === 'cuarto' ? 0.25 : 0.5
const next = words[fractionStart + 1]
if (next === 'docena') {
amount = value * 12
index = fractionStart + 2
} else if (next !== undefined && parseUnit(next)) {
amount = value
unit = parseUnit(next)
index = fractionStart + 2
} else if (next === 'de') {
// "medio de helado", "un cuarto de jamón": a kilo is implied.
amount = value
unit = 'kg'
index = fractionStart + 1
} else {
return null
}
} else {
amount = parseNumber(words[0] ?? '') ?? parseNumberWord(words[0] ?? '')
if (amount === null) return null
index = 1
if (words[index] === 'docena' || words[index] === 'docenas') {
amount *= 12
index += 1
} else if (words[index] !== undefined && parseUnit(words[index]) !== null) {
unit = parseUnit(words[index])
index += 1
}
// "1 kilo y medio", "2 litros y medio"
if (words[index] === 'y' && (words[index + 1] === 'medio' || words[index + 1] === 'media')) {
amount += 0.5
index += 2
}
}
if (words[index] === 'de' || words[index] === 'del') index += 1
return { quantity: { amount, unit: unit || null }, consumed: index }
}
/**
* Reads a quantity from the end of `tokens`: `x2`, `x 3`, `400 g`, `2 paquetes`. A bare
* trailing number is not taken (`Sprite 2.25`, `Pilas AA 2` keep it in the name).
*/
export function readTrailingQuantity(
tokens: string[],
): { quantity: Quantity; consumed: number } | null {
const words = tokens.map(normalizeWord)
const last = words.length - 1
if (last < 1) return null
// "x2" / "x 2" (also "x 2 kg")
for (const [xIndex, consumed] of [
[last - 1, 2],
[last - 2, 3],
] as const) {
if (xIndex < 1 || words[xIndex] !== 'x') continue
const amount = parseNumber(words[xIndex + 1])
if (amount === null) continue
if (consumed === 2) return { quantity: { amount, unit: null }, consumed }
const unit = parseUnit(words[last])
if (unit !== null) return { quantity: { amount, unit: unit || null }, consumed }
}
// "400 g", "2 paquetes"
const amount = parseNumber(words[last - 1])
const unit = parseUnit(words[last])
if (last >= 2 && amount !== null && unit !== null) {
return { quantity: { amount, unit: unit || null }, consumed: 2 }
}
return null
}
/** Parses a stored quantity string (`2`, `400 g`, `½ kg`), or `null` if it is free text. */
export function parseQuantity(text: string): Quantity | null {
const tokens = splitTokens(text)
if (tokens.length === 0) return null
const leading = readLeadingQuantity(tokens)
return leading && leading.consumed === tokens.length ? leading.quantity : null
}
/**
* Splits text into whitespace tokens, also separating a number glued to a known unit
* (`400g` → `400 g`) and the `x` glued to a number (`x2` → `x 2`).
*/
export function splitTokens(text: string): string[] {
return text
.trim()
.split(/\s+/)
.filter(Boolean)
.flatMap((token) => {
const times = /^x(\d+(?:[.,]\d+)?)$/i.exec(token)
if (times) return ['x', times[1]]
const glued = /^(\d+(?:[.,]\d+)?|[½¼¾])([a-zA-Z]+\.?)$/.exec(token)
if (glued && parseUnit(glued[2]) !== null) return [glued[1], glued[2]]
return [token]
})
}
/**
* Adds two stored quantities, used when an item is added again. Compatible quantities
* are summed (`400 g` + `0,2 kg` → `600 g`, `2` + `3` → `5`); an empty one counts as
* one unit when the other is a plain count (so adding "leche" twice gives `2`) and is
* otherwise ignored; incompatible ones are joined with `+`.
*/
export function addQuantities(a: string | null, b: string | null): string | null {
if (!a && !b) return '2'
const left = a ? parseQuantity(a) : { amount: 1, unit: null }
const right = b ? parseQuantity(b) : { amount: 1, unit: null }
if (left && right) {
const sum = sumQuantities(left, right)
if (sum) return formatQuantity(sum)
}
if (!a) return b
if (!b) return a
return `${a} + ${b}`.slice(0, 40)
}
/** Bare numbers from here up are weights/volumes, not counts: "400 de jamón" is 400 g. */
const IMPLIED_MEASURE_FROM = 50
function sumQuantities(a: Quantity, b: Quantity): Quantity | null {
if (a.unit === b.unit) return { amount: a.amount + b.amount, unit: a.unit }
// A bare "400" next to grams or millilitres is in that same base unit.
for (const [bare, measured] of [
[a, b],
[b, a],
]) {
const base = measured.unit ? MEASURES[measured.unit]?.base : undefined
if (!bare.unit && base && bare.amount >= IMPLIED_MEASURE_FROM) {
return sumQuantities({ ...bare, unit: base }, measured)
}
}
const measureA = a.unit ? MEASURES[a.unit] : undefined
const measureB = b.unit ? MEASURES[b.unit] : undefined
if (!measureA || !measureB || measureA.base !== measureB.base) return null
const total = a.amount * measureA.factor + b.amount * measureB.factor
const big = measureA.factor > 1 ? a.unit : b.unit
// Mixed units: kilos/litres once the total reaches one, grams/millilitres below it.
return total >= 1000 && big
? { amount: total / 1000, unit: big }
: { amount: total, unit: measureA.base }
}

View File

@@ -0,0 +1,9 @@
/** Lowercases and strips accents (`Jamón` → `jamon`, `Ñoquis` → `noquis`) for comparisons. */
export function normalizeWord(word: string): string {
return word.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase()
}
/** Upper-cases the first letter and leaves the rest as typed. */
export function capitalize(text: string): string {
return text.charAt(0).toUpperCase() + text.slice(1)
}

View File

@@ -0,0 +1,53 @@
import { VOICE_SPLIT_EXAMPLES } from '@superlist/shared'
import { describe, expect, it } from 'vitest'
import { parseItemInput } from './parse-item'
import { parseQuantity } from './quantity'
/**
* The dictation examples the API shows the model (`@superlist/shared` → voice.ts) must be
* written exactly the way this parser reads them: each string is one item with the
* expected quantity, unit and note.
*/
const EXPECTED: Record<
string,
{ name: string; amount: number | null; unit: string | null; notes: string | null }
> = {
'2 pascualinas': { name: 'Pascualinas', amount: 2, unit: null, notes: null },
'1,5 kg de papas': { name: 'Papas', amount: 1.5, unit: 'kg', notes: null },
'400 de jamon. Feteado fino': { name: 'Jamón', amount: 400, unit: null, notes: 'Feteado fino' },
'1 lata de atun': { name: 'Atún', amount: 1, unit: 'lata', notes: null },
'Queso crema. Solo si hay marca Tregar': {
name: 'Queso crema',
amount: null,
unit: null,
notes: 'Solo si hay marca Tregar',
},
'6 unidades de yogur': { name: 'Yogur', amount: 6, unit: null, notes: null },
'400g de queso': { name: 'Queso', amount: 400, unit: 'g', notes: null },
'Leche (descremada)': { name: 'Leche', amount: null, unit: null, notes: 'Descremada' },
}
describe('dictation few-shot examples', () => {
const items = VOICE_SPLIT_EXAMPLES.flatMap((example) => example.items)
it('has an expectation for every example item', () => {
expect([...items].sort()).toEqual(Object.keys(EXPECTED).sort())
})
it.each(items)('parses "%s" as one item with the expected quantity and note', (text) => {
const parsed = parseItemInput(text)
expect(parsed).toHaveLength(1)
const [item] = parsed
const quantity = item.quantity ? parseQuantity(item.quantity) : null
const expected = EXPECTED[text]
expect({
name: item.name,
amount: quantity?.amount ?? null,
unit: quantity?.unit ?? null,
notes: item.notes,
}).toEqual(expected)
})
})

View File

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

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

View File

@@ -0,0 +1,78 @@
import { registerSW } from 'virtual:pwa-register'
/** How often an open app asks the server for a new service worker. */
const UPDATE_INTERVAL_MS = 30 * 60 * 1000
function isEditing() {
const element = document.activeElement
if (!(element instanceof HTMLElement)) return false
return (
element.isContentEditable ||
element instanceof HTMLInputElement ||
element instanceof HTMLTextAreaElement ||
element instanceof HTMLSelectElement
)
}
/**
* Reloads into the new release as soon as it is safe: right away, unless the
* user is typing (an item name, a list name...), in which case it waits until
* the app goes to the background so nothing they wrote is lost.
*/
function reloadWhenIdle() {
if (document.visibilityState === 'hidden' || !isEditing()) {
window.location.reload()
return
}
document.addEventListener(
'visibilitychange',
() => {
if (document.visibilityState === 'hidden') window.location.reload()
},
{ once: true },
)
}
/**
* Registers the service worker and keeps the installed PWA up to date.
*
* With `registerType: 'autoUpdate'` the new worker skips waiting and claims the
* page as soon as it is installed, but the browser only looks for one on a
* navigation. An installed PWA is rarely navigated (it stays open in the
* background for days), so this also checks periodically, whenever the app
* comes back to the foreground and when the connection returns.
*/
export function registerServiceWorker() {
if (!('serviceWorker' in navigator)) return
registerSW({
immediate: true,
onNeedReload: reloadWhenIdle,
onRegisteredSW(swUrl, registration) {
if (!registration) return
const checkForUpdate = async () => {
if (registration.installing || !navigator.onLine) return
// Skip the check when the server is unreachable instead of letting
// `update()` reject (it would log an unhandled error offline).
try {
const response = await fetch(swUrl, {
cache: 'no-store',
headers: { 'cache-control': 'no-cache' },
})
if (response.ok) await registration.update()
} catch {
// Offline or server down: try again on the next trigger.
}
}
setInterval(checkForUpdate, UPDATE_INTERVAL_MS)
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') void checkForUpdate()
})
window.addEventListener('online', () => void checkForUpdate())
},
})
}

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

View File

@@ -4,10 +4,13 @@ import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { createQueryClient } from '@/lib/query-client'
import { registerServiceWorker } from '@/lib/register-sw'
import { routeTree } from './routeTree.gen'
import './index.css'
registerServiceWorker()
const queryClient = createQueryClient()
const router = createRouter({

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

View File

@@ -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}>
<FieldLabel htmlFor="password">Contraseña</FieldLabel>
<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"

View File

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

View File

@@ -1,15 +1,13 @@
import type { ShoppingListSummary } from '@superlist/shared'
import { createFileRoute, Link } from '@tanstack/react-router'
import { PlusIcon, ShoppingCartIcon } from 'lucide-react'
import { CreateItemForm } from '@/components/items/create-item-form'
import { ItemList } from '@/components/items/item-list'
import { ListComposer } from '@/components/items/list-composer'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { listsQueryOptions, useLists } from '@/hooks/use-lists'
import { listsQueryOptions, pickPrimaryList, useLists } from '@/hooks/use-lists'
import { ApiError } from '@/lib/api-client'
export const Route = createFileRoute('/_authenticated/')({
@@ -17,11 +15,6 @@ export const Route = createFileRoute('/_authenticated/')({
component: HomePage,
})
/** The list a user lands on: their primary one, falling back to the first. */
function pickPrimaryList(lists: ShoppingListSummary[]): ShoppingListSummary | undefined {
return lists.find((list) => list.isPrimary) ?? lists[0]
}
function HomePage() {
const { data: lists, isPending, error } = useLists()
@@ -43,7 +36,6 @@ function HomePage() {
if (isPending || !lists) {
return (
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4">
<Skeleton className="h-8 w-48" />
<Skeleton className="h-10 w-full" />
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
@@ -59,12 +51,7 @@ function HomePage() {
return (
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4 md:gap-6">
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-lg font-semibold">{primaryList.name}</h1>
{primaryList.isPrimary && <Badge>Principal</Badge>}
</div>
<CreateItemForm listId={primaryList.id} autoFocus />
<ListComposer listId={primaryList.id} />
<ItemList listId={primaryList.id} />
</div>

Some files were not shown because too many files have changed in this diff Show More