Compare commits
32 Commits
debf3b2728
...
feat/obser
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b9c6ab92e3 | ||
|
|
dd9cf4ce43 | ||
|
|
3411b4b145 | ||
|
|
eace15b140 | ||
|
|
aa170de8d1 | ||
|
|
7ed4d27844 | ||
| f3d9996b11 | |||
|
|
6830c827d7 | ||
|
|
cc0611b6a0 | ||
|
|
9159dd9c9b | ||
|
|
1964d3e08b | ||
| 01769314cb | |||
|
|
2117188bf9 | ||
|
|
9bd2cc9089 | ||
|
|
9d4388ed8c | ||
|
|
48c0c83424 | ||
|
|
a814b34036 | ||
|
|
eb1f6cb2a9 | ||
|
|
feb8df14c0 | ||
|
|
86d4796d88 | ||
|
|
d5feb65d62 | ||
|
|
71793dbd3a | ||
|
|
5abdb08204 | ||
|
|
d02ab28fc5 | ||
|
|
db7cdd5585 | ||
|
|
247ea903a9 | ||
|
|
b913fe3299 | ||
|
|
b7fa930831 | ||
|
|
812d4b7170 | ||
|
|
123601939c | ||
|
|
686325d8a4 | ||
|
|
56853bbdeb |
17
.claude/launch.json
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"version": "0.0.1",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "web",
|
||||||
|
"runtimeExecutable": "bun",
|
||||||
|
"runtimeArgs": ["run", "dev", "--filter=@superlist/web"],
|
||||||
|
"port": 7153
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "api",
|
||||||
|
"runtimeExecutable": "bun",
|
||||||
|
"runtimeArgs": ["run", "dev", "--filter=@superlist/api"],
|
||||||
|
"port": 4100
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,4 +1,8 @@
|
|||||||
.git
|
.git
|
||||||
|
# Just enough of the repository for the web build to read the commit hash.
|
||||||
|
!.git/HEAD
|
||||||
|
!.git/refs
|
||||||
|
!.git/packed-refs
|
||||||
.github
|
.github
|
||||||
**/node_modules
|
**/node_modules
|
||||||
**/.turbo
|
**/.turbo
|
||||||
|
|||||||
33
.env.example
@@ -11,14 +11,41 @@ BETTER_AUTH_SECRET="change-me-with-openssl-rand-base64-32"
|
|||||||
BETTER_AUTH_URL="http://localhost:4100"
|
BETTER_AUTH_URL="http://localhost:4100"
|
||||||
# "development" enables pretty logs, "production" emits JSON
|
# "development" enables pretty logs, "production" emits JSON
|
||||||
NODE_ENV="development"
|
NODE_ENV="development"
|
||||||
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
|
# Optional: log level (trace, debug, info, warning, error, fatal) (defaults to "debug" outside production, "info" in production)
|
||||||
# LOG_LEVEL="info"
|
# LOG_LEVEL="info"
|
||||||
# Resend API key used to send invitation emails. Without it, emails are logged instead.
|
# Optional: ship logs to OpenObserve over OTLP/HTTP. Without OPENOBSERVE_URL logs only go to the console.
|
||||||
|
# OPENOBSERVE_URL="http://localhost:5080"
|
||||||
|
# Optional: organization (defaults to "default") and stream (defaults to "superlist")
|
||||||
|
# OPENOBSERVE_ORG="default"
|
||||||
|
# OPENOBSERVE_STREAM="superlist"
|
||||||
|
# OpenObserve user email and password (sent as Basic auth)
|
||||||
|
# OPENOBSERVE_USER="root@example.com"
|
||||||
|
# OPENOBSERVE_PASSWORD=""
|
||||||
|
# Optional: how often HTTP metrics are pushed to OpenObserve, in milliseconds (defaults to 15000)
|
||||||
|
# METRICS_EXPORT_INTERVAL_MS="15000"
|
||||||
|
# Resend API key used to send invitation and password reset emails. Without it, emails are logged instead.
|
||||||
# RESEND_API_KEY="re_xxxxxxxx"
|
# RESEND_API_KEY="re_xxxxxxxx"
|
||||||
# From address for outgoing email (must be a verified Resend sender)
|
# From address for outgoing email (must be a verified Resend sender)
|
||||||
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
||||||
# Public URL of the web app, used to build the accept-invitation links
|
# Public URL of the web app. Used to build invitation links and as the WebAuthn
|
||||||
|
# relying-party origin for passkeys (no trailing slash), so it must be the exact
|
||||||
|
# public origin users open in the browser.
|
||||||
WEB_APP_URL="http://localhost:7153"
|
WEB_APP_URL="http://localhost:7153"
|
||||||
|
# Dictation: AI Studio (Gemini API) key, backend only. NEVER prefix it with VITE_
|
||||||
|
# or Vite would put it in the browser bundle. Without it, dictated text is split
|
||||||
|
# on commas and "y" instead of by the model.
|
||||||
|
# GEMINI_API_KEY=""
|
||||||
|
# Optional: model id (defaults to Gemma 4's small variant)
|
||||||
|
# GEMINI_MODEL="gemma-4-26b-a4b-it"
|
||||||
|
# Optional: timeout of the model request, in milliseconds
|
||||||
|
# GEMINI_TIMEOUT_MS="8000"
|
||||||
|
# Dictation: Groq API key, backend only (NEVER prefix it with VITE_). When set, Groq
|
||||||
|
# splits dictated text instead of Gemini; it is faster and steadier.
|
||||||
|
# GROQ_API_KEY=""
|
||||||
|
# Optional: model id
|
||||||
|
# GROQ_MODEL="openai/gpt-oss-120b"
|
||||||
|
# Optional: timeout of the model request, in milliseconds
|
||||||
|
# GROQ_TIMEOUT_MS="8000"
|
||||||
|
|
||||||
# --- apps/web ---
|
# --- apps/web ---
|
||||||
# Optional. In dev, Vite proxies /api/* to the API (http://localhost:4100), so
|
# Optional. In dev, Vite proxies /api/* to the API (http://localhost:4100), so
|
||||||
|
|||||||
72
AGENTS.md
@@ -6,14 +6,16 @@ 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
|
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.
|
Dokploy (`docker-compose.yml`); there is no hosted CI.
|
||||||
|
|
||||||
Not done yet: product features are just starting (sign-up, shopping lists, list items and invitations exist;
|
Not done yet: product features are just starting (sign-up, password recovery with an emailed OTP, passkeys,
|
||||||
there is no Google login and no email verification). The `health` module is the reference example.
|
shopping lists, list items and invitations exist; there is no Google login and no email verification; the
|
||||||
|
`voice` module splits dictated text with Groq, or Gemma 4 through the Gemini API when Groq is not configured).
|
||||||
|
The `health` module is the reference example.
|
||||||
|
|
||||||
## Stack (source of truth: `STACK.md`)
|
## Stack (source of truth: `STACK.md`)
|
||||||
|
|
||||||
- Monorepo orchestrated with **Turborepo** (see the managed block at the end of this file)
|
- Monorepo orchestrated with **Turborepo** (see the managed block at the end of this file)
|
||||||
- Backend: **Bun** + **Hono**, **Prisma 7** against **Postgres** (via `@prisma/adapter-pg`), **Zod** for
|
- Backend: **Bun** + **Hono**, **Prisma 7** against **Postgres** (via `@prisma/adapter-pg`), **Zod** for
|
||||||
validation, **Pino** for logging, **BetterAuth** for auth
|
validation, **LogTape** for logging (shipped to **OpenObserve**), **BetterAuth** for auth
|
||||||
- Frontend: **React + Vite + TypeScript**, **Tailwind v4**, UI components from **shadcn/ui**
|
- Frontend: **React + Vite + TypeScript**, **Tailwind v4**, UI components from **shadcn/ui**
|
||||||
- Frontend routing: **TanStack Router** (file-based) · server state: **TanStack Query** ·
|
- Frontend routing: **TanStack Router** (file-based) · server state: **TanStack Query** ·
|
||||||
forms: **React Hook Form + Zod**
|
forms: **React Hook Form + Zod**
|
||||||
@@ -90,15 +92,19 @@ 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
|
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.
|
set `map:` unless you have a reason to.
|
||||||
- **Deployment: Docker Compose on Dokploy** (`docker-compose.yml` at the repo root). Two services, `api` and
|
- **Deployment: Docker Compose on Dokploy** (`docker-compose.yml` at the repo root). Two services, `api` and
|
||||||
`web`; the database is external (Dokploy's). Only `web` joins the external `dokploy-network` for Traefik;
|
`web`; the database is external (Dokploy's). Both join the external `dokploy-network` — `web` for Traefik,
|
||||||
`web` and `api` share the stack-private `internal` network, where the API has the alias `superlist-api`
|
`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
|
(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
|
`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
|
`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://superlist-api:4100` (re-resolved through
|
`apps/web/nginx.conf`, which also proxies `/api/*` to `http://superlist-api:4100` (re-resolved through
|
||||||
Docker's DNS, so API redeploys don't leave nginx on a stale IP). Required env vars are interpolated
|
Docker's DNS, so API redeploys don't leave nginx on a stale IP). Required env vars are interpolated
|
||||||
by Compose (`DATABASE_URL`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `CORS_ORIGIN`, `WEB_APP_URL`); set them
|
by Compose (`DATABASE_URL`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `CORS_ORIGIN`, `WEB_APP_URL`); set them
|
||||||
in Dokploy. There is no hosted CI.
|
in Dokploy. `WEB_APP_URL` is not only used for email links: it is also the WebAuthn relying-party origin, so
|
||||||
|
it must be the exact public URL of the web app. The dictation variables (`GROQ_API_KEY`, `GROQ_MODEL`, `GROQ_TIMEOUT_MS`, `GEMINI_API_KEY`, `GEMINI_MODEL`,
|
||||||
|
`GEMINI_TIMEOUT_MS`) are optional (Groq wins when its key is set) and
|
||||||
|
backend-only — never give them a `VITE_` prefix, or Vite would ship the key in the browser bundle. There is no hosted CI.
|
||||||
- Generated files are gitignored and must never be edited by hand: `apps/web/src/routeTree.gen.ts`,
|
- Generated files are gitignored and must never be edited by hand: `apps/web/src/routeTree.gen.ts`,
|
||||||
`apps/api/src/generated/`.
|
`apps/api/src/generated/`.
|
||||||
- Tests live next to the code as `*.test.ts`. The API uses `bun test` (`src/lib/result-json.test.ts`,
|
- Tests live next to the code as `*.test.ts`. The API uses `bun test` (`src/lib/result-json.test.ts`,
|
||||||
@@ -191,16 +197,45 @@ export class CreateAlert {
|
|||||||
(`problemResponse`, `notFoundHandler`, `errorHandler`) in `apps/api/src/lib/problem-details.ts`.
|
(`problemResponse`, `notFoundHandler`, `errorHandler`) in `apps/api/src/lib/problem-details.ts`.
|
||||||
- Zod is the only validation library, and Zod 4 is what is installed. Define schemas next to the feature that
|
- Zod is the only validation library, and Zod 4 is what is installed. Define schemas next to the feature that
|
||||||
uses them (`schema.ts`); share them through `@superlist/shared` only when more than one module needs them.
|
uses them (`schema.ts`); share them through `@superlist/shared` only when more than one module needs them.
|
||||||
- **Logging: Pino** — one shared logger in `apps/api/src/lib/logger.ts`, reachable from handlers as
|
- **Logging: LogTape** — root logger (`superlist` category) exported from `apps/api/src/lib/logger.ts`, reachable
|
||||||
`c.get('logger')` (already enriched with the request id); never `console.log` in the backend. Level comes from
|
from handlers as `c.get('logger')`; never `console.log` in the backend. The call shape is
|
||||||
`LOG_LEVEL`, defaulting to `debug` (pretty) outside production and `info` (JSON) in production.
|
`logger.info('message {prop}', { prop })` (message first, properties second; pass errors as `{ error }`).
|
||||||
|
`configureLogging()` runs once in `src/index.ts` (tests never call it, so logging is silent there) and
|
||||||
|
`dispose()` flushes on SIGINT/SIGTERM. Sinks: console (`@logtape/pretty` outside production, JSON lines in
|
||||||
|
production) plus OpenObserve over OTLP/HTTP (`@logtape/otel`, `/api/<org>/v1/logs`, Basic auth, `stream-name`
|
||||||
|
header) when `OPENOBSERVE_URL` is set (`OPENOBSERVE_ORG`, `OPENOBSERVE_STREAM`, `OPENOBSERVE_USER`,
|
||||||
|
`OPENOBSERVE_PASSWORD`). Level comes from `LOG_LEVEL` (`debug` in dev, `info` in production; `warn` is accepted
|
||||||
|
for `warning`). The request middleware in `app.ts` wraps each request in `withContext({ requestId })`, so every
|
||||||
|
record logged during it carries the request id, and logs one `superlist.http` record per request with
|
||||||
|
`method`, `path`, `route` (the Hono pattern, e.g. `/api/lists/:listId`), `status`, `durationMs`, `userId` and
|
||||||
|
`userAgent` — `error` for 5xx, `warning` for 4xx, `debug` for `/api/health`, `info` otherwise. SSE routes
|
||||||
|
return their `Response` immediately, so their duration is the time to open the stream.
|
||||||
|
- **Metrics: OpenTelemetry SDK** (`apps/api/src/lib/metrics.ts`), pushed to OpenObserve over OTLP/HTTP
|
||||||
|
(`/api/<org>/v1/metrics`, cumulative temporality) every `METRICS_EXPORT_INTERVAL_MS` (15 s) when
|
||||||
|
`OPENOBSERVE_URL` is set; otherwise the global meter is a no-op. The same request middleware records
|
||||||
|
`http.server.request.duration` (histogram, seconds; attributes `http.request.method`, `http.route`,
|
||||||
|
`http.response.status_code`) and `http.server.active_requests`. Always use the route pattern
|
||||||
|
(`routePath(c, -1)`), never the raw path, as an attribute. The OpenObserve settings live in
|
||||||
|
`lib/openobserve.ts`, shared by logs and metrics. Dashboard guide: `docs/openobserve-dashboard.md` (importable JSON: `docs/openobserve-dashboard.json`).
|
||||||
- Unexpected throws are turned into Problem Details by `app.onError`; unmatched routes by `app.notFound`
|
- Unexpected throws are turned into Problem Details by `app.onError`; unmatched routes by `app.notFound`
|
||||||
(both in `apps/api/src/lib/problem-details.ts`).
|
(both in `apps/api/src/lib/problem-details.ts`).
|
||||||
- `createApp()` middleware order matters: `secureHeaders` → `cors` (origins from `CORS_ORIGIN`, credentials on)
|
- `createApp()` middleware order matters: `secureHeaders` → `cors` (origins from `CORS_ORIGIN`, credentials on)
|
||||||
→ `requestId` → request logger → BetterAuth → modules.
|
→ `requestId` → request logger → BetterAuth → modules.
|
||||||
- **Auth**: BetterAuth is configured in `apps/api/src/lib/auth.ts` (Prisma adapter, `baseURL` from
|
- **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`,
|
`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.
|
||||||
|
- **Passkeys**: the separate `@better-auth/passkey` package (installed in both apps) adds WebAuthn sign-in.
|
||||||
|
Pin it to the exact same version as `better-auth` (currently `1.7.7`): its peer dependencies
|
||||||
|
(`better-call`, `@better-auth/core`) are version-locked, so a newer passkey package breaks the API.
|
||||||
|
`lib/passkey-config.ts` derives `rpID` and `origin` from `WEB_APP_URL`, **not** from `BETTER_AUTH_URL`:
|
||||||
|
WebAuthn runs in the browser, where the web origin is `:7153` in dev and the public web domain in
|
||||||
|
production. Sign-in is username-less, so the plugin is configured with `residentKey: 'required'`.
|
||||||
|
Passkeys are bound to the domain: those registered on `localhost` do not work in production (and vice
|
||||||
|
versa). The `Passkey`/`passkeys` Prisma model is mapped by hand like the rest of the schema; the plugin
|
||||||
|
also runs `prisma migrate deploy` before starting in production.
|
||||||
- **Prisma 7**: the generator is `prisma-client` and writes to `apps/api/src/generated/prisma` (gitignored), so
|
- **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
|
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
|
`@prisma/adapter-pg` adapter with `DATABASE_URL` and is exported as `prisma` (plus the `Database` type) from
|
||||||
@@ -209,9 +244,10 @@ export class CreateAlert {
|
|||||||
the generated migration under `apps/api/prisma/migrations` — never edit migration files by hand. The
|
the generated migration under `apps/api/prisma/migrations` — never edit migration files by hand. The
|
||||||
datasource has no `url` in the schema: it comes from `prisma.config.ts` (`env('DATABASE_URL')`). For
|
datasource has no `url` in the schema: it comes from `prisma.config.ts` (`env('DATABASE_URL')`). For
|
||||||
production, `apps/api` also has `db:deploy` (`prisma migrate deploy`), which is not wired to a turbo task yet.
|
production, `apps/api` also has `db:deploy` (`prisma migrate deploy`), which is not wired to a turbo task yet.
|
||||||
- The BetterAuth models (`User`, `Session`, `Account`, `Verification`) are already in the schema and follow the
|
- The BetterAuth models (`User`, `Session`, `Account`, `Verification`, `Passkey`) are already in the schema and
|
||||||
naming convention above (`users`, `sessions`, `accounts`, `verifications` with snake_case columns); regenerate
|
follow the naming convention above (`users`, `sessions`, `accounts`, `verifications`, `passkeys` with
|
||||||
them with the BetterAuth CLI rather than by hand if the auth config changes, then re-apply the mapping.
|
snake_case columns); regenerate them with the BetterAuth CLI rather than by hand if the auth config changes,
|
||||||
|
then re-apply the mapping. `Passkey` comes from the `@better-auth/passkey` plugin, not the core CLI.
|
||||||
|
|
||||||
## Shared package (`@superlist/shared`)
|
## Shared package (`@superlist/shared`)
|
||||||
|
|
||||||
@@ -238,7 +274,7 @@ apps/web/src/
|
|||||||
- **Routing: TanStack Router with file-based routes.** Add a file under `src/routes` and the route tree is
|
- **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
|
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.
|
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
|
- `_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
|
(`authClient.useSession()`) and redirects to `/sign-in` when there is none. Add authenticated pages inside
|
||||||
`_authenticated/`.
|
`_authenticated/`.
|
||||||
@@ -262,6 +298,14 @@ apps/web/src/
|
|||||||
hook (`use-list-events.ts`) reuses it, so the browser calls `/api/*` on the current origin: Vite proxies it
|
hook (`use-list-events.ts`) reuses it, so the browser calls `/api/*` on the current origin: Vite proxies it
|
||||||
to `:4100` in dev and nginx does in production. `VITE_API_URL` is an optional override for a separate API
|
to `:4100` in dev and nginx does in production. `VITE_API_URL` is an optional override for a separate API
|
||||||
origin, and `auth-client.ts` defaults `baseURL` to `window.location.origin` (BetterAuth appends `/api/auth`).
|
origin, and `auth-client.ts` defaults `baseURL` to `window.location.origin` (BetterAuth appends `/api/auth`).
|
||||||
|
- **Icon badge**: the installed PWA shows the pending items of the primary list on its icon through the Badging
|
||||||
|
API (`lib/app-badge.ts`). `hooks/use-app-badge.ts`, mounted by the authenticated layout, follows that list's
|
||||||
|
SSE stream even from other pages (the shared `lib/list-events-stream.ts` avoids opening a second stream) and
|
||||||
|
re-syncs on foreground. It only runs in standalone mode; iOS additionally needs notification permission,
|
||||||
|
requested from the settings card (`components/settings/app-badge-card.tsx`) because WebKit only grants
|
||||||
|
badging alongside notifications. Chrome on Android does not support numeric badges (notifications show a
|
||||||
|
dot), so this is a progressive enhancement. Updating the badge while the app is closed would need Web Push,
|
||||||
|
which is not implemented.
|
||||||
- **Forms: React Hook Form + Zod** (`zodResolver`). Render errors with the shadcn `Field`/`FieldError`
|
- **Forms: React Hook Form + Zod** (`zodResolver`). Render errors with the shadcn `Field`/`FieldError`
|
||||||
components — this registry version ships `field` instead of the older `form` component.
|
components — this registry version ships `field` instead of the older `form` component.
|
||||||
- **shadcn/ui**: components live in `src/components/ui` and are source, not generated output — edit them
|
- **shadcn/ui**: components live in `src/components/ui` and are source, not generated output — edit them
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ Monorepo with a Bun + Hono API and a React + Vite admin app.
|
|||||||
|
|
||||||
| Workspace | What it is |
|
| Workspace | What it is |
|
||||||
| ----------------- | ----------------------------------------------------------------------- |
|
| ----------------- | ----------------------------------------------------------------------- |
|
||||||
| `apps/api` | Bun + Hono backend, Prisma (Postgres), Zod validation, Pino logging |
|
| `apps/api` | Bun + Hono backend, Prisma (Postgres), Zod validation, LogTape logging |
|
||||||
| `apps/web` | React + Vite + TypeScript frontend, shadcn/ui, TanStack Router + Query |
|
| `apps/web` | React + Vite + TypeScript frontend, shadcn/ui, TanStack Router + Query |
|
||||||
| `packages/shared` | `@superlist/shared` — Result pattern and RFC 9457 Problem Details types |
|
| `packages/shared` | `@superlist/shared` — Result pattern and RFC 9457 Problem Details types |
|
||||||
|
|
||||||
|
|||||||
4
STACK.md
@@ -1,8 +1,8 @@
|
|||||||
- Monorepo con TURBO
|
- Monorepo con TURBO
|
||||||
- Backend en Bun con Hono. Acceso a DB Postgres con Prisma. Validación con Zod. Logging con Pino
|
- Backend en Bun con Hono. Acceso a DB Postgres con Prisma. Validación con Zod. Logging con LogTape (consola + OpenObserve vía OTLP)
|
||||||
- Salidas del backend según RFC 9457 (Problem Details)
|
- Salidas del backend según RFC 9457 (Problem Details)
|
||||||
- Frontend en React con vite y typescript. Componentes Shadcn
|
- Frontend en React con vite y typescript. Componentes Shadcn
|
||||||
- Rutas del frontend con TanStack Router usando file-based routing
|
- Rutas del frontend con TanStack Router usando file-based routing
|
||||||
- Estado del servidor en el frontend con TanStack Query
|
- Estado del servidor en el frontend con TanStack Query
|
||||||
- Formularios del frontend con React Hook Form + Zod
|
- Formularios del frontend con React Hook Form + Zod
|
||||||
- BetterAuth para autenticación
|
- BetterAuth para autenticación (email + contraseña, OTP por correo y passkeys/WebAuthn)
|
||||||
|
|||||||
@@ -4,11 +4,38 @@ CORS_ORIGIN="http://localhost:7153"
|
|||||||
BETTER_AUTH_SECRET="change-me-with-openssl-rand-base64-32"
|
BETTER_AUTH_SECRET="change-me-with-openssl-rand-base64-32"
|
||||||
BETTER_AUTH_URL="http://localhost:4100"
|
BETTER_AUTH_URL="http://localhost:4100"
|
||||||
NODE_ENV="development"
|
NODE_ENV="development"
|
||||||
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
|
# Optional: log level (trace, debug, info, warning, error, fatal) (defaults to "debug" outside production, "info" in production)
|
||||||
# LOG_LEVEL="info"
|
# LOG_LEVEL="info"
|
||||||
# Resend API key used to send invitation emails. Without it, emails are logged instead.
|
# Optional: ship logs to OpenObserve over OTLP/HTTP. Without OPENOBSERVE_URL logs only go to the console.
|
||||||
|
# OPENOBSERVE_URL="http://localhost:5080"
|
||||||
|
# Optional: organization (defaults to "default") and stream (defaults to "superlist")
|
||||||
|
# OPENOBSERVE_ORG="default"
|
||||||
|
# OPENOBSERVE_STREAM="superlist"
|
||||||
|
# OpenObserve user email and password (sent as Basic auth)
|
||||||
|
# OPENOBSERVE_USER="root@example.com"
|
||||||
|
# OPENOBSERVE_PASSWORD=""
|
||||||
|
# Optional: how often HTTP metrics are pushed to OpenObserve, in milliseconds (defaults to 15000)
|
||||||
|
# METRICS_EXPORT_INTERVAL_MS="15000"
|
||||||
|
# Resend API key used to send invitation and password reset emails. Without it, emails are logged instead.
|
||||||
# RESEND_API_KEY="re_xxxxxxxx"
|
# RESEND_API_KEY="re_xxxxxxxx"
|
||||||
# From address for outgoing email (must be a verified Resend sender)
|
# From address for outgoing email (must be a verified Resend sender)
|
||||||
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
||||||
# Public URL of the web app, used to build the accept-invitation links
|
# Public URL of the web app. Used to build invitation links and as the WebAuthn
|
||||||
|
# relying-party origin for passkeys (no trailing slash), so it must be the exact
|
||||||
|
# public origin users open in the browser.
|
||||||
WEB_APP_URL="http://localhost:7153"
|
WEB_APP_URL="http://localhost:7153"
|
||||||
|
# Dictation: AI Studio (Gemini API) key, backend only. NEVER prefix it with VITE_
|
||||||
|
# or Vite would put it in the browser bundle. Without it, dictated text is split
|
||||||
|
# on commas and "y" instead of by the model.
|
||||||
|
# GEMINI_API_KEY=""
|
||||||
|
# Optional: model id (defaults to Gemma 4's small variant)
|
||||||
|
# GEMINI_MODEL="gemma-4-26b-a4b-it"
|
||||||
|
# Optional: timeout of the model request, in milliseconds
|
||||||
|
# GEMINI_TIMEOUT_MS="8000"
|
||||||
|
# Dictation: Groq API key, backend only (NEVER prefix it with VITE_). When set, Groq
|
||||||
|
# splits dictated text instead of Gemini; it is faster and steadier.
|
||||||
|
# GROQ_API_KEY=""
|
||||||
|
# Optional: model id
|
||||||
|
# GROQ_MODEL="openai/gpt-oss-120b"
|
||||||
|
# Optional: timeout of the model request, in milliseconds
|
||||||
|
# GROQ_TIMEOUT_MS="8000"
|
||||||
|
|||||||
@@ -16,15 +16,21 @@
|
|||||||
"db:studio": "prisma studio"
|
"db:studio": "prisma studio"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@better-auth/passkey": "1.7.7",
|
||||||
"@hono/zod-validator": "^0.9.1",
|
"@hono/zod-validator": "^0.9.1",
|
||||||
|
"@logtape/logtape": "^2.4.2",
|
||||||
|
"@logtape/otel": "^2.4.2",
|
||||||
|
"@logtape/pretty": "^2.4.2",
|
||||||
|
"@opentelemetry/api": "1.9.0",
|
||||||
|
"@opentelemetry/exporter-metrics-otlp-http": "0.208.0",
|
||||||
|
"@opentelemetry/resources": "2.2.0",
|
||||||
|
"@opentelemetry/sdk-metrics": "2.2.0",
|
||||||
"@prisma/adapter-pg": "^7.10.0",
|
"@prisma/adapter-pg": "^7.10.0",
|
||||||
"@prisma/client": "^7.10.0",
|
"@prisma/client": "^7.10.0",
|
||||||
"@superlist/shared": "workspace:*",
|
"@superlist/shared": "workspace:*",
|
||||||
"better-auth": "^1.7.7",
|
"better-auth": "^1.7.7",
|
||||||
"hono": "^4.13.13",
|
"hono": "^4.13.13",
|
||||||
"pg": "^8.23.1",
|
"pg": "^8.23.1",
|
||||||
"pino": "^10.4.0",
|
|
||||||
"pino-pretty": "^13.2.0",
|
|
||||||
"resend": "^6.32.1",
|
"resend": "^6.32.1",
|
||||||
"zod": "^4.6.7"
|
"zod": "^4.6.7"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "passkeys" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"name" TEXT,
|
||||||
|
"public_key" TEXT NOT NULL,
|
||||||
|
"user_id" TEXT NOT NULL,
|
||||||
|
"credential_id" TEXT NOT NULL,
|
||||||
|
"counter" INTEGER NOT NULL,
|
||||||
|
"device_type" TEXT NOT NULL,
|
||||||
|
"backed_up" BOOLEAN NOT NULL,
|
||||||
|
"transports" TEXT,
|
||||||
|
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"aaguid" TEXT,
|
||||||
|
|
||||||
|
CONSTRAINT "passkeys_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "passkeys_user_id_idx" ON "passkeys"("user_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "passkeys_credential_id_idx" ON "passkeys"("credential_id");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "passkeys" ADD CONSTRAINT "passkeys_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "shopping_list_members" ADD COLUMN "icon" TEXT,
|
||||||
|
ADD COLUMN "is_pinned" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
ADD COLUMN "pinned_order" INTEGER;
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "shopping_list_members_user_id_is_pinned_idx" ON "shopping_list_members"("user_id", "is_pinned");
|
||||||
@@ -34,6 +34,7 @@ model User {
|
|||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
sessions Session[]
|
sessions Session[]
|
||||||
accounts Account[]
|
accounts Account[]
|
||||||
|
passkeys Passkey[]
|
||||||
ownedLists ShoppingList[] @relation("ListOwner")
|
ownedLists ShoppingList[] @relation("ListOwner")
|
||||||
memberships ShoppingListMember[]
|
memberships ShoppingListMember[]
|
||||||
invitations ShoppingListInvitation[] @relation("InvitedBy")
|
invitations ShoppingListInvitation[] @relation("InvitedBy")
|
||||||
@@ -90,6 +91,29 @@ model Verification {
|
|||||||
@@map("verifications")
|
@@map("verifications")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WebAuthn credentials registered through the BetterAuth passkey plugin.
|
||||||
|
// `credentialID` is the raw credential id and `publicKey` the stored public key;
|
||||||
|
// the plugin reads and writes these rows directly, so keep the column names it
|
||||||
|
// expects (mapped to snake_case like the rest of the schema).
|
||||||
|
model Passkey {
|
||||||
|
id String @id
|
||||||
|
name String?
|
||||||
|
publicKey String @map("public_key")
|
||||||
|
userId String @map("user_id")
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
credentialID String @map("credential_id")
|
||||||
|
counter Int
|
||||||
|
deviceType String @map("device_type")
|
||||||
|
backedUp Boolean @map("backed_up")
|
||||||
|
transports String?
|
||||||
|
createdAt DateTime? @default(now()) @map("created_at")
|
||||||
|
aaguid String?
|
||||||
|
|
||||||
|
@@index([userId])
|
||||||
|
@@index([credentialID])
|
||||||
|
@@map("passkeys")
|
||||||
|
}
|
||||||
|
|
||||||
// --- Domain models ----------------------------------------------------------
|
// --- Domain models ----------------------------------------------------------
|
||||||
|
|
||||||
/// A collaborative shopping list. Membership (and therefore access) lives in
|
/// A collaborative shopping list. Membership (and therefore access) lives in
|
||||||
@@ -144,11 +168,18 @@ model ShoppingListMember {
|
|||||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
role ListRole @default(collaborator)
|
role ListRole @default(collaborator)
|
||||||
isPrimary Boolean @default(false) @map("is_primary")
|
isPrimary Boolean @default(false) @map("is_primary")
|
||||||
|
/// Per user: the list is pinned to the always-visible bar (at most 4 per user).
|
||||||
|
isPinned Boolean @default(false) @map("is_pinned")
|
||||||
|
/// Position among the user's pinned lists (pin order); null when not pinned.
|
||||||
|
pinnedOrder Int? @map("pinned_order")
|
||||||
|
/// Per user: key of the icon chosen for the list (see `LIST_ICONS` in `@superlist/shared`).
|
||||||
|
icon String?
|
||||||
createdAt DateTime @default(now()) @map("created_at")
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
@@unique([listId, userId])
|
@@unique([listId, userId])
|
||||||
@@index([userId, isPrimary])
|
@@index([userId, isPrimary])
|
||||||
|
@@index([userId, isPinned])
|
||||||
@@map("shopping_list_members")
|
@@map("shopping_list_members")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,15 +1,21 @@
|
|||||||
|
import { withContext } from '@logtape/logtape'
|
||||||
import { Hono } from 'hono'
|
import { Hono } from 'hono'
|
||||||
import { cors } from 'hono/cors'
|
import { cors } from 'hono/cors'
|
||||||
import { requestId } from 'hono/request-id'
|
import { requestId } from 'hono/request-id'
|
||||||
|
import { routePath } from 'hono/route'
|
||||||
import { secureHeaders } from 'hono/secure-headers'
|
import { secureHeaders } from 'hono/secure-headers'
|
||||||
|
|
||||||
import { auth } from '@/lib/auth'
|
import { auth } from '@/lib/auth'
|
||||||
import { logger } from '@/lib/logger'
|
import { logger } from '@/lib/logger'
|
||||||
|
import { httpMetrics } from '@/lib/metrics'
|
||||||
import { errorHandler, notFoundHandler } from '@/lib/problem-details'
|
import { errorHandler, notFoundHandler } from '@/lib/problem-details'
|
||||||
import { healthModule } from '@/modules/health'
|
import { healthModule } from '@/modules/health'
|
||||||
import { invitationsModule } from '@/modules/invitations'
|
import { invitationsModule } from '@/modules/invitations'
|
||||||
import { listsModule } from '@/modules/lists'
|
import { listsModule } from '@/modules/lists'
|
||||||
import type { AppEnv } from '@/types'
|
import { voiceModule } from '@/modules/voice'
|
||||||
|
import type { AppEnv, SessionUser } from '@/types'
|
||||||
|
|
||||||
|
const httpLogger = logger.getChild('http')
|
||||||
|
|
||||||
const allowedOrigins = (process.env.CORS_ORIGIN ?? 'http://localhost:7153')
|
const allowedOrigins = (process.env.CORS_ORIGIN ?? 'http://localhost:7153')
|
||||||
.split(',')
|
.split(',')
|
||||||
@@ -23,20 +29,53 @@ export function createApp() {
|
|||||||
app.use(cors({ origin: allowedOrigins, credentials: true }))
|
app.use(cors({ origin: allowedOrigins, credentials: true }))
|
||||||
app.use(requestId())
|
app.use(requestId())
|
||||||
app.use(async (c, next) => {
|
app.use(async (c, next) => {
|
||||||
const requestLogger = logger.child({ requestId: c.get('requestId') })
|
const requestId = c.get('requestId')
|
||||||
c.set('logger', requestLogger)
|
c.set('logger', httpLogger.with({ requestId }))
|
||||||
|
|
||||||
|
const http = httpMetrics()
|
||||||
|
const method = c.req.method
|
||||||
|
http.activeRequests.add(1, { 'http.request.method': method })
|
||||||
|
|
||||||
const start = performance.now()
|
const start = performance.now()
|
||||||
await next()
|
try {
|
||||||
requestLogger.info(
|
// Every record logged while the request runs (module loggers included)
|
||||||
{
|
// inherits the requestId through LogTape's implicit context.
|
||||||
method: c.req.method,
|
await withContext({ requestId }, next)
|
||||||
|
} finally {
|
||||||
|
http.activeRequests.add(-1, { 'http.request.method': method })
|
||||||
|
}
|
||||||
|
const elapsedMs = performance.now() - start
|
||||||
|
const durationMs = Math.round(elapsedMs * 10) / 10
|
||||||
|
|
||||||
|
const status = c.res.status
|
||||||
|
const route = routePath(c, -1)
|
||||||
|
// SSE streams (/events) return their Response right away, so for them this is
|
||||||
|
// the time to open the stream, not the lifetime of the connection.
|
||||||
|
http.duration.record(elapsedMs / 1000, {
|
||||||
|
'http.request.method': method,
|
||||||
|
// The Hono pattern (/api/lists/:listId), never the raw path, to keep cardinality low.
|
||||||
|
'http.route': route,
|
||||||
|
'http.response.status_code': status,
|
||||||
|
})
|
||||||
|
|
||||||
|
const userId = (c.get('user') as SessionUser | undefined)?.id
|
||||||
|
const properties = {
|
||||||
|
requestId,
|
||||||
|
method,
|
||||||
path: c.req.path,
|
path: c.req.path,
|
||||||
status: c.res.status,
|
route,
|
||||||
durationMs: Math.round(performance.now() - start),
|
status,
|
||||||
},
|
durationMs,
|
||||||
'request',
|
userAgent: c.req.header('user-agent'),
|
||||||
)
|
...(userId && { userId }),
|
||||||
|
}
|
||||||
|
const message = '{method} {path} {status} in {durationMs} ms'
|
||||||
|
|
||||||
|
if (status >= 500) httpLogger.error(message, properties)
|
||||||
|
else if (status >= 400) httpLogger.warn(message, properties)
|
||||||
|
// The container healthcheck hits /api/health every 10 s.
|
||||||
|
else if (c.req.path === '/api/health') httpLogger.debug(message, properties)
|
||||||
|
else httpLogger.info(message, properties)
|
||||||
})
|
})
|
||||||
|
|
||||||
// Every API route lives under /api: in production nginx serves the SPA on the
|
// Every API route lives under /api: in production nginx serves the SPA on the
|
||||||
@@ -47,6 +86,7 @@ export function createApp() {
|
|||||||
app.route('/api/health', healthModule)
|
app.route('/api/health', healthModule)
|
||||||
app.route('/api/lists', listsModule)
|
app.route('/api/lists', listsModule)
|
||||||
app.route('/api/invitations', invitationsModule)
|
app.route('/api/invitations', invitationsModule)
|
||||||
|
app.route('/api/voice', voiceModule)
|
||||||
|
|
||||||
app.notFound(notFoundHandler)
|
app.notFound(notFoundHandler)
|
||||||
app.onError(errorHandler)
|
app.onError(errorHandler)
|
||||||
|
|||||||
@@ -1,11 +1,25 @@
|
|||||||
|
import { dispose } from '@logtape/logtape'
|
||||||
|
|
||||||
import { createApp } from '@/app'
|
import { createApp } from '@/app'
|
||||||
import { logger } from '@/lib/logger'
|
import { configureLogging, logger } from '@/lib/logger'
|
||||||
|
import { configureMetrics, shutdownMetrics } from '@/lib/metrics'
|
||||||
|
|
||||||
|
await configureLogging()
|
||||||
|
const metricsEnabled = configureMetrics()
|
||||||
|
|
||||||
const port = Number(process.env.PORT ?? 4100)
|
const port = Number(process.env.PORT ?? 4100)
|
||||||
|
|
||||||
const app = createApp()
|
const app = createApp()
|
||||||
|
|
||||||
logger.info({ port }, 'api listening')
|
logger.info('api listening on port {port}', { port, metricsEnabled })
|
||||||
|
|
||||||
|
// Flush buffered logs and the last metrics batch before exiting.
|
||||||
|
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
||||||
|
process.once(signal, async () => {
|
||||||
|
await Promise.allSettled([shutdownMetrics(), dispose()])
|
||||||
|
process.exit(0)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
port,
|
port,
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
|
import { passkey } from '@better-auth/passkey'
|
||||||
import { betterAuth } from 'better-auth'
|
import { betterAuth } from 'better-auth'
|
||||||
import { prismaAdapter } from 'better-auth/adapters/prisma'
|
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 { acceptPendingInvitations, ensurePrimaryList } from '@/lib/list-membership'
|
||||||
|
import { logger } from '@/lib/logger'
|
||||||
|
import { sendEmail } from '@/lib/mailer'
|
||||||
|
import { passkeyConfig } from '@/lib/passkey-config'
|
||||||
import { prisma } from '@/lib/prisma'
|
import { prisma } from '@/lib/prisma'
|
||||||
|
|
||||||
const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
|
const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
|
||||||
@@ -9,6 +15,8 @@ const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
|
|||||||
.map((origin) => origin.trim())
|
.map((origin) => origin.trim())
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
|
|
||||||
|
const OTP_EXPIRES_IN_SECONDS = 10 * 60
|
||||||
|
|
||||||
export const auth = betterAuth({
|
export const auth = betterAuth({
|
||||||
database: prismaAdapter(prisma, { provider: 'postgresql' }),
|
database: prismaAdapter(prisma, { provider: 'postgresql' }),
|
||||||
baseURL: process.env.BETTER_AUTH_URL,
|
baseURL: process.env.BETTER_AUTH_URL,
|
||||||
@@ -27,7 +35,40 @@ export const auth = betterAuth({
|
|||||||
enabled: true,
|
enabled: true,
|
||||||
minPasswordLength: 8,
|
minPasswordLength: 8,
|
||||||
requireEmailVerification: false,
|
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('failed to send the password reset email', { error, to: email })
|
||||||
|
})
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
// Passkeys (Face ID, Touch ID, Windows Hello, security keys). Sign-in is
|
||||||
|
// username-less, so credentials must be discoverable: `residentKey` is
|
||||||
|
// required instead of the plugin's `preferred` default.
|
||||||
|
passkey({
|
||||||
|
...passkeyConfig,
|
||||||
|
authenticatorSelection: {
|
||||||
|
residentKey: 'required',
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
],
|
||||||
databaseHooks: {
|
databaseHooks: {
|
||||||
user: {
|
user: {
|
||||||
create: {
|
create: {
|
||||||
|
|||||||
47
apps/api/src/lib/emails/password-reset.ts
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import type { Email } from '@/lib/mailer'
|
||||||
|
|
||||||
|
type PasswordResetEmailInput = {
|
||||||
|
otp: string
|
||||||
|
expiresInMinutes: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Builds the "your password reset code" email (in Spanish). */
|
||||||
|
export function passwordResetEmail({
|
||||||
|
otp,
|
||||||
|
expiresInMinutes,
|
||||||
|
}: PasswordResetEmailInput): Omit<Email, 'to'> {
|
||||||
|
const subject = `Tu código para restablecer la contraseña: ${otp}`
|
||||||
|
|
||||||
|
const text = [
|
||||||
|
'Recibimos una solicitud para restablecer la contraseña de tu cuenta de Superlist.',
|
||||||
|
'',
|
||||||
|
`Tu código es: ${otp}`,
|
||||||
|
'',
|
||||||
|
`Vence en ${expiresInMinutes} minutos.`,
|
||||||
|
'Si no lo pediste, ignora este correo: tu contraseña no cambiará.',
|
||||||
|
].join('\n')
|
||||||
|
|
||||||
|
const html = `<!doctype html>
|
||||||
|
<html lang="es">
|
||||||
|
<body style="font-family: ui-sans-serif, system-ui, sans-serif; background:#f4f4f5; padding:32px;">
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:480px; margin:0 auto; background:#ffffff; border-radius:12px; padding:32px;">
|
||||||
|
<tr><td>
|
||||||
|
<h1 style="font-size:20px; margin:0 0 16px;">Restablece tu contraseña</h1>
|
||||||
|
<p style="font-size:15px; line-height:1.5; color:#3f3f46; margin:0 0 24px;">
|
||||||
|
Recibimos una solicitud para restablecer la contraseña de tu cuenta de Superlist.
|
||||||
|
Usa este código para elegir una nueva:
|
||||||
|
</p>
|
||||||
|
<p style="font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size:32px; font-weight:700; letter-spacing:8px; text-align:center; background:#f4f4f5; border-radius:8px; padding:16px; margin:0 0 24px; color:#18181b;">
|
||||||
|
${otp}
|
||||||
|
</p>
|
||||||
|
<p style="font-size:13px; line-height:1.5; color:#71717a; margin:0;">
|
||||||
|
El código vence en ${expiresInMinutes} minutos. Si no lo pediste, ignora este correo:
|
||||||
|
tu contraseña no cambiará.
|
||||||
|
</p>
|
||||||
|
</td></tr>
|
||||||
|
</table>
|
||||||
|
</body>
|
||||||
|
</html>`
|
||||||
|
|
||||||
|
return { subject, html, text }
|
||||||
|
}
|
||||||
83
apps/api/src/lib/gemini.ts
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
/**
|
||||||
|
* 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 (retries included).
|
||||||
|
*
|
||||||
|
* Gemma 4 writes out its reasoning before answering, which takes from 5 to over 30
|
||||||
|
* seconds, so the request asks for `thinkingLevel: 'minimal'` (about a second). The API
|
||||||
|
* also answers 5xx now and then, fast; those calls are retried once.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import {
|
||||||
|
type GenerateInput,
|
||||||
|
ModelError,
|
||||||
|
postJson,
|
||||||
|
readTimeout,
|
||||||
|
type TextGenerator,
|
||||||
|
} from './text-generator'
|
||||||
|
|
||||||
|
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) {
|
||||||
|
return {
|
||||||
|
apiKey: env.GEMINI_API_KEY?.trim() || undefined,
|
||||||
|
model: env.GEMINI_MODEL?.trim() || DEFAULT_GEMINI_MODEL,
|
||||||
|
timeoutMs: readTimeout(env.GEMINI_TIMEOUT_MS, DEFAULT_GEMINI_TIMEOUT_MS),
|
||||||
|
} satisfies GeminiConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
type GenerateContentResponse = {
|
||||||
|
candidates?: { content?: { parts?: { text?: string; thought?: boolean }[] } }[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GeminiClient implements TextGenerator {
|
||||||
|
constructor(
|
||||||
|
private readonly config: GeminiConfig = geminiConfigFromEnv(),
|
||||||
|
private readonly fetchFn: typeof fetch = fetch,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** The model's text answer. Throws `ModelError` on any failure. */
|
||||||
|
async generate({ systemInstruction, turns }: GenerateInput): Promise<string> {
|
||||||
|
if (!this.config.apiKey) throw new ModelError('missing-key')
|
||||||
|
|
||||||
|
const body = (await postJson(
|
||||||
|
this.fetchFn,
|
||||||
|
`${GEMINI_API_URL}/${encodeURIComponent(this.config.model)}:generateContent`,
|
||||||
|
{ 'x-goog-api-key': this.config.apiKey },
|
||||||
|
{
|
||||||
|
systemInstruction: { parts: [{ text: systemInstruction }] },
|
||||||
|
contents: turns.map(({ role, text }) => ({ role, parts: [{ text }] })),
|
||||||
|
generationConfig: { temperature: 0, thinkingConfig: { thinkingLevel: 'minimal' } },
|
||||||
|
},
|
||||||
|
this.config.timeoutMs,
|
||||||
|
)) as GenerateContentResponse
|
||||||
|
|
||||||
|
// 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 ModelError('empty-response')
|
||||||
|
|
||||||
|
return text
|
||||||
|
}
|
||||||
|
}
|
||||||
79
apps/api/src/lib/groq.ts
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
/**
|
||||||
|
* Minimal client for Groq's OpenAI-compatible `chat/completions` endpoint, called with
|
||||||
|
* `fetch` — no SDK. Groq answers in about a second, which suits dictation. The model is
|
||||||
|
* a reasoning one (gpt-oss): Groq returns its reasoning apart, so `content` is the answer.
|
||||||
|
*
|
||||||
|
* Configuration (backend only — never prefix these with `VITE_`, or Vite would put the
|
||||||
|
* key in the browser bundle):
|
||||||
|
* - `GROQ_API_KEY`: Groq API key (`gsk_…`). Without it every call fails with `missing-key`.
|
||||||
|
* - `GROQ_MODEL`: model id, `openai/gpt-oss-120b` by default.
|
||||||
|
* - `GROQ_TIMEOUT_MS`: request timeout, 8000 ms by default (retries included).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import {
|
||||||
|
type GenerateInput,
|
||||||
|
ModelError,
|
||||||
|
postJson,
|
||||||
|
readTimeout,
|
||||||
|
type TextGenerator,
|
||||||
|
} from './text-generator'
|
||||||
|
|
||||||
|
const GROQ_API_URL = 'https://api.groq.com/openai/v1/chat/completions'
|
||||||
|
|
||||||
|
export const DEFAULT_GROQ_MODEL = 'openai/gpt-oss-120b'
|
||||||
|
|
||||||
|
export const DEFAULT_GROQ_TIMEOUT_MS = 8000
|
||||||
|
|
||||||
|
export type GroqConfig = {
|
||||||
|
apiKey: string | undefined
|
||||||
|
model: string
|
||||||
|
timeoutMs: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads the configuration from the environment, with the defaults above. */
|
||||||
|
export function groqConfigFromEnv(env: Record<string, string | undefined> = process.env) {
|
||||||
|
return {
|
||||||
|
apiKey: env.GROQ_API_KEY?.trim() || undefined,
|
||||||
|
model: env.GROQ_MODEL?.trim() || DEFAULT_GROQ_MODEL,
|
||||||
|
timeoutMs: readTimeout(env.GROQ_TIMEOUT_MS, DEFAULT_GROQ_TIMEOUT_MS),
|
||||||
|
} satisfies GroqConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
type ChatCompletionResponse = {
|
||||||
|
choices?: { message?: { content?: string | null } }[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GroqClient implements TextGenerator {
|
||||||
|
constructor(
|
||||||
|
private readonly config: GroqConfig = groqConfigFromEnv(),
|
||||||
|
private readonly fetchFn: typeof fetch = fetch,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** The model's text answer. Throws `ModelError` on any failure. */
|
||||||
|
async generate({ systemInstruction, turns }: GenerateInput): Promise<string> {
|
||||||
|
if (!this.config.apiKey) throw new ModelError('missing-key')
|
||||||
|
|
||||||
|
const body = (await postJson(
|
||||||
|
this.fetchFn,
|
||||||
|
GROQ_API_URL,
|
||||||
|
{ authorization: `Bearer ${this.config.apiKey}` },
|
||||||
|
{
|
||||||
|
model: this.config.model,
|
||||||
|
messages: [
|
||||||
|
{ role: 'system', content: systemInstruction },
|
||||||
|
...turns.map(({ role, text }) => ({
|
||||||
|
role: role === 'model' ? 'assistant' : 'user',
|
||||||
|
content: text,
|
||||||
|
})),
|
||||||
|
],
|
||||||
|
temperature: 0,
|
||||||
|
},
|
||||||
|
this.config.timeoutMs,
|
||||||
|
)) as ChatCompletionResponse
|
||||||
|
|
||||||
|
const text = body.choices?.[0]?.message?.content?.trim()
|
||||||
|
if (!text) throw new ModelError('empty-response')
|
||||||
|
|
||||||
|
return text
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,21 +1,99 @@
|
|||||||
import { pino } from 'pino'
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
||||||
|
|
||||||
|
import {
|
||||||
|
configure,
|
||||||
|
getConsoleSink,
|
||||||
|
getLogger,
|
||||||
|
isLogLevel,
|
||||||
|
jsonLinesFormatter,
|
||||||
|
type Logger,
|
||||||
|
type LogLevel,
|
||||||
|
type Sink,
|
||||||
|
} from '@logtape/logtape'
|
||||||
|
import { getOpenTelemetrySink } from '@logtape/otel'
|
||||||
|
import { getPrettyFormatter } from '@logtape/pretty'
|
||||||
|
|
||||||
|
import { getOpenObserveConfig, SERVICE_NAME } from '@/lib/openobserve'
|
||||||
|
|
||||||
|
export type { Logger } from '@logtape/logtape'
|
||||||
|
|
||||||
const isProduction = process.env.NODE_ENV === 'production'
|
const isProduction = process.env.NODE_ENV === 'production'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Single logger instance for the whole API. Import it wherever you need to log —
|
* Root logger of the API (category `superlist`). Import it wherever you need to
|
||||||
* never use `console.log` in the backend.
|
* log — never use `console.log` in the backend. Inside a request, prefer
|
||||||
|
* `c.get('logger')`; either way every record emitted while the request runs
|
||||||
|
* carries its `requestId` (see `withContext` in `app.ts`).
|
||||||
|
*
|
||||||
|
* LogTape loggers are inert until `configureLogging()` runs (from `index.ts`),
|
||||||
|
* so tests that import modules using it stay silent.
|
||||||
*/
|
*/
|
||||||
export const logger = pino({
|
export const logger: Logger = getLogger(['superlist'])
|
||||||
level: process.env.LOG_LEVEL || (isProduction ? 'info' : 'debug'),
|
|
||||||
...(isProduction
|
/** Accepts LogTape levels plus Pino-style aliases (`warn`) for `LOG_LEVEL`. */
|
||||||
? {}
|
function resolveLevel(value: string | undefined): LogLevel {
|
||||||
: {
|
const level = value?.trim().toLowerCase()
|
||||||
transport: {
|
if (level === 'warn') return 'warning'
|
||||||
target: 'pino-pretty',
|
if (level && isLogLevel(level)) return level
|
||||||
options: { colorize: true, translateTime: 'HH:MM:ss', ignore: 'pid,hostname' },
|
|
||||||
|
return isProduction ? 'info' : 'debug'
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ships logs to OpenObserve over OTLP/HTTP (`/api/<org>/v1/logs`), routed to a
|
||||||
|
* stream by the `stream-name` header. Returns `null` when it is not configured.
|
||||||
|
*/
|
||||||
|
function openObserveSink(): Sink | null {
|
||||||
|
const config = getOpenObserveConfig()
|
||||||
|
if (!config) return null
|
||||||
|
|
||||||
|
return getOpenTelemetrySink({
|
||||||
|
serviceName: SERVICE_NAME,
|
||||||
|
// Nested property objects become JSON instead of util.inspect output.
|
||||||
|
objectRenderer: 'json',
|
||||||
|
otlpExporterConfig: {
|
||||||
|
url: `${config.otlpBaseUrl}/v1/logs`,
|
||||||
|
headers: { Authorization: config.authorization, 'stream-name': config.logStream },
|
||||||
},
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configures LogTape once, at startup: console output (pretty in development,
|
||||||
|
* JSON lines in production) plus OpenObserve when `OPENOBSERVE_URL` is set.
|
||||||
|
* Call `dispose()` from `@logtape/logtape` on shutdown to flush pending records.
|
||||||
|
*/
|
||||||
|
export async function configureLogging(): Promise<void> {
|
||||||
|
const consoleSink = getConsoleSink({
|
||||||
|
formatter: isProduction
|
||||||
|
? jsonLinesFormatter
|
||||||
|
: getPrettyFormatter({
|
||||||
|
properties: true,
|
||||||
|
categoryWidth: 16,
|
||||||
|
wordWrap: false,
|
||||||
|
// Interpolate strings bare ("GET /api/lists") instead of quoted.
|
||||||
|
value: 'bare',
|
||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
|
const openObserve = openObserveSink()
|
||||||
|
|
||||||
export type Logger = typeof logger
|
const sinks: Record<string, Sink> = { console: consoleSink }
|
||||||
|
if (openObserve) sinks.openObserve = openObserve
|
||||||
|
|
||||||
|
await configure({
|
||||||
|
sinks,
|
||||||
|
contextLocalStorage: new AsyncLocalStorage(),
|
||||||
|
loggers: [
|
||||||
|
{
|
||||||
|
category: ['superlist'],
|
||||||
|
sinks: Object.keys(sinks),
|
||||||
|
lowestLevel: resolveLevel(process.env.LOG_LEVEL),
|
||||||
|
},
|
||||||
|
{ category: ['logtape', 'meta'], sinks: ['console'], lowestLevel: 'warning' },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
if (openObserve) {
|
||||||
|
logger.info('shipping logs to OpenObserve at {url}', { url: process.env.OPENOBSERVE_URL })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -24,17 +24,18 @@ function getClient(): Resend | null {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Sends an email through Resend. Without `RESEND_API_KEY` (local development)
|
* Sends an email through Resend. Without `RESEND_API_KEY` (local development)
|
||||||
* it logs the message with Pino instead of sending it, so invitation links are
|
* it logs the message instead of sending it, so invitation links are
|
||||||
* still discoverable in the terminal.
|
* still discoverable in the terminal.
|
||||||
*/
|
*/
|
||||||
export async function sendEmail(email: Email): Promise<void> {
|
export async function sendEmail(email: Email): Promise<void> {
|
||||||
const resend = getClient()
|
const resend = getClient()
|
||||||
|
|
||||||
if (!resend) {
|
if (!resend) {
|
||||||
logger.info(
|
logger.info('email not sent (RESEND_API_KEY is not set) — logging payload instead', {
|
||||||
{ to: email.to, subject: email.subject, text: email.text },
|
to: email.to,
|
||||||
'email not sent (RESEND_API_KEY is not set) — logging payload instead',
|
subject: email.subject,
|
||||||
)
|
text: email.text,
|
||||||
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
92
apps/api/src/lib/metrics.ts
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
import { type Histogram, metrics, type UpDownCounter } from '@opentelemetry/api'
|
||||||
|
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'
|
||||||
|
import { resourceFromAttributes } from '@opentelemetry/resources'
|
||||||
|
import {
|
||||||
|
AggregationTemporality,
|
||||||
|
AggregationType,
|
||||||
|
MeterProvider,
|
||||||
|
PeriodicExportingMetricReader,
|
||||||
|
} from '@opentelemetry/sdk-metrics'
|
||||||
|
|
||||||
|
import { getOpenObserveConfig, SERVICE_NAME } from '@/lib/openobserve'
|
||||||
|
|
||||||
|
const DEFAULT_EXPORT_INTERVAL_MS = 15_000
|
||||||
|
|
||||||
|
/** Bucket bounds (seconds) of the request duration histogram: 5 ms … 10 s. */
|
||||||
|
const DURATION_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
|
||||||
|
|
||||||
|
let provider: MeterProvider | null = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts exporting metrics to OpenObserve (`/api/<org>/v1/metrics`) every
|
||||||
|
* `METRICS_EXPORT_INTERVAL_MS` (15 s by default). Without `OPENOBSERVE_URL` the
|
||||||
|
* global meter stays a no-op, so instruments cost nothing in tests or locally.
|
||||||
|
*/
|
||||||
|
export function configureMetrics(): boolean {
|
||||||
|
const config = getOpenObserveConfig()
|
||||||
|
if (!config) return false
|
||||||
|
|
||||||
|
const exporter = new OTLPMetricExporter({
|
||||||
|
url: `${config.otlpBaseUrl}/v1/metrics`,
|
||||||
|
headers: { Authorization: config.authorization },
|
||||||
|
// Cumulative is what OpenObserve's PromQL (rate, histogram_quantile) expects.
|
||||||
|
temporalityPreference: AggregationTemporality.CUMULATIVE,
|
||||||
|
})
|
||||||
|
|
||||||
|
provider = new MeterProvider({
|
||||||
|
resource: resourceFromAttributes({ 'service.name': SERVICE_NAME }),
|
||||||
|
views: [
|
||||||
|
{
|
||||||
|
instrumentName: 'http.server.request.duration',
|
||||||
|
aggregation: {
|
||||||
|
type: AggregationType.EXPLICIT_BUCKET_HISTOGRAM,
|
||||||
|
options: { boundaries: DURATION_BUCKETS },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
readers: [
|
||||||
|
new PeriodicExportingMetricReader({
|
||||||
|
exporter,
|
||||||
|
exportIntervalMillis:
|
||||||
|
Number(process.env.METRICS_EXPORT_INTERVAL_MS) || DEFAULT_EXPORT_INTERVAL_MS,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
})
|
||||||
|
metrics.setGlobalMeterProvider(provider)
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Flushes the last batch and stops the exporter (call on shutdown). */
|
||||||
|
export async function shutdownMetrics(): Promise<void> {
|
||||||
|
await provider?.shutdown()
|
||||||
|
}
|
||||||
|
|
||||||
|
type HttpInstruments = {
|
||||||
|
duration: Histogram
|
||||||
|
activeRequests: UpDownCounter
|
||||||
|
}
|
||||||
|
|
||||||
|
let http: HttpInstruments | null = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTP server instruments, following the OpenTelemetry semantic conventions.
|
||||||
|
* Created lazily so they bind to the provider set by `configureMetrics()`.
|
||||||
|
*/
|
||||||
|
export function httpMetrics(): HttpInstruments {
|
||||||
|
if (!http) {
|
||||||
|
const meter = metrics.getMeter(SERVICE_NAME)
|
||||||
|
http = {
|
||||||
|
duration: meter.createHistogram('http.server.request.duration', {
|
||||||
|
description: 'Duration of HTTP server requests.',
|
||||||
|
unit: 's',
|
||||||
|
}),
|
||||||
|
activeRequests: meter.createUpDownCounter('http.server.active_requests', {
|
||||||
|
description: 'Number of HTTP server requests in flight.',
|
||||||
|
unit: '{request}',
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return http
|
||||||
|
}
|
||||||
17
apps/api/src/lib/model.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { GeminiClient, geminiConfigFromEnv } from './gemini'
|
||||||
|
import { GroqClient, groqConfigFromEnv } from './groq'
|
||||||
|
import type { TextGenerator } from './text-generator'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The model the API asks: Groq when `GROQ_API_KEY` is set (fast and steady), Gemini /
|
||||||
|
* Gemma otherwise. Without any key the Gemini client fails with `missing-key` and
|
||||||
|
* callers fall back to their own non-AI path.
|
||||||
|
*/
|
||||||
|
export function createTextGenerator(
|
||||||
|
env: Record<string, string | undefined> = process.env,
|
||||||
|
): TextGenerator {
|
||||||
|
const groq = groqConfigFromEnv(env)
|
||||||
|
if (groq.apiKey) return new GroqClient(groq)
|
||||||
|
|
||||||
|
return new GeminiClient(geminiConfigFromEnv(env))
|
||||||
|
}
|
||||||
30
apps/api/src/lib/openobserve.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
/** Service name reported to OpenObserve for logs and metrics. */
|
||||||
|
export const SERVICE_NAME = 'superlist-api'
|
||||||
|
|
||||||
|
export type OpenObserveConfig = {
|
||||||
|
/** Base of the OTLP/HTTP endpoints: `<OPENOBSERVE_URL>/api/<org>` (append `/v1/logs`, `/v1/metrics`). */
|
||||||
|
otlpBaseUrl: string
|
||||||
|
/** Basic auth (user email + password) for every OTLP request. */
|
||||||
|
authorization: string
|
||||||
|
/** Stream that receives the logs (`stream-name` header); metrics get one stream per metric. */
|
||||||
|
logStream: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads the OpenObserve settings from the environment, or `null` when
|
||||||
|
* `OPENOBSERVE_URL` is not set (logs and metrics then stay local).
|
||||||
|
*/
|
||||||
|
export function getOpenObserveConfig(): OpenObserveConfig | null {
|
||||||
|
const baseUrl = process.env.OPENOBSERVE_URL?.trim().replace(/\/+$/, '')
|
||||||
|
if (!baseUrl) return null
|
||||||
|
|
||||||
|
const org = process.env.OPENOBSERVE_ORG || 'default'
|
||||||
|
const user = process.env.OPENOBSERVE_USER ?? ''
|
||||||
|
const password = process.env.OPENOBSERVE_PASSWORD ?? ''
|
||||||
|
|
||||||
|
return {
|
||||||
|
otlpBaseUrl: `${baseUrl}/api/${org}`,
|
||||||
|
authorization: `Basic ${btoa(`${user}:${password}`)}`,
|
||||||
|
logStream: process.env.OPENOBSERVE_STREAM || 'superlist',
|
||||||
|
}
|
||||||
|
}
|
||||||
37
apps/api/src/lib/passkey-config.test.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { describe, expect, test } from 'bun:test'
|
||||||
|
|
||||||
|
import { passkeyOrigins } from './passkey-config'
|
||||||
|
|
||||||
|
describe('passkeyOrigins', () => {
|
||||||
|
test('keeps the development port in the origin but not in the RP ID', () => {
|
||||||
|
expect(passkeyOrigins('http://localhost:7153')).toEqual({
|
||||||
|
origin: 'http://localhost:7153',
|
||||||
|
rpID: 'localhost',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('normalises trailing slashes and paths to a bare origin', () => {
|
||||||
|
expect(passkeyOrigins('https://superlist.app/')).toEqual({
|
||||||
|
origin: 'https://superlist.app',
|
||||||
|
rpID: 'superlist.app',
|
||||||
|
})
|
||||||
|
expect(passkeyOrigins('https://superlist.app/settings')).toEqual({
|
||||||
|
origin: 'https://superlist.app',
|
||||||
|
rpID: 'superlist.app',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('uses a subdomain as the RP ID', () => {
|
||||||
|
expect(passkeyOrigins('https://app.superlist.app')).toEqual({
|
||||||
|
origin: 'https://app.superlist.app',
|
||||||
|
rpID: 'app.superlist.app',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('falls back to localhost when the URL is invalid', () => {
|
||||||
|
expect(passkeyOrigins('not a url')).toEqual({
|
||||||
|
origin: 'http://localhost:7153',
|
||||||
|
rpID: 'localhost',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
30
apps/api/src/lib/passkey-config.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import { webAppUrl } from '@/lib/web-app-url'
|
||||||
|
|
||||||
|
const FALLBACK_ORIGIN = 'http://localhost:7153'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WebAuthn ceremonies happen in the browser, so the relying party is the public
|
||||||
|
* web origin, not the API one: in development the web runs on :7153 while the
|
||||||
|
* API listens on :4100. `WEB_APP_URL` is already the canonical public URL of
|
||||||
|
* the frontend (used for invitation links), so derive both values from it.
|
||||||
|
*
|
||||||
|
* The RP ID must be a registrable suffix of the origin and cannot include the
|
||||||
|
* port; `new URL().hostname` does the right thing for both `localhost` and a
|
||||||
|
* production domain.
|
||||||
|
*/
|
||||||
|
export function passkeyOrigins(webUrl: string) {
|
||||||
|
let origin: string
|
||||||
|
|
||||||
|
try {
|
||||||
|
origin = new URL(webUrl).origin
|
||||||
|
} catch {
|
||||||
|
origin = FALLBACK_ORIGIN
|
||||||
|
}
|
||||||
|
|
||||||
|
return { origin, rpID: new URL(origin).hostname }
|
||||||
|
}
|
||||||
|
|
||||||
|
export const passkeyConfig = {
|
||||||
|
...passkeyOrigins(webAppUrl),
|
||||||
|
rpName: 'Superlist',
|
||||||
|
}
|
||||||
@@ -25,7 +25,7 @@ export function errorHandler(error: Error, c: Context) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.error({ err: error, path: c.req.path }, 'unhandled error')
|
logger.error('unhandled error on {path}', { error, path: c.req.path })
|
||||||
|
|
||||||
return problemResponse(
|
return problemResponse(
|
||||||
c,
|
c,
|
||||||
|
|||||||
89
apps/api/src/lib/text-generator.ts
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
/**
|
||||||
|
* What every model client shares: the prompt shape, the `TextGenerator` contract and the
|
||||||
|
* HTTP call with its deadline, retry and error reasons. The clients themselves
|
||||||
|
* (`gemini.ts`, `groq.ts`) only build the request body and read the answer.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Attempts per call when the API answers 5xx (those fail fast and often pass on retry). */
|
||||||
|
const MAX_ATTEMPTS = 2
|
||||||
|
|
||||||
|
/** One turn of the conversation: `user` for the input, `model` for an example answer. */
|
||||||
|
export type ModelTurn = { role: 'user' | 'model'; text: string }
|
||||||
|
|
||||||
|
export type GenerateInput = {
|
||||||
|
systemInstruction: string
|
||||||
|
turns: ModelTurn[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Something that answers a prompt with text: a model client, or a fake in tests. */
|
||||||
|
export type TextGenerator = { generate(input: GenerateInput): Promise<string> }
|
||||||
|
|
||||||
|
/** Why a call failed, short enough to log (it never includes the prompt). */
|
||||||
|
export type ModelFailureReason =
|
||||||
|
| 'missing-key'
|
||||||
|
| 'timeout'
|
||||||
|
| 'rate-limited'
|
||||||
|
| `http-${number}`
|
||||||
|
| 'network'
|
||||||
|
| 'empty-response'
|
||||||
|
|
||||||
|
export class ModelError extends Error {
|
||||||
|
constructor(readonly reason: ModelFailureReason) {
|
||||||
|
super(`Model request failed: ${reason}`)
|
||||||
|
this.name = 'ModelError'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads a positive number of milliseconds, or `fallback` when it is missing or invalid. */
|
||||||
|
export function readTimeout(value: string | undefined, fallback: number): number {
|
||||||
|
const timeout = Number.parseInt(value ?? '', 10)
|
||||||
|
|
||||||
|
return Number.isFinite(timeout) && timeout > 0 ? timeout : fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
function isAbort(error: unknown): boolean {
|
||||||
|
const name = error instanceof Error ? error.name : ''
|
||||||
|
|
||||||
|
return name === 'TimeoutError' || name === 'AbortError'
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POSTs `body` as JSON and returns the parsed answer. A 5xx is retried once, all attempts
|
||||||
|
* within one `timeoutMs` deadline so a retry never makes the user wait longer. Throws
|
||||||
|
* `ModelError` on any failure.
|
||||||
|
*/
|
||||||
|
export async function postJson(
|
||||||
|
fetchFn: typeof fetch,
|
||||||
|
url: string,
|
||||||
|
headers: Record<string, string>,
|
||||||
|
body: unknown,
|
||||||
|
timeoutMs: number,
|
||||||
|
): Promise<unknown> {
|
||||||
|
const init = {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json', ...headers },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
signal: AbortSignal.timeout(timeoutMs),
|
||||||
|
}
|
||||||
|
|
||||||
|
let response: Response | undefined
|
||||||
|
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
||||||
|
try {
|
||||||
|
response = await fetchFn(url, init)
|
||||||
|
} catch (error) {
|
||||||
|
throw new ModelError(isAbort(error) ? 'timeout' : 'network')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.status < 500) break
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response) throw new ModelError('network')
|
||||||
|
if (response.status === 429) throw new ModelError('rate-limited')
|
||||||
|
if (!response.ok) throw new ModelError(`http-${response.status}`)
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await response.json()
|
||||||
|
} catch (error) {
|
||||||
|
throw new ModelError(isAbort(error) ? 'timeout' : 'empty-response')
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -137,7 +137,7 @@ export class CreateInvitation {
|
|||||||
|
|
||||||
// Best effort: the person already sees the list, so a mail failure is not fatal.
|
// Best effort: the person already sees the list, so a mail failure is not fatal.
|
||||||
await this.mailer(message).catch((error: unknown) => {
|
await this.mailer(message).catch((error: unknown) => {
|
||||||
logger.warn({ err: error, to: email }, 'could not send the invitation email')
|
logger.warn('could not send the invitation email', { error, to: email })
|
||||||
})
|
})
|
||||||
|
|
||||||
return Ok({ status: 'added', email })
|
return Ok({ status: 'added', email })
|
||||||
@@ -148,7 +148,7 @@ export class CreateInvitation {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Without the email the invitee cannot know about the list: undo everything.
|
// Without the email the invitee cannot know about the list: undo everything.
|
||||||
await this.db.shoppingListInvitation.delete({ where: { id: invitation.id } })
|
await this.db.shoppingListInvitation.delete({ where: { id: invitation.id } })
|
||||||
logger.error({ err: error, to: email }, 'failed to send the invitation email')
|
logger.error('failed to send the invitation email', { error, to: email })
|
||||||
|
|
||||||
return Failure(
|
return Failure(
|
||||||
problems.unavailable('No pudimos enviar la invitación por correo. Inténtalo de nuevo.'),
|
problems.unavailable('No pudimos enviar la invitación por correo. Inténtalo de nuevo.'),
|
||||||
|
|||||||
@@ -33,12 +33,14 @@ function createDb({
|
|||||||
name: input.data.name,
|
name: input.data.name,
|
||||||
createdAt: new Date('2026-10-15T00:00:00.000Z'),
|
createdAt: new Date('2026-10-15T00:00:00.000Z'),
|
||||||
updatedAt: new Date('2026-10-15T00:00:00.000Z'),
|
updatedAt: new Date('2026-10-15T00:00:00.000Z'),
|
||||||
_count: { members: membershipsOnCreate },
|
_count: { members: membershipsOnCreate, items: 0 },
|
||||||
members: [
|
members: [
|
||||||
{
|
{
|
||||||
id: 'member-1',
|
id: 'member-1',
|
||||||
role: 'owner',
|
role: 'owner',
|
||||||
isPrimary: input.data.members.create.isPrimary,
|
isPrimary: input.data.members.create.isPrimary,
|
||||||
|
isPinned: false,
|
||||||
|
icon: null,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
@@ -65,6 +67,9 @@ describe('CreateShoppingList', () => {
|
|||||||
name: 'Compra semanal',
|
name: 'Compra semanal',
|
||||||
role: 'owner',
|
role: 'owner',
|
||||||
isPrimary: true,
|
isPrimary: true,
|
||||||
|
isPinned: false,
|
||||||
|
icon: null,
|
||||||
|
pendingCount: 0,
|
||||||
memberCount: 1,
|
memberCount: 1,
|
||||||
createdAt: '2026-10-15T00:00:00.000Z',
|
createdAt: '2026-10-15T00:00:00.000Z',
|
||||||
updatedAt: '2026-10-15T00:00:00.000Z',
|
updatedAt: '2026-10-15T00:00:00.000Z',
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { Ok, type ProblemDetails, type Result, type ShoppingListSummary } from '
|
|||||||
|
|
||||||
import type { Database } from '@/lib/prisma'
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
import { toSummary } from '../serialize'
|
import { summaryCountInclude, toSummary } from '../serialize'
|
||||||
|
|
||||||
/** Creates a shopping list owned by the user. The first list becomes primary. */
|
/** Creates a shopping list owned by the user. The first list becomes primary. */
|
||||||
export class CreateShoppingList {
|
export class CreateShoppingList {
|
||||||
@@ -29,7 +29,7 @@ export class CreateShoppingList {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
include: {
|
include: {
|
||||||
_count: { select: { members: true } },
|
...summaryCountInclude,
|
||||||
members: { where: { userId: input.userId } },
|
members: { where: { userId: input.userId } },
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -44,6 +44,8 @@ export class CreateShoppingList {
|
|||||||
toSummary({
|
toSummary({
|
||||||
role: membership.role,
|
role: membership.role,
|
||||||
isPrimary: membership.isPrimary,
|
isPrimary: membership.isPrimary,
|
||||||
|
isPinned: membership.isPinned,
|
||||||
|
icon: membership.icon,
|
||||||
list: {
|
list: {
|
||||||
id: list.id,
|
id: list.id,
|
||||||
name: list.name,
|
name: list.name,
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { listEventsRoute } from './events/route'
|
|||||||
import { getListRoute } from './get/route'
|
import { getListRoute } from './get/route'
|
||||||
import { listItemsModule } from './items'
|
import { listItemsModule } from './items'
|
||||||
import { listListsRoute } from './list/route'
|
import { listListsRoute } from './list/route'
|
||||||
|
import { updateListPreferencesRoute } from './preferences/route'
|
||||||
import { setPrimaryListRoute } from './set-primary/route'
|
import { setPrimaryListRoute } from './set-primary/route'
|
||||||
import { updateListRoute } from './update/route'
|
import { updateListRoute } from './update/route'
|
||||||
|
|
||||||
@@ -17,5 +18,6 @@ export const listsModule = new Hono<AppEnv>()
|
|||||||
.route('/', getListRoute)
|
.route('/', getListRoute)
|
||||||
.route('/', updateListRoute)
|
.route('/', updateListRoute)
|
||||||
.route('/', setPrimaryListRoute)
|
.route('/', setPrimaryListRoute)
|
||||||
|
.route('/', updateListPreferencesRoute)
|
||||||
.route('/:listId/items', listItemsModule)
|
.route('/:listId/items', listItemsModule)
|
||||||
.route('/:listId/events', listEventsRoute)
|
.route('/:listId/events', listEventsRoute)
|
||||||
|
|||||||
27
apps/api/src/modules/lists/items/delete/route.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import { requireSession } from '@/lib/auth-session'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { resultJson } from '@/lib/result-json'
|
||||||
|
import { validate } from '@/lib/validate'
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { ItemParamsSchema } from '../update/schema'
|
||||||
|
import { DeleteItem } from './use-case'
|
||||||
|
|
||||||
|
/** DELETE /lists/:listId/items/:itemId — deletes an item from a list the user belongs to. */
|
||||||
|
export const deleteItemRoute = new Hono<AppEnv>().delete(
|
||||||
|
'/:itemId',
|
||||||
|
requireSession,
|
||||||
|
validate.param(ItemParamsSchema),
|
||||||
|
async (c) => {
|
||||||
|
const { listId, itemId } = c.req.valid('param')
|
||||||
|
const result = await new DeleteItem(prisma).execute({
|
||||||
|
listId,
|
||||||
|
itemId,
|
||||||
|
userId: c.get('user').id,
|
||||||
|
})
|
||||||
|
|
||||||
|
return resultJson(c, result, { status: 204 })
|
||||||
|
},
|
||||||
|
)
|
||||||
75
apps/api/src/modules/lists/items/delete/use-case.test.ts
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
import { describe, expect, it } from 'bun:test'
|
||||||
|
import type { ListEvent } from '@superlist/shared'
|
||||||
|
|
||||||
|
import { ListEvents } from '@/lib/events'
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
import { DeleteItem } from './use-case'
|
||||||
|
|
||||||
|
function createDb(options: { membership: unknown; item: { id: string } | null }) {
|
||||||
|
const deletes: unknown[] = []
|
||||||
|
|
||||||
|
const db = {
|
||||||
|
shoppingListMember: {
|
||||||
|
findUnique: async () => options.membership,
|
||||||
|
},
|
||||||
|
listItem: {
|
||||||
|
findFirst: async () => options.item,
|
||||||
|
delete: async (args: unknown) => {
|
||||||
|
deletes.push(args)
|
||||||
|
return options.item
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
return { db: db as unknown as Database, deletes }
|
||||||
|
}
|
||||||
|
|
||||||
|
function createBus() {
|
||||||
|
const events = new ListEvents()
|
||||||
|
const published: ListEvent[] = []
|
||||||
|
events.subscribe('list-1', (event) => published.push(event))
|
||||||
|
|
||||||
|
return { events, published }
|
||||||
|
}
|
||||||
|
|
||||||
|
const input = { listId: 'list-1', itemId: 'item-1', userId: 'user-1' }
|
||||||
|
|
||||||
|
describe('DeleteItem', () => {
|
||||||
|
it('answers 404 when the user does not belong to the list', async () => {
|
||||||
|
const { db, deletes } = createDb({ membership: null, item: { id: 'item-1' } })
|
||||||
|
const { events, published } = createBus()
|
||||||
|
const result = await new DeleteItem(db, events).execute(input)
|
||||||
|
|
||||||
|
expect(result.ok).toBe(false)
|
||||||
|
if (result.ok) throw new Error('expected the use case to fail')
|
||||||
|
expect(result.error.status).toBe(404)
|
||||||
|
expect(deletes).toHaveLength(0)
|
||||||
|
expect(published).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('answers 404 when the item does not belong to the list', async () => {
|
||||||
|
const { db, deletes } = createDb({ membership: { role: 'owner' }, item: null })
|
||||||
|
const { events, published } = createBus()
|
||||||
|
const result = await new DeleteItem(db, events).execute(input)
|
||||||
|
|
||||||
|
expect(result.ok).toBe(false)
|
||||||
|
if (result.ok) throw new Error('expected the use case to fail')
|
||||||
|
expect(result.error.status).toBe(404)
|
||||||
|
expect(deletes).toHaveLength(0)
|
||||||
|
expect(published).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('deletes the item and publishes item.removed', async () => {
|
||||||
|
const { db, deletes } = createDb({
|
||||||
|
membership: { role: 'collaborator' },
|
||||||
|
item: { id: 'item-1' },
|
||||||
|
})
|
||||||
|
const { events, published } = createBus()
|
||||||
|
const result = await new DeleteItem(db, events).execute(input)
|
||||||
|
|
||||||
|
expect(result.ok).toBe(true)
|
||||||
|
expect(deletes).toEqual([{ where: { id: 'item-1' } }])
|
||||||
|
expect(published).toEqual([{ type: 'item.removed', listId: 'list-1', itemId: 'item-1' }])
|
||||||
|
})
|
||||||
|
})
|
||||||
42
apps/api/src/modules/lists/items/delete/use-case.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import { Failure, Ok, type ProblemDetails, problems, type Result } from '@superlist/shared'
|
||||||
|
|
||||||
|
import { type ListEvents, listEvents } from '@/lib/events'
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
type DeleteItemFields = {
|
||||||
|
listId: string
|
||||||
|
itemId: string
|
||||||
|
userId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Deletes an item from a list. Only members can do it. */
|
||||||
|
export class DeleteItem {
|
||||||
|
constructor(
|
||||||
|
private readonly db: Database,
|
||||||
|
private readonly events: ListEvents = listEvents,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async execute(input: DeleteItemFields): Promise<Result<void, ProblemDetails>> {
|
||||||
|
const membership = await this.db.shoppingListMember.findUnique({
|
||||||
|
where: { listId_userId: { listId: input.listId, userId: input.userId } },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!membership) {
|
||||||
|
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const item = await this.db.listItem.findFirst({
|
||||||
|
where: { id: input.itemId, shoppingListId: input.listId },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!item) {
|
||||||
|
return Failure(problems.notFound('El artículo no existe en esta lista.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.db.listItem.delete({ where: { id: item.id } })
|
||||||
|
|
||||||
|
this.events.publish({ type: 'item.removed', listId: input.listId, itemId: item.id })
|
||||||
|
|
||||||
|
return Ok(undefined)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,7 +3,9 @@ import { Hono } from 'hono'
|
|||||||
import type { AppEnv } from '@/types'
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
import { createItemRoute } from './create/route'
|
import { createItemRoute } from './create/route'
|
||||||
|
import { deleteItemRoute } from './delete/route'
|
||||||
import { listItemsRoute } from './list/route'
|
import { listItemsRoute } from './list/route'
|
||||||
|
import { moveItemRoute } from './move/route'
|
||||||
import { updateItemRoute } from './update/route'
|
import { updateItemRoute } from './update/route'
|
||||||
|
|
||||||
/** `items` sub-module of `lists`: mounted at `/lists/:listId/items`. */
|
/** `items` sub-module of `lists`: mounted at `/lists/:listId/items`. */
|
||||||
@@ -11,3 +13,5 @@ export const listItemsModule = new Hono<AppEnv>()
|
|||||||
.route('/', listItemsRoute)
|
.route('/', listItemsRoute)
|
||||||
.route('/', createItemRoute)
|
.route('/', createItemRoute)
|
||||||
.route('/', updateItemRoute)
|
.route('/', updateItemRoute)
|
||||||
|
.route('/', moveItemRoute)
|
||||||
|
.route('/', deleteItemRoute)
|
||||||
|
|||||||
31
apps/api/src/modules/lists/items/move/route.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import { requireSession } from '@/lib/auth-session'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { resultJson } from '@/lib/result-json'
|
||||||
|
import { validate } from '@/lib/validate'
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { ItemParamsSchema } from '../update/schema'
|
||||||
|
import { MoveItemSchema } from './schema'
|
||||||
|
import { MoveItem } from './use-case'
|
||||||
|
|
||||||
|
/** POST /lists/:listId/items/:itemId/move — moves an item to another list of the user. */
|
||||||
|
export const moveItemRoute = new Hono<AppEnv>().post(
|
||||||
|
'/:itemId/move',
|
||||||
|
requireSession,
|
||||||
|
validate.param(ItemParamsSchema),
|
||||||
|
validate.json(MoveItemSchema),
|
||||||
|
async (c) => {
|
||||||
|
const { listId, itemId } = c.req.valid('param')
|
||||||
|
const { targetListId } = c.req.valid('json')
|
||||||
|
const result = await new MoveItem(prisma).execute({
|
||||||
|
listId,
|
||||||
|
itemId,
|
||||||
|
userId: c.get('user').id,
|
||||||
|
targetListId,
|
||||||
|
})
|
||||||
|
|
||||||
|
return resultJson(c, result)
|
||||||
|
},
|
||||||
|
)
|
||||||
8
apps/api/src/modules/lists/items/move/schema.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
/** Body of `POST /lists/:listId/items/:itemId/move`. */
|
||||||
|
export const MoveItemSchema = z.object({
|
||||||
|
targetListId: z.uuid('El identificador de la lista de destino no es válido'),
|
||||||
|
})
|
||||||
|
|
||||||
|
export type MoveItemInput = z.infer<typeof MoveItemSchema>
|
||||||
141
apps/api/src/modules/lists/items/move/use-case.test.ts
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
import { describe, expect, it } from 'bun:test'
|
||||||
|
import type { ListEvent } from '@superlist/shared'
|
||||||
|
|
||||||
|
import { ListEvents } from '@/lib/events'
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
import { MoveItem } from './use-case'
|
||||||
|
|
||||||
|
type ItemRow = {
|
||||||
|
id: string
|
||||||
|
shoppingListId: string
|
||||||
|
name: string
|
||||||
|
completed: boolean
|
||||||
|
boughtAt: Date | null
|
||||||
|
quantity: string | null
|
||||||
|
notes: string | null
|
||||||
|
order: number
|
||||||
|
createdAt: Date
|
||||||
|
updatedAt: Date
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date('2026-10-20T10:00:00.000Z')
|
||||||
|
|
||||||
|
const item: ItemRow = {
|
||||||
|
id: 'item-1',
|
||||||
|
shoppingListId: 'list-1',
|
||||||
|
name: 'Leche',
|
||||||
|
completed: false,
|
||||||
|
boughtAt: null,
|
||||||
|
quantity: '1 L',
|
||||||
|
notes: 'sin lactosa',
|
||||||
|
order: 0,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
}
|
||||||
|
|
||||||
|
function createDb(options: { memberOf: string[]; item: ItemRow | null }) {
|
||||||
|
const updates: unknown[] = []
|
||||||
|
|
||||||
|
const db = {
|
||||||
|
shoppingListMember: {
|
||||||
|
findUnique: async (args: { where: { listId_userId: { listId: string } } }) =>
|
||||||
|
options.memberOf.includes(args.where.listId_userId.listId) ? { role: 'owner' } : null,
|
||||||
|
},
|
||||||
|
listItem: {
|
||||||
|
findFirst: async () => options.item,
|
||||||
|
update: async (args: { data: Partial<ItemRow> }) => {
|
||||||
|
updates.push(args)
|
||||||
|
return { ...options.item, ...args.data } as ItemRow
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
return { db: db as unknown as Database, updates }
|
||||||
|
}
|
||||||
|
|
||||||
|
function createBus() {
|
||||||
|
const events = new ListEvents()
|
||||||
|
const published: ListEvent[] = []
|
||||||
|
events.subscribe('list-1', (event) => published.push(event))
|
||||||
|
events.subscribe('list-2', (event) => published.push(event))
|
||||||
|
|
||||||
|
return { events, published }
|
||||||
|
}
|
||||||
|
|
||||||
|
const input = { listId: 'list-1', itemId: 'item-1', userId: 'user-1', targetListId: 'list-2' }
|
||||||
|
|
||||||
|
describe('MoveItem', () => {
|
||||||
|
it('answers 400 when the target is the same list', async () => {
|
||||||
|
const { db, updates } = createDb({ memberOf: ['list-1'], item })
|
||||||
|
const { events, published } = createBus()
|
||||||
|
const result = await new MoveItem(db, events).execute({ ...input, targetListId: 'list-1' })
|
||||||
|
|
||||||
|
expect(result.ok).toBe(false)
|
||||||
|
if (result.ok) throw new Error('expected the use case to fail')
|
||||||
|
expect(result.error.status).toBe(400)
|
||||||
|
expect(updates).toHaveLength(0)
|
||||||
|
expect(published).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('answers 404 when the user does not belong to the source list', async () => {
|
||||||
|
const { db, updates } = createDb({ memberOf: ['list-2'], item })
|
||||||
|
const { events, published } = createBus()
|
||||||
|
const result = await new MoveItem(db, events).execute(input)
|
||||||
|
|
||||||
|
expect(result.ok).toBe(false)
|
||||||
|
if (result.ok) throw new Error('expected the use case to fail')
|
||||||
|
expect(result.error.status).toBe(404)
|
||||||
|
expect(updates).toHaveLength(0)
|
||||||
|
expect(published).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('answers 404 when the user does not belong to the target list', async () => {
|
||||||
|
const { db, updates } = createDb({ memberOf: ['list-1'], item })
|
||||||
|
const { events, published } = createBus()
|
||||||
|
const result = await new MoveItem(db, events).execute(input)
|
||||||
|
|
||||||
|
expect(result.ok).toBe(false)
|
||||||
|
if (result.ok) throw new Error('expected the use case to fail')
|
||||||
|
expect(result.error.status).toBe(404)
|
||||||
|
expect(result.error.detail).toBe('La lista de destino no existe o no tienes acceso.')
|
||||||
|
expect(updates).toHaveLength(0)
|
||||||
|
expect(published).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('answers 404 when the item does not belong to the source list', async () => {
|
||||||
|
const { db, updates } = createDb({ memberOf: ['list-1', 'list-2'], item: null })
|
||||||
|
const { events, published } = createBus()
|
||||||
|
const result = await new MoveItem(db, events).execute(input)
|
||||||
|
|
||||||
|
expect(result.ok).toBe(false)
|
||||||
|
if (result.ok) throw new Error('expected the use case to fail')
|
||||||
|
expect(result.error.status).toBe(404)
|
||||||
|
expect(updates).toHaveLength(0)
|
||||||
|
expect(published).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('moves the item, keeping its details, and notifies both lists', async () => {
|
||||||
|
const { db, updates } = createDb({ memberOf: ['list-1', 'list-2'], item })
|
||||||
|
const { events, published } = createBus()
|
||||||
|
const result = await new MoveItem(db, events).execute(input)
|
||||||
|
|
||||||
|
expect(result.ok).toBe(true)
|
||||||
|
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||||
|
|
||||||
|
expect(updates).toEqual([{ where: { id: 'item-1' }, data: { shoppingListId: 'list-2' } }])
|
||||||
|
expect(result.value).toMatchObject({
|
||||||
|
id: 'item-1',
|
||||||
|
listId: 'list-2',
|
||||||
|
name: 'Leche',
|
||||||
|
quantity: '1 L',
|
||||||
|
notes: 'sin lactosa',
|
||||||
|
completed: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(published).toEqual([
|
||||||
|
{ type: 'item.removed', listId: 'list-1', itemId: 'item-1' },
|
||||||
|
{ type: 'item.created', listId: 'list-2', item: result.value },
|
||||||
|
])
|
||||||
|
})
|
||||||
|
})
|
||||||
72
apps/api/src/modules/lists/items/move/use-case.ts
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
import {
|
||||||
|
Failure,
|
||||||
|
type ListItem,
|
||||||
|
Ok,
|
||||||
|
type ProblemDetails,
|
||||||
|
problems,
|
||||||
|
type Result,
|
||||||
|
} from '@superlist/shared'
|
||||||
|
|
||||||
|
import { type ListEvents, listEvents } from '@/lib/events'
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
import { toListItem } from '../serialize'
|
||||||
|
|
||||||
|
type MoveItemFields = {
|
||||||
|
listId: string
|
||||||
|
itemId: string
|
||||||
|
userId: string
|
||||||
|
targetListId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moves an item to another list, keeping its name, quantity, notes and bought
|
||||||
|
* state. The user has to be a member of both lists.
|
||||||
|
*/
|
||||||
|
export class MoveItem {
|
||||||
|
constructor(
|
||||||
|
private readonly db: Database,
|
||||||
|
private readonly events: ListEvents = listEvents,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async execute(input: MoveItemFields): Promise<Result<ListItem, ProblemDetails>> {
|
||||||
|
if (input.targetListId === input.listId) {
|
||||||
|
return Failure(problems.badRequest('El artículo ya está en esa lista.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const membership = await this.db.shoppingListMember.findUnique({
|
||||||
|
where: { listId_userId: { listId: input.listId, userId: input.userId } },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!membership) {
|
||||||
|
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetMembership = await this.db.shoppingListMember.findUnique({
|
||||||
|
where: { listId_userId: { listId: input.targetListId, userId: input.userId } },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!targetMembership) {
|
||||||
|
return Failure(problems.notFound('La lista de destino no existe o no tienes acceso.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const item = await this.db.listItem.findFirst({
|
||||||
|
where: { id: input.itemId, shoppingListId: input.listId },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!item) {
|
||||||
|
return Failure(problems.notFound('El artículo no existe en esta lista.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const moved = await this.db.listItem.update({
|
||||||
|
where: { id: item.id },
|
||||||
|
data: { shoppingListId: input.targetListId },
|
||||||
|
})
|
||||||
|
|
||||||
|
const dto = toListItem(moved)
|
||||||
|
this.events.publish({ type: 'item.removed', listId: input.listId, itemId: item.id })
|
||||||
|
this.events.publish({ type: 'item.created', listId: input.targetListId, item: dto })
|
||||||
|
|
||||||
|
return Ok(dto)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,7 +9,7 @@ import type { AppEnv } from '@/types'
|
|||||||
import { ItemParamsSchema, UpdateItemSchema } from './schema'
|
import { ItemParamsSchema, UpdateItemSchema } from './schema'
|
||||||
import { UpdateItem } from './use-case'
|
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(
|
export const updateItemRoute = new Hono<AppEnv>().patch(
|
||||||
'/:itemId',
|
'/:itemId',
|
||||||
requireSession,
|
requireSession,
|
||||||
@@ -17,12 +17,15 @@ export const updateItemRoute = new Hono<AppEnv>().patch(
|
|||||||
validate.json(UpdateItemSchema),
|
validate.json(UpdateItemSchema),
|
||||||
async (c) => {
|
async (c) => {
|
||||||
const { listId, itemId } = c.req.valid('param')
|
const { listId, itemId } = c.req.valid('param')
|
||||||
const { completed } = c.req.valid('json')
|
const { name, completed, quantity, notes } = c.req.valid('json')
|
||||||
const result = await new UpdateItem(prisma).execute({
|
const result = await new UpdateItem(prisma).execute({
|
||||||
listId,
|
listId,
|
||||||
itemId,
|
itemId,
|
||||||
userId: c.get('user').id,
|
userId: c.get('user').id,
|
||||||
|
name,
|
||||||
completed,
|
completed,
|
||||||
|
quantity,
|
||||||
|
notes,
|
||||||
})
|
})
|
||||||
|
|
||||||
return resultJson(c, result)
|
return resultJson(c, result)
|
||||||
|
|||||||
@@ -8,9 +8,28 @@ export const ItemParamsSchema = z.object({
|
|||||||
|
|
||||||
export type ItemParams = z.infer<typeof ItemParamsSchema>
|
export type ItemParams = z.infer<typeof ItemParamsSchema>
|
||||||
|
|
||||||
/** Body of `PATCH /lists/:listId/items/:itemId`. */
|
/** Body of `PATCH /lists/:listId/items/:itemId` — at least one field is required. */
|
||||||
export const UpdateItemSchema = z.object({
|
export const UpdateItemSchema = z
|
||||||
completed: z.boolean(),
|
.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>
|
export type UpdateItemInput = z.infer<typeof UpdateItemSchema>
|
||||||
|
|||||||
@@ -45,9 +45,13 @@ function createDb(options: { membership: unknown; item: ItemRow | null }) {
|
|||||||
},
|
},
|
||||||
listItem: {
|
listItem: {
|
||||||
findFirst: async () => options.item,
|
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)
|
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 }])
|
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 () => {
|
it('marks the item back to pending, clears boughtAt and publishes item.updated', async () => {
|
||||||
const { db, updates } = createDb({
|
const { db, updates } = createDb({
|
||||||
membership: { role: 'collaborator' },
|
membership: { role: 'collaborator' },
|
||||||
|
|||||||
@@ -12,9 +12,23 @@ import type { Database } from '@/lib/prisma'
|
|||||||
|
|
||||||
import { toListItem } from '../serialize'
|
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.
|
* Updates an item's name, its bought state, its quantity and/or its notes. Only members can do it.
|
||||||
* `boughtAt` records the moment it was marked as bought, for future
|
* `boughtAt` records the moment an item was marked as bought, for future
|
||||||
* statistics, and is cleared when the item goes back to pending.
|
* statistics, and is cleared when the item goes back to pending.
|
||||||
*/
|
*/
|
||||||
export class UpdateItem {
|
export class UpdateItem {
|
||||||
@@ -23,12 +37,7 @@ export class UpdateItem {
|
|||||||
private readonly events: ListEvents = listEvents,
|
private readonly events: ListEvents = listEvents,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async execute(input: {
|
async execute(input: UpdateItemFields): Promise<Result<ListItem, ProblemDetails>> {
|
||||||
listId: string
|
|
||||||
itemId: string
|
|
||||||
userId: string
|
|
||||||
completed: boolean
|
|
||||||
}): Promise<Result<ListItem, ProblemDetails>> {
|
|
||||||
const membership = await this.db.shoppingListMember.findUnique({
|
const membership = await this.db.shoppingListMember.findUnique({
|
||||||
where: { listId_userId: { listId: input.listId, userId: input.userId } },
|
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.'))
|
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({
|
const updated = await this.db.listItem.update({
|
||||||
where: { id: item.id },
|
where: { id: item.id },
|
||||||
data: {
|
data,
|
||||||
completed: input.completed,
|
|
||||||
boughtAt: input.completed ? new Date() : null,
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const dto = toListItem(updated)
|
const dto = toListItem(updated)
|
||||||
|
|||||||
60
apps/api/src/modules/lists/list/use-case.test.ts
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
import { describe, expect, it } from 'bun:test'
|
||||||
|
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
import { ListShoppingLists } from './use-case'
|
||||||
|
|
||||||
|
describe('ListShoppingLists', () => {
|
||||||
|
it('returns the pending count and the user preferences of each list', async () => {
|
||||||
|
const queries: unknown[] = []
|
||||||
|
const db = {
|
||||||
|
shoppingListMember: {
|
||||||
|
findMany: async (args: unknown) => {
|
||||||
|
queries.push(args)
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
role: 'owner',
|
||||||
|
isPrimary: false,
|
||||||
|
isPinned: true,
|
||||||
|
icon: 'unknown-icon',
|
||||||
|
list: {
|
||||||
|
id: 'list-1',
|
||||||
|
name: 'Verdulería',
|
||||||
|
createdAt: new Date('2026-11-01T00:00:00.000Z'),
|
||||||
|
updatedAt: new Date('2026-11-02T00:00:00.000Z'),
|
||||||
|
_count: { members: 1, items: 4 },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await new ListShoppingLists(db as unknown as Database).execute({
|
||||||
|
userId: 'user-1',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result.ok).toBe(true)
|
||||||
|
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||||
|
expect(result.value).toEqual([
|
||||||
|
{
|
||||||
|
id: 'list-1',
|
||||||
|
name: 'Verdulería',
|
||||||
|
role: 'owner',
|
||||||
|
isPrimary: false,
|
||||||
|
isPinned: true,
|
||||||
|
icon: null,
|
||||||
|
pendingCount: 4,
|
||||||
|
memberCount: 1,
|
||||||
|
createdAt: '2026-11-01T00:00:00.000Z',
|
||||||
|
updatedAt: '2026-11-02T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
])
|
||||||
|
expect(queries[0]).toMatchObject({
|
||||||
|
include: {
|
||||||
|
list: { include: { _count: { select: { items: { where: { completed: false } } } } } },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -2,27 +2,27 @@ import { Ok, type ProblemDetails, type Result, type ShoppingListSummary } from '
|
|||||||
|
|
||||||
import type { Database } from '@/lib/prisma'
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
/** Lists every shopping list the user belongs to (owned or shared). */
|
import { summaryCountInclude, toSummary } from '../serialize'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lists every shopping list the user belongs to (owned or shared): the primary
|
||||||
|
* one first, then the pinned ones in pin order, then the rest, newest first.
|
||||||
|
*/
|
||||||
export class ListShoppingLists {
|
export class ListShoppingLists {
|
||||||
constructor(private readonly db: Database) {}
|
constructor(private readonly db: Database) {}
|
||||||
|
|
||||||
async execute(input: { userId: string }): Promise<Result<ShoppingListSummary[], ProblemDetails>> {
|
async execute(input: { userId: string }): Promise<Result<ShoppingListSummary[], ProblemDetails>> {
|
||||||
const memberships = await this.db.shoppingListMember.findMany({
|
const memberships = await this.db.shoppingListMember.findMany({
|
||||||
where: { userId: input.userId },
|
where: { userId: input.userId },
|
||||||
include: { list: { include: { _count: { select: { members: true } } } } },
|
include: { list: { include: summaryCountInclude } },
|
||||||
orderBy: [{ isPrimary: 'desc' }, { list: { createdAt: 'desc' } }],
|
orderBy: [
|
||||||
|
{ isPrimary: 'desc' },
|
||||||
|
{ isPinned: 'desc' },
|
||||||
|
{ pinnedOrder: { sort: 'asc', nulls: 'last' } },
|
||||||
|
{ list: { createdAt: 'desc' } },
|
||||||
|
],
|
||||||
})
|
})
|
||||||
|
|
||||||
const lists = memberships.map((membership) => ({
|
return Ok(memberships.map(toSummary))
|
||||||
id: membership.list.id,
|
|
||||||
name: membership.list.name,
|
|
||||||
role: membership.role,
|
|
||||||
isPrimary: membership.isPrimary,
|
|
||||||
memberCount: membership.list._count.members,
|
|
||||||
createdAt: membership.list.createdAt.toISOString(),
|
|
||||||
updatedAt: membership.list.updatedAt.toISOString(),
|
|
||||||
}))
|
|
||||||
|
|
||||||
return Ok(lists)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
30
apps/api/src/modules/lists/preferences/route.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
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 { ListParamsSchema } from '../schema'
|
||||||
|
import { UpdateListPreferencesSchema } from './schema'
|
||||||
|
import { UpdateListPreferences } from './use-case'
|
||||||
|
|
||||||
|
/** PATCH /lists/:listId/preferences — pins the list or changes its icon (per user). */
|
||||||
|
export const updateListPreferencesRoute = new Hono<AppEnv>().patch(
|
||||||
|
'/:listId/preferences',
|
||||||
|
requireSession,
|
||||||
|
validate.param(ListParamsSchema),
|
||||||
|
validate.json(UpdateListPreferencesSchema),
|
||||||
|
async (c) => {
|
||||||
|
const { listId } = c.req.valid('param')
|
||||||
|
const body = c.req.valid('json')
|
||||||
|
const result = await new UpdateListPreferences(prisma).execute({
|
||||||
|
listId,
|
||||||
|
userId: c.get('user').id,
|
||||||
|
...body,
|
||||||
|
})
|
||||||
|
|
||||||
|
return resultJson(c, result)
|
||||||
|
},
|
||||||
|
)
|
||||||
14
apps/api/src/modules/lists/preferences/schema.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { ListIconSchema } from '@superlist/shared'
|
||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
/** Body of `PATCH /lists/:listId/preferences`: the user's own settings for the list. */
|
||||||
|
export const UpdateListPreferencesSchema = z
|
||||||
|
.object({
|
||||||
|
isPinned: z.boolean().optional(),
|
||||||
|
icon: ListIconSchema.nullable().optional(),
|
||||||
|
})
|
||||||
|
.refine((body) => body.isPinned !== undefined || body.icon !== undefined, {
|
||||||
|
message: 'Indica al menos una preferencia para actualizar',
|
||||||
|
})
|
||||||
|
|
||||||
|
export type UpdateListPreferencesInput = z.infer<typeof UpdateListPreferencesSchema>
|
||||||
147
apps/api/src/modules/lists/preferences/use-case.test.ts
Normal file
@@ -0,0 +1,147 @@
|
|||||||
|
import { describe, expect, it } from 'bun:test'
|
||||||
|
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
import { UpdateListPreferences } from './use-case'
|
||||||
|
|
||||||
|
type Membership = {
|
||||||
|
role: 'owner' | 'collaborator'
|
||||||
|
isPrimary: boolean
|
||||||
|
isPinned: boolean
|
||||||
|
icon: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
function createDb({
|
||||||
|
membership,
|
||||||
|
pinnedCount = 0,
|
||||||
|
maxPinnedOrder = null,
|
||||||
|
}: {
|
||||||
|
membership: Membership | null
|
||||||
|
pinnedCount?: number
|
||||||
|
maxPinnedOrder?: number | null
|
||||||
|
}) {
|
||||||
|
const updates: Array<{ data: Record<string, unknown> }> = []
|
||||||
|
|
||||||
|
const tx = {
|
||||||
|
shoppingListMember: {
|
||||||
|
findUnique: async () => membership,
|
||||||
|
aggregate: async () => ({
|
||||||
|
_count: { _all: pinnedCount },
|
||||||
|
_max: { pinnedOrder: maxPinnedOrder },
|
||||||
|
}),
|
||||||
|
update: async (args: { data: Record<string, unknown> }) => {
|
||||||
|
updates.push(args)
|
||||||
|
|
||||||
|
return {
|
||||||
|
...membership,
|
||||||
|
...args.data,
|
||||||
|
list: {
|
||||||
|
id: 'list-1',
|
||||||
|
name: 'Casa de fin de semana',
|
||||||
|
createdAt: new Date('2026-11-01T00:00:00.000Z'),
|
||||||
|
updatedAt: new Date('2026-11-01T00:00:00.000Z'),
|
||||||
|
_count: { members: 2, items: 3 },
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
const db = { $transaction: async (fn: (client: typeof tx) => unknown) => fn(tx) }
|
||||||
|
|
||||||
|
return { db: db as unknown as Database, updates }
|
||||||
|
}
|
||||||
|
|
||||||
|
const collaborator: Membership = {
|
||||||
|
role: 'collaborator',
|
||||||
|
isPrimary: false,
|
||||||
|
isPinned: false,
|
||||||
|
icon: null,
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('UpdateListPreferences', () => {
|
||||||
|
it('answers 404 when the user does not belong to the list', async () => {
|
||||||
|
const { db, updates } = createDb({ membership: null })
|
||||||
|
const result = await new UpdateListPreferences(db).execute({
|
||||||
|
listId: 'list-1',
|
||||||
|
userId: 'user-1',
|
||||||
|
isPinned: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
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)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('pins the list after the last pinned one and returns its pending count', async () => {
|
||||||
|
const { db, updates } = createDb({
|
||||||
|
membership: collaborator,
|
||||||
|
pinnedCount: 2,
|
||||||
|
maxPinnedOrder: 5,
|
||||||
|
})
|
||||||
|
const result = await new UpdateListPreferences(db).execute({
|
||||||
|
listId: 'list-1',
|
||||||
|
userId: 'user-1',
|
||||||
|
isPinned: true,
|
||||||
|
icon: 'park',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result.ok).toBe(true)
|
||||||
|
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||||
|
expect(updates[0]?.data).toEqual({ isPinned: true, pinnedOrder: 6, icon: 'park' })
|
||||||
|
expect(result.value).toMatchObject({
|
||||||
|
isPinned: true,
|
||||||
|
icon: 'park',
|
||||||
|
pendingCount: 3,
|
||||||
|
memberCount: 2,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses to pin more than four lists', async () => {
|
||||||
|
const { db, updates } = createDb({
|
||||||
|
membership: collaborator,
|
||||||
|
pinnedCount: 4,
|
||||||
|
maxPinnedOrder: 4,
|
||||||
|
})
|
||||||
|
const result = await new UpdateListPreferences(db).execute({
|
||||||
|
listId: 'list-1',
|
||||||
|
userId: 'user-1',
|
||||||
|
isPinned: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result.ok).toBe(false)
|
||||||
|
if (result.ok) throw new Error('expected the use case to fail')
|
||||||
|
expect(result.error.status).toBe(409)
|
||||||
|
expect(updates).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('unpins the list and clears its position', async () => {
|
||||||
|
const { db, updates } = createDb({ membership: { ...collaborator, isPinned: true } })
|
||||||
|
const result = await new UpdateListPreferences(db).execute({
|
||||||
|
listId: 'list-1',
|
||||||
|
userId: 'user-1',
|
||||||
|
isPinned: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result.ok).toBe(true)
|
||||||
|
expect(updates[0]?.data).toEqual({ isPinned: false, pinnedOrder: null })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('changes only the icon of an already pinned list', async () => {
|
||||||
|
const { db, updates } = createDb({
|
||||||
|
membership: { ...collaborator, isPinned: true, icon: 'carrot' },
|
||||||
|
})
|
||||||
|
const result = await new UpdateListPreferences(db).execute({
|
||||||
|
listId: 'list-1',
|
||||||
|
userId: 'user-1',
|
||||||
|
isPinned: true,
|
||||||
|
icon: null,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result.ok).toBe(true)
|
||||||
|
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||||
|
expect(updates[0]?.data).toEqual({ icon: null })
|
||||||
|
expect(result.value.icon).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
76
apps/api/src/modules/lists/preferences/use-case.ts
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
import {
|
||||||
|
Failure,
|
||||||
|
type ListIcon,
|
||||||
|
MAX_PINNED_LISTS,
|
||||||
|
Ok,
|
||||||
|
type ProblemDetails,
|
||||||
|
problems,
|
||||||
|
type Result,
|
||||||
|
type ShoppingListSummary,
|
||||||
|
} from '@superlist/shared'
|
||||||
|
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
import { summaryCountInclude, toSummary } from '../serialize'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates the user's own settings for a list: whether it is pinned to the
|
||||||
|
* always-visible bar and which icon it shows. Any member may do it, because
|
||||||
|
* the settings are per user (like the primary list), not shared with the list.
|
||||||
|
*/
|
||||||
|
export class UpdateListPreferences {
|
||||||
|
constructor(private readonly db: Database) {}
|
||||||
|
|
||||||
|
async execute(input: {
|
||||||
|
listId: string
|
||||||
|
userId: string
|
||||||
|
isPinned?: boolean
|
||||||
|
icon?: ListIcon | null
|
||||||
|
}): Promise<Result<ShoppingListSummary, ProblemDetails>> {
|
||||||
|
const where = { listId_userId: { listId: input.listId, userId: input.userId } }
|
||||||
|
|
||||||
|
return this.db.$transaction(async (tx) => {
|
||||||
|
const membership = await tx.shoppingListMember.findUnique({ where })
|
||||||
|
|
||||||
|
if (!membership) {
|
||||||
|
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const data: { isPinned?: boolean; pinnedOrder?: number | null; icon?: ListIcon | null } = {}
|
||||||
|
|
||||||
|
if (input.icon !== undefined) data.icon = input.icon
|
||||||
|
|
||||||
|
if (input.isPinned === true && !membership.isPinned) {
|
||||||
|
const pinned = await tx.shoppingListMember.aggregate({
|
||||||
|
where: { userId: input.userId, isPinned: true },
|
||||||
|
_count: { _all: true },
|
||||||
|
_max: { pinnedOrder: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (pinned._count._all >= MAX_PINNED_LISTS) {
|
||||||
|
return Failure(
|
||||||
|
problems.conflict(
|
||||||
|
`Puedes fijar hasta ${MAX_PINNED_LISTS} listas. Desfija otra para fijar esta.`,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
data.isPinned = true
|
||||||
|
data.pinnedOrder = (pinned._max.pinnedOrder ?? 0) + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.isPinned === false && membership.isPinned) {
|
||||||
|
data.isPinned = false
|
||||||
|
data.pinnedOrder = null
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await tx.shoppingListMember.update({
|
||||||
|
where,
|
||||||
|
data,
|
||||||
|
include: { list: { include: summaryCountInclude } },
|
||||||
|
})
|
||||||
|
|
||||||
|
return Ok(toSummary(updated))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,17 @@
|
|||||||
import type { ListMember, ShoppingListDetail, ShoppingListSummary } from '@superlist/shared'
|
import {
|
||||||
|
type ListIcon,
|
||||||
|
ListIconSchema,
|
||||||
|
type ListMember,
|
||||||
|
type ShoppingListDetail,
|
||||||
|
type ShoppingListSummary,
|
||||||
|
} from '@superlist/shared'
|
||||||
|
|
||||||
|
/** Reads a stored icon key; unknown keys (e.g. one removed from the set) fall back to none. */
|
||||||
|
export function toListIcon(icon: string | null): ListIcon | null {
|
||||||
|
const parsed = ListIconSchema.safeParse(icon)
|
||||||
|
|
||||||
|
return parsed.success ? parsed.data : null
|
||||||
|
}
|
||||||
|
|
||||||
type ListRow = {
|
type ListRow = {
|
||||||
id: string
|
id: string
|
||||||
@@ -10,16 +23,29 @@ type ListRow = {
|
|||||||
type MemberRow = {
|
type MemberRow = {
|
||||||
role: 'owner' | 'collaborator'
|
role: 'owner' | 'collaborator'
|
||||||
isPrimary: boolean
|
isPrimary: boolean
|
||||||
list: ListRow & { _count: { members: number } }
|
isPinned: boolean
|
||||||
|
icon: string | null
|
||||||
|
list: ListRow & { _count: { members: number; items: number } }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Maps a membership (with its list and member count) to the summary DTO. */
|
/**
|
||||||
|
* Prisma `include` for a summary: the member count plus the pending items
|
||||||
|
* (`items` counts only the ones not bought yet).
|
||||||
|
*/
|
||||||
|
export const summaryCountInclude = {
|
||||||
|
_count: { select: { members: true, items: { where: { completed: false } } } },
|
||||||
|
} as const
|
||||||
|
|
||||||
|
/** Maps a membership (with its list, member and pending counts) to the summary DTO. */
|
||||||
export function toSummary(member: MemberRow): ShoppingListSummary {
|
export function toSummary(member: MemberRow): ShoppingListSummary {
|
||||||
return {
|
return {
|
||||||
id: member.list.id,
|
id: member.list.id,
|
||||||
name: member.list.name,
|
name: member.list.name,
|
||||||
role: member.role,
|
role: member.role,
|
||||||
isPrimary: member.isPrimary,
|
isPrimary: member.isPrimary,
|
||||||
|
isPinned: member.isPinned,
|
||||||
|
icon: toListIcon(member.icon),
|
||||||
|
pendingCount: member.list._count.items,
|
||||||
memberCount: member.list._count.members,
|
memberCount: member.list._count.members,
|
||||||
createdAt: member.list.createdAt.toISOString(),
|
createdAt: member.list.createdAt.toISOString(),
|
||||||
updatedAt: member.list.updatedAt.toISOString(),
|
updatedAt: member.list.updatedAt.toISOString(),
|
||||||
@@ -29,6 +55,8 @@ export function toSummary(member: MemberRow): ShoppingListSummary {
|
|||||||
type DetailRow = {
|
type DetailRow = {
|
||||||
role: 'owner' | 'collaborator'
|
role: 'owner' | 'collaborator'
|
||||||
isPrimary: boolean
|
isPrimary: boolean
|
||||||
|
isPinned: boolean
|
||||||
|
icon: string | null
|
||||||
list: ListRow & {
|
list: ListRow & {
|
||||||
members: Array<{
|
members: Array<{
|
||||||
id: string
|
id: string
|
||||||
@@ -65,6 +93,8 @@ export function toDetail(member: DetailRow): ShoppingListDetail {
|
|||||||
name: member.list.name,
|
name: member.list.name,
|
||||||
role: member.role,
|
role: member.role,
|
||||||
isPrimary: member.isPrimary,
|
isPrimary: member.isPrimary,
|
||||||
|
isPinned: member.isPinned,
|
||||||
|
icon: toListIcon(member.icon),
|
||||||
members,
|
members,
|
||||||
invitations: member.list.invitations.map((invitation) => ({
|
invitations: member.list.invitations.map((invitation) => ({
|
||||||
id: invitation.id,
|
id: invitation.id,
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import {
|
|||||||
import { type ListEvents, listEvents } from '@/lib/events'
|
import { type ListEvents, listEvents } from '@/lib/events'
|
||||||
import type { Database } from '@/lib/prisma'
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
import { summaryCountInclude, toSummary } from '../serialize'
|
||||||
|
|
||||||
/** Renames a list. Only the owner (`role: owner`) may do it. */
|
/** Renames a list. Only the owner (`role: owner`) may do it. */
|
||||||
export class UpdateShoppingList {
|
export class UpdateShoppingList {
|
||||||
constructor(
|
constructor(
|
||||||
@@ -37,19 +39,11 @@ export class UpdateShoppingList {
|
|||||||
const list = await this.db.shoppingList.update({
|
const list = await this.db.shoppingList.update({
|
||||||
where: { id: input.listId },
|
where: { id: input.listId },
|
||||||
data: { name: input.name },
|
data: { name: input.name },
|
||||||
include: { _count: { select: { members: true } } },
|
include: summaryCountInclude,
|
||||||
})
|
})
|
||||||
|
|
||||||
this.events.publish({ type: 'list.updated', listId: list.id, name: list.name })
|
this.events.publish({ type: 'list.updated', listId: list.id, name: list.name })
|
||||||
|
|
||||||
return Ok({
|
return Ok(toSummary({ ...membership, list }))
|
||||||
id: list.id,
|
|
||||||
name: list.name,
|
|
||||||
role: membership.role,
|
|
||||||
isPrimary: membership.isPrimary,
|
|
||||||
memberCount: list._count.members,
|
|
||||||
createdAt: list.createdAt.toISOString(),
|
|
||||||
updatedAt: list.updatedAt.toISOString(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
8
apps/api/src/modules/voice/index.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { splitVoiceRoute } from './split/route'
|
||||||
|
|
||||||
|
/** `voice` module: every feature of the module is mounted here. */
|
||||||
|
export const voiceModule = new Hono<AppEnv>().route('/', splitVoiceRoute)
|
||||||
60
apps/api/src/modules/voice/split/items.test.ts
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
import { describe, expect, it } from 'bun:test'
|
||||||
|
|
||||||
|
import { fallbackSplit, parseModelItems } from './items'
|
||||||
|
|
||||||
|
describe('fallbackSplit', () => {
|
||||||
|
it('splits on commas, semicolons, " y " and " e "', () => {
|
||||||
|
expect(fallbackSplit('dos litros de leche, una docena de huevos y bolsas; pan e hilo')).toEqual(
|
||||||
|
['dos litros de leche', 'una docena de huevos', 'bolsas', 'pan', 'hilo'],
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps decimal commas and drops empty segments', () => {
|
||||||
|
expect(fallbackSplit('1,5 kg de papas, , cebolla ;')).toEqual(['1,5 kg de papas', 'cebolla'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not split inside words', () => {
|
||||||
|
expect(fallbackSplit('yerba y yogur')).toEqual(['yerba', 'yogur'])
|
||||||
|
expect(fallbackSplit('mayonesa')).toEqual(['mayonesa'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('caps the number and the length of the items', () => {
|
||||||
|
const many = Array.from({ length: 40 }, (_, index) => `item ${index}`).join(', ')
|
||||||
|
expect(fallbackSplit(many)).toHaveLength(30)
|
||||||
|
expect(fallbackSplit('a'.repeat(150))[0]).toHaveLength(100)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('parseModelItems', () => {
|
||||||
|
it('reads a valid array, trimming and dropping empty items', () => {
|
||||||
|
expect(parseModelItems('["2 l de leche", " 12 huevos ", ""]')).toEqual([
|
||||||
|
'2 l de leche',
|
||||||
|
'12 huevos',
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('reads JSON inside a code fence or surrounded by prose', () => {
|
||||||
|
expect(parseModelItems('```json\n["pan", "queso"]\n```')).toEqual(['pan', 'queso'])
|
||||||
|
expect(parseModelItems('Claro, acá va: ["pan", "queso [rallado]"] ¡Listo!')).toEqual([
|
||||||
|
'pan',
|
||||||
|
'queso [rallado]',
|
||||||
|
])
|
||||||
|
expect(parseModelItems('{"items": ["pan"]}')).toEqual(['pan'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects invalid JSON and anything that is not an array of strings', () => {
|
||||||
|
expect(parseModelItems('no sé')).toBeNull()
|
||||||
|
expect(parseModelItems('["pan", ')).toBeNull()
|
||||||
|
expect(parseModelItems('[1, 2]')).toBeNull()
|
||||||
|
expect(parseModelItems('{"producto": "pan"}')).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps at most 30 items of at most 100 characters', () => {
|
||||||
|
const items = parseModelItems(
|
||||||
|
JSON.stringify([...Array.from({ length: 35 }, (_, i) => `item ${i}`), 'x']),
|
||||||
|
)
|
||||||
|
expect(items).toHaveLength(30)
|
||||||
|
expect(items?.at(-1)).toBe('item 29')
|
||||||
|
expect(parseModelItems(JSON.stringify(['b'.repeat(120)]))?.[0]).toHaveLength(100)
|
||||||
|
})
|
||||||
|
})
|
||||||
91
apps/api/src/modules/voice/split/items.ts
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
import { VOICE_ITEM_MAX_LENGTH, VOICE_MAX_ITEMS } from '@superlist/shared'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trims every item, drops empty ones and caps the result: at most `VOICE_MAX_ITEMS`
|
||||||
|
* items of at most `VOICE_ITEM_MAX_LENGTH` characters each.
|
||||||
|
*/
|
||||||
|
export function cleanItems(items: string[]): string[] {
|
||||||
|
return items
|
||||||
|
.map((item) => item.trim().slice(0, VOICE_ITEM_MAX_LENGTH).trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
.slice(0, VOICE_MAX_ITEMS)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Plan B when the model cannot be used: splits on commas, semicolons, " y " and " e ".
|
||||||
|
* A comma between digits is a decimal ("1,5 kg") and stays.
|
||||||
|
*/
|
||||||
|
export function fallbackSplit(text: string): string[] {
|
||||||
|
return cleanItems(text.split(/\s*[;\n]\s*|\s*,\s*(?!\d)|\s+[ye]\s+/i))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Removes a Markdown code fence around the answer (```json … ```), if any. */
|
||||||
|
function stripCodeFences(text: string): string {
|
||||||
|
const fenced = /```(?:json|JSON)?\s*([\s\S]*?)```/.exec(text)
|
||||||
|
|
||||||
|
return (fenced?.[1] ?? text).trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The first balanced JSON array or object in `text`, skipping brackets inside strings.
|
||||||
|
* Returns `null` when there is none.
|
||||||
|
*/
|
||||||
|
function firstJsonValue(text: string): string | null {
|
||||||
|
const start = text.search(/[[{]/)
|
||||||
|
if (start === -1) return null
|
||||||
|
|
||||||
|
let depth = 0
|
||||||
|
let inString = false
|
||||||
|
let escaped = false
|
||||||
|
|
||||||
|
for (let index = start; index < text.length; index++) {
|
||||||
|
const char = text[index]
|
||||||
|
|
||||||
|
if (inString) {
|
||||||
|
if (escaped) escaped = false
|
||||||
|
else if (char === '\\') escaped = true
|
||||||
|
else if (char === '"') inString = false
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (char === '"') inString = true
|
||||||
|
else if (char === '[' || char === '{') depth++
|
||||||
|
else if (char === ']' || char === '}') {
|
||||||
|
depth--
|
||||||
|
if (depth === 0) return text.slice(start, index + 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
function tryParse(text: string): unknown {
|
||||||
|
try {
|
||||||
|
return JSON.parse(text)
|
||||||
|
} catch {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads the model's answer: a JSON array of strings, possibly inside a code fence,
|
||||||
|
* surrounded by prose or wrapped as `{ "items": [...] }`. Returns the cleaned items,
|
||||||
|
* or `null` when the answer is not an array of strings.
|
||||||
|
*/
|
||||||
|
export function parseModelItems(answer: string): string[] | null {
|
||||||
|
const unfenced = stripCodeFences(answer)
|
||||||
|
let value = tryParse(unfenced)
|
||||||
|
|
||||||
|
if (value === undefined) {
|
||||||
|
const json = firstJsonValue(unfenced)
|
||||||
|
value = json ? tryParse(json) : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value && typeof value === 'object' && !Array.isArray(value) && 'items' in value) {
|
||||||
|
value = value.items
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) return null
|
||||||
|
|
||||||
|
return cleanItems(value)
|
||||||
|
}
|
||||||
31
apps/api/src/modules/voice/split/prompt.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { VOICE_SPLIT_EXAMPLES } from '@superlist/shared'
|
||||||
|
|
||||||
|
import type { GenerateInput, ModelTurn } from '@/lib/text-generator'
|
||||||
|
|
||||||
|
/** 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.
|
||||||
|
- La transcripción casi nunca trae comas: los productos nombrados uno tras otro son elementos distintos ("azúcar leche y café" son 3), salvo que juntos formen un solo producto ("dulce de leche", "queso crema", "pan rallado").
|
||||||
|
- 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: ModelTurn[] = 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 }],
|
||||||
|
}
|
||||||
|
}
|
||||||
245
apps/api/src/modules/voice/split/route.test.ts
Normal file
@@ -0,0 +1,245 @@
|
|||||||
|
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'
|
||||||
|
// `bun test` loads `.env`: a real Groq key there would take over these Gemini tests.
|
||||||
|
delete process.env.GROQ_API_KEY
|
||||||
|
delete process.env.GROQ_MODEL
|
||||||
|
delete process.env.GROQ_TIMEOUT_MS
|
||||||
|
})
|
||||||
|
|
||||||
|
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('asks for minimal thinking and retries a 5xx once', async () => {
|
||||||
|
let calls = 0
|
||||||
|
const fetchMock = mockFetch(async () =>
|
||||||
|
++calls === 1
|
||||||
|
? new Response('{}', { status: 500 })
|
||||||
|
: modelAnswer('["Azúcar", "Leche", "Café"]'),
|
||||||
|
)
|
||||||
|
|
||||||
|
const response = await split({ text: 'azúcar leche y café' })
|
||||||
|
|
||||||
|
expect(await response.json()).toEqual({ items: ['Azúcar', 'Leche', 'Café'] })
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||||
|
const sent = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))
|
||||||
|
expect(sent.generationConfig.thinkingConfig).toEqual({ thinkingLevel: 'minimal' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back when the model answers 5xx twice', async () => {
|
||||||
|
const fetchMock = mockFetch(async () => new Response('{}', { status: 503 }))
|
||||||
|
|
||||||
|
const response = await split({ text: 'pan y leche' })
|
||||||
|
|
||||||
|
expect(await response.json()).toEqual({ items: ['pan', 'leche'] })
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||||
|
expect(JSON.stringify(warnings)).toContain('http-503')
|
||||||
|
})
|
||||||
|
|
||||||
|
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)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('POST /api/voice/split with Groq', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
process.env.GROQ_API_KEY = 'gsk_test'
|
||||||
|
process.env.GROQ_MODEL = 'llama-test'
|
||||||
|
process.env.GROQ_TIMEOUT_MS = '50'
|
||||||
|
})
|
||||||
|
|
||||||
|
function groqAnswer(content: string) {
|
||||||
|
return Response.json({ choices: [{ message: { role: 'assistant', content } }] })
|
||||||
|
}
|
||||||
|
|
||||||
|
it('asks Groq instead of Gemini when its key is set', async () => {
|
||||||
|
const fetchMock = mockFetch(async () => groqAnswer('["Azúcar", "Leche", "Café"]'))
|
||||||
|
|
||||||
|
const response = await split({ text: 'azúcar leche y café' })
|
||||||
|
|
||||||
|
expect(await response.json()).toEqual({ items: ['Azúcar', 'Leche', 'Café'] })
|
||||||
|
expect(warnings).toHaveLength(0)
|
||||||
|
|
||||||
|
const [url, init] = fetchMock.mock.calls[0] ?? []
|
||||||
|
expect(url).toBe('https://api.groq.com/openai/v1/chat/completions')
|
||||||
|
expect(new Headers(init?.headers).get('authorization')).toBe('Bearer gsk_test')
|
||||||
|
const sent = JSON.parse(String(init?.body))
|
||||||
|
expect(sent.model).toBe('llama-test')
|
||||||
|
expect(sent.temperature).toBe(0)
|
||||||
|
expect(sent.messages[0]).toEqual({
|
||||||
|
role: 'system',
|
||||||
|
content: expect.stringContaining('array JSON'),
|
||||||
|
})
|
||||||
|
expect(sent.messages[2].role).toBe('assistant')
|
||||||
|
expect(sent.messages.at(-1)).toEqual({ role: 'user', content: 'azúcar leche y café' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('retries a 5xx once', async () => {
|
||||||
|
let calls = 0
|
||||||
|
const fetchMock = mockFetch(async () =>
|
||||||
|
++calls === 1 ? new Response('{}', { status: 502 }) : groqAnswer('["Pan"]'),
|
||||||
|
)
|
||||||
|
|
||||||
|
const response = await split({ text: 'pan' })
|
||||||
|
|
||||||
|
expect(await response.json()).toEqual({ items: ['Pan'] })
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back when Groq is rate limited (429)', async () => {
|
||||||
|
mockFetch(async () => new Response('{}', { status: 429 }))
|
||||||
|
|
||||||
|
const response = await split({ text: 'pan y queso' })
|
||||||
|
|
||||||
|
expect(await response.json()).toEqual({ items: ['pan', 'queso'] })
|
||||||
|
expect(JSON.stringify(warnings)).toContain('rate-limited')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back when Groq answers with no content', async () => {
|
||||||
|
mockFetch(async () => groqAnswer(''))
|
||||||
|
|
||||||
|
const response = await split({ text: 'pan, queso' })
|
||||||
|
|
||||||
|
expect(await response.json()).toEqual({ items: ['pan', 'queso'] })
|
||||||
|
expect(JSON.stringify(warnings)).toContain('empty-response')
|
||||||
|
})
|
||||||
|
})
|
||||||
25
apps/api/src/modules/voice/split/route.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import { requireSession } from '@/lib/auth-session'
|
||||||
|
import { createTextGenerator } from '@/lib/model'
|
||||||
|
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(createTextGenerator(), c.get('logger')).execute({
|
||||||
|
text,
|
||||||
|
})
|
||||||
|
|
||||||
|
return resultJson(c, result)
|
||||||
|
},
|
||||||
|
)
|
||||||
13
apps/api/src/modules/voice/split/schema.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { VOICE_TEXT_MAX_LENGTH } from '@superlist/shared'
|
||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
/** Body of `POST /voice/split`. Longer transcripts are cut to `VOICE_TEXT_MAX_LENGTH`. */
|
||||||
|
export const SplitVoiceSchema = z.object({
|
||||||
|
text: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.min(1, 'El texto no puede estar vacío')
|
||||||
|
.transform((text) => text.slice(0, VOICE_TEXT_MAX_LENGTH)),
|
||||||
|
})
|
||||||
|
|
||||||
|
export type SplitVoiceInput = z.infer<typeof SplitVoiceSchema>
|
||||||
57
apps/api/src/modules/voice/split/use-case.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import {
|
||||||
|
Ok,
|
||||||
|
type ProblemDetails,
|
||||||
|
type Result,
|
||||||
|
VOICE_TEXT_MAX_LENGTH,
|
||||||
|
type VoiceSplitResponse,
|
||||||
|
} from '@superlist/shared'
|
||||||
|
|
||||||
|
import type { Logger } from '@/lib/logger'
|
||||||
|
import { ModelError, type TextGenerator } from '@/lib/text-generator'
|
||||||
|
|
||||||
|
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 ModelError ? 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('voice split: using the fallback split ({reason})', {
|
||||||
|
reason,
|
||||||
|
textLength: text.length,
|
||||||
|
})
|
||||||
|
|
||||||
|
return Ok({ items: fallbackSplit(text) })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,8 +8,9 @@
|
|||||||
name="viewport"
|
name="viewport"
|
||||||
content="width=device-width, initial-scale=1.0, viewport-fit=cover"
|
content="width=device-width, initial-scale=1.0, viewport-fit=cover"
|
||||||
/>
|
/>
|
||||||
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#ffffff" />
|
<!-- Set from the resolved theme (script below and `theme-provider.tsx`), not with
|
||||||
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#0a0a0a" />
|
`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="apple-mobile-web-app-capable" content="yes" />
|
||||||
<meta name="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" />
|
<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)
|
stored === 'dark' || (stored !== 'light' && matchMedia('(prefers-color-scheme: dark)').matches)
|
||||||
document.documentElement.classList.toggle('dark', dark)
|
document.documentElement.classList.toggle('dark', dark)
|
||||||
document.documentElement.style.colorScheme = dark ? 'dark' : 'light'
|
document.documentElement.style.colorScheme = dark ? 'dark' : 'light'
|
||||||
|
document
|
||||||
|
.querySelector('meta[name="theme-color"]')
|
||||||
|
.setAttribute('content', dark ? '#0f1411' : '#f9f8f5')
|
||||||
})()
|
})()
|
||||||
</script>
|
</script>
|
||||||
</head>
|
</head>
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
"test": "vitest run --passWithNoTests"
|
"test": "vitest run --passWithNoTests"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@better-auth/passkey": "1.7.7",
|
||||||
"@fontsource-variable/geist": "^5.3.0",
|
"@fontsource-variable/geist": "^5.3.0",
|
||||||
"@hookform/resolvers": "^5.9.1",
|
"@hookform/resolvers": "^5.9.1",
|
||||||
"@superlist/shared": "workspace:*",
|
"@superlist/shared": "workspace:*",
|
||||||
@@ -31,6 +32,7 @@
|
|||||||
"recharts": "^3.10.1",
|
"recharts": "^3.10.1",
|
||||||
"sonner": "^2.0.8",
|
"sonner": "^2.0.8",
|
||||||
"tailwind-merge": "^3.7.0",
|
"tailwind-merge": "^3.7.0",
|
||||||
|
"workbox-window": "^7.4.1",
|
||||||
"zod": "^4.6.7"
|
"zod": "^4.6.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 2.9 KiB After Width: | Height: | Size: 5.1 KiB |
@@ -1,14 +1,6 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32" height="32" role="img" aria-label="Superlist">
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-label="Superlist">
|
||||||
<rect width="32" height="32" rx="7" fill="#0a0a0a" />
|
<rect width="512" height="512" rx="116" fill="#287c39"/>
|
||||||
<text
|
<path d="M190 206c0-58 26-86 66-86s66 28 66 86" fill="none" stroke="#faf9f6" stroke-width="26" stroke-linecap="round"/>
|
||||||
x="16"
|
<path d="M150 196h212l20 196H130z" fill="#faf9f6" stroke="#faf9f6" stroke-width="44" stroke-linejoin="round"/>
|
||||||
y="17"
|
<path d="M198 300l42 42 78-80" fill="none" stroke="#287c39" stroke-width="34" stroke-linecap="round" stroke-linejoin="round"/>
|
||||||
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>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 431 B After Width: | Height: | Size: 552 B |
|
Before Width: | Height: | Size: 8.9 KiB After Width: | Height: | Size: 13 KiB |
@@ -1,14 +1,8 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-label="Superlist">
|
<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" />
|
<rect width="512" height="512" fill="#287c39"/>
|
||||||
<text
|
<g transform="translate(256 262) scale(0.78) translate(-256 -262)">
|
||||||
x="256"
|
<path d="M190 206c0-58 26-86 66-86s66 28 66 86" fill="none" stroke="#faf9f6" stroke-width="26" stroke-linecap="round"/>
|
||||||
y="270"
|
<path d="M150 196h212l20 196H130z" fill="#faf9f6" stroke="#faf9f6" stroke-width="44" stroke-linejoin="round"/>
|
||||||
text-anchor="middle"
|
<path d="M198 300l42 42 78-80" fill="none" stroke="#287c39" stroke-width="34" stroke-linecap="round" stroke-linejoin="round"/>
|
||||||
dominant-baseline="middle"
|
</g>
|
||||||
font-family="'Geist Variable', Helvetica, Arial, sans-serif"
|
|
||||||
font-size="216"
|
|
||||||
font-weight="600"
|
|
||||||
letter-spacing="-9"
|
|
||||||
fill="#fafafa"
|
|
||||||
>SL</text>
|
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 431 B After Width: | Height: | Size: 620 B |
|
Before Width: | Height: | Size: 5.0 KiB After Width: | Height: | Size: 7.4 KiB |
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 22 KiB |
10
apps/web/src/components/app-badge.tsx
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { useAppBadge } from '@/hooks/use-app-badge'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keeps the installed app's icon badge in sync with the primary list. It renders
|
||||||
|
* nothing: the icon lives outside the page.
|
||||||
|
*/
|
||||||
|
export function AppBadge() {
|
||||||
|
useAppBadge()
|
||||||
|
return null
|
||||||
|
}
|
||||||
50
apps/web/src/components/app-logo.tsx
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Superlist's mark: a shopping bag with a check, on the app's green. It is the same
|
||||||
|
* drawing as `public/favicon.svg` and the PWA icons, so keep them in sync.
|
||||||
|
*/
|
||||||
|
export function AppLogo({ className }: { className?: string }) {
|
||||||
|
return (
|
||||||
|
<svg
|
||||||
|
viewBox="0 0 512 512"
|
||||||
|
className={cn('size-8 shrink-0', className)}
|
||||||
|
role="img"
|
||||||
|
aria-label="Superlist"
|
||||||
|
>
|
||||||
|
<rect width="512" height="512" rx="116" fill="#287c39" />
|
||||||
|
<path
|
||||||
|
d="M190 206c0-58 26-86 66-86s66 28 66 86"
|
||||||
|
fill="none"
|
||||||
|
stroke="#faf9f6"
|
||||||
|
strokeWidth="26"
|
||||||
|
strokeLinecap="round"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
d="M150 196h212l20 196H130z"
|
||||||
|
fill="#faf9f6"
|
||||||
|
stroke="#faf9f6"
|
||||||
|
strokeWidth="44"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
d="M198 300l42 42 78-80"
|
||||||
|
fill="none"
|
||||||
|
stroke="#287c39"
|
||||||
|
strokeWidth="34"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The mark next to the "Superlist" name, for the sign-in and sign-up pages. */
|
||||||
|
export function AppBrand({ className }: { className?: string }) {
|
||||||
|
return (
|
||||||
|
<div className={cn('flex items-center justify-center gap-2.5', className)}>
|
||||||
|
<AppLogo className="size-10" />
|
||||||
|
<span className="text-2xl font-bold tracking-tight">Superlist</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -9,7 +9,7 @@ export function InstallPrompt() {
|
|||||||
if (!visible) return null
|
if (!visible) return null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-x-0 bottom-0 z-40 px-3 pb-[calc(4.75rem+env(safe-area-inset-bottom))] md:left-auto md:right-4 md:max-w-md md:px-4 md:pb-4">
|
<div className="fixed inset-x-0 bottom-0 z-40 px-3 pb-[calc(var(--bottom-nav-height,4.5rem)+0.25rem+env(safe-area-inset-bottom))] md:left-auto md:right-4 md:max-w-md md:px-4 md:pb-4">
|
||||||
<div className="bg-card shadow-lg border rounded-xl p-3 flex items-center gap-3 w-full">
|
<div className="bg-card shadow-lg border rounded-xl p-3 flex items-center gap-3 w-full">
|
||||||
<div className="bg-primary/10 text-primary rounded-lg p-2">
|
<div className="bg-primary/10 text-primary rounded-lg p-2">
|
||||||
{needsManualInstructions ? (
|
{needsManualInstructions ? (
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { ListItem } from '@superlist/shared'
|
import type { ListItem } from '@superlist/shared'
|
||||||
import { ChevronDownIcon } from 'lucide-react'
|
import { CheckIcon, ChevronDownIcon } from 'lucide-react'
|
||||||
|
|
||||||
|
import { Card } from '@/components/ui/card'
|
||||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
|
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
|
||||||
import type { useUpdateItem } from '@/hooks/use-items'
|
import type { useUpdateItem } from '@/hooks/use-items'
|
||||||
|
|
||||||
@@ -10,33 +11,53 @@ type BoughtItemListProps = {
|
|||||||
items: ListItem[]
|
items: ListItem[]
|
||||||
updateItem: ReturnType<typeof useUpdateItem>
|
updateItem: ReturnType<typeof useUpdateItem>
|
||||||
savingIds: string[]
|
savingIds: string[]
|
||||||
|
onEdit: (item: ListItem) => void
|
||||||
|
onMove: (item: ListItem) => void
|
||||||
|
onDelete: (item: ListItem) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Collapsible "Comprados hoy" section below the pending items. Expanded by
|
* Collapsible "Comprados (N)" section at the end of the list, folded by default so
|
||||||
* default so marking an item visibly moves it down; the user can fold it.
|
* the pending items stay in focus. Tapping an item here un-buys it and it returns
|
||||||
* Tapping an item here un-buys it and it returns to the pending list.
|
* to the pending list.
|
||||||
*/
|
*/
|
||||||
export function BoughtItemList({ items, updateItem, savingIds }: BoughtItemListProps) {
|
export function BoughtItemList({
|
||||||
|
items,
|
||||||
|
updateItem,
|
||||||
|
savingIds,
|
||||||
|
onEdit,
|
||||||
|
onMove,
|
||||||
|
onDelete,
|
||||||
|
}: BoughtItemListProps) {
|
||||||
return (
|
return (
|
||||||
<Collapsible defaultOpen>
|
<Collapsible asChild>
|
||||||
<CollapsibleTrigger className="group flex w-full items-center gap-1.5 py-1 text-left">
|
<section className="border-border overflow-hidden rounded-xl border border-dashed">
|
||||||
<ChevronDownIcon className="text-muted-foreground size-4 transition-transform group-data-[state=closed]:-rotate-90" />
|
<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">
|
||||||
<span className="text-muted-foreground text-sm font-medium">Comprados hoy</span>
|
<CheckIcon className="text-primary size-4" strokeWidth={2.5} aria-hidden />
|
||||||
<span className="text-muted-foreground text-sm">({items.length})</span>
|
<span className="flex-1 text-base">Comprados ({items.length})</span>
|
||||||
|
<ChevronDownIcon
|
||||||
|
className="size-5 transition-transform group-data-[state=open]:rotate-180"
|
||||||
|
aria-hidden
|
||||||
|
/>
|
||||||
</CollapsibleTrigger>
|
</CollapsibleTrigger>
|
||||||
<CollapsibleContent>
|
<CollapsibleContent>
|
||||||
<ul className="flex flex-col gap-2 pt-2">
|
<Card className="gap-0 rounded-none border-x-0 border-b-0 py-0 shadow-none">
|
||||||
|
<ul className="divide-y">
|
||||||
{items.map((item) => (
|
{items.map((item) => (
|
||||||
<ItemRow
|
<ItemRow
|
||||||
key={item.id}
|
key={item.id}
|
||||||
item={item}
|
item={item}
|
||||||
updateItem={updateItem}
|
updateItem={updateItem}
|
||||||
isSaving={savingIds.includes(item.id)}
|
isSaving={savingIds.includes(item.id)}
|
||||||
|
onEdit={() => onEdit(item)}
|
||||||
|
onMove={() => onMove(item)}
|
||||||
|
onDelete={() => onDelete(item)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
|
</Card>
|
||||||
</CollapsibleContent>
|
</CollapsibleContent>
|
||||||
|
</section>
|
||||||
</Collapsible>
|
</Collapsible>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,28 @@
|
|||||||
import { zodResolver } from '@hookform/resolvers/zod'
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
import { PlusIcon } from 'lucide-react'
|
import { Loader2Icon, MicIcon, PlusIcon } from 'lucide-react'
|
||||||
import { useForm } from 'react-hook-form'
|
import { type ClipboardEvent, useEffect, useState } from 'react'
|
||||||
|
import { useForm, useWatch } from 'react-hook-form'
|
||||||
import { z } from 'zod'
|
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 { Field, FieldError } from '@/components/ui/field'
|
||||||
import { Input } from '@/components/ui/input'
|
import {
|
||||||
import { useCreateItem } from '@/hooks/use-items'
|
InputGroup,
|
||||||
import { ApiError } from '@/lib/api-client'
|
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({
|
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>
|
type CreateItemValues = z.infer<typeof createItemSchema>
|
||||||
@@ -43,50 +55,203 @@ export function refocusNewItemInput(): void {
|
|||||||
document.getElementById(NEW_ITEM_INPUT_ID)?.focus()
|
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) {
|
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>({
|
const form = useForm<CreateItemValues>({
|
||||||
resolver: zodResolver(createItemSchema),
|
resolver: zodResolver(createItemSchema),
|
||||||
defaultValues: { name: '' },
|
defaultValues: { entry: '' },
|
||||||
})
|
})
|
||||||
|
|
||||||
// The input clears at once (the item is added optimistically) so several items
|
const text = useWatch({ control: form.control, name: 'entry' })
|
||||||
// can be typed in a row; if the request fails the text comes back with the error.
|
const literal = literalText !== null && literalText === text
|
||||||
const onSubmit = form.handleSubmit((values) => {
|
|
||||||
form.reset()
|
const restoreText = (source: string, message: string) => {
|
||||||
createItem.mutate(values, {
|
const current = form.getValues('entry').trim()
|
||||||
onError: (error) => {
|
form.setValue('entry', current ? `${current}; ${source}` : source)
|
||||||
form.setValue('name', values.name)
|
form.setError('entry', { message })
|
||||||
form.setError('name', {
|
}
|
||||||
message:
|
|
||||||
error instanceof ApiError
|
// A failed item comes back to the input, and so does a dictation that breaks the limits.
|
||||||
? (error.problem.detail ?? error.problem.title)
|
const { existing, addItems, addDictation, processing } = useAddItems(listId, {
|
||||||
: 'No pudimos añadir el artículo.',
|
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 (
|
return (
|
||||||
<form onSubmit={onSubmit} className="flex items-start gap-2">
|
<form
|
||||||
<Field className="flex-1" data-invalid={!!form.formState.errors.name}>
|
onSubmit={(event) => {
|
||||||
<Input
|
// 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}
|
id={NEW_ITEM_INPUT_ID}
|
||||||
aria-label="Nuevo artículo"
|
aria-label="Nuevo artículo"
|
||||||
|
aria-invalid={!!form.formState.errors.entry}
|
||||||
|
aria-describedby={dictation.error ? 'dictation-error' : undefined}
|
||||||
autoComplete="off"
|
autoComplete="off"
|
||||||
placeholder="Añade un artículo…"
|
placeholder={
|
||||||
|
dictation.listening ? 'Escuchando…' : 'Agregar… ej: 400 g de jamón. Feteado fino'
|
||||||
|
}
|
||||||
autoFocus={autoFocus}
|
autoFocus={autoFocus}
|
||||||
{...form.register('name')}
|
readOnly={dictating}
|
||||||
|
className="text-base"
|
||||||
|
onPaste={onPaste}
|
||||||
|
onKeyDown={keyboardDictation.onKeyDown}
|
||||||
|
onInput={keyboardDictation.onInput}
|
||||||
|
{...form.register('entry', { onChange: dictation.clearError })}
|
||||||
/>
|
/>
|
||||||
<FieldError errors={[form.formState.errors.name]} />
|
{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>
|
</Field>
|
||||||
|
|
||||||
<Button type="submit">
|
|
||||||
<PlusIcon />
|
|
||||||
Agregar
|
|
||||||
</Button>
|
|
||||||
</form>
|
</form>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
161
apps/web/src/components/items/dictate-fab.tsx
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
import { Loader2Icon, MicIcon, SquareIcon, XIcon } from 'lucide-react'
|
||||||
|
import { useRef, useState } from 'react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
import { refocusNewItemInput } from '@/components/items/create-item-form'
|
||||||
|
import { DictationFeedback } from '@/components/items/dictation-feedback'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import {
|
||||||
|
Sheet,
|
||||||
|
SheetClose,
|
||||||
|
SheetContent,
|
||||||
|
SheetDescription,
|
||||||
|
SheetTitle,
|
||||||
|
} from '@/components/ui/sheet'
|
||||||
|
import { useDictateItems } from '@/hooks/use-dictate-items'
|
||||||
|
import { DICTATION_MESSAGES } from '@/hooks/use-microphone-dictation'
|
||||||
|
|
||||||
|
type DictateFabProps = {
|
||||||
|
listId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Floating microphone for a list that already has items. An empty list dictates from
|
||||||
|
* its central card; this repeats that experience on a bottom sheet so the rows stay
|
||||||
|
* on screen. The tap opens the sheet and starts listening in the same gesture, which
|
||||||
|
* is what Safari needs to grant the microphone.
|
||||||
|
*/
|
||||||
|
export function DictateFab({ listId }: DictateFabProps) {
|
||||||
|
const [open, setOpen] = useState(false)
|
||||||
|
// "Escribir a mano" moves the focus to the composer once the sheet is gone.
|
||||||
|
const focusInput = useRef(false)
|
||||||
|
|
||||||
|
const { listening, busy, processing, supported, heard, message, start, stop } = useDictateItems(
|
||||||
|
listId,
|
||||||
|
{
|
||||||
|
onFinish: (added) => added && setOpen(false),
|
||||||
|
// Closing the sheet while it listened can still end in a rejection: show it.
|
||||||
|
onMessage: (detail) => {
|
||||||
|
if (!open) toast.error(detail)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
const label = processing
|
||||||
|
? 'Procesando el dictado'
|
||||||
|
: busy
|
||||||
|
? 'Pidiendo acceso al micrófono'
|
||||||
|
: listening
|
||||||
|
? 'Detener dictado'
|
||||||
|
: 'Dictar ítems'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="icon"
|
||||||
|
aria-label="Dictar ítems"
|
||||||
|
aria-haspopup="dialog"
|
||||||
|
aria-expanded={open}
|
||||||
|
className="fixed right-4 bottom-[calc(var(--bottom-nav-height,4.5rem)+env(safe-area-inset-bottom)+0.75rem)] z-40 size-14 rounded-full shadow-lg md:right-6 md:bottom-6"
|
||||||
|
onClick={() => {
|
||||||
|
setOpen(true)
|
||||||
|
// Called right in the click, before any state update, so the browser still
|
||||||
|
// treats the microphone request as the user's.
|
||||||
|
start()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<MicIcon className="size-6" />
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Sheet
|
||||||
|
open={open}
|
||||||
|
onOpenChange={(next) => {
|
||||||
|
setOpen(next)
|
||||||
|
// Leaving the sheet ends the dictation: what was heard is delivered, like
|
||||||
|
// "Detener". While the permission is still being asked it just cancels, and
|
||||||
|
// with a request in flight it is a no-op.
|
||||||
|
if (!next) stop()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<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"
|
||||||
|
onCloseAutoFocus={(event) => {
|
||||||
|
if (!focusInput.current) return
|
||||||
|
focusInput.current = false
|
||||||
|
event.preventDefault()
|
||||||
|
refocusNewItemInput()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="bg-muted-foreground/30 mx-auto mb-3 h-1 w-10 rounded-full" aria-hidden />
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<SheetTitle className="text-lg font-semibold">Dictar ítems</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="text-muted-foreground mt-1">
|
||||||
|
Di los ítems con una pausa entre cada uno y los añadimos a la lista.
|
||||||
|
</SheetDescription>
|
||||||
|
|
||||||
|
<div className="flex flex-col items-center gap-3 pt-6 pb-2">
|
||||||
|
{supported ? (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={listening ? 'default' : 'secondary'}
|
||||||
|
aria-label={label}
|
||||||
|
aria-pressed={listening}
|
||||||
|
disabled={busy}
|
||||||
|
className="relative h-12 rounded-full px-6 text-base"
|
||||||
|
onClick={() => {
|
||||||
|
if (listening) stop()
|
||||||
|
else start()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{busy ? (
|
||||||
|
<Loader2Icon className="size-5 animate-spin" />
|
||||||
|
) : listening ? (
|
||||||
|
<SquareIcon className="size-5 fill-current" />
|
||||||
|
) : (
|
||||||
|
<MicIcon className="size-5" />
|
||||||
|
)}
|
||||||
|
{processing ? 'Procesando…' : listening ? 'Detener dictado' : 'Dictar ítems'}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<DictationFeedback listening={listening} heard={heard} message={message} />
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<p className="text-muted-foreground max-w-xs text-center text-sm">
|
||||||
|
{DICTATION_MESSAGES.unsupported}
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="secondary"
|
||||||
|
className="h-11 rounded-full px-5"
|
||||||
|
onClick={() => {
|
||||||
|
focusInput.current = true
|
||||||
|
setOpen(false)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Escribir a mano
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
51
apps/web/src/components/items/dictate-items-button.tsx
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import { Loader2Icon, MicIcon, SquareIcon } from 'lucide-react'
|
||||||
|
|
||||||
|
import { DictationFeedback } from '@/components/items/dictation-feedback'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { useDictateItems } from '@/hooks/use-dictate-items'
|
||||||
|
|
||||||
|
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 { listening, busy, processing, heard, message, start, stop } = useDictateItems(listId)
|
||||||
|
|
||||||
|
const label = processing
|
||||||
|
? 'Procesando el dictado'
|
||||||
|
: 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={() => {
|
||||||
|
if (listening) stop()
|
||||||
|
else start()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{busy ? (
|
||||||
|
<Loader2Icon className="animate-spin" />
|
||||||
|
) : listening ? (
|
||||||
|
<SquareIcon className="fill-current" />
|
||||||
|
) : (
|
||||||
|
<MicIcon />
|
||||||
|
)}
|
||||||
|
{listening ? 'Detener dictado' : 'Dictar ítems'}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<DictationFeedback listening={listening} heard={heard} message={message} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
44
apps/web/src/components/items/dictation-feedback.tsx
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
type DictationFeedbackProps = {
|
||||||
|
/** Whether the microphone is listening right now. */
|
||||||
|
listening: boolean
|
||||||
|
/** What has been heard so far, one phrase per item. */
|
||||||
|
heard: string
|
||||||
|
/** Why the last dictation did not deliver anything, in Spanish. */
|
||||||
|
message: string | null
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Live state of a dictation: that we are listening, the phrases heard so far and the
|
||||||
|
* last error. Shared by the empty list's card and the floating button's sheet so both
|
||||||
|
* tell the same thing.
|
||||||
|
*/
|
||||||
|
export function DictationFeedback({
|
||||||
|
listening,
|
||||||
|
heard,
|
||||||
|
message,
|
||||||
|
className,
|
||||||
|
}: DictationFeedbackProps) {
|
||||||
|
return (
|
||||||
|
<div aria-live="polite" className={cn('flex flex-col items-center gap-1 text-sm', className)}>
|
||||||
|
{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 && heard && <p className="text-muted-foreground max-w-xs text-center">{heard}</p>}
|
||||||
|
{listening && !heard && (
|
||||||
|
<p className="text-muted-foreground text-center">
|
||||||
|
Di «nuevo ítem» o haz una pausa entre artículos.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{message && !listening && <p className="text-destructive max-w-xs text-center">{message}</p>}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
55
apps/web/src/components/items/item-input-preview.tsx
Normal 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,17 +1,28 @@
|
|||||||
|
import type { ListItem } from '@superlist/shared'
|
||||||
import { ShoppingBasketIcon } from 'lucide-react'
|
import { ShoppingBasketIcon } from 'lucide-react'
|
||||||
|
import { useState } from 'react'
|
||||||
|
|
||||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||||
import { Card, CardContent } from '@/components/ui/card'
|
import { Card, CardContent } from '@/components/ui/card'
|
||||||
import { Separator } from '@/components/ui/separator'
|
|
||||||
import { Skeleton } from '@/components/ui/skeleton'
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
import { useItems, usePendingItemUpdates, useUpdateItem } from '@/hooks/use-items'
|
import {
|
||||||
|
useDeleteItem,
|
||||||
|
useItems,
|
||||||
|
usePendingDeletions,
|
||||||
|
usePendingItemUpdates,
|
||||||
|
useUpdateItem,
|
||||||
|
} from '@/hooks/use-items'
|
||||||
import { useListEvents } from '@/hooks/use-list-events'
|
import { useListEvents } from '@/hooks/use-list-events'
|
||||||
import { useToday } from '@/hooks/use-today'
|
import { useToday } from '@/hooks/use-today'
|
||||||
import { ApiError } from '@/lib/api-client'
|
import { ApiError } from '@/lib/api-client'
|
||||||
import { splitItems } from '@/lib/items'
|
import { splitItems } from '@/lib/items'
|
||||||
|
|
||||||
import { BoughtItemList } from './bought-item-list'
|
import { BoughtItemList } from './bought-item-list'
|
||||||
|
import { DictateFab } from './dictate-fab'
|
||||||
|
import { DictateItemsButton } from './dictate-items-button'
|
||||||
import { ItemRow } from './item-row'
|
import { ItemRow } from './item-row'
|
||||||
|
import { ItemSheet } from './item-sheet'
|
||||||
|
import { MoveItemDialog } from './move-item-dialog'
|
||||||
|
|
||||||
type ItemListProps = {
|
type ItemListProps = {
|
||||||
listId: string
|
listId: string
|
||||||
@@ -19,14 +30,31 @@ type ItemListProps = {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Items loaded from the API, pending ones first. Tapping an item marks it as
|
* Items loaded from the API, pending ones first. Tapping an item marks it as
|
||||||
* bought; bought items move to a collapsible "Comprados 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.
|
* and are only shown on the day they were bought.
|
||||||
*/
|
*/
|
||||||
export function ItemList({ listId }: ItemListProps) {
|
export function ItemList({ listId }: ItemListProps) {
|
||||||
const { data: items, isPending, error } = useItems(listId)
|
const { data: items, isPending, error } = useItems(listId)
|
||||||
const updateItem = useUpdateItem(listId)
|
const updateItem = useUpdateItem(listId)
|
||||||
const savingIds = usePendingItemUpdates(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()
|
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.
|
// Live updates: another member adds or buys an item and this list refreshes.
|
||||||
useListEvents(listId)
|
useListEvents(listId)
|
||||||
@@ -54,7 +82,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) {
|
if (pending.length === 0 && boughtToday.length === 0) {
|
||||||
return (
|
return (
|
||||||
@@ -69,32 +103,53 @@ export function ItemList({ listId }: ItemListProps) {
|
|||||||
Usa el campo de arriba para añadir tu primer artículo.
|
Usa el campo de arriba para añadir tu primer artículo.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<DictateItemsButton listId={listId} />
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-4 pb-16">
|
||||||
{pending.length > 0 && (
|
{pending.length > 0 && (
|
||||||
<ul className="flex flex-col gap-2">
|
<Card className="py-0">
|
||||||
|
<ul className="divide-y">
|
||||||
{pending.map((item) => (
|
{pending.map((item) => (
|
||||||
<ItemRow
|
<ItemRow
|
||||||
key={item.id}
|
key={item.id}
|
||||||
item={item}
|
item={item}
|
||||||
updateItem={updateItem}
|
updateItem={updateItem}
|
||||||
isSaving={savingIds.includes(item.id)}
|
isSaving={savingIds.includes(item.id)}
|
||||||
|
onEdit={() => setEditingId(item.id)}
|
||||||
|
onMove={() => openMoveDialog(item)}
|
||||||
|
onDelete={() => handleDelete(item)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
|
</Card>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{boughtToday.length > 0 && (
|
{boughtToday.length > 0 && (
|
||||||
<>
|
<BoughtItemList
|
||||||
{pending.length > 0 && <Separator className="mt-2" />}
|
items={boughtToday}
|
||||||
<BoughtItemList items={boughtToday} updateItem={updateItem} savingIds={savingIds} />
|
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)} />
|
||||||
|
|
||||||
|
{/* An empty list dictates from its central card; with items, from this button. */}
|
||||||
|
<DictateFab listId={listId} />
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,61 +1,234 @@
|
|||||||
import type { ListItem } from '@superlist/shared'
|
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 { refocusNewItemInput } from '@/components/items/create-item-form'
|
import {
|
||||||
import { Card, CardContent } from '@/components/ui/card'
|
ContextMenu,
|
||||||
|
ContextMenuContent,
|
||||||
|
ContextMenuItem,
|
||||||
|
ContextMenuSeparator,
|
||||||
|
ContextMenuTrigger,
|
||||||
|
} from '@/components/ui/context-menu'
|
||||||
import { isOptimisticItem, type useUpdateItem } from '@/hooks/use-items'
|
import { isOptimisticItem, type useUpdateItem } from '@/hooks/use-items'
|
||||||
|
import { quantityLabel } from '@/lib/items'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
type ItemRowProps = {
|
export type ItemRowProps = {
|
||||||
item: ListItem
|
item: ListItem
|
||||||
updateItem: ReturnType<typeof useUpdateItem>
|
updateItem: ReturnType<typeof useUpdateItem>
|
||||||
/** This item's bought state is being saved; only this row waits for it. */
|
/** This item's bought state is being saved; only this row waits for it. */
|
||||||
isSaving: boolean
|
isSaving: boolean
|
||||||
|
/** 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. */
|
/** Horizontal drag (px) that turns a touch on the row into "edit the item". */
|
||||||
export function ItemRow({ item, updateItem, isSaving }: ItemRowProps) {
|
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 (
|
return (
|
||||||
<li>
|
<li>
|
||||||
<Card>
|
<div className="relative overflow-hidden">
|
||||||
<CardContent className="p-0">
|
{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',
|
||||||
|
)}
|
||||||
|
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
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
aria-pressed={item.completed}
|
aria-pressed={item.completed}
|
||||||
// A placeholder has no server id yet, so it cannot be toggled.
|
disabled={!editable}
|
||||||
disabled={isSaving || isOptimisticItem(item)}
|
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
|
if (swiped.current) {
|
||||||
|
swiped.current = null
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
updateItem.mutate({ itemId: item.id, completed: !item.completed })
|
updateItem.mutate({ itemId: item.id, completed: !item.completed })
|
||||||
// Back to the input, so the next item can be typed right away.
|
|
||||||
refocusNewItemInput()
|
|
||||||
}}
|
}}
|
||||||
className="flex w-full cursor-pointer items-center gap-3 p-3 text-left disabled:cursor-default disabled:opacity-60"
|
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
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
'flex size-5 shrink-0 items-center justify-center rounded-full border',
|
'flex size-6 shrink-0 items-center justify-center rounded-full border-[1.5px] transition-colors',
|
||||||
item.completed
|
item.completed
|
||||||
? 'bg-primary text-primary-foreground border-primary'
|
? 'bg-primary text-primary-foreground border-primary'
|
||||||
: 'border-muted-foreground/40 text-transparent',
|
: 'border-muted-foreground/45 text-transparent',
|
||||||
)}
|
)}
|
||||||
aria-hidden
|
aria-hidden
|
||||||
>
|
>
|
||||||
<CheckIcon className="size-3" />
|
<CheckIcon className="size-3.5" strokeWidth={3} />
|
||||||
</span>
|
</span>
|
||||||
|
<span className="flex min-w-0 flex-1 flex-col">
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
'min-w-0 flex-1 truncate',
|
'truncate text-base',
|
||||||
item.completed && 'text-muted-foreground line-through',
|
item.completed && 'text-muted-foreground line-through',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{item.name}
|
{item.name}
|
||||||
</span>
|
</span>
|
||||||
{item.quantity && (
|
{item.notes && (
|
||||||
<span className="text-muted-foreground shrink-0 text-sm">{item.quantity}</span>
|
<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>
|
</button>
|
||||||
</CardContent>
|
</ContextMenuTrigger>
|
||||||
</Card>
|
{/* 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>
|
</li>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
245
apps/web/src/components/items/item-sheet.tsx
Normal file
@@ -0,0 +1,245 @@
|
|||||||
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
|
import type { ListItem } from '@superlist/shared'
|
||||||
|
import { MinusIcon, PlusIcon, Trash2Icon, XIcon } from 'lucide-react'
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { useForm, useWatch } from 'react-hook-form'
|
||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Field, FieldError, FieldLabel } from '@/components/ui/field'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import {
|
||||||
|
Sheet,
|
||||||
|
SheetClose,
|
||||||
|
SheetContent,
|
||||||
|
SheetDescription,
|
||||||
|
SheetTitle,
|
||||||
|
} from '@/components/ui/sheet'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import type { useUpdateItem } from '@/hooks/use-items'
|
||||||
|
import {
|
||||||
|
amountValue,
|
||||||
|
EDITOR_UNITS,
|
||||||
|
fromEditableQuantity,
|
||||||
|
stepAmount,
|
||||||
|
toEditableQuantity,
|
||||||
|
} from '@/lib/item-quantity'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
const itemSchema = z
|
||||||
|
.object({
|
||||||
|
name: z.string().trim().min(1, 'Escribe un nombre').max(120, 'Máximo 120 caracteres'),
|
||||||
|
amount: z.string().trim().max(30, 'Máximo 30 caracteres'),
|
||||||
|
unit: z.string(),
|
||||||
|
notes: z.string().trim().max(280, 'Máximo 280 caracteres'),
|
||||||
|
})
|
||||||
|
.refine((value) => (fromEditableQuantity(value)?.length ?? 0) <= 40, {
|
||||||
|
path: ['amount'],
|
||||||
|
message: 'La cantidad es demasiado larga',
|
||||||
|
})
|
||||||
|
|
||||||
|
type ItemValues = z.infer<typeof itemSchema>
|
||||||
|
|
||||||
|
type ItemSheetProps = {
|
||||||
|
/** The item being edited; `null` keeps the sheet closed. */
|
||||||
|
item: ListItem | null
|
||||||
|
updateItem: ReturnType<typeof useUpdateItem>
|
||||||
|
onClose: () => void
|
||||||
|
/** Deletes the item (undoable for a few seconds) and closes the sheet. */
|
||||||
|
onDelete: (item: ListItem) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bottom sheet to edit an item: name, quantity (− / + and a unit), note, delete and
|
||||||
|
* save. Opened by swiping the row to the left or with "Editar" in its right-click menu.
|
||||||
|
*/
|
||||||
|
export function ItemSheet({ item, updateItem, onClose, onDelete }: ItemSheetProps) {
|
||||||
|
// While the sheet slides out `item` is already `null`: keep showing the last one.
|
||||||
|
const [shown, setShown] = useState(item)
|
||||||
|
if (item && item !== shown) setShown(item)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Sheet open={item !== null} onOpenChange={(open) => !open && onClose()}>
|
||||||
|
<SheetContent
|
||||||
|
side="bottom"
|
||||||
|
showCloseButton={false}
|
||||||
|
className="max-h-[90dvh] gap-0 overflow-y-auto rounded-t-3xl px-5 pt-3 pb-[calc(1.25rem+env(safe-area-inset-bottom))] sm:mx-auto sm:max-w-lg"
|
||||||
|
>
|
||||||
|
<div className="bg-muted-foreground/30 mx-auto mb-3 h-1 w-10 rounded-full" aria-hidden />
|
||||||
|
{/* Mounted per item so the form always starts from its current values. */}
|
||||||
|
{shown && (
|
||||||
|
<ItemForm
|
||||||
|
key={shown.id}
|
||||||
|
item={shown}
|
||||||
|
updateItem={updateItem}
|
||||||
|
onClose={onClose}
|
||||||
|
onDelete={onDelete}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemForm({ item, updateItem, onClose, onDelete }: ItemSheetProps & { item: ListItem }) {
|
||||||
|
const form = useForm<ItemValues>({
|
||||||
|
resolver: zodResolver(itemSchema),
|
||||||
|
defaultValues: {
|
||||||
|
name: item.name,
|
||||||
|
...toEditableQuantity(item.quantity),
|
||||||
|
notes: item.notes ?? '',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const [amount, unit] = useWatch({ control: form.control, name: ['amount', 'unit'] })
|
||||||
|
const numeric = amountValue(amount) !== null
|
||||||
|
// A unit the selector does not offer ("paquete") stays available, so it is not lost.
|
||||||
|
const units = EDITOR_UNITS.some((option) => option.value === unit)
|
||||||
|
? EDITOR_UNITS
|
||||||
|
: [...EDITOR_UNITS, { value: unit, label: unit }]
|
||||||
|
|
||||||
|
const step = (direction: 1 | -1) =>
|
||||||
|
form.setValue('amount', stepAmount(amount, unit, direction), { shouldDirty: true })
|
||||||
|
|
||||||
|
const onSubmit = form.handleSubmit((values) => {
|
||||||
|
updateItem.mutate(
|
||||||
|
{
|
||||||
|
itemId: item.id,
|
||||||
|
name: values.name,
|
||||||
|
quantity: fromEditableQuantity(values),
|
||||||
|
notes: values.notes || null,
|
||||||
|
},
|
||||||
|
// The list already shows the new values optimistically; on error the hook reports
|
||||||
|
// the problem and the sheet stays open with what was typed.
|
||||||
|
{ onSuccess: onClose },
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
const errors = form.formState.errors
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={onSubmit} className="flex flex-col gap-5">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<SheetTitle className="text-lg font-semibold">Editar producto</SheetTitle>
|
||||||
|
<SheetClose asChild>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="secondary"
|
||||||
|
size="icon"
|
||||||
|
className="size-11 rounded-full"
|
||||||
|
aria-label="Cerrar"
|
||||||
|
>
|
||||||
|
<XIcon className="size-5" />
|
||||||
|
</Button>
|
||||||
|
</SheetClose>
|
||||||
|
</div>
|
||||||
|
<SheetDescription className="sr-only">
|
||||||
|
Cambia el nombre, la cantidad o la nota de «{item.name}».
|
||||||
|
</SheetDescription>
|
||||||
|
|
||||||
|
<Field data-invalid={!!errors.name}>
|
||||||
|
<FieldLabel htmlFor="item-name">Producto</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="item-name"
|
||||||
|
autoComplete="off"
|
||||||
|
aria-invalid={!!errors.name}
|
||||||
|
className="bg-card h-12 rounded-xl px-4"
|
||||||
|
{...form.register('name')}
|
||||||
|
/>
|
||||||
|
<FieldError errors={[errors.name]} />
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field data-invalid={!!errors.amount}>
|
||||||
|
<FieldLabel htmlFor="item-amount">Cantidad</FieldLabel>
|
||||||
|
<div className="flex flex-wrap items-center gap-3">
|
||||||
|
<div className="bg-card flex h-12 items-center overflow-hidden rounded-xl border">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-full w-12 rounded-none"
|
||||||
|
aria-label="Restar"
|
||||||
|
disabled={!numeric || amount === stepAmount(amount, unit, -1)}
|
||||||
|
onClick={() => step(-1)}
|
||||||
|
>
|
||||||
|
<MinusIcon className="size-5" />
|
||||||
|
</Button>
|
||||||
|
<input
|
||||||
|
id="item-amount"
|
||||||
|
inputMode="decimal"
|
||||||
|
autoComplete="off"
|
||||||
|
aria-invalid={!!errors.amount}
|
||||||
|
className="h-full w-16 border-x bg-transparent text-center text-base outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
|
||||||
|
{...form.register('amount')}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-full w-12 rounded-none"
|
||||||
|
aria-label="Sumar"
|
||||||
|
onClick={() => step(1)}
|
||||||
|
>
|
||||||
|
<PlusIcon className="size-5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<fieldset className="flex flex-wrap gap-2">
|
||||||
|
<legend className="sr-only">Unidad</legend>
|
||||||
|
{units.map((option) => {
|
||||||
|
const selected = option.value === unit
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={option.value || 'count'}
|
||||||
|
type="button"
|
||||||
|
aria-pressed={selected}
|
||||||
|
onClick={() => form.setValue('unit', option.value, { shouldDirty: true })}
|
||||||
|
className={cn(
|
||||||
|
'focus-visible:ring-ring/50 h-11 min-w-11 rounded-xl border px-3 text-base transition-colors outline-none focus-visible:ring-3',
|
||||||
|
selected
|
||||||
|
? 'bg-accent text-accent-foreground border-transparent font-semibold'
|
||||||
|
: 'bg-card hover:bg-muted',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{option.label}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</fieldset>
|
||||||
|
</div>
|
||||||
|
<FieldError errors={[errors.amount]} />
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field data-invalid={!!errors.notes}>
|
||||||
|
<FieldLabel htmlFor="item-notes">Nota</FieldLabel>
|
||||||
|
<Textarea
|
||||||
|
id="item-notes"
|
||||||
|
rows={2}
|
||||||
|
placeholder="Marca, tipo, corte…"
|
||||||
|
aria-invalid={!!errors.notes}
|
||||||
|
className="bg-card min-h-16 rounded-xl px-4 py-3"
|
||||||
|
{...form.register('notes')}
|
||||||
|
/>
|
||||||
|
<FieldError errors={[errors.notes]} />
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="text-destructive hover:text-destructive size-12 rounded-xl"
|
||||||
|
aria-label={`Eliminar «${item.name}»`}
|
||||||
|
onClick={() => onDelete(item)}
|
||||||
|
>
|
||||||
|
<Trash2Icon className="size-5" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
className="h-12 flex-1 rounded-xl text-base font-semibold"
|
||||||
|
disabled={updateItem.isPending}
|
||||||
|
>
|
||||||
|
Guardar
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
)
|
||||||
|
}
|
||||||
21
apps/web/src/components/items/list-composer.tsx
Normal 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
34
apps/web/src/components/items/list-progress.tsx
Normal 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"
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
94
apps/web/src/components/items/move-item-dialog.tsx
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
import type { ListItem } from '@superlist/shared'
|
||||||
|
import { Link } from '@tanstack/react-router'
|
||||||
|
import { ChevronRightIcon, ListIcon } from 'lucide-react'
|
||||||
|
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
|
import { useMoveItem } from '@/hooks/use-items'
|
||||||
|
import { useLists } from '@/hooks/use-lists'
|
||||||
|
import { ApiError } from '@/lib/api-client'
|
||||||
|
|
||||||
|
type MoveItemDialogProps = {
|
||||||
|
listId: string
|
||||||
|
/** The item being moved; `null` keeps the dialog closed. */
|
||||||
|
item: ListItem | null
|
||||||
|
onClose: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lets the user pick another of their lists for an item. Picking one moves the
|
||||||
|
* item there and closes the dialog; the user stays on the current list.
|
||||||
|
*/
|
||||||
|
export function MoveItemDialog({ listId, item, onClose }: MoveItemDialogProps) {
|
||||||
|
const { data: lists, isPending, error } = useLists()
|
||||||
|
const moveItem = useMoveItem(listId)
|
||||||
|
|
||||||
|
const targets = lists?.filter((list) => list.id !== listId) ?? []
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={item !== null} onOpenChange={(open) => !open && onClose()}>
|
||||||
|
<DialogContent className="sm:max-w-sm">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Mover a otra lista</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{item ? `Elige a qué lista quieres mover «${item.name}».` : null}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
{error ? (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertDescription>
|
||||||
|
{error instanceof ApiError
|
||||||
|
? (error.problem.detail ?? error.problem.title)
|
||||||
|
: 'No pudimos cargar tus listas.'}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
) : isPending ? (
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Skeleton className="h-11 w-full" />
|
||||||
|
<Skeleton className="h-11 w-full" />
|
||||||
|
</div>
|
||||||
|
) : targets.length === 0 ? (
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
No tienes otras listas.{' '}
|
||||||
|
<Link to="/lists" className="text-primary underline-offset-4 hover:underline">
|
||||||
|
Crea una
|
||||||
|
</Link>{' '}
|
||||||
|
para poder mover artículos.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<ul className="-mx-2 flex flex-col">
|
||||||
|
{targets.map((list) => (
|
||||||
|
<li key={list.id}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="hover:bg-muted focus-visible:bg-muted flex w-full items-center gap-3 rounded-md px-2 py-3 text-left outline-none transition-colors"
|
||||||
|
onClick={() => {
|
||||||
|
if (!item) return
|
||||||
|
moveItem.mutate({
|
||||||
|
itemId: item.id,
|
||||||
|
targetListId: list.id,
|
||||||
|
targetListName: list.name,
|
||||||
|
})
|
||||||
|
onClose()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ListIcon className="text-muted-foreground size-5 shrink-0" />
|
||||||
|
<span className="min-w-0 flex-1 truncate text-base">{list.name}</span>
|
||||||
|
<ChevronRightIcon className="text-muted-foreground size-4 shrink-0" />
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query'
|
|||||||
import { Link, useMatch, useRouterState } from '@tanstack/react-router'
|
import { Link, useMatch, useRouterState } from '@tanstack/react-router'
|
||||||
import { ArrowLeftIcon, SettingsIcon } from 'lucide-react'
|
import { ArrowLeftIcon, SettingsIcon } from 'lucide-react'
|
||||||
|
|
||||||
|
import { ListSwitcher } from '@/components/layout/list-switcher'
|
||||||
import { sectionTitle } from '@/components/layout/nav-items'
|
import { sectionTitle } from '@/components/layout/nav-items'
|
||||||
import { ThemeToggle } from '@/components/theme-toggle'
|
import { ThemeToggle } from '@/components/theme-toggle'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
@@ -45,8 +46,12 @@ export function AppHeader() {
|
|||||||
)}
|
)}
|
||||||
<div className="ml-auto flex shrink-0 items-center gap-1">
|
<div className="ml-auto flex shrink-0 items-center gap-1">
|
||||||
{list && (
|
{list && (
|
||||||
<Button variant="outline" size="sm" asChild>
|
<Button variant="outline" size="sm" className="h-11 min-w-11" asChild>
|
||||||
<Link to="/lists/$listId/settings" params={{ listId: list.id }}>
|
<Link
|
||||||
|
to="/lists/$listId/settings"
|
||||||
|
params={{ listId: list.id }}
|
||||||
|
aria-label="Gestionar la lista"
|
||||||
|
>
|
||||||
<SettingsIcon className="size-4" />
|
<SettingsIcon className="size-4" />
|
||||||
<span className="hidden sm:inline">Gestionar</span>
|
<span className="hidden sm:inline">Gestionar</span>
|
||||||
</Link>
|
</Link>
|
||||||
@@ -63,14 +68,13 @@ function ListHeading({ list, showBack }: { list: HeaderList; showBack: boolean }
|
|||||||
return (
|
return (
|
||||||
<div className="flex min-w-0 items-center gap-2">
|
<div className="flex min-w-0 items-center gap-2">
|
||||||
{showBack && (
|
{showBack && (
|
||||||
<Button variant="ghost" size="icon" className="-ml-2 size-8 shrink-0" asChild>
|
<Button variant="ghost" size="icon" className="-ml-2 size-11 shrink-0" asChild>
|
||||||
<Link to="/lists" aria-label="Volver a listas">
|
<Link to="/lists" aria-label="Volver a listas">
|
||||||
<ArrowLeftIcon className="size-4" />
|
<ArrowLeftIcon className="size-4" />
|
||||||
</Link>
|
</Link>
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<h1 className="truncate text-sm font-medium">{list.name}</h1>
|
<ListSwitcher list={list} />
|
||||||
{list.isPrimary && <Badge className="shrink-0">Principal</Badge>}
|
|
||||||
<Badge variant="secondary" className="hidden shrink-0 sm:inline-flex">
|
<Badge variant="secondary" className="hidden shrink-0 sm:inline-flex">
|
||||||
{list.role === 'owner' ? 'Propietario' : 'Colaborador'}
|
{list.role === 'owner' ? 'Propietario' : 'Colaborador'}
|
||||||
</Badge>
|
</Badge>
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import { Link, useRouterState } from '@tanstack/react-router'
|
import { Link, useRouterState } from '@tanstack/react-router'
|
||||||
|
import { AppLogo } from '@/components/app-logo'
|
||||||
import { focusNewItemInput } from '@/components/items/create-item-form'
|
import { focusNewItemInput } from '@/components/items/create-item-form'
|
||||||
import { isNavItemActive, NAV_ITEMS } from '@/components/layout/nav-items'
|
import { isNavItemActive, NAV_ITEMS } from '@/components/layout/nav-items'
|
||||||
import { NavUser } from '@/components/layout/nav-user'
|
import { NavUser } from '@/components/layout/nav-user'
|
||||||
|
import { PinnedListsSidebarGroup } from '@/components/layout/pinned-lists'
|
||||||
import {
|
import {
|
||||||
Sidebar,
|
Sidebar,
|
||||||
SidebarContent,
|
SidebarContent,
|
||||||
@@ -25,9 +27,7 @@ export function AppSidebar() {
|
|||||||
<SidebarMenuItem>
|
<SidebarMenuItem>
|
||||||
<SidebarMenuButton size="lg" asChild>
|
<SidebarMenuButton size="lg" asChild>
|
||||||
<Link to="/" onClick={() => focusNewItemInput(pathname)}>
|
<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">
|
<AppLogo className="size-8 rounded-lg" />
|
||||||
SL
|
|
||||||
</div>
|
|
||||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||||
<span className="truncate font-medium">Superlist</span>
|
<span className="truncate font-medium">Superlist</span>
|
||||||
<span className="text-muted-foreground truncate text-xs">Listas compartidas</span>
|
<span className="text-muted-foreground truncate text-xs">Listas compartidas</span>
|
||||||
@@ -61,6 +61,7 @@ export function AppSidebar() {
|
|||||||
))}
|
))}
|
||||||
</SidebarMenu>
|
</SidebarMenu>
|
||||||
</SidebarGroup>
|
</SidebarGroup>
|
||||||
|
<PinnedListsSidebarGroup />
|
||||||
</SidebarContent>
|
</SidebarContent>
|
||||||
|
|
||||||
<SidebarFooter>
|
<SidebarFooter>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Link, useRouterState } from '@tanstack/react-router'
|
|||||||
|
|
||||||
import { focusNewItemInput } from '@/components/items/create-item-form'
|
import { focusNewItemInput } from '@/components/items/create-item-form'
|
||||||
import { isNavItemActive, NAV_ITEMS } from '@/components/layout/nav-items'
|
import { isNavItemActive, NAV_ITEMS } from '@/components/layout/nav-items'
|
||||||
|
import { PinnedListsBar } from '@/components/layout/pinned-lists'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
export function BottomNav() {
|
export function BottomNav() {
|
||||||
@@ -9,7 +10,8 @@ export function BottomNav() {
|
|||||||
|
|
||||||
return (
|
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)]">
|
<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">
|
<PinnedListsBar />
|
||||||
|
<nav className="mx-auto flex h-18 max-w-lg items-center justify-around px-2">
|
||||||
{NAV_ITEMS.map((item) => {
|
{NAV_ITEMS.map((item) => {
|
||||||
const active = isNavItemActive(pathname, item.to)
|
const active = isNavItemActive(pathname, item.to)
|
||||||
|
|
||||||
@@ -20,12 +22,15 @@ export function BottomNav() {
|
|||||||
onClick={item.to === '/' ? () => focusNewItemInput(pathname) : undefined}
|
onClick={item.to === '/' ? () => focusNewItemInput(pathname) : undefined}
|
||||||
aria-current={active ? 'page' : undefined}
|
aria-current={active ? 'page' : undefined}
|
||||||
className={cn(
|
className={cn(
|
||||||
'flex flex-col items-center gap-1 rounded-md px-3 py-1.5 text-xs transition-colors',
|
'relative flex flex-col items-center gap-1 rounded-md px-3 py-1.5 text-xs transition-colors',
|
||||||
active ? 'text-foreground' : 'text-muted-foreground hover:text-foreground',
|
active ? 'text-primary font-medium' : 'text-muted-foreground hover:text-foreground',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<item.icon className="size-5" />
|
<item.icon className="size-5" />
|
||||||
<span>{item.title}</span>
|
<span>{item.title}</span>
|
||||||
|
{active && (
|
||||||
|
<span className="bg-primary absolute -bottom-1 size-1 rounded-full" aria-hidden />
|
||||||
|
)}
|
||||||
</Link>
|
</Link>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
|
|||||||
99
apps/web/src/components/layout/list-switcher.tsx
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
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 { ListGlyph } from '@/components/lists/list-glyph'
|
||||||
|
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()
|
||||||
|
const icon = lists?.find((option) => option.id === list.id)?.icon
|
||||||
|
|
||||||
|
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">
|
||||||
|
{icon && <ListGlyph list={{ name: list.name, icon }} className="mr-1" />}
|
||||||
|
<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 (
|
||||||
|
<>
|
||||||
|
<ListGlyph list={list} className="text-muted-foreground size-4" />
|
||||||
|
<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>
|
||||||
|
)
|
||||||
|
}
|
||||||
183
apps/web/src/components/layout/pinned-lists.tsx
Normal file
@@ -0,0 +1,183 @@
|
|||||||
|
import type { ShoppingListSummary } from '@superlist/shared'
|
||||||
|
import { Link, useRouterState } from '@tanstack/react-router'
|
||||||
|
import { CheckIcon } from 'lucide-react'
|
||||||
|
import type { ComponentProps } from 'react'
|
||||||
|
|
||||||
|
import { ListGlyph } from '@/components/lists/list-glyph'
|
||||||
|
import {
|
||||||
|
SidebarGroup,
|
||||||
|
SidebarGroupLabel,
|
||||||
|
SidebarMenu,
|
||||||
|
SidebarMenuBadge,
|
||||||
|
SidebarMenuButton,
|
||||||
|
SidebarMenuItem,
|
||||||
|
} from '@/components/ui/sidebar'
|
||||||
|
import { pickPrimaryList, useLists, usePinnedLists } from '@/hooks/use-lists'
|
||||||
|
import { usePendingCount } from '@/hooks/use-pending-count'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
/** The list the current page shows: the primary one on `/`, the one in the URL under `/lists/:id`. */
|
||||||
|
function useCurrentListId(): string | undefined {
|
||||||
|
const pathname = useRouterState({ select: (state) => state.location.pathname })
|
||||||
|
const { data: lists } = useLists()
|
||||||
|
|
||||||
|
if (pathname === '/') return lists ? pickPrimaryList(lists)?.id : undefined
|
||||||
|
|
||||||
|
return /^\/lists\/([^/]+)/.exec(pathname)?.[1]
|
||||||
|
}
|
||||||
|
|
||||||
|
function pendingLabel(list: ShoppingListSummary, count: number) {
|
||||||
|
return `${list.name}: ${count === 0 ? 'nada pendiente' : `${count} ${count === 1 ? 'pendiente' : 'pendientes'}`}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Opens a list where the app expects it: the primary one on the home page, the rest on their own page. */
|
||||||
|
function PinnedListLink({
|
||||||
|
list,
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: ComponentProps<'a'> & { list: ShoppingListSummary }) {
|
||||||
|
return list.isPrimary ? (
|
||||||
|
<Link to="/" className={className} {...props}>
|
||||||
|
{children}
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<Link to="/lists/$listId" params={{ listId: list.id }} className={className} {...props}>
|
||||||
|
{children}
|
||||||
|
</Link>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mobile: the pinned lists as chips above the bottom navigation, each with its
|
||||||
|
* icon and the number of items still to buy, so the other lists stay in sight
|
||||||
|
* while shopping from one. Renders nothing when no list is pinned.
|
||||||
|
*
|
||||||
|
* It is exactly 4.5rem tall (as the navigation itself), which is what the
|
||||||
|
* authenticated layout adds to `--bottom-nav-height` while lists are pinned.
|
||||||
|
*/
|
||||||
|
export function PinnedListsBar() {
|
||||||
|
const pinned = usePinnedLists()
|
||||||
|
const currentListId = useCurrentListId()
|
||||||
|
|
||||||
|
if (pinned.length === 0) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<nav aria-label="Listas fijadas" className="mx-auto max-w-lg px-3 pt-2.5">
|
||||||
|
<ul className="bg-muted/60 flex gap-1 rounded-2xl border p-1">
|
||||||
|
{pinned.map((list) => (
|
||||||
|
<li key={list.id} className="min-w-0 flex-1">
|
||||||
|
<PinnedChip list={list} current={list.id === currentListId} />
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</nav>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PinnedChip({ list, current }: { list: ShoppingListSummary; current: boolean }) {
|
||||||
|
const count = usePendingCount(list)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<PinnedListLink
|
||||||
|
list={list}
|
||||||
|
aria-current={current ? 'page' : undefined}
|
||||||
|
aria-label={pendingLabel(list, count)}
|
||||||
|
className={cn(
|
||||||
|
'relative flex h-13 flex-col items-center justify-center gap-0.5 rounded-xl px-1 text-[11px] leading-tight transition-colors',
|
||||||
|
current
|
||||||
|
? 'bg-background text-foreground font-medium shadow-xs'
|
||||||
|
: count > 0
|
||||||
|
? 'text-foreground hover:bg-background/60'
|
||||||
|
: 'text-muted-foreground hover:bg-background/60',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span className="relative">
|
||||||
|
<ListGlyph list={list} />
|
||||||
|
<PendingBadge count={count} current={current} className="absolute -top-1.5 left-3.5" />
|
||||||
|
</span>
|
||||||
|
<span className="w-full truncate text-center">{list.name}</span>
|
||||||
|
</PinnedListLink>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PendingBadge({
|
||||||
|
count,
|
||||||
|
current,
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
count: number
|
||||||
|
current: boolean
|
||||||
|
className?: string
|
||||||
|
}) {
|
||||||
|
if (count === 0) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
aria-hidden
|
||||||
|
className={cn(
|
||||||
|
'bg-muted text-muted-foreground flex size-4 items-center justify-center rounded-full border',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<CheckIcon className="size-2.5" />
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
aria-hidden
|
||||||
|
className={cn(
|
||||||
|
'flex h-4.5 min-w-4.5 items-center justify-center rounded-full px-1 text-[10px] font-semibold tabular-nums',
|
||||||
|
// The open list is already in front of the user; the others are the ones to remember.
|
||||||
|
current ? 'bg-primary text-primary-foreground' : 'bg-destructive text-white',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{count > 99 ? '99+' : count}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Desktop: the pinned lists as a sidebar group, with the pending count (a dot when collapsed). */
|
||||||
|
export function PinnedListsSidebarGroup() {
|
||||||
|
const pinned = usePinnedLists()
|
||||||
|
const currentListId = useCurrentListId()
|
||||||
|
|
||||||
|
if (pinned.length === 0) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SidebarGroup>
|
||||||
|
<SidebarGroupLabel>Fijadas</SidebarGroupLabel>
|
||||||
|
<SidebarMenu>
|
||||||
|
{pinned.map((list) => (
|
||||||
|
<PinnedSidebarItem key={list.id} list={list} current={list.id === currentListId} />
|
||||||
|
))}
|
||||||
|
</SidebarMenu>
|
||||||
|
</SidebarGroup>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PinnedSidebarItem({ list, current }: { list: ShoppingListSummary; current: boolean }) {
|
||||||
|
const count = usePendingCount(list)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SidebarMenuItem>
|
||||||
|
<SidebarMenuButton asChild isActive={current} tooltip={pendingLabel(list, count)}>
|
||||||
|
<PinnedListLink list={list}>
|
||||||
|
<ListGlyph list={list} className="size-4" />
|
||||||
|
<span>{list.name}</span>
|
||||||
|
{count > 0 && !current && (
|
||||||
|
<span
|
||||||
|
aria-hidden
|
||||||
|
className="bg-destructive absolute top-1 right-1 hidden size-2 rounded-full group-data-[collapsible=icon]:block"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</PinnedListLink>
|
||||||
|
</SidebarMenuButton>
|
||||||
|
<SidebarMenuBadge className={cn(count > 0 && !current && 'text-destructive')}>
|
||||||
|
{count === 0 ? <CheckIcon className="size-3.5" aria-label="Nada pendiente" /> : count}
|
||||||
|
</SidebarMenuBadge>
|
||||||
|
</SidebarMenuItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,11 +1,13 @@
|
|||||||
import type { ShoppingListSummary } from '@superlist/shared'
|
import type { ShoppingListSummary } from '@superlist/shared'
|
||||||
|
import { MAX_PINNED_LISTS } from '@superlist/shared'
|
||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { SettingsIcon, StarIcon, UsersIcon } from 'lucide-react'
|
import { PinIcon, PinOffIcon, SettingsIcon, StarIcon, UsersIcon } from 'lucide-react'
|
||||||
|
|
||||||
|
import { ListGlyph } from '@/components/lists/list-glyph'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Card, CardContent } from '@/components/ui/card'
|
import { Card, CardContent } from '@/components/ui/card'
|
||||||
import { useSetPrimaryList } from '@/hooks/use-lists'
|
import { usePinnedLists, useSetPrimaryList, useUpdateListPreferences } from '@/hooks/use-lists'
|
||||||
|
|
||||||
type ListCardProps = {
|
type ListCardProps = {
|
||||||
list: ShoppingListSummary
|
list: ShoppingListSummary
|
||||||
@@ -18,20 +20,34 @@ export function ListCard({ list }: ListCardProps) {
|
|||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<CardContent className="flex items-center gap-1 p-4">
|
<CardContent className="flex items-center gap-1 p-4">
|
||||||
<Link to="/lists/$listId" params={{ listId: list.id }} className="min-w-0 flex-1">
|
<Link
|
||||||
|
to="/lists/$listId"
|
||||||
|
params={{ listId: list.id }}
|
||||||
|
className="flex min-w-0 flex-1 items-center gap-3"
|
||||||
|
>
|
||||||
|
<span className="bg-muted text-muted-foreground flex size-10 shrink-0 items-center justify-center rounded-lg">
|
||||||
|
<ListGlyph list={list} />
|
||||||
|
</span>
|
||||||
|
<span className="min-w-0 flex-1">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<span className="truncate font-medium">{list.name}</span>
|
<span className="truncate font-medium">{list.name}</span>
|
||||||
{list.isPrimary && <Badge>Principal</Badge>}
|
{list.isPrimary && <Badge>Principal</Badge>}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-muted-foreground mt-1 flex items-center gap-3 text-xs">
|
<div className="text-muted-foreground mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-xs whitespace-nowrap">
|
||||||
<span className="flex items-center gap-1">
|
<span className="flex items-center gap-1">
|
||||||
<UsersIcon className="size-3.5" />
|
<UsersIcon className="size-3.5" />
|
||||||
{list.memberCount} {list.memberCount === 1 ? 'persona' : 'personas'}
|
{list.memberCount} {list.memberCount === 1 ? 'persona' : 'personas'}
|
||||||
</span>
|
</span>
|
||||||
<span>{list.role === 'owner' ? 'Propietario' : 'Colaborador'}</span>
|
<span>{list.role === 'owner' ? 'Propietario' : 'Colaborador'}</span>
|
||||||
|
<span>
|
||||||
|
{list.pendingCount} {list.pendingCount === 1 ? 'pendiente' : 'pendientes'}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
</span>
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
|
<PinButton list={list} />
|
||||||
|
|
||||||
{!list.isPrimary && (
|
{!list.isPrimary && (
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
@@ -53,3 +69,24 @@ export function ListCard({ list }: ListCardProps) {
|
|||||||
</Card>
|
</Card>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Pins or unpins the list to the always-visible bar (disabled once the limit is reached). */
|
||||||
|
function PinButton({ list }: ListCardProps) {
|
||||||
|
const updatePreferences = useUpdateListPreferences(list.id)
|
||||||
|
const pinnedCount = usePinnedLists().length
|
||||||
|
const limitReached = !list.isPinned && pinnedCount >= MAX_PINNED_LISTS
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-pressed={list.isPinned}
|
||||||
|
aria-label={list.isPinned ? `Desfijar ${list.name}` : `Fijar ${list.name} en la barra`}
|
||||||
|
title={limitReached ? `Puedes fijar hasta ${MAX_PINNED_LISTS} listas` : undefined}
|
||||||
|
disabled={limitReached || updatePreferences.isPending}
|
||||||
|
onClick={() => updatePreferences.mutate({ isPinned: !list.isPinned })}
|
||||||
|
>
|
||||||
|
{list.isPinned ? <PinOffIcon className="size-4" /> : <PinIcon className="size-4" />}
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
29
apps/web/src/components/lists/list-glyph.tsx
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import type { ShoppingListSummary } from '@superlist/shared'
|
||||||
|
|
||||||
|
import { LIST_ICON_OPTIONS } from '@/lib/list-icons'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
type ListGlyphProps = {
|
||||||
|
list: Pick<ShoppingListSummary, 'name' | 'icon'>
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The icon the user picked for a list, or the first letter of its name when there is none. */
|
||||||
|
export function ListGlyph({ list, className }: ListGlyphProps) {
|
||||||
|
if (list.icon) {
|
||||||
|
const { icon: Icon } = LIST_ICON_OPTIONS[list.icon]
|
||||||
|
return <Icon aria-hidden className={cn('size-5 shrink-0', className)} />
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
aria-hidden
|
||||||
|
className={cn(
|
||||||
|
'flex size-5 shrink-0 items-center justify-center text-sm leading-none font-semibold uppercase',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{list.name.trim().charAt(0) || '?'}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
94
apps/web/src/components/lists/list-preferences-card.tsx
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
import { LIST_ICONS, MAX_PINNED_LISTS, type ShoppingListDetail } from '@superlist/shared'
|
||||||
|
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
import { usePinnedLists, useUpdateListPreferences } from '@/hooks/use-lists'
|
||||||
|
import { ApiError } from '@/lib/api-client'
|
||||||
|
import { LIST_ICON_OPTIONS } from '@/lib/list-icons'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
type ListPreferencesCardProps = {
|
||||||
|
list: Pick<ShoppingListDetail, 'id' | 'name' | 'isPinned' | 'icon'>
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The user's own settings for a list: pin it to the always-visible bar and pick
|
||||||
|
* its icon. Every member has their own, so it is shown to collaborators too.
|
||||||
|
*/
|
||||||
|
export function ListPreferencesCard({ list }: ListPreferencesCardProps) {
|
||||||
|
const updatePreferences = useUpdateListPreferences(list.id)
|
||||||
|
const pinnedCount = usePinnedLists().length
|
||||||
|
const pinLimitReached = !list.isPinned && pinnedCount >= MAX_PINNED_LISTS
|
||||||
|
const error = updatePreferences.error
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-base">Acceso rápido</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="flex flex-col gap-5">
|
||||||
|
{error && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertDescription>
|
||||||
|
{error instanceof ApiError
|
||||||
|
? (error.problem.detail ?? error.problem.title)
|
||||||
|
: 'No pudimos guardar el cambio.'}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<label htmlFor="pin-list" className="flex items-start gap-3">
|
||||||
|
<span className="min-w-0 flex-1">
|
||||||
|
<span className="block text-sm font-medium">Fijar en la barra</span>
|
||||||
|
<span className="text-muted-foreground block text-sm">
|
||||||
|
{pinLimitReached
|
||||||
|
? `Ya tienes ${MAX_PINNED_LISTS} listas fijadas. Desfija otra para fijar esta.`
|
||||||
|
: `Siempre visible con sus pendientes, en cualquier pantalla. Hasta ${MAX_PINNED_LISTS} listas.`}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
<Switch
|
||||||
|
id="pin-list"
|
||||||
|
className="mt-1"
|
||||||
|
checked={list.isPinned}
|
||||||
|
disabled={pinLimitReached}
|
||||||
|
onCheckedChange={(checked) => updatePreferences.mutate({ isPinned: checked })}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<fieldset className="flex flex-col gap-2">
|
||||||
|
<legend className="mb-2 text-sm font-medium">Ícono</legend>
|
||||||
|
<div className="grid grid-cols-6 gap-2 sm:grid-cols-9">
|
||||||
|
{LIST_ICONS.map((key) => {
|
||||||
|
const { icon: Icon, label } = LIST_ICON_OPTIONS[key]
|
||||||
|
const selected = list.icon === key
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={key}
|
||||||
|
type="button"
|
||||||
|
aria-pressed={selected}
|
||||||
|
aria-label={label}
|
||||||
|
title={label}
|
||||||
|
// Tapping the selected icon again clears it (back to the initial).
|
||||||
|
onClick={() => updatePreferences.mutate({ icon: selected ? null : key })}
|
||||||
|
className={cn(
|
||||||
|
'focus-visible:ring-ring/50 flex aspect-square min-h-11 items-center justify-center rounded-lg border outline-none transition-colors focus-visible:ring-3',
|
||||||
|
selected
|
||||||
|
? 'border-primary bg-primary/10 text-primary border-2'
|
||||||
|
: 'text-muted-foreground hover:bg-muted hover:text-foreground',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Icon className="size-5" />
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
<p className="text-muted-foreground text-xs">
|
||||||
|
Sin ícono se muestra la inicial: «{list.name.trim().charAt(0).toUpperCase()}».
|
||||||
|
</p>
|
||||||
|
</fieldset>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
76
apps/web/src/components/settings/app-badge-card.tsx
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
import { BellRingIcon } from 'lucide-react'
|
||||||
|
import { useState } from 'react'
|
||||||
|
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { refreshAppBadge, supportsAppBadge } from '@/lib/app-badge'
|
||||||
|
import { isIos, isStandalone } from '@/lib/platform'
|
||||||
|
|
||||||
|
type Permission = NotificationPermission | 'unsupported'
|
||||||
|
|
||||||
|
function readPermission(): Permission {
|
||||||
|
return typeof Notification === 'undefined' ? 'unsupported' : Notification.permission
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Explains the icon badge and, on iOS, asks for the notification permission the
|
||||||
|
* system requires before showing it. Elsewhere the badge works without asking.
|
||||||
|
*/
|
||||||
|
export function AppBadgeCard() {
|
||||||
|
const [permission, setPermission] = useState(readPermission)
|
||||||
|
const supported = supportsAppBadge()
|
||||||
|
const installed = isStandalone()
|
||||||
|
const needsPermission = supported && installed && isIos() && permission === 'default'
|
||||||
|
|
||||||
|
const enable = async () => {
|
||||||
|
if (typeof Notification === 'undefined') return
|
||||||
|
|
||||||
|
const result = await Notification.requestPermission()
|
||||||
|
setPermission(result)
|
||||||
|
if (result === 'granted') refreshAppBadge()
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Indicador en el ícono</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Muestra cuántos artículos quedan por comprar en tu lista principal, en el ícono de la app
|
||||||
|
instalada. Se actualiza solo cuando agregas o compras artículos, aquí o desde otro móvil.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="flex flex-col gap-3">
|
||||||
|
{!supported ? (
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Este navegador no permite mostrar números en el ícono. En Android, Chrome solo muestra
|
||||||
|
un punto cuando la app tiene avisos.
|
||||||
|
</p>
|
||||||
|
) : !installed ? (
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Abre Superlist desde su ícono (la app instalada) para activar el indicador.
|
||||||
|
</p>
|
||||||
|
) : needsPermission ? (
|
||||||
|
<>
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
En iPhone y iPad, el sistema pide permiso de avisos para mostrar el número en el
|
||||||
|
ícono. No enviamos notificaciones: solo usamos el permiso para el indicador.
|
||||||
|
</p>
|
||||||
|
<Button size="sm" className="self-start" onClick={enable}>
|
||||||
|
<BellRingIcon className="size-4" />
|
||||||
|
Activar indicador
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
) : permission === 'denied' ? (
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Bloqueaste los avisos para Superlist. Actívalos en los ajustes de iOS para ver el número
|
||||||
|
en el ícono.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Activo: el número sigue a los artículos pendientes de tu lista principal.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
336
apps/web/src/components/settings/passkeys-card.tsx
Normal file
@@ -0,0 +1,336 @@
|
|||||||
|
import {
|
||||||
|
FingerprintIcon,
|
||||||
|
KeyRoundIcon,
|
||||||
|
MoreHorizontalIcon,
|
||||||
|
PencilIcon,
|
||||||
|
PlusIcon,
|
||||||
|
Trash2Icon,
|
||||||
|
} from 'lucide-react'
|
||||||
|
import { type FormEvent, useState } from 'react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from '@/components/ui/dropdown-menu'
|
||||||
|
import { Field, FieldDescription, FieldLabel } from '@/components/ui/field'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
|
import {
|
||||||
|
type Passkey,
|
||||||
|
useAddPasskey,
|
||||||
|
useDeletePasskey,
|
||||||
|
usePasskeys,
|
||||||
|
useUpdatePasskey,
|
||||||
|
} from '@/hooks/use-passkeys'
|
||||||
|
|
||||||
|
const DEFAULT_NAME = 'Este dispositivo'
|
||||||
|
const createdOnFormat = new Intl.DateTimeFormat('es', { dateStyle: 'medium' })
|
||||||
|
|
||||||
|
function passkeyLabel(passkey: Passkey) {
|
||||||
|
return passkey.name?.trim() || 'Passkey sin nombre'
|
||||||
|
}
|
||||||
|
|
||||||
|
function passkeyDetails(passkey: Passkey) {
|
||||||
|
const created = passkey.createdAt ? new Date(passkey.createdAt) : null
|
||||||
|
|
||||||
|
if (!created || Number.isNaN(created.getTime())) return 'Passkey de acceso'
|
||||||
|
|
||||||
|
return `Creada el ${createdOnFormat.format(created)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PasskeysCard() {
|
||||||
|
const supportsPasskeys = typeof window !== 'undefined' && 'PublicKeyCredential' in window
|
||||||
|
const passkeys = usePasskeys()
|
||||||
|
const addPasskey = useAddPasskey()
|
||||||
|
const updatePasskey = useUpdatePasskey()
|
||||||
|
const deletePasskey = useDeletePasskey()
|
||||||
|
|
||||||
|
const [addOpen, setAddOpen] = useState(false)
|
||||||
|
const [newName, setNewName] = useState(DEFAULT_NAME)
|
||||||
|
const [renaming, setRenaming] = useState<Passkey | null>(null)
|
||||||
|
const [renameName, setRenameName] = useState('')
|
||||||
|
const [deleting, setDeleting] = useState<Passkey | null>(null)
|
||||||
|
|
||||||
|
const openAdd = () => {
|
||||||
|
setNewName(DEFAULT_NAME)
|
||||||
|
setAddOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const openRename = (passkey: Passkey) => {
|
||||||
|
setRenameName(passkeyLabel(passkey))
|
||||||
|
setRenaming(passkey)
|
||||||
|
}
|
||||||
|
|
||||||
|
const onAdd = async (event: FormEvent) => {
|
||||||
|
event.preventDefault()
|
||||||
|
|
||||||
|
try {
|
||||||
|
await addPasskey.mutateAsync(newName.trim() || DEFAULT_NAME)
|
||||||
|
setAddOpen(false)
|
||||||
|
toast.success('Passkey creada.')
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(error instanceof Error ? error.message : 'No pudimos crear la passkey.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onRename = async (event: FormEvent) => {
|
||||||
|
event.preventDefault()
|
||||||
|
if (!renaming) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
await updatePasskey.mutateAsync({ id: renaming.id, name: renameName.trim() || DEFAULT_NAME })
|
||||||
|
setRenaming(null)
|
||||||
|
toast.success('Passkey renombrada.')
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(error instanceof Error ? error.message : 'No pudimos renombrar la passkey.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onDelete = async () => {
|
||||||
|
if (!deleting) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
await deletePasskey.mutateAsync(deleting.id)
|
||||||
|
setDeleting(null)
|
||||||
|
toast.success('Passkey eliminada.')
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(error instanceof Error ? error.message : 'No pudimos eliminar la passkey.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<CardTitle>Passkeys</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Entra con Face ID, Touch ID o Windows Hello, sin escribir tu contraseña.
|
||||||
|
</CardDescription>
|
||||||
|
</div>
|
||||||
|
{supportsPasskeys && (
|
||||||
|
<Button variant="outline" size="sm" onClick={openAdd} disabled={addPasskey.isPending}>
|
||||||
|
<PlusIcon />
|
||||||
|
Añadir
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{!supportsPasskeys ? (
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Este navegador no admite passkeys. Prueba con uno más reciente o con la app instalada.
|
||||||
|
</p>
|
||||||
|
) : passkeys.isPending ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Skeleton className="h-14 w-full" />
|
||||||
|
<Skeleton className="h-14 w-full" />
|
||||||
|
</div>
|
||||||
|
) : passkeys.isError ? (
|
||||||
|
<div className="flex flex-col items-start gap-2">
|
||||||
|
<p className="text-destructive text-sm">
|
||||||
|
{passkeys.error instanceof Error
|
||||||
|
? passkeys.error.message
|
||||||
|
: 'No pudimos cargar tus passkeys.'}
|
||||||
|
</p>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => void passkeys.refetch()}>
|
||||||
|
Reintentar
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : passkeys.data.length === 0 ? (
|
||||||
|
<div className="flex flex-col items-center gap-2 rounded-lg border border-dashed p-6 text-center">
|
||||||
|
<KeyRoundIcon className="text-muted-foreground size-6" />
|
||||||
|
<p className="text-sm font-medium">Todavía no tienes passkeys</p>
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Añade una para entrar sin escribir tu contraseña.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ul className="divide-y rounded-lg border">
|
||||||
|
{passkeys.data.map((passkey) => (
|
||||||
|
<li key={passkey.id} className="flex items-center gap-3 px-3 py-3">
|
||||||
|
<span className="bg-muted flex size-9 shrink-0 items-center justify-center rounded-full">
|
||||||
|
<FingerprintIcon className="size-4" />
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<p className="truncate text-sm font-medium">{passkeyLabel(passkey)}</p>
|
||||||
|
{passkey.backedUp && (
|
||||||
|
<Badge variant="secondary" className="shrink-0">
|
||||||
|
Sincronizada
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="text-muted-foreground truncate text-xs">
|
||||||
|
{passkeyDetails(passkey)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label={`Acciones de ${passkeyLabel(passkey)}`}
|
||||||
|
>
|
||||||
|
<MoreHorizontalIcon />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end" className="w-40">
|
||||||
|
<DropdownMenuItem onClick={() => openRename(passkey)}>
|
||||||
|
<PencilIcon />
|
||||||
|
Renombrar
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem variant="destructive" onClick={() => setDeleting(passkey)}>
|
||||||
|
<Trash2Icon />
|
||||||
|
Eliminar
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
|
||||||
|
<Dialog
|
||||||
|
open={addOpen}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!addPasskey.isPending) setAddOpen(open)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Añadir passkey</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Tu dispositivo te pedirá Face ID, Touch ID, Windows Hello o tu llave de seguridad.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<form onSubmit={onAdd} className="flex flex-col gap-4">
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="new-passkey-name">Nombre</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="new-passkey-name"
|
||||||
|
value={newName}
|
||||||
|
onChange={(event) => setNewName(event.target.value)}
|
||||||
|
maxLength={60}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
<FieldDescription>Te ayuda a reconocerla si añades más de una.</FieldDescription>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setAddOpen(false)}
|
||||||
|
disabled={addPasskey.isPending}
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={addPasskey.isPending}>
|
||||||
|
{addPasskey.isPending ? 'Creando…' : 'Crear passkey'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<Dialog
|
||||||
|
open={renaming !== null}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!open && !updatePasskey.isPending) setRenaming(null)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Renombrar passkey</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Elige un nombre que te ayude a reconocer este dispositivo o llave.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<form onSubmit={onRename} className="flex flex-col gap-4">
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="rename-passkey">Nombre</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="rename-passkey"
|
||||||
|
value={renameName}
|
||||||
|
onChange={(event) => setRenameName(event.target.value)}
|
||||||
|
maxLength={60}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setRenaming(null)}
|
||||||
|
disabled={updatePasskey.isPending}
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={updatePasskey.isPending}>
|
||||||
|
{updatePasskey.isPending ? 'Guardando…' : 'Guardar'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<Dialog
|
||||||
|
open={deleting !== null}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!open && !deletePasskey.isPending) setDeleting(null)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Eliminar passkey</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{deleting
|
||||||
|
? `«${passkeyLabel(deleting)}» dejará de servir para iniciar sesión.`
|
||||||
|
: 'Esta passkey dejará de servir para iniciar sesión.'}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setDeleting(null)}
|
||||||
|
disabled={deletePasskey.isPending}
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="destructive"
|
||||||
|
onClick={() => void onDelete()}
|
||||||
|
disabled={deletePasskey.isPending}
|
||||||
|
>
|
||||||
|
{deletePasskey.isPending ? 'Eliminando…' : 'Eliminar passkey'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -16,6 +16,9 @@ type ThemeContextValue = {
|
|||||||
const STORAGE_KEY = 'superlist-theme'
|
const STORAGE_KEY = 'superlist-theme'
|
||||||
const DARK_QUERY = '(prefers-color-scheme: dark)'
|
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`
|
* 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
|
* 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'
|
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 }) {
|
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||||
const [theme, setThemeState] = useState<Theme>(readStoredTheme)
|
const [theme, setThemeState] = useState<Theme>(readStoredTheme)
|
||||||
const [systemDark, setSystemDark] = useState(() => systemTheme() === 'dark')
|
const [systemDark, setSystemDark] = useState(() => systemTheme() === 'dark')
|
||||||
@@ -60,16 +72,27 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
|||||||
const root = document.documentElement
|
const root = document.documentElement
|
||||||
root.classList.toggle('dark', resolvedTheme === 'dark')
|
root.classList.toggle('dark', resolvedTheme === 'dark')
|
||||||
root.style.colorScheme = resolvedTheme
|
root.style.colorScheme = resolvedTheme
|
||||||
|
document
|
||||||
|
.querySelector('meta[name="theme-color"]')
|
||||||
|
?.setAttribute('content', THEME_COLORS[resolvedTheme])
|
||||||
}, [resolvedTheme])
|
}, [resolvedTheme])
|
||||||
|
|
||||||
const setTheme = useCallback((next: Theme) => {
|
const setTheme = useCallback(
|
||||||
|
(next: Theme) => {
|
||||||
setThemeState(next)
|
setThemeState(next)
|
||||||
try {
|
try {
|
||||||
window.localStorage.setItem(STORAGE_KEY, next)
|
window.localStorage.setItem(STORAGE_KEY, next)
|
||||||
} catch {
|
} catch {
|
||||||
// Ignore storage failures: the theme still applies for this session.
|
// 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(
|
const value = useMemo(
|
||||||
() => ({ theme, resolvedTheme, setTheme }),
|
() => ({ theme, resolvedTheme, setTheme }),
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ export function ThemeToggle() {
|
|||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
className="relative"
|
className="relative size-11"
|
||||||
aria-label={`Tema: ${current.label} — cambiar a ${next.label}`}
|
aria-label={`Tema: ${current.label} — cambiar a ${next.label}`}
|
||||||
onClick={() => setTheme(next.value)}
|
onClick={() => setTheme(next.value)}
|
||||||
>
|
>
|
||||||
|
|||||||
244
apps/web/src/components/ui/context-menu.tsx
Normal file
@@ -0,0 +1,244 @@
|
|||||||
|
import { cn } from 'cn'
|
||||||
|
import { CheckIcon, ChevronRightIcon } from 'lucide-react'
|
||||||
|
import { ContextMenu as ContextMenuPrimitive } from 'radix-ui'
|
||||||
|
import * as React from 'react'
|
||||||
|
|
||||||
|
function ContextMenu({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
||||||
|
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuTrigger({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Trigger
|
||||||
|
data-slot="context-menu-trigger"
|
||||||
|
className={cn('select-none', className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
||||||
|
return <ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuPortal({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
||||||
|
return <ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuSub({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
||||||
|
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuRadioGroup({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
||||||
|
return <ContextMenuPrimitive.RadioGroup data-slot="context-menu-radio-group" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Content> & {
|
||||||
|
side?: 'top' | 'right' | 'bottom' | 'left'
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Portal>
|
||||||
|
<ContextMenuPrimitive.Content
|
||||||
|
data-slot="context-menu-content"
|
||||||
|
className={cn(
|
||||||
|
'z-50 max-h-(--radix-context-menu-content-available-height) min-w-36 origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</ContextMenuPrimitive.Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuItem({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
variant = 'default',
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
||||||
|
inset?: boolean
|
||||||
|
variant?: 'default' | 'destructive'
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Item
|
||||||
|
data-slot="context-menu-item"
|
||||||
|
data-inset={inset}
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(
|
||||||
|
"group/context-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 focus:*:[svg]:text-accent-foreground data-[variant=destructive]:*:[svg]:text-destructive",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuSubTrigger({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.SubTrigger
|
||||||
|
data-slot="context-menu-sub-trigger"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronRightIcon className="ml-auto" />
|
||||||
|
</ContextMenuPrimitive.SubTrigger>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuSubContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.SubContent
|
||||||
|
data-slot="context-menu-sub-content"
|
||||||
|
className={cn(
|
||||||
|
'z-50 min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-lg border bg-popover p-1 text-popover-foreground shadow-lg duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuCheckboxItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
checked,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.CheckboxItem
|
||||||
|
data-slot="context-menu-checkbox-item"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
checked={checked}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute right-2">
|
||||||
|
<ContextMenuPrimitive.ItemIndicator>
|
||||||
|
<CheckIcon />
|
||||||
|
</ContextMenuPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</ContextMenuPrimitive.CheckboxItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuRadioItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.RadioItem
|
||||||
|
data-slot="context-menu-radio-item"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute right-2">
|
||||||
|
<ContextMenuPrimitive.ItemIndicator>
|
||||||
|
<CheckIcon />
|
||||||
|
</ContextMenuPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</ContextMenuPrimitive.RadioItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuLabel({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Label
|
||||||
|
data-slot="context-menu-label"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
'px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Separator
|
||||||
|
data-slot="context-menu-separator"
|
||||||
|
className={cn('-mx-1 my-1 h-px bg-border', className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="context-menu-shortcut"
|
||||||
|
className={cn(
|
||||||
|
'ml-auto text-xs tracking-widest text-muted-foreground group-focus/context-menu-item:text-accent-foreground',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
ContextMenu,
|
||||||
|
ContextMenuCheckboxItem,
|
||||||
|
ContextMenuContent,
|
||||||
|
ContextMenuGroup,
|
||||||
|
ContextMenuItem,
|
||||||
|
ContextMenuLabel,
|
||||||
|
ContextMenuPortal,
|
||||||
|
ContextMenuRadioGroup,
|
||||||
|
ContextMenuRadioItem,
|
||||||
|
ContextMenuSeparator,
|
||||||
|
ContextMenuShortcut,
|
||||||
|
ContextMenuSub,
|
||||||
|
ContextMenuSubContent,
|
||||||
|
ContextMenuSubTrigger,
|
||||||
|
ContextMenuTrigger,
|
||||||
|
}
|
||||||
142
apps/web/src/components/ui/dialog.tsx
Normal 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,
|
||||||
|
}
|
||||||
142
apps/web/src/components/ui/input-group.tsx
Normal 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,
|
||||||
|
}
|
||||||
28
apps/web/src/components/ui/progress.tsx
Normal 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 }
|
||||||
171
apps/web/src/hooks/use-add-items.ts
Normal file
@@ -0,0 +1,171 @@
|
|||||||
|
import type { ListItem } from '@superlist/shared'
|
||||||
|
import { useRef } from 'react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
import type { PreviewItem } from '@/components/items/item-input-preview'
|
||||||
|
import {
|
||||||
|
isOptimisticItem,
|
||||||
|
useCreateItem,
|
||||||
|
useItems,
|
||||||
|
useRemoveItems,
|
||||||
|
useUpdateItem,
|
||||||
|
} from '@/hooks/use-items'
|
||||||
|
import { useVoiceSplit } from '@/hooks/use-voice-split'
|
||||||
|
import { ApiError } from '@/lib/api-client'
|
||||||
|
import { findDuplicate, mergeBatch, mergeInto } from '@/lib/natural-input/merge'
|
||||||
|
import { literalItem, parseItemInput } from '@/lib/natural-input/parse-item'
|
||||||
|
|
||||||
|
/** How long the "Deshacer" of a dictation stays on screen. */
|
||||||
|
const DICTATION_UNDO_MS = 8000
|
||||||
|
|
||||||
|
/** Why a read item cannot be sent as is, mirroring the API limits, or `null`. */
|
||||||
|
export function itemLimitError(item: PreviewItem): string | null {
|
||||||
|
if (item.name.length > 120) return `«${item.name.slice(0, 20)}…»: máximo 120 caracteres`
|
||||||
|
if ((item.quantity?.length ?? 0) > 40) return `«${item.name}»: la cantidad es demasiado larga`
|
||||||
|
if ((item.notes?.length ?? 0) > 280) return `«${item.name}»: la nota es demasiado larga`
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The items `text` adds, each with the pending item it repeats, if any. */
|
||||||
|
export function readItems(text: string, literal: boolean, existing: ListItem[]): PreviewItem[] {
|
||||||
|
if (!text.trim()) return []
|
||||||
|
|
||||||
|
const items = literal ? [literalItem(text)] : mergeBatch(parseItemInput(text))
|
||||||
|
|
||||||
|
return items.map((item) => ({ ...item, duplicate: findDuplicate(existing, item.name) }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What adding a batch of items did, so a dictation can be undone. */
|
||||||
|
type AddedItems = {
|
||||||
|
/** Ids of the items created (failed ones are left out). */
|
||||||
|
created: Promise<string[]>
|
||||||
|
/** The previous quantity/notes of the pending items that were added to. */
|
||||||
|
merged: { itemId: string; quantity: string | null; notes: string | null }[]
|
||||||
|
}
|
||||||
|
|
||||||
|
type UseAddItemsOptions = {
|
||||||
|
/** An item could not be created: `source` is the text it was read from. */
|
||||||
|
onItemFailed: (source: string, message: string) => void
|
||||||
|
/** A dictation was not added because an item breaks the API limits. */
|
||||||
|
onDictationRejected: (transcript: string, message: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds items to a list the way the "add an item" input does: an item already pending is
|
||||||
|
* added to instead of repeated, and a dictation is split into items by the API (with AI)
|
||||||
|
* and can be undone as a whole.
|
||||||
|
*/
|
||||||
|
export function useAddItems(
|
||||||
|
listId: string,
|
||||||
|
{ onItemFailed, onDictationRejected }: UseAddItemsOptions,
|
||||||
|
) {
|
||||||
|
const createItem = useCreateItem(listId)
|
||||||
|
const updateItem = useUpdateItem(listId)
|
||||||
|
const removeItems = useRemoveItems(listId)
|
||||||
|
const voiceSplit = useVoiceSplit()
|
||||||
|
const { data: items } = useItems(listId)
|
||||||
|
// Placeholders have no server id yet, so they cannot be added to.
|
||||||
|
const existing = (items ?? []).filter((item) => !isOptimisticItem(item))
|
||||||
|
// A dictation finishes after a request: by then the list may have changed.
|
||||||
|
const existingRef = useRef(existing)
|
||||||
|
existingRef.current = existing
|
||||||
|
|
||||||
|
/** Adds the items, or adds to the pending ones they repeat. */
|
||||||
|
const addItems = (toAdd: PreviewItem[]): AddedItems => {
|
||||||
|
const created: Promise<string | null>[] = []
|
||||||
|
const merged: AddedItems['merged'] = []
|
||||||
|
|
||||||
|
for (const item of toAdd) {
|
||||||
|
if (item.duplicate) {
|
||||||
|
const patch = mergeInto(item.duplicate, item)
|
||||||
|
if (patch.quantity !== undefined || patch.notes !== undefined) {
|
||||||
|
updateItem.mutate({ itemId: item.duplicate.id, ...patch })
|
||||||
|
merged.push({
|
||||||
|
itemId: item.duplicate.id,
|
||||||
|
quantity: item.duplicate.quantity,
|
||||||
|
notes: item.duplicate.notes,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
toast(
|
||||||
|
patch.quantity
|
||||||
|
? `Se sumó a «${item.duplicate.name}» (${patch.quantity})`
|
||||||
|
: `«${item.duplicate.name}» ya está en la lista`,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
created.push(
|
||||||
|
createItem
|
||||||
|
.mutateAsync({
|
||||||
|
name: item.name,
|
||||||
|
quantity: item.quantity ?? undefined,
|
||||||
|
notes: item.notes ?? undefined,
|
||||||
|
})
|
||||||
|
.then(
|
||||||
|
(createdItem) => createdItem.id,
|
||||||
|
(error) => {
|
||||||
|
onItemFailed(
|
||||||
|
item.source,
|
||||||
|
error instanceof ApiError
|
||||||
|
? (error.problem.detail ?? error.problem.title)
|
||||||
|
: 'No pudimos añadir el artículo.',
|
||||||
|
)
|
||||||
|
return null
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
created: Promise.all(created).then((ids) => ids.filter((id): id is string => id !== null)),
|
||||||
|
merged,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The API splits the transcript into one string per item and each one is read by the
|
||||||
|
* usual parser. If the request fails, the transcript is read as typed text when it is
|
||||||
|
* already split into lines, and added as a single item otherwise.
|
||||||
|
*
|
||||||
|
* @returns how many items were understood (0 when the dictation had none).
|
||||||
|
*/
|
||||||
|
const addDictation = async (transcript: string): Promise<number> => {
|
||||||
|
let toAdd: PreviewItem[]
|
||||||
|
try {
|
||||||
|
const { items: spoken } = await voiceSplit.mutateAsync({ text: transcript })
|
||||||
|
toAdd = readItems(spoken.join('; '), false, existingRef.current)
|
||||||
|
} catch {
|
||||||
|
toAdd = readItems(transcript, !/[;\n]/.test(transcript), existingRef.current)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (toAdd.length === 0) return 0
|
||||||
|
|
||||||
|
const limitError = toAdd.map(itemLimitError).find(Boolean)
|
||||||
|
if (limitError) {
|
||||||
|
onDictationRejected(transcript, limitError)
|
||||||
|
return toAdd.length
|
||||||
|
}
|
||||||
|
|
||||||
|
const { created, merged } = addItems(toAdd)
|
||||||
|
const createdIds = await created
|
||||||
|
const count = createdIds.length + merged.length
|
||||||
|
if (count === 0) return toAdd.length
|
||||||
|
|
||||||
|
toast(`Se ${count === 1 ? 'agregó 1 producto' : `agregaron ${count} productos`}`, {
|
||||||
|
// Longer than a plain toast: the user has to check what was understood first.
|
||||||
|
duration: DICTATION_UNDO_MS,
|
||||||
|
action: {
|
||||||
|
label: 'Deshacer',
|
||||||
|
onClick: () => {
|
||||||
|
void removeItems(createdIds)
|
||||||
|
for (const previous of merged) updateItem.mutate(previous)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return toAdd.length
|
||||||
|
}
|
||||||
|
|
||||||
|
return { existing, addItems, addDictation, processing: voiceSplit.isPending }
|
||||||
|
}
|
||||||
88
apps/web/src/hooks/use-app-badge.ts
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { itemsQueryOptions, usePendingDeletions } from '@/hooks/use-items'
|
||||||
|
import { useListEvents } from '@/hooks/use-list-events'
|
||||||
|
import { listsQueryOptions, pickPrimaryList } from '@/hooks/use-lists'
|
||||||
|
import { APP_BADGE_REFRESH_EVENT, setAppBadge, supportsAppBadge } from '@/lib/app-badge'
|
||||||
|
import { countPendingItems } from '@/lib/items'
|
||||||
|
import { isStandalone } from '@/lib/platform'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keeps the number on the installed app's icon equal to the items still to buy
|
||||||
|
* in the primary list — the list the home page opens. It follows that list's SSE
|
||||||
|
* stream even from other pages, so a change made by another member updates the
|
||||||
|
* badge too, and re-syncs whenever the app comes back to the foreground (iOS
|
||||||
|
* suspends the page, and with it the stream, in the background).
|
||||||
|
*
|
||||||
|
* Only runs in the installed app: browsers show the badge nowhere else.
|
||||||
|
*/
|
||||||
|
export function useAppBadge() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const active = isStandalone() && supportsAppBadge()
|
||||||
|
|
||||||
|
const { data: lists } = useQuery({ ...listsQueryOptions(), enabled: active })
|
||||||
|
const primaryList = lists ? pickPrimaryList(lists) : undefined
|
||||||
|
const listId = primaryList?.id
|
||||||
|
|
||||||
|
const { data: items } = useQuery({
|
||||||
|
...itemsQueryOptions(listId ?? ''),
|
||||||
|
enabled: active && Boolean(listId),
|
||||||
|
})
|
||||||
|
const deletingIds = usePendingDeletions()
|
||||||
|
|
||||||
|
// Permission can be granted while the app is open (see the settings card); the
|
||||||
|
// data does not change, so the effect is nudged through this event.
|
||||||
|
const [refreshToken, setRefreshToken] = useState(0)
|
||||||
|
useEffect(() => {
|
||||||
|
const refresh = () => setRefreshToken((token) => token + 1)
|
||||||
|
window.addEventListener(APP_BADGE_REFRESH_EVENT, refresh)
|
||||||
|
return () => window.removeEventListener(APP_BADGE_REFRESH_EVENT, refresh)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!active) return
|
||||||
|
|
||||||
|
// Re-run after a permission change even though the data is the same.
|
||||||
|
void refreshToken
|
||||||
|
|
||||||
|
// Lists still loading: keep whatever the badge already shows instead of
|
||||||
|
// flickering to zero (or clearing) on every launch.
|
||||||
|
if (!lists) return
|
||||||
|
|
||||||
|
if (!listId) {
|
||||||
|
void setAppBadge(0)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!items) return
|
||||||
|
|
||||||
|
void setAppBadge(countPendingItems(items, deletingIds))
|
||||||
|
}, [active, lists, listId, items, deletingIds, refreshToken])
|
||||||
|
|
||||||
|
// The icon outlives the page: signing out should not leave somebody else's
|
||||||
|
// pending items on it.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!active) return
|
||||||
|
return () => void setAppBadge(0)
|
||||||
|
}, [active])
|
||||||
|
|
||||||
|
// Remote additions to the primary list while another page is open.
|
||||||
|
useListEvents(active ? listId : undefined)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!active) return
|
||||||
|
|
||||||
|
const refresh = () => {
|
||||||
|
if (document.visibilityState !== 'visible') return
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['lists'] })
|
||||||
|
if (listId) void queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] })
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('visibilitychange', refresh)
|
||||||
|
window.addEventListener('online', refresh)
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('visibilitychange', refresh)
|
||||||
|
window.removeEventListener('online', refresh)
|
||||||
|
}
|
||||||
|
}, [active, listId, queryClient])
|
||||||
|
}
|
||||||
78
apps/web/src/hooks/use-dictate-items.ts
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
import { useRef, useState } from 'react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
import { useAddItems } from '@/hooks/use-add-items'
|
||||||
|
import { DICTATION_MESSAGES, useMicrophoneDictation } from '@/hooks/use-microphone-dictation'
|
||||||
|
|
||||||
|
type UseDictateItemsOptions = {
|
||||||
|
/**
|
||||||
|
* The dictation finished: `added` says whether anything made it to the list, so a
|
||||||
|
* sheet can close on success and stay open to show why nothing was added.
|
||||||
|
*/
|
||||||
|
onFinish?: (added: boolean) => void
|
||||||
|
/**
|
||||||
|
* A message was set (an error, or a dictation the API limits rejected). A surface that
|
||||||
|
* may already be closed uses this to show it somewhere else, e.g. as a toast.
|
||||||
|
*/
|
||||||
|
onMessage?: (message: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dictation of items into a list, shared by the empty list's card and the floating
|
||||||
|
* button: the microphone listens until the user stops it and the transcript goes
|
||||||
|
* through `addDictation` (split by the API, undoable). Errors and limits stay in
|
||||||
|
* `message` so each surface can show them where it fits.
|
||||||
|
*/
|
||||||
|
export function useDictateItems(
|
||||||
|
listId: string,
|
||||||
|
{ onFinish, onMessage }: UseDictateItemsOptions = {},
|
||||||
|
) {
|
||||||
|
const [message, setMessage] = useState<string | null>(null)
|
||||||
|
// A rejected dictation is reported from a callback, so the outcome of `addDictation`
|
||||||
|
// is read from here once it resolves.
|
||||||
|
const rejected = useRef(false)
|
||||||
|
|
||||||
|
const showMessage = (detail: string) => {
|
||||||
|
setMessage(detail)
|
||||||
|
onMessage?.(detail)
|
||||||
|
}
|
||||||
|
|
||||||
|
const { addDictation, processing } = useAddItems(listId, {
|
||||||
|
onItemFailed: (source, detail) => toast.error(`No pudimos añadir «${source}»: ${detail}`),
|
||||||
|
onDictationRejected: (_, detail) => {
|
||||||
|
rejected.current = true
|
||||||
|
showMessage(detail)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const dictation = useMicrophoneDictation({
|
||||||
|
onPhrases: async (phrases) => {
|
||||||
|
rejected.current = false
|
||||||
|
const understood = await addDictation(phrases.join('\n'))
|
||||||
|
if (!rejected.current && understood === 0) showMessage(DICTATION_MESSAGES.empty)
|
||||||
|
onFinish?.(understood > 0 && !rejected.current)
|
||||||
|
},
|
||||||
|
onError: (detail) => {
|
||||||
|
showMessage(detail)
|
||||||
|
onFinish?.(false)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const listening = dictation.status === 'listening'
|
||||||
|
|
||||||
|
return {
|
||||||
|
listening,
|
||||||
|
/** Asking for the microphone or splitting the transcript: no new dictation yet. */
|
||||||
|
busy: dictation.status === 'requesting' || processing,
|
||||||
|
processing,
|
||||||
|
supported: dictation.supported,
|
||||||
|
/** What has been heard so far, shown while listening. */
|
||||||
|
heard: dictation.heard,
|
||||||
|
message,
|
||||||
|
start: () => {
|
||||||
|
setMessage(null)
|
||||||
|
dictation.start()
|
||||||
|
},
|
||||||
|
stop: dictation.stop,
|
||||||
|
}
|
||||||
|
}
|
||||||