Compare commits
37 Commits
6aa86a3b68
...
feat/passw
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1964d3e08b | ||
|
|
2117188bf9 | ||
|
|
9bd2cc9089 | ||
|
|
9d4388ed8c | ||
|
|
48c0c83424 | ||
|
|
a814b34036 | ||
|
|
eb1f6cb2a9 | ||
|
|
feb8df14c0 | ||
|
|
86d4796d88 | ||
|
|
d5feb65d62 | ||
|
|
71793dbd3a | ||
|
|
5abdb08204 | ||
|
|
d02ab28fc5 | ||
|
|
db7cdd5585 | ||
|
|
247ea903a9 | ||
|
|
b913fe3299 | ||
|
|
b7fa930831 | ||
|
|
812d4b7170 | ||
|
|
123601939c | ||
|
|
686325d8a4 | ||
|
|
56853bbdeb | ||
|
|
debf3b2728 | ||
|
|
bba10361f0 | ||
|
|
c374db1616 | ||
|
|
815dcc300d | ||
|
|
371e59de92 | ||
|
|
5a8604298e | ||
|
|
e0003490b3 | ||
|
|
9e16dc1c81 | ||
|
|
fbd6942a6e | ||
|
|
f87d46c975 | ||
|
|
370e3022c8 | ||
|
|
4035a4bf20 | ||
|
|
4ed6432f60 | ||
|
|
09f9c4fdf0 | ||
|
|
4ff864a557 | ||
|
|
c4f6b8bc85 |
17
.claude/launch.json
Normal file
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
|
||||
}
|
||||
]
|
||||
}
|
||||
24
.dockerignore
Normal file
24
.dockerignore
Normal file
@@ -0,0 +1,24 @@
|
||||
.git
|
||||
# Just enough of the repository for the web build to read the commit hash.
|
||||
!.git/HEAD
|
||||
!.git/refs
|
||||
!.git/packed-refs
|
||||
.github
|
||||
**/node_modules
|
||||
**/.turbo
|
||||
**/dist
|
||||
**/build
|
||||
**/coverage
|
||||
**/*.tsbuildinfo
|
||||
**/*.log
|
||||
.DS_Store
|
||||
|
||||
# env (examples are kept: they never contain secrets)
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# generated files (rebuilt inside the image)
|
||||
apps/api/src/generated
|
||||
apps/web/src/routeTree.gen.ts
|
||||
apps/web/.tanstack
|
||||
16
.env.example
16
.env.example
@@ -13,13 +13,23 @@ BETTER_AUTH_URL="http://localhost:4100"
|
||||
NODE_ENV="development"
|
||||
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
|
||||
# LOG_LEVEL="info"
|
||||
# Resend API key used to send invitation emails. Without it, emails are logged instead.
|
||||
# Resend API key used to send invitation and password reset emails. Without it, emails are logged instead.
|
||||
# RESEND_API_KEY="re_xxxxxxxx"
|
||||
# From address for outgoing email (must be a verified Resend sender)
|
||||
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
||||
# Public URL of the web app, used to build the accept-invitation links
|
||||
WEB_APP_URL="http://localhost:7153"
|
||||
# Dictation: AI Studio (Gemini API) key, backend only. NEVER prefix it with VITE_
|
||||
# or Vite would put it in the browser bundle. Without it, dictated text is split
|
||||
# on commas and "y" instead of by the model.
|
||||
# GEMINI_API_KEY=""
|
||||
# Optional: model id (defaults to Gemma 4's small variant)
|
||||
# GEMINI_MODEL="gemma-4-26b-a4b-it"
|
||||
# Optional: timeout of the model request, in milliseconds
|
||||
# GEMINI_TIMEOUT_MS="8000"
|
||||
|
||||
# --- apps/web ---
|
||||
# Public URL of the API consumed by the frontend
|
||||
VITE_API_URL="http://localhost:4100"
|
||||
# Optional. In dev, Vite proxies /api/* to the API (http://localhost:4100), so
|
||||
# you normally leave this unset. Only set it to point the frontend at a
|
||||
# different API origin; the client always appends /api to it.
|
||||
# VITE_API_URL=""
|
||||
|
||||
53
.github/workflows/ci.yml
vendored
53
.github/workflows/ci.yml
vendored
@@ -1,53 +0,0 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
# Prisma needs a connection string to generate the client; no database is
|
||||
# contacted during lint, typecheck, test or build.
|
||||
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/superlist?schema=public
|
||||
BETTER_AUTH_SECRET: ci-only-secret-not-used-at-build-time
|
||||
BETTER_AUTH_URL: http://localhost:4100
|
||||
CORS_ORIGIN: http://localhost:7153
|
||||
VITE_API_URL: http://localhost:4100
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
name: Verify
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.4.0
|
||||
|
||||
# The Prisma CLI runs on Node.
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Generate Prisma client
|
||||
run: bun run db:generate
|
||||
|
||||
- name: Lint and format check
|
||||
run: bun run lint:ci
|
||||
|
||||
- name: Typecheck
|
||||
run: bun run typecheck
|
||||
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- name: Build
|
||||
run: bun run build
|
||||
46
AGENTS.md
46
AGENTS.md
@@ -3,10 +3,12 @@
|
||||
## Status
|
||||
|
||||
Scaffold is in place and verified: Turborepo monorepo with `apps/api`, `apps/web` and `packages/shared`,
|
||||
CI on GitHub Actions, Biome as the only JS/TS tool and the text Bun lockfile committed.
|
||||
Biome as the only JS/TS tool and the text Bun lockfile committed. It is deployed with Docker Compose on
|
||||
Dokploy (`docker-compose.yml`); there is no hosted CI.
|
||||
|
||||
Not done yet: product features are just starting (sign-up, shopping lists, list items and invitations exist;
|
||||
there is no Google login and no email verification). The `health` module is the reference example.
|
||||
Not done yet: product features are just starting (sign-up, password recovery with an emailed OTP, shopping lists, list items and invitations exist;
|
||||
there is no Google login and no email verification; the `voice` module splits dictated text with Gemma 4
|
||||
through the Gemini API). The `health` module is the reference example.
|
||||
|
||||
## Stack (source of truth: `STACK.md`)
|
||||
|
||||
@@ -46,7 +48,7 @@ Run from the repo root. Verification order is `build`, then `lint` → `typechec
|
||||
| `bun run build` | `turbo run build` (API bundle + web production build) |
|
||||
| `bun run lint` | `biome check .` per package via turbo — fails on lint, format or import order |
|
||||
| `bun run lint:fix` | `biome check --write .` across the repo (lint fixes, formatting, imports) |
|
||||
| `bun run lint:ci` | `biome ci .` — whole repo, exactly what CI runs |
|
||||
| `bun run lint:ci` | `biome ci .` — whole repo, works without a git index |
|
||||
| `bun run format` | `biome format --write .` (`format:check` to verify only) |
|
||||
| `bun run typecheck` | `tsc` per package (`apps/web` regenerates the route tree first) |
|
||||
| `bun run test` | `bun test` in the API, `vitest` in web and shared |
|
||||
@@ -73,12 +75,12 @@ Run from the repo root. Verification order is `build`, then `lint` → `typechec
|
||||
every task that needs one lists it in `turbo.json`: `db:*` use `env: ["DATABASE_URL"]`, `test` declares the
|
||||
API variables, `dev` uses `passThroughEnv` (they must reach the process but don't change its output).
|
||||
`VITE_*` is covered by Vite framework inference. **When you introduce a new variable, add it to `turbo.json`**
|
||||
or the task will fail (or worse, hit a stale cache) in CI.
|
||||
or the task will fail (or worse, hit a stale cache).
|
||||
- Env files: `cp apps/api/.env.example apps/api/.env` and `cp apps/web/.env.example apps/web/.env` (both
|
||||
gitignored, and `.env.example` at the root documents every variable). Bun loads `.env` automatically; the
|
||||
Prisma CLI does not, which is why `prisma.config.ts` imports `dotenv/config`.
|
||||
- Dev ports: API `4100`, web `7153`. They live in the `.env.example` files, `apps/web/vite.config.ts` and
|
||||
`.github/workflows/ci.yml` — change them together.
|
||||
- Dev ports: API `4100`, web `7153`. They live in the `.env.example` files and `apps/web/vite.config.ts`
|
||||
— change them together.
|
||||
- **TypeScript 6 specifics:** `baseUrl` no longer exists (aliases are declared with `paths` only), and
|
||||
`apps/web/tsconfig.app.json` enables `erasableSyntaxOnly` — no enums, namespaces or constructor parameter
|
||||
properties in the web app. Both apps use `@/*` → `src/*` and `verbatimModuleSyntax` (use `import type`).
|
||||
@@ -88,8 +90,18 @@ Run from the repo root. Verification order is `build`, then `lint` → `typechec
|
||||
PascalCase/camelCase, because BetterAuth and the generated client address models by those names, so a column
|
||||
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.
|
||||
- CI (`.github/workflows/ci.yml`) runs on PRs and pushes to `main`: `bun install --frozen-lockfile` →
|
||||
`db:generate` → `lint:ci` → `typecheck` → `test` → `build`, with Bun 1.4.0 and Node 22 for the Prisma CLI.
|
||||
- **Deployment: Docker Compose on Dokploy** (`docker-compose.yml` at the repo root). Two services, `api` and
|
||||
`web`; the database is external (Dokploy's). Both join the external `dokploy-network` — `web` for Traefik,
|
||||
`api` to reach the database (without it `prisma migrate deploy` fails with P1001). nginx reaches the API
|
||||
over the stack-private `internal` network, where it has the alias `superlist-api`, declared only there
|
||||
(never rely on a generic service name on the shared network: other projects can answer to it). The
|
||||
`api` image (`apps/api/Dockerfile`) builds the Bun bundle and runs `prisma migrate deploy` before
|
||||
`bun run start`; the `web` image (`apps/web/Dockerfile`) builds with Vite and serves `dist/` with
|
||||
`apps/web/nginx.conf`, which also proxies `/api/*` to `http://superlist-api:4100` (re-resolved through
|
||||
Docker's DNS, so API redeploys don't leave nginx on a stale IP). Required env vars are interpolated
|
||||
by Compose (`DATABASE_URL`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `CORS_ORIGIN`, `WEB_APP_URL`); set them
|
||||
in Dokploy. The dictation variables (`GEMINI_API_KEY`, `GEMINI_MODEL`, `GEMINI_TIMEOUT_MS`) are optional and
|
||||
backend-only — never give them a `VITE_` prefix, or Vite would ship the key in the browser bundle. There is no hosted CI.
|
||||
- Generated files are gitignored and must never be edited by hand: `apps/web/src/routeTree.gen.ts`,
|
||||
`apps/api/src/generated/`.
|
||||
- Tests live next to the code as `*.test.ts`. The API uses `bun test` (`src/lib/result-json.test.ts`,
|
||||
@@ -125,7 +137,10 @@ apps/api/src/modules/alerts/
|
||||
- **Routes never check `result.ok` by hand**: every route ends with `resultJson(c, result)`, which serializes
|
||||
`Ok` as JSON (200 by default, override with `{ status: 201 }`, `204` sends an empty body) and maps `Failure`
|
||||
to the matching RFC 9457 `application/problem+json` response.
|
||||
- Wire the module in `createApp()` (`apps/api/src/app.ts`): `app.route('/alerts', alertsModule)`.
|
||||
- Wire the module in `createApp()` (`apps/api/src/app.ts`): `app.route('/api/alerts', alertsModule)`.
|
||||
**Every API route is mounted under `/api`** (BetterAuth already owns `/api/auth/*`) because nginx proxies
|
||||
`/api/*` to the API while serving the SPA at the root — an unprefixed path such as `/lists` would be
|
||||
swallowed by the frontend router.
|
||||
|
||||
```ts
|
||||
// apps/api/src/modules/alerts/list/route.ts
|
||||
@@ -188,7 +203,10 @@ export class CreateAlert {
|
||||
→ `requestId` → request logger → BetterAuth → modules.
|
||||
- **Auth**: BetterAuth is configured in `apps/api/src/lib/auth.ts` (Prisma adapter, `baseURL` from
|
||||
`BETTER_AUTH_URL`, `secret` from `BETTER_AUTH_SECRET`, `trustedOrigins` from `CORS_ORIGIN`,
|
||||
email+password enabled) and owns every route under `/api/auth/*`.
|
||||
email+password enabled) and owns every route under `/api/auth/*`. Password recovery uses the `emailOTP`
|
||||
plugin (6-digit code, 10 minutes, hashed in `verifications`): the web `/forgot-password` route calls
|
||||
`emailOtp.requestPasswordReset` / `emailOtp.resetPassword`, and the code is sent with `sendEmail`
|
||||
(`lib/mailer.ts`, template in `lib/emails/password-reset.ts`). Without `RESEND_API_KEY` the code is logged.
|
||||
- **Prisma 7**: the generator is `prisma-client` and writes to `apps/api/src/generated/prisma` (gitignored), so
|
||||
import it as `@/generated/prisma/client` — never `@prisma/client` directly. The client uses the
|
||||
`@prisma/adapter-pg` adapter with `DATABASE_URL` and is exported as `prisma` (plus the `Database` type) from
|
||||
@@ -226,7 +244,7 @@ apps/web/src/
|
||||
- **Routing: TanStack Router with file-based routes.** Add a file under `src/routes` and the route tree is
|
||||
regenerated (`bun run routes:generate`, also run by `dev`, `build` and `typecheck`; the Vite plugin watches
|
||||
the directory in dev). Never edit `routeTree.gen.ts`; `tsr.config.json` holds the generator config.
|
||||
- `(auth)/sign-in.tsx` — public routes.
|
||||
- `(auth)/sign-in.tsx`, `sign-up.tsx`, `forgot-password.tsx` — public routes.
|
||||
- `_authenticated/route.tsx` — pathless layout for signed-in pages; it guards on the BetterAuth session
|
||||
(`authClient.useSession()`) and redirects to `/sign-in` when there is none. Add authenticated pages inside
|
||||
`_authenticated/`.
|
||||
@@ -246,6 +264,10 @@ apps/web/src/
|
||||
- `apiFetch` returns parsed JSON, sends `credentials: 'include'` (BetterAuth sessions are cookies) and throws
|
||||
`ApiError` carrying the parsed `ProblemDetails` for non-2xx responses; `204` resolves to `undefined`. Error
|
||||
UIs read `error.problem.detail`.
|
||||
- **Same-origin `/api` in every environment.** `apiBaseUrl` is `` `${VITE_API_URL || ''}/api` `` and the SSE
|
||||
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
|
||||
origin, and `auth-client.ts` defaults `baseURL` to `window.location.origin` (BetterAuth appends `/api/auth`).
|
||||
- **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.
|
||||
- **shadcn/ui**: components live in `src/components/ui` and are source, not generated output — edit them
|
||||
|
||||
29
README.md
29
README.md
@@ -46,15 +46,38 @@ bun run typecheck # tsc
|
||||
bun run test # bun test (api) / vitest (web, shared)
|
||||
```
|
||||
|
||||
CI (`.github/workflows/ci.yml`) runs `db:generate` → `lint:ci` → `typecheck` → `test` → `build` on every push
|
||||
to `main` and every pull request.
|
||||
There is no hosted CI: run these locally (in that order) before pushing. `bun run lint:ci` runs the exact
|
||||
same Biome check as `biome ci` would.
|
||||
|
||||
## Deployment (Dokploy)
|
||||
|
||||
`docker-compose.yml` at the repo root defines the two runtime services — `api` (Bun + nginx-free Hono server)
|
||||
and `web` (static build behind nginx, proxying `/api/*` to the API). The database is external (provided by
|
||||
Dokploy). Only `web` joins the external `dokploy-network` so Traefik can reach it; `web` and `api` talk over
|
||||
the stack-private `internal` network, where the API answers to the unique alias `superlist-api` (a generic
|
||||
name like `api` on the shared network could resolve to another project's container).
|
||||
|
||||
- One public domain: nginx serves the SPA and proxies `/api/*` → `http://superlist-api:4100`. All API routes are
|
||||
mounted under `/api` for that reason — never mount a route at the root of the API.
|
||||
- Env vars are interpolated from the Dokploy service env (`docker-compose.yml` marks `DATABASE_URL`,
|
||||
`BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `CORS_ORIGIN` and `WEB_APP_URL` as required). See `.env.example`.
|
||||
- Point the domain in Dokploy's **Domains** UI at the `web` service, container port `80` (the compose file
|
||||
publishes no host ports on purpose).
|
||||
- Migrations run automatically on API startup (`prisma migrate deploy` before `bun run start`).
|
||||
|
||||
Local smoke test of the same setup:
|
||||
|
||||
```bash
|
||||
docker network create dokploy-network # once, mimics Dokploy's network
|
||||
docker compose up --build
|
||||
```
|
||||
|
||||
## Useful scripts
|
||||
|
||||
| Command | Effect |
|
||||
| --------------------- | ------------------------------------------------------------------- |
|
||||
| `bun run lint:fix` | Apply Biome fixes: lint, formatting and import sorting (whole repo) |
|
||||
| `bun run lint:ci` | `biome ci` — check the whole repo exactly as CI does |
|
||||
| `bun run lint:ci` | `biome ci` — whole-repo check, stricter than `lint` |
|
||||
| `bun run format` | Format with Biome (`format:check` to verify only) |
|
||||
| `bun run db:generate` | Regenerate the Prisma client into `apps/api/src/generated` |
|
||||
| `bun run db:migrate` | Create and apply a migration (development) |
|
||||
|
||||
@@ -6,9 +6,17 @@ BETTER_AUTH_URL="http://localhost:4100"
|
||||
NODE_ENV="development"
|
||||
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
|
||||
# LOG_LEVEL="info"
|
||||
# Resend API key used to send invitation emails. Without it, emails are logged instead.
|
||||
# Resend API key used to send invitation and password reset emails. Without it, emails are logged instead.
|
||||
# RESEND_API_KEY="re_xxxxxxxx"
|
||||
# From address for outgoing email (must be a verified Resend sender)
|
||||
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
||||
# Public URL of the web app, used to build the accept-invitation links
|
||||
WEB_APP_URL="http://localhost:7153"
|
||||
# Dictation: AI Studio (Gemini API) key, backend only. NEVER prefix it with VITE_
|
||||
# or Vite would put it in the browser bundle. Without it, dictated text is split
|
||||
# on commas and "y" instead of by the model.
|
||||
# GEMINI_API_KEY=""
|
||||
# Optional: model id (defaults to Gemma 4's small variant)
|
||||
# GEMINI_MODEL="gemma-4-26b-a4b-it"
|
||||
# Optional: timeout of the model request, in milliseconds
|
||||
# GEMINI_TIMEOUT_MS="8000"
|
||||
|
||||
27
apps/api/Dockerfile
Normal file
27
apps/api/Dockerfile
Normal file
@@ -0,0 +1,27 @@
|
||||
# Build context is the repository root (Bun workspace monorepo).
|
||||
FROM oven/bun:1.4.0 AS base
|
||||
WORKDIR /app
|
||||
|
||||
# Manifests first so `bun install` only reruns when the lockfile changes.
|
||||
FROM base AS deps
|
||||
COPY package.json bun.lock bunfig.toml ./
|
||||
COPY apps/api/package.json apps/api/package.json
|
||||
COPY apps/web/package.json apps/web/package.json
|
||||
COPY packages/shared/package.json packages/shared/package.json
|
||||
RUN bun install --frozen-lockfile
|
||||
|
||||
FROM deps AS build
|
||||
COPY . .
|
||||
# `prisma.config.ts` reads DATABASE_URL at load time; generate never connects,
|
||||
# so a placeholder is enough to produce the client in src/generated/.
|
||||
RUN cd apps/api && DATABASE_URL="postgresql://user:pass@localhost:5432/db" bunx prisma generate
|
||||
RUN cd apps/api && bun run build
|
||||
|
||||
# Runtime keeps the full tree: `prisma migrate deploy` runs on startup and
|
||||
# needs the Prisma CLI (devDependency), prisma/ and prisma.config.ts.
|
||||
FROM base AS runtime
|
||||
ENV NODE_ENV=production
|
||||
COPY --from=build /app /app
|
||||
WORKDIR /app/apps/api
|
||||
EXPOSE 4100
|
||||
CMD ["sh", "-c", "bunx prisma migrate deploy && bun run start"]
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "list_items" ADD COLUMN "bought_at" TIMESTAMP(3);
|
||||
@@ -114,6 +114,7 @@ model ListItem {
|
||||
shoppingListId String @map("shopping_list_id")
|
||||
name String
|
||||
completed Boolean @default(false)
|
||||
boughtAt DateTime? @map("bought_at")
|
||||
quantity String? @map("quantity")
|
||||
notes String? @map("notes")
|
||||
order Int @default(0) @map("order")
|
||||
|
||||
@@ -9,6 +9,7 @@ import { errorHandler, notFoundHandler } from '@/lib/problem-details'
|
||||
import { healthModule } from '@/modules/health'
|
||||
import { invitationsModule } from '@/modules/invitations'
|
||||
import { listsModule } from '@/modules/lists'
|
||||
import { voiceModule } from '@/modules/voice'
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
const allowedOrigins = (process.env.CORS_ORIGIN ?? 'http://localhost:7153')
|
||||
@@ -39,12 +40,15 @@ export function createApp() {
|
||||
)
|
||||
})
|
||||
|
||||
// BetterAuth owns every route under /api/auth/*.
|
||||
// Every API route lives under /api: in production nginx serves the SPA on the
|
||||
// root and proxies /api/* to this server, so unprefixed paths would collide
|
||||
// with client routes (/lists, /invitations, ...). BetterAuth owns /api/auth/*.
|
||||
app.on(['POST', 'GET'], '/api/auth/*', (c) => auth.handler(c.req.raw))
|
||||
|
||||
app.route('/health', healthModule)
|
||||
app.route('/lists', listsModule)
|
||||
app.route('/invitations', invitationsModule)
|
||||
app.route('/api/health', healthModule)
|
||||
app.route('/api/lists', listsModule)
|
||||
app.route('/api/invitations', invitationsModule)
|
||||
app.route('/api/voice', voiceModule)
|
||||
|
||||
app.notFound(notFoundHandler)
|
||||
app.onError(errorHandler)
|
||||
|
||||
@@ -9,5 +9,14 @@ logger.info({ port }, 'api listening')
|
||||
|
||||
export default {
|
||||
port,
|
||||
fetch: app.fetch,
|
||||
fetch(req: Request, server: Bun.Server<unknown>) {
|
||||
// SSE streams stay open while the list is quiet: without this, Bun closes
|
||||
// the connection after its 10s idle timeout. Heartbeats are not enough on
|
||||
// their own because they are sent less often than the default timeout.
|
||||
if (new URL(req.url).pathname.endsWith('/events')) {
|
||||
server.timeout(req, 0)
|
||||
}
|
||||
|
||||
return app.fetch(req)
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { betterAuth } from 'better-auth'
|
||||
import { prismaAdapter } from 'better-auth/adapters/prisma'
|
||||
import { emailOTP } from 'better-auth/plugins'
|
||||
|
||||
import { passwordResetEmail } from '@/lib/emails/password-reset'
|
||||
import { acceptPendingInvitations, ensurePrimaryList } from '@/lib/list-membership'
|
||||
import { logger } from '@/lib/logger'
|
||||
import { sendEmail } from '@/lib/mailer'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
|
||||
@@ -9,16 +13,51 @@ const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
|
||||
.map((origin) => origin.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const OTP_EXPIRES_IN_SECONDS = 10 * 60
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: prismaAdapter(prisma, { provider: 'postgresql' }),
|
||||
baseURL: process.env.BETTER_AUTH_URL,
|
||||
secret: process.env.BETTER_AUTH_SECRET,
|
||||
trustedOrigins,
|
||||
session: {
|
||||
// A signed copy of the session lives in a cookie for 5 minutes, so protected
|
||||
// routes skip the session lookup in Postgres on every request. Trade-off: a
|
||||
// session revoked elsewhere stays valid on other devices until the cache expires.
|
||||
cookieCache: {
|
||||
enabled: true,
|
||||
maxAge: 5 * 60,
|
||||
},
|
||||
},
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
minPasswordLength: 8,
|
||||
requireEmailVerification: false,
|
||||
revokeSessionsOnPasswordReset: true,
|
||||
},
|
||||
plugins: [
|
||||
// Password recovery: a 6-digit code sent by email, checked by
|
||||
// /api/auth/email-otp/reset-password. Codes live (hashed) in `verifications`.
|
||||
emailOTP({
|
||||
otpLength: 6,
|
||||
expiresIn: OTP_EXPIRES_IN_SECONDS,
|
||||
allowedAttempts: 3,
|
||||
storeOTP: 'hashed',
|
||||
disableSignUp: true,
|
||||
sendVerificationOTP: async ({ email, otp, type }) => {
|
||||
if (type !== 'forget-password') return
|
||||
|
||||
// Not awaited on purpose: answering at the same speed whether or not the
|
||||
// email exists avoids leaking which addresses have an account.
|
||||
void sendEmail({
|
||||
to: email,
|
||||
...passwordResetEmail({ otp, expiresInMinutes: OTP_EXPIRES_IN_SECONDS / 60 }),
|
||||
}).catch((error: unknown) => {
|
||||
logger.error({ err: error, to: email }, 'failed to send the password reset email')
|
||||
})
|
||||
},
|
||||
}),
|
||||
],
|
||||
databaseHooks: {
|
||||
user: {
|
||||
create: {
|
||||
|
||||
47
apps/api/src/lib/emails/password-reset.ts
Normal file
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 }
|
||||
}
|
||||
64
apps/api/src/lib/events.test.ts
Normal file
64
apps/api/src/lib/events.test.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
import type { ListEvent, ListItem } from '@superlist/shared'
|
||||
|
||||
import { ListEvents } from './events'
|
||||
|
||||
const item: ListItem = {
|
||||
id: 'item-1',
|
||||
listId: 'list-1',
|
||||
name: 'Leche',
|
||||
completed: false,
|
||||
boughtAt: null,
|
||||
quantity: null,
|
||||
notes: null,
|
||||
order: 0,
|
||||
createdAt: '2026-10-16T10:00:00.000Z',
|
||||
updatedAt: '2026-10-16T10:00:00.000Z',
|
||||
}
|
||||
|
||||
describe('ListEvents', () => {
|
||||
it('delivers an event to the subscribers of its list', () => {
|
||||
const bus = new ListEvents()
|
||||
const received: ListEvent[] = []
|
||||
bus.subscribe('list-1', (event) => received.push(event))
|
||||
|
||||
const event: ListEvent = { type: 'item.created', listId: 'list-1', item }
|
||||
bus.publish(event)
|
||||
|
||||
expect(received).toEqual([event])
|
||||
})
|
||||
|
||||
it('does not deliver to the subscribers of another list', () => {
|
||||
const bus = new ListEvents()
|
||||
const received: ListEvent[] = []
|
||||
bus.subscribe('list-2', (event) => received.push(event))
|
||||
|
||||
bus.publish({ type: 'item.created', listId: 'list-1', item })
|
||||
|
||||
expect(received).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('delivers to every subscriber of the same list', () => {
|
||||
const bus = new ListEvents()
|
||||
const first: ListEvent[] = []
|
||||
const second: ListEvent[] = []
|
||||
bus.subscribe('list-1', (event) => first.push(event))
|
||||
bus.subscribe('list-1', (event) => second.push(event))
|
||||
|
||||
bus.publish({ type: 'item.updated', listId: 'list-1', item })
|
||||
|
||||
expect(first).toHaveLength(1)
|
||||
expect(second).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('stops delivering after unsubscribe', () => {
|
||||
const bus = new ListEvents()
|
||||
const received: ListEvent[] = []
|
||||
const unsubscribe = bus.subscribe('list-1', (event) => received.push(event))
|
||||
|
||||
unsubscribe()
|
||||
bus.publish({ type: 'item.created', listId: 'list-1', item })
|
||||
|
||||
expect(received).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
38
apps/api/src/lib/events.ts
Normal file
38
apps/api/src/lib/events.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import type { ListEvent } from '@superlist/shared'
|
||||
|
||||
type ListEventListener = (event: ListEvent) => void
|
||||
|
||||
/**
|
||||
* In-process pub/sub used to fan out list changes to the SSE streams of every
|
||||
* member currently viewing a list.
|
||||
*
|
||||
* It only reaches the API instance that published the event, which is enough
|
||||
* for a single-instance deployment. Scaling horizontally would need a shared
|
||||
* bus (e.g. Postgres `LISTEN`/`NOTIFY`); this interface would stay the same.
|
||||
*/
|
||||
export class ListEvents {
|
||||
private readonly listeners = new Map<string, Set<ListEventListener>>()
|
||||
|
||||
/** Subscribes to one list's events; returns the unsubscribe function. */
|
||||
subscribe(listId: string, listener: ListEventListener): () => void {
|
||||
const listeners = this.listeners.get(listId) ?? new Set<ListEventListener>()
|
||||
listeners.add(listener)
|
||||
this.listeners.set(listId, listeners)
|
||||
|
||||
return () => {
|
||||
listeners.delete(listener)
|
||||
if (listeners.size === 0) this.listeners.delete(listId)
|
||||
}
|
||||
}
|
||||
|
||||
/** Delivers the event to every subscriber of its list. */
|
||||
publish(event: ListEvent): void {
|
||||
const listeners = this.listeners.get(event.listId)
|
||||
if (!listeners) return
|
||||
|
||||
for (const listener of listeners) listener(event)
|
||||
}
|
||||
}
|
||||
|
||||
/** Process-wide bus shared by the use cases and the SSE routes. */
|
||||
export const listEvents = new ListEvents()
|
||||
123
apps/api/src/lib/gemini.ts
Normal file
123
apps/api/src/lib/gemini.ts
Normal file
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Minimal client for the Gemini API `generateContent` REST endpoint (Google AI Studio),
|
||||
* called with `fetch` — no SDK. It serves Gemma models too, which is what the API uses.
|
||||
*
|
||||
* Configuration (backend only — never prefix these with `VITE_`, or Vite would put the
|
||||
* key in the browser bundle):
|
||||
* - `GEMINI_API_KEY`: AI Studio API key. Without it every call fails with `missing-key`.
|
||||
* - `GEMINI_MODEL`: model id, `gemma-4-26b-a4b-it` by default.
|
||||
* - `GEMINI_TIMEOUT_MS`: request timeout, 8000 ms by default.
|
||||
*/
|
||||
|
||||
const GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models'
|
||||
|
||||
/** Gemma 4's small, fast variant (a mixture of experts with ~4B active parameters). */
|
||||
export const DEFAULT_GEMINI_MODEL = 'gemma-4-26b-a4b-it'
|
||||
|
||||
export const DEFAULT_GEMINI_TIMEOUT_MS = 8000
|
||||
|
||||
export type GeminiConfig = {
|
||||
apiKey: string | undefined
|
||||
model: string
|
||||
timeoutMs: number
|
||||
}
|
||||
|
||||
/** Reads the configuration from the environment, with the defaults above. */
|
||||
export function geminiConfigFromEnv(env: Record<string, string | undefined> = process.env) {
|
||||
const timeout = Number.parseInt(env.GEMINI_TIMEOUT_MS ?? '', 10)
|
||||
|
||||
return {
|
||||
apiKey: env.GEMINI_API_KEY?.trim() || undefined,
|
||||
model: env.GEMINI_MODEL?.trim() || DEFAULT_GEMINI_MODEL,
|
||||
timeoutMs: Number.isFinite(timeout) && timeout > 0 ? timeout : DEFAULT_GEMINI_TIMEOUT_MS,
|
||||
} satisfies GeminiConfig
|
||||
}
|
||||
|
||||
/** Why a call failed, short enough to log (it never includes the prompt). */
|
||||
export type GeminiFailureReason =
|
||||
| 'missing-key'
|
||||
| 'timeout'
|
||||
| 'rate-limited'
|
||||
| `http-${number}`
|
||||
| 'network'
|
||||
| 'empty-response'
|
||||
|
||||
export class GeminiError extends Error {
|
||||
constructor(readonly reason: GeminiFailureReason) {
|
||||
super(`Gemini request failed: ${reason}`)
|
||||
this.name = 'GeminiError'
|
||||
}
|
||||
}
|
||||
|
||||
/** One turn of the conversation: `user` for the input, `model` for an example answer. */
|
||||
export type GeminiTurn = { role: 'user' | 'model'; text: string }
|
||||
|
||||
export type GenerateInput = {
|
||||
systemInstruction: string
|
||||
turns: GeminiTurn[]
|
||||
}
|
||||
|
||||
type GenerateContentResponse = {
|
||||
candidates?: { content?: { parts?: { text?: string; thought?: boolean }[] } }[]
|
||||
}
|
||||
|
||||
/** Something that answers a prompt with text: the Gemini client, or a fake in tests. */
|
||||
export type TextGenerator = { generate(input: GenerateInput): Promise<string> }
|
||||
|
||||
export class GeminiClient implements TextGenerator {
|
||||
constructor(
|
||||
private readonly config: GeminiConfig = geminiConfigFromEnv(),
|
||||
private readonly fetchFn: typeof fetch = fetch,
|
||||
) {}
|
||||
|
||||
/** The model's text answer. Throws `GeminiError` on any failure. */
|
||||
async generate({ systemInstruction, turns }: GenerateInput): Promise<string> {
|
||||
if (!this.config.apiKey) throw new GeminiError('missing-key')
|
||||
|
||||
let response: Response
|
||||
try {
|
||||
response = await this.fetchFn(
|
||||
`${GEMINI_API_URL}/${encodeURIComponent(this.config.model)}:generateContent`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', 'x-goog-api-key': this.config.apiKey },
|
||||
body: JSON.stringify({
|
||||
systemInstruction: { parts: [{ text: systemInstruction }] },
|
||||
contents: turns.map(({ role, text }) => ({ role, parts: [{ text }] })),
|
||||
generationConfig: { temperature: 0 },
|
||||
}),
|
||||
signal: AbortSignal.timeout(this.config.timeoutMs),
|
||||
},
|
||||
)
|
||||
} catch (error) {
|
||||
const name = error instanceof Error ? error.name : ''
|
||||
throw new GeminiError(
|
||||
name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'network',
|
||||
)
|
||||
}
|
||||
|
||||
if (response.status === 429) throw new GeminiError('rate-limited')
|
||||
if (!response.ok) throw new GeminiError(`http-${response.status}`)
|
||||
|
||||
let body: GenerateContentResponse
|
||||
try {
|
||||
body = (await response.json()) as GenerateContentResponse
|
||||
} catch (error) {
|
||||
const name = error instanceof Error ? error.name : ''
|
||||
throw new GeminiError(
|
||||
name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'empty-response',
|
||||
)
|
||||
}
|
||||
|
||||
// Thinking models may send their reasoning as `thought` parts: only the answer counts.
|
||||
const text = (body.candidates?.[0]?.content?.parts ?? [])
|
||||
.filter((part) => !part.thought && typeof part.text === 'string')
|
||||
.map((part) => part.text)
|
||||
.join('')
|
||||
.trim()
|
||||
|
||||
if (!text) throw new GeminiError('empty-response')
|
||||
|
||||
return text
|
||||
}
|
||||
}
|
||||
27
apps/api/src/lib/list-access.ts
Normal file
27
apps/api/src/lib/list-access.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { problems } from '@superlist/shared'
|
||||
import type { MiddlewareHandler } from 'hono'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { problemResponse } from '@/lib/problem-details'
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
/**
|
||||
* Guards a `/:listId/*` route so only members of the list reach it. Expects
|
||||
* `requireSession` to have run first (it reads `c.get('user')`).
|
||||
*/
|
||||
export const requireListMembership: MiddlewareHandler<AppEnv> = async (c, next) => {
|
||||
const listId = c.req.param('listId')
|
||||
|
||||
if (!listId) {
|
||||
return problemResponse(c, problems.notFound('La lista no existe o no tienes acceso.'))
|
||||
}
|
||||
|
||||
const membership = await prisma.shoppingListMember.findUnique({
|
||||
where: { listId_userId: { listId, userId: c.get('user').id } },
|
||||
})
|
||||
|
||||
if (!membership) {
|
||||
return problemResponse(c, problems.notFound('La lista no existe o no tienes acceso.'))
|
||||
}
|
||||
|
||||
await next()
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { type ListEvents, listEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
/**
|
||||
@@ -12,6 +13,7 @@ import type { Database } from '@/lib/prisma'
|
||||
export async function acceptPendingInvitations(
|
||||
db: Database,
|
||||
{ userId, email }: { userId: string; email: string },
|
||||
events: ListEvents = listEvents,
|
||||
): Promise<number> {
|
||||
const pending = await db.shoppingListInvitation.findMany({
|
||||
where: { email, status: 'pending', expiresAt: { gt: new Date() } },
|
||||
@@ -29,6 +31,8 @@ export async function acceptPendingInvitations(
|
||||
data: { status: 'accepted', acceptedAt: new Date() },
|
||||
}),
|
||||
])
|
||||
|
||||
events.publish({ type: 'member.added', listId: invitation.listId, userId })
|
||||
}
|
||||
|
||||
return pending.length
|
||||
|
||||
@@ -7,7 +7,7 @@ const isProduction = process.env.NODE_ENV === 'production'
|
||||
* never use `console.log` in the backend.
|
||||
*/
|
||||
export const logger = pino({
|
||||
level: process.env.LOG_LEVEL ?? (isProduction ? 'info' : 'debug'),
|
||||
level: process.env.LOG_LEVEL || (isProduction ? 'info' : 'debug'),
|
||||
...(isProduction
|
||||
? {}
|
||||
: {
|
||||
|
||||
@@ -11,7 +11,7 @@ export type Email = {
|
||||
}
|
||||
|
||||
const apiKey = process.env.RESEND_API_KEY
|
||||
const from = process.env.MAIL_FROM ?? 'Superlist <onboarding@resend.dev>'
|
||||
const from = process.env.MAIL_FROM || 'Superlist <onboarding@resend.dev>'
|
||||
|
||||
let client: Resend | null = null
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
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 { AcceptInvitation } from './use-case'
|
||||
@@ -46,6 +48,14 @@ function createDb({
|
||||
return { db: db as unknown as Database, updates, created }
|
||||
}
|
||||
|
||||
function createBus() {
|
||||
const events = new ListEvents()
|
||||
const published: ListEvent[] = []
|
||||
events.subscribe('list-1', (event) => published.push(event))
|
||||
|
||||
return { events, published }
|
||||
}
|
||||
|
||||
describe('AcceptInvitation', () => {
|
||||
it('answers 404 for an unknown token', async () => {
|
||||
const { db } = createDb({ invitation: undefined })
|
||||
@@ -79,7 +89,8 @@ describe('AcceptInvitation', () => {
|
||||
invitation: INVITATION,
|
||||
membership: { id: 'member-1' },
|
||||
})
|
||||
const result = await new AcceptInvitation(db, () => NOW).execute({
|
||||
const { events, published } = createBus()
|
||||
const result = await new AcceptInvitation(db, () => NOW, events).execute({
|
||||
token: INVITATION.id,
|
||||
userId: 'user-1',
|
||||
email: 'beto@ejemplo.com',
|
||||
@@ -89,6 +100,7 @@ describe('AcceptInvitation', () => {
|
||||
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||
expect(result.value).toEqual({ listId: 'list-1', listName: 'Compra semanal' })
|
||||
expect(updates).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('answers 400 and marks expired invitations', async () => {
|
||||
@@ -111,9 +123,10 @@ describe('AcceptInvitation', () => {
|
||||
expect(created).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('grants access and marks the invitation as accepted', async () => {
|
||||
it('grants access, marks the invitation as accepted and publishes member.added', async () => {
|
||||
const { db, updates, created } = createDb({ invitation: INVITATION })
|
||||
const result = await new AcceptInvitation(db, () => NOW).execute({
|
||||
const { events, published } = createBus()
|
||||
const result = await new AcceptInvitation(db, () => NOW, events).execute({
|
||||
token: INVITATION.id,
|
||||
userId: 'user-1',
|
||||
// Compared in lower case, so the casing of the session email does not matter.
|
||||
@@ -129,5 +142,6 @@ describe('AcceptInvitation', () => {
|
||||
},
|
||||
])
|
||||
expect(updates).toHaveLength(1)
|
||||
expect(published).toEqual([{ type: 'member.added', listId: 'list-1', userId: 'user-1' }])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type Result,
|
||||
} from '@superlist/shared'
|
||||
|
||||
import { type ListEvents, listEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
/** Accepts an invitation for the signed-in user, matching it by token and email. */
|
||||
@@ -14,6 +15,7 @@ export class AcceptInvitation {
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly now: () => Date = () => new Date(),
|
||||
private readonly events: ListEvents = listEvents,
|
||||
) {}
|
||||
|
||||
async execute(input: {
|
||||
@@ -66,6 +68,8 @@ export class AcceptInvitation {
|
||||
}),
|
||||
])
|
||||
|
||||
this.events.publish({ type: 'member.added', listId: invitation.listId, userId: input.userId })
|
||||
|
||||
return Ok({ listId: invitation.list.id, listName: invitation.list.name })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
} from '@superlist/shared'
|
||||
|
||||
import { invitationEmail } from '@/lib/emails/invitation'
|
||||
import { type ListEvents, listEvents } from '@/lib/events'
|
||||
import { logger } from '@/lib/logger'
|
||||
import { type Email, sendEmail } from '@/lib/mailer'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
@@ -24,6 +25,7 @@ type CreateInvitationDependencies = {
|
||||
mailer?: Mailer
|
||||
now?: () => Date
|
||||
generateToken?: () => string
|
||||
events?: ListEvents
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -37,6 +39,7 @@ export class CreateInvitation {
|
||||
private readonly mailer: Mailer
|
||||
private readonly now: () => Date
|
||||
private readonly generateToken: () => string
|
||||
private readonly events: ListEvents
|
||||
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
@@ -45,6 +48,7 @@ export class CreateInvitation {
|
||||
this.mailer = dependencies.mailer ?? sendEmail
|
||||
this.now = dependencies.now ?? (() => new Date())
|
||||
this.generateToken = dependencies.generateToken ?? (() => randomUUID())
|
||||
this.events = dependencies.events ?? listEvents
|
||||
}
|
||||
|
||||
async execute(input: {
|
||||
@@ -129,6 +133,8 @@ export class CreateInvitation {
|
||||
}
|
||||
|
||||
if (invitedUser) {
|
||||
this.events.publish({ type: 'member.added', listId: input.listId, userId: invitedUser.id })
|
||||
|
||||
// Best effort: the person already sees the list, so a mail failure is not fatal.
|
||||
await this.mailer(message).catch((error: unknown) => {
|
||||
logger.warn({ err: error, to: email }, 'could not send the invitation email')
|
||||
@@ -149,6 +155,8 @@ export class CreateInvitation {
|
||||
)
|
||||
}
|
||||
|
||||
this.events.publish({ type: 'invitation.created', listId: input.listId, email })
|
||||
|
||||
return Ok({ status: 'invited', email })
|
||||
}
|
||||
}
|
||||
|
||||
75
apps/api/src/modules/lists/events/route.ts
Normal file
75
apps/api/src/modules/lists/events/route.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import type { ListEvent } from '@superlist/shared'
|
||||
import { Hono } from 'hono'
|
||||
import { streamSSE } from 'hono/streaming'
|
||||
|
||||
import { requireSession } from '@/lib/auth-session'
|
||||
import { listEvents } from '@/lib/events'
|
||||
import { requireListMembership } from '@/lib/list-access'
|
||||
import { validate } from '@/lib/validate'
|
||||
import { ListParamsSchema } from '@/modules/lists/schema'
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
/** Maximum silence between frames; a comment heartbeat is sent in between. */
|
||||
const HEARTBEAT_MS = 20_000
|
||||
|
||||
/**
|
||||
* GET /lists/:listId/events — Server-Sent Events stream with the changes
|
||||
* happening on a list (items, members, invitations). Members only.
|
||||
*
|
||||
* Events are buffered and written as they arrive; while the list is quiet a
|
||||
* comment heartbeat keeps the connection open through Bun's idle timeout and
|
||||
* any proxy in between.
|
||||
*/
|
||||
export const listEventsRoute = new Hono<AppEnv>().get(
|
||||
'/',
|
||||
requireSession,
|
||||
validate.param(ListParamsSchema),
|
||||
requireListMembership,
|
||||
(c) => {
|
||||
const { listId } = c.req.valid('param')
|
||||
|
||||
return streamSSE(c, async (stream) => {
|
||||
const pending: ListEvent[] = []
|
||||
|
||||
// Resolves a pending wait as soon as an event is buffered, so nothing has
|
||||
// to wait for the heartbeat interval.
|
||||
let wake: (() => void) | undefined
|
||||
const unsubscribe = listEvents.subscribe(listId, (event) => {
|
||||
pending.push(event)
|
||||
wake?.()
|
||||
})
|
||||
|
||||
stream.onAbort(() => unsubscribe())
|
||||
|
||||
const waitForEvent = () =>
|
||||
new Promise<void>((resolve) => {
|
||||
wake = resolve
|
||||
})
|
||||
|
||||
await stream.writeSSE({ event: 'ready', data: JSON.stringify({ listId }) })
|
||||
|
||||
while (!stream.aborted) {
|
||||
const event = pending.shift()
|
||||
|
||||
if (event) {
|
||||
await stream.writeSSE({ event: event.type, data: JSON.stringify(event) })
|
||||
continue
|
||||
}
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
await Promise.race([
|
||||
waitForEvent(),
|
||||
new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, HEARTBEAT_MS)
|
||||
}),
|
||||
])
|
||||
clearTimeout(timer)
|
||||
wake = undefined
|
||||
|
||||
if (pending.length === 0 && !stream.aborted) {
|
||||
await stream.write(': ping\n\n')
|
||||
}
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
@@ -3,6 +3,7 @@ import { Hono } from 'hono'
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
import { createListRoute } from './create/route'
|
||||
import { listEventsRoute } from './events/route'
|
||||
import { getListRoute } from './get/route'
|
||||
import { listItemsModule } from './items'
|
||||
import { listListsRoute } from './list/route'
|
||||
@@ -17,3 +18,4 @@ export const listsModule = new Hono<AppEnv>()
|
||||
.route('/', updateListRoute)
|
||||
.route('/', setPrimaryListRoute)
|
||||
.route('/:listId/items', listItemsModule)
|
||||
.route('/:listId/events', listEventsRoute)
|
||||
|
||||
104
apps/api/src/modules/lists/items/create/use-case.test.ts
Normal file
104
apps/api/src/modules/lists/items/create/use-case.test.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
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 { CreateItem } 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-16T10:00:00.000Z')
|
||||
|
||||
function itemRow(input: {
|
||||
name: string
|
||||
quantity?: string | null
|
||||
notes?: string | null
|
||||
}): ItemRow {
|
||||
return {
|
||||
id: 'item-1',
|
||||
shoppingListId: 'list-1',
|
||||
name: input.name,
|
||||
completed: false,
|
||||
boughtAt: null,
|
||||
quantity: input.quantity ?? null,
|
||||
notes: input.notes ?? null,
|
||||
order: 0,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
}
|
||||
|
||||
function createDb(options: { membership: unknown; item: ItemRow }) {
|
||||
const created: unknown[] = []
|
||||
|
||||
const db = {
|
||||
shoppingListMember: {
|
||||
findUnique: async () => options.membership,
|
||||
},
|
||||
listItem: {
|
||||
create: async (args: unknown) => {
|
||||
created.push(args)
|
||||
return options.item
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return { db: db as unknown as Database, created }
|
||||
}
|
||||
|
||||
function createBus() {
|
||||
const events = new ListEvents()
|
||||
const published: ListEvent[] = []
|
||||
events.subscribe('list-1', (event) => published.push(event))
|
||||
|
||||
return { events, published }
|
||||
}
|
||||
|
||||
describe('CreateItem', () => {
|
||||
it('answers 404 when the user does not belong to the list', async () => {
|
||||
const { db, created } = createDb({ membership: null, item: itemRow({ name: 'Leche' }) })
|
||||
const { events, published } = createBus()
|
||||
const result = await new CreateItem(db, events).execute({
|
||||
listId: 'list-1',
|
||||
userId: 'user-1',
|
||||
name: 'Leche',
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(404)
|
||||
expect(created).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('creates the item and publishes item.created', async () => {
|
||||
const { db } = createDb({
|
||||
membership: { role: 'collaborator' },
|
||||
item: itemRow({ name: 'Leche', quantity: '1 L' }),
|
||||
})
|
||||
const { events, published } = createBus()
|
||||
const result = await new CreateItem(db, events).execute({
|
||||
listId: 'list-1',
|
||||
userId: 'user-1',
|
||||
name: 'Leche',
|
||||
quantity: '1 L',
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||
expect(result.value.name).toBe('Leche')
|
||||
expect(published).toEqual([{ type: 'item.created', listId: 'list-1', item: result.value }])
|
||||
})
|
||||
})
|
||||
@@ -7,13 +7,17 @@ import {
|
||||
type Result,
|
||||
} from '@superlist/shared'
|
||||
|
||||
import { type ListEvents, listEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
import { toListItem } from '../serialize'
|
||||
|
||||
/** Adds an item to a shopping list. Only members can add items. */
|
||||
export class CreateItem {
|
||||
constructor(private readonly db: Database) {}
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly events: ListEvents = listEvents,
|
||||
) {}
|
||||
|
||||
async execute(input: {
|
||||
listId: string
|
||||
@@ -39,6 +43,9 @@ export class CreateItem {
|
||||
},
|
||||
})
|
||||
|
||||
return Ok(toListItem(item))
|
||||
const created = toListItem(item)
|
||||
this.events.publish({ type: 'item.created', listId: input.listId, item: created })
|
||||
|
||||
return Ok(created)
|
||||
}
|
||||
}
|
||||
|
||||
27
apps/api/src/modules/lists/items/delete/route.ts
Normal file
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
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
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,9 +3,15 @@ import { Hono } from 'hono'
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
import { createItemRoute } from './create/route'
|
||||
import { deleteItemRoute } from './delete/route'
|
||||
import { listItemsRoute } from './list/route'
|
||||
import { moveItemRoute } from './move/route'
|
||||
import { updateItemRoute } from './update/route'
|
||||
|
||||
/** `items` sub-module of `lists`: mounted at `/lists/:listId/items`. */
|
||||
export const listItemsModule = new Hono<AppEnv>()
|
||||
.route('/', listItemsRoute)
|
||||
.route('/', createItemRoute)
|
||||
.route('/', updateItemRoute)
|
||||
.route('/', moveItemRoute)
|
||||
.route('/', deleteItemRoute)
|
||||
|
||||
31
apps/api/src/modules/lists/items/move/route.ts
Normal file
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
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
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
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)
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ type ItemRow = {
|
||||
shoppingListId: string
|
||||
name: string
|
||||
completed: boolean
|
||||
boughtAt: Date | null
|
||||
quantity: string | null
|
||||
notes: string | null
|
||||
order: number
|
||||
@@ -19,6 +20,7 @@ export function toListItem(item: ItemRow): ListItem {
|
||||
listId: item.shoppingListId,
|
||||
name: item.name,
|
||||
completed: item.completed,
|
||||
boughtAt: item.boughtAt?.toISOString() ?? null,
|
||||
quantity: item.quantity,
|
||||
notes: item.notes,
|
||||
order: item.order,
|
||||
|
||||
33
apps/api/src/modules/lists/items/update/route.ts
Normal file
33
apps/api/src/modules/lists/items/update/route.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
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, UpdateItemSchema } from './schema'
|
||||
import { UpdateItem } from './use-case'
|
||||
|
||||
/** PATCH /lists/:listId/items/:itemId — updates an item's name, bought state, quantity and/or notes. */
|
||||
export const updateItemRoute = new Hono<AppEnv>().patch(
|
||||
'/:itemId',
|
||||
requireSession,
|
||||
validate.param(ItemParamsSchema),
|
||||
validate.json(UpdateItemSchema),
|
||||
async (c) => {
|
||||
const { listId, itemId } = c.req.valid('param')
|
||||
const { name, completed, quantity, notes } = c.req.valid('json')
|
||||
const result = await new UpdateItem(prisma).execute({
|
||||
listId,
|
||||
itemId,
|
||||
userId: c.get('user').id,
|
||||
name,
|
||||
completed,
|
||||
quantity,
|
||||
notes,
|
||||
})
|
||||
|
||||
return resultJson(c, result)
|
||||
},
|
||||
)
|
||||
35
apps/api/src/modules/lists/items/update/schema.ts
Normal file
35
apps/api/src/modules/lists/items/update/schema.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
/** Path params of `PATCH /lists/:listId/items/:itemId`. */
|
||||
export const ItemParamsSchema = z.object({
|
||||
listId: z.uuid('El identificador de la lista no es válido'),
|
||||
itemId: z.string().min(1, 'El identificador del artículo no es válido'),
|
||||
})
|
||||
|
||||
export type ItemParams = z.infer<typeof ItemParamsSchema>
|
||||
|
||||
/** Body of `PATCH /lists/:listId/items/:itemId` — at least one field is required. */
|
||||
export const UpdateItemSchema = z
|
||||
.object({
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, 'El nombre es obligatorio')
|
||||
.max(120, 'Máximo 120 caracteres')
|
||||
.optional(),
|
||||
completed: z.boolean().optional(),
|
||||
quantity: z.string().trim().max(40, 'Máximo 40 caracteres').nullable().optional(),
|
||||
notes: z.string().trim().max(280, 'Máximo 280 caracteres').nullable().optional(),
|
||||
})
|
||||
.refine(
|
||||
(value) =>
|
||||
value.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>
|
||||
257
apps/api/src/modules/lists/items/update/use-case.test.ts
Normal file
257
apps/api/src/modules/lists/items/update/use-case.test.ts
Normal file
@@ -0,0 +1,257 @@
|
||||
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 { UpdateItem } 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-16T10:00:00.000Z')
|
||||
|
||||
function itemRow(completed: boolean, boughtAt: Date | null): ItemRow {
|
||||
return {
|
||||
id: 'item-1',
|
||||
shoppingListId: 'list-1',
|
||||
name: 'Leche',
|
||||
completed,
|
||||
boughtAt,
|
||||
quantity: '1 L',
|
||||
notes: null,
|
||||
order: 0,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
}
|
||||
|
||||
function createDb(options: { membership: unknown; item: ItemRow | null }) {
|
||||
const updates: unknown[] = []
|
||||
|
||||
const db = {
|
||||
shoppingListMember: {
|
||||
findUnique: async () => options.membership,
|
||||
},
|
||||
listItem: {
|
||||
findFirst: async () => options.item,
|
||||
// The use case only sends the fields it changes, so the stored row is
|
||||
// simulated by merging those fields into the row the query returned.
|
||||
update: async (args: {
|
||||
data: Partial<Pick<ItemRow, 'name' | 'completed' | 'boughtAt' | 'quantity' | 'notes'>>
|
||||
}) => {
|
||||
updates.push(args)
|
||||
return { ...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))
|
||||
|
||||
return { events, published }
|
||||
}
|
||||
|
||||
describe('UpdateItem', () => {
|
||||
it('answers 404 when the user does not belong to the list', async () => {
|
||||
const { db, updates } = createDb({ membership: null, 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',
|
||||
completed: 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)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('answers 404 when the item does not belong to the list', async () => {
|
||||
const { db, updates } = createDb({ membership: { role: 'owner' }, item: null })
|
||||
const { events, published } = createBus()
|
||||
const result = await new UpdateItem(db, events).execute({
|
||||
listId: 'list-1',
|
||||
itemId: 'item-of-another-list',
|
||||
userId: 'user-1',
|
||||
completed: 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)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('marks the item as bought and publishes item.updated', 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',
|
||||
completed: true,
|
||||
})
|
||||
|
||||
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 } }
|
||||
expect(data.data.completed).toBe(true)
|
||||
expect(data.data.boughtAt).toBeInstanceOf(Date)
|
||||
|
||||
expect(result.value.completed).toBe(true)
|
||||
expect(result.value.boughtAt).toBe(data.data.boughtAt?.toISOString() ?? null)
|
||||
|
||||
expect(published).toEqual([{ type: 'item.updated', listId: 'list-1', item: result.value }])
|
||||
})
|
||||
|
||||
it('updates only the quantity, leaving the bought state untouched', async () => {
|
||||
const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) })
|
||||
const { events, published } = createBus()
|
||||
const result = await new UpdateItem(db, events).execute({
|
||||
listId: 'list-1',
|
||||
itemId: 'item-1',
|
||||
userId: 'user-1',
|
||||
quantity: ' 3 ',
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||
|
||||
expect(updates).toHaveLength(1)
|
||||
const data = updates[0] as {
|
||||
data: { completed?: boolean; boughtAt?: Date | null; quantity?: string | null }
|
||||
}
|
||||
expect(data.data).toEqual({ quantity: '3' })
|
||||
expect(data.data.completed).toBeUndefined()
|
||||
|
||||
expect(result.value.completed).toBe(false)
|
||||
expect(result.value.quantity).toBe('3')
|
||||
|
||||
expect(published).toEqual([{ type: 'item.updated', listId: 'list-1', item: result.value }])
|
||||
})
|
||||
|
||||
it('clears the quantity when an empty value is sent', async () => {
|
||||
const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) })
|
||||
const { events } = createBus()
|
||||
const result = await new UpdateItem(db, events).execute({
|
||||
listId: 'list-1',
|
||||
itemId: 'item-1',
|
||||
userId: 'user-1',
|
||||
quantity: '',
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||
|
||||
const data = updates[0] as { data: { quantity?: string | null } }
|
||||
expect(data.data).toEqual({ quantity: null })
|
||||
expect(result.value.quantity).toBeNull()
|
||||
})
|
||||
|
||||
it('renames the item, leaving the rest untouched', async () => {
|
||||
const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) })
|
||||
const { events } = createBus()
|
||||
const result = await new UpdateItem(db, events).execute({
|
||||
listId: 'list-1',
|
||||
itemId: 'item-1',
|
||||
userId: 'user-1',
|
||||
name: ' Leche descremada ',
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||
|
||||
const data = updates[0] as { data: { name?: string } }
|
||||
expect(data.data).toEqual({ name: 'Leche descremada' })
|
||||
expect(result.value.name).toBe('Leche descremada')
|
||||
expect(result.value.quantity).toBe('1 L')
|
||||
})
|
||||
|
||||
it('updates only the notes, leaving the rest untouched', async () => {
|
||||
const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) })
|
||||
const { events, published } = createBus()
|
||||
const result = await new UpdateItem(db, events).execute({
|
||||
listId: 'list-1',
|
||||
itemId: 'item-1',
|
||||
userId: 'user-1',
|
||||
notes: ' sin lactosa ',
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||
|
||||
const data = updates[0] as { data: { notes?: string | null } }
|
||||
expect(data.data).toEqual({ notes: 'sin lactosa' })
|
||||
expect(result.value.notes).toBe('sin lactosa')
|
||||
expect(result.value.quantity).toBe('1 L')
|
||||
|
||||
expect(published).toEqual([{ type: 'item.updated', listId: 'list-1', item: result.value }])
|
||||
})
|
||||
|
||||
it('clears the notes when an empty value is sent', async () => {
|
||||
const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) })
|
||||
const { events } = createBus()
|
||||
const result = await new UpdateItem(db, events).execute({
|
||||
listId: 'list-1',
|
||||
itemId: 'item-1',
|
||||
userId: 'user-1',
|
||||
notes: '',
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||
|
||||
const data = updates[0] as { data: { notes?: string | null } }
|
||||
expect(data.data).toEqual({ notes: null })
|
||||
expect(result.value.notes).toBeNull()
|
||||
})
|
||||
|
||||
it('marks the item back to pending, clears boughtAt and publishes item.updated', async () => {
|
||||
const { db, updates } = createDb({
|
||||
membership: { role: 'collaborator' },
|
||||
item: itemRow(true, new Date('2026-10-15T12:00:00.000Z')),
|
||||
})
|
||||
const { events, published } = createBus()
|
||||
const result = await new UpdateItem(db, events).execute({
|
||||
listId: 'list-1',
|
||||
itemId: 'item-1',
|
||||
userId: 'user-1',
|
||||
completed: false,
|
||||
})
|
||||
|
||||
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 } }
|
||||
expect(data.data.completed).toBe(false)
|
||||
expect(data.data.boughtAt).toBeNull()
|
||||
|
||||
expect(result.value.completed).toBe(false)
|
||||
expect(result.value.boughtAt).toBeNull()
|
||||
|
||||
expect(published).toEqual([{ type: 'item.updated', listId: 'list-1', item: result.value }])
|
||||
})
|
||||
})
|
||||
92
apps/api/src/modules/lists/items/update/use-case.ts
Normal file
92
apps/api/src/modules/lists/items/update/use-case.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
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 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
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates an item's name, its bought state, its quantity and/or its notes. Only members can do it.
|
||||
* `boughtAt` records the moment an item was marked as bought, for future
|
||||
* statistics, and is cleared when the item goes back to pending.
|
||||
*/
|
||||
export class UpdateItem {
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly events: ListEvents = listEvents,
|
||||
) {}
|
||||
|
||||
async execute(input: UpdateItemFields): Promise<Result<ListItem, 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.'))
|
||||
}
|
||||
|
||||
const data: {
|
||||
name?: string
|
||||
completed?: boolean
|
||||
boughtAt?: Date | null
|
||||
quantity?: string | null
|
||||
notes?: string | null
|
||||
} = {}
|
||||
|
||||
if (input.name !== undefined) {
|
||||
data.name = input.name.trim()
|
||||
}
|
||||
|
||||
if (input.completed !== undefined) {
|
||||
data.completed = input.completed
|
||||
data.boughtAt = input.completed ? new Date() : null
|
||||
}
|
||||
|
||||
if (input.quantity !== undefined) {
|
||||
data.quantity = input.quantity?.trim() || null
|
||||
}
|
||||
|
||||
if (input.notes !== undefined) {
|
||||
data.notes = input.notes?.trim() || null
|
||||
}
|
||||
|
||||
const updated = await this.db.listItem.update({
|
||||
where: { id: item.id },
|
||||
data,
|
||||
})
|
||||
|
||||
const dto = toListItem(updated)
|
||||
this.events.publish({ type: 'item.updated', listId: input.listId, item: dto })
|
||||
|
||||
return Ok(dto)
|
||||
}
|
||||
}
|
||||
@@ -7,11 +7,15 @@ import {
|
||||
type ShoppingListSummary,
|
||||
} from '@superlist/shared'
|
||||
|
||||
import { type ListEvents, listEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
/** Renames a list. Only the owner (`role: owner`) may do it. */
|
||||
export class UpdateShoppingList {
|
||||
constructor(private readonly db: Database) {}
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly events: ListEvents = listEvents,
|
||||
) {}
|
||||
|
||||
async execute(input: {
|
||||
listId: string
|
||||
@@ -36,6 +40,8 @@ export class UpdateShoppingList {
|
||||
include: { _count: { select: { members: true } } },
|
||||
})
|
||||
|
||||
this.events.publish({ type: 'list.updated', listId: list.id, name: list.name })
|
||||
|
||||
return Ok({
|
||||
id: list.id,
|
||||
name: list.name,
|
||||
|
||||
8
apps/api/src/modules/voice/index.ts
Normal file
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
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
91
apps/api/src/modules/voice/split/items.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { VOICE_ITEM_MAX_LENGTH, VOICE_MAX_ITEMS } from '@superlist/shared'
|
||||
|
||||
/**
|
||||
* Trims every item, drops empty ones and caps the result: at most `VOICE_MAX_ITEMS`
|
||||
* items of at most `VOICE_ITEM_MAX_LENGTH` characters each.
|
||||
*/
|
||||
export function cleanItems(items: string[]): string[] {
|
||||
return items
|
||||
.map((item) => item.trim().slice(0, VOICE_ITEM_MAX_LENGTH).trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, VOICE_MAX_ITEMS)
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan B when the model cannot be used: splits on commas, semicolons, " y " and " e ".
|
||||
* A comma between digits is a decimal ("1,5 kg") and stays.
|
||||
*/
|
||||
export function fallbackSplit(text: string): string[] {
|
||||
return cleanItems(text.split(/\s*[;\n]\s*|\s*,\s*(?!\d)|\s+[ye]\s+/i))
|
||||
}
|
||||
|
||||
/** Removes a Markdown code fence around the answer (```json … ```), if any. */
|
||||
function stripCodeFences(text: string): string {
|
||||
const fenced = /```(?:json|JSON)?\s*([\s\S]*?)```/.exec(text)
|
||||
|
||||
return (fenced?.[1] ?? text).trim()
|
||||
}
|
||||
|
||||
/**
|
||||
* The first balanced JSON array or object in `text`, skipping brackets inside strings.
|
||||
* Returns `null` when there is none.
|
||||
*/
|
||||
function firstJsonValue(text: string): string | null {
|
||||
const start = text.search(/[[{]/)
|
||||
if (start === -1) return null
|
||||
|
||||
let depth = 0
|
||||
let inString = false
|
||||
let escaped = false
|
||||
|
||||
for (let index = start; index < text.length; index++) {
|
||||
const char = text[index]
|
||||
|
||||
if (inString) {
|
||||
if (escaped) escaped = false
|
||||
else if (char === '\\') escaped = true
|
||||
else if (char === '"') inString = false
|
||||
continue
|
||||
}
|
||||
|
||||
if (char === '"') inString = true
|
||||
else if (char === '[' || char === '{') depth++
|
||||
else if (char === ']' || char === '}') {
|
||||
depth--
|
||||
if (depth === 0) return text.slice(start, index + 1)
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function tryParse(text: string): unknown {
|
||||
try {
|
||||
return JSON.parse(text)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the model's answer: a JSON array of strings, possibly inside a code fence,
|
||||
* surrounded by prose or wrapped as `{ "items": [...] }`. Returns the cleaned items,
|
||||
* or `null` when the answer is not an array of strings.
|
||||
*/
|
||||
export function parseModelItems(answer: string): string[] | null {
|
||||
const unfenced = stripCodeFences(answer)
|
||||
let value = tryParse(unfenced)
|
||||
|
||||
if (value === undefined) {
|
||||
const json = firstJsonValue(unfenced)
|
||||
value = json ? tryParse(json) : undefined
|
||||
}
|
||||
|
||||
if (value && typeof value === 'object' && !Array.isArray(value) && 'items' in value) {
|
||||
value = value.items
|
||||
}
|
||||
|
||||
if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) return null
|
||||
|
||||
return cleanItems(value)
|
||||
}
|
||||
30
apps/api/src/modules/voice/split/prompt.ts
Normal file
30
apps/api/src/modules/voice/split/prompt.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { VOICE_SPLIT_EXAMPLES } from '@superlist/shared'
|
||||
|
||||
import type { GeminiTurn, GenerateInput } from '@/lib/gemini'
|
||||
|
||||
/** What the model is told to do. Gemma accepts it as `systemInstruction`. */
|
||||
export const SPLIT_INSTRUCTION = `Sos un asistente que arma listas de compras en español rioplatense.
|
||||
Recibís la transcripción de lo que alguien dictó y respondés SOLO con un array JSON de strings, sin texto antes ni después.
|
||||
|
||||
Reglas:
|
||||
- Un elemento por producto.
|
||||
- Números en dígitos: "dos" → 2, "media docena" → 6, "una docena" → 12, "un kilo" → 1 kg, "un kilo y medio" → 1,5 kg.
|
||||
- Unidades abreviadas: g, kg, ml, l. Los envases quedan como palabra: "1 lata", "2 paquetes".
|
||||
- La cantidad va al principio: "2 l de leche", "400 g de queso", "12 huevos".
|
||||
- Detalles como marca, color, tipo o corte van como nota, después de un punto: "Bolsas de residuos. Negras y verdes".
|
||||
- No inventes productos ni cantidades: si no se dijo una cantidad, no pongas ninguna.
|
||||
- Corregí errores obvios de la transcripción (palabras mal reconocidas, mayúsculas).
|
||||
- Si no hay ningún producto, respondé [].`
|
||||
|
||||
/** The conversation sent to the model: the few-shot examples, then the transcript. */
|
||||
export function buildSplitPrompt(text: string): GenerateInput {
|
||||
const examples: GeminiTurn[] = VOICE_SPLIT_EXAMPLES.flatMap(({ said, items }) => [
|
||||
{ role: 'user' as const, text: said },
|
||||
{ role: 'model' as const, text: JSON.stringify(items) },
|
||||
])
|
||||
|
||||
return {
|
||||
systemInstruction: SPLIT_INSTRUCTION,
|
||||
turns: [...examples, { role: 'user', text }],
|
||||
}
|
||||
}
|
||||
151
apps/api/src/modules/voice/split/route.test.ts
Normal file
151
apps/api/src/modules/voice/split/route.test.ts
Normal file
@@ -0,0 +1,151 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test'
|
||||
import type { MiddlewareHandler } from 'hono'
|
||||
import { Hono } from 'hono'
|
||||
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
// The session is BetterAuth's (and its database's) business: here every request is signed in.
|
||||
mock.module('@/lib/auth-session', () => ({
|
||||
requireSession: (async (c, next) => {
|
||||
c.set('user', { id: 'user-1', name: 'Ana', email: 'ana@example.com' })
|
||||
await next()
|
||||
}) satisfies MiddlewareHandler<AppEnv>,
|
||||
}))
|
||||
|
||||
const { voiceModule } = await import('@/modules/voice')
|
||||
|
||||
const warnings: unknown[] = []
|
||||
const originalFetch = globalThis.fetch
|
||||
const originalEnv = { ...process.env }
|
||||
|
||||
function createTestApp() {
|
||||
return new Hono<AppEnv>()
|
||||
.use(async (c, next) => {
|
||||
c.set('logger', { warn: (...args: unknown[]) => warnings.push(args) } as never)
|
||||
await next()
|
||||
})
|
||||
.route('/api/voice', voiceModule)
|
||||
}
|
||||
|
||||
function split(body: unknown) {
|
||||
return createTestApp().request('/api/voice/split', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
function mockFetch(handler: (url: string, init: RequestInit) => Promise<Response>) {
|
||||
const fn = mock(handler)
|
||||
globalThis.fetch = fn as unknown as typeof fetch
|
||||
return fn
|
||||
}
|
||||
|
||||
function modelAnswer(text: string) {
|
||||
return Response.json({ candidates: [{ content: { parts: [{ text }] } }] })
|
||||
}
|
||||
|
||||
const TEXT = 'dos litros de leche descremada, una docena de huevos y bolsas de residuos'
|
||||
|
||||
beforeEach(() => {
|
||||
warnings.length = 0
|
||||
process.env.GEMINI_API_KEY = 'test-key'
|
||||
process.env.GEMINI_MODEL = 'gemma-test'
|
||||
process.env.GEMINI_TIMEOUT_MS = '50'
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch
|
||||
process.env = { ...originalEnv }
|
||||
})
|
||||
|
||||
describe('POST /api/voice/split', () => {
|
||||
it('returns the items the model answers with', async () => {
|
||||
const fetchMock = mockFetch(async () =>
|
||||
modelAnswer('["2 l de leche descremada", "12 huevos", "Bolsas de residuos"]'),
|
||||
)
|
||||
|
||||
const response = await split({ text: TEXT })
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toEqual({
|
||||
items: ['2 l de leche descremada', '12 huevos', 'Bolsas de residuos'],
|
||||
})
|
||||
expect(warnings).toHaveLength(0)
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0] ?? []
|
||||
expect(url).toContain('/models/gemma-test:generateContent')
|
||||
expect(new Headers(init?.headers).get('x-goog-api-key')).toBe('test-key')
|
||||
const sent = JSON.parse(String(init?.body))
|
||||
expect(sent.generationConfig.temperature).toBe(0)
|
||||
expect(sent.systemInstruction.parts[0].text).toContain('array JSON')
|
||||
expect(sent.contents.at(-1)).toEqual({ role: 'user', parts: [{ text: TEXT }] })
|
||||
})
|
||||
|
||||
it('falls back to splitting the text when the model times out', async () => {
|
||||
mockFetch(
|
||||
(_url, init) =>
|
||||
new Promise((_resolve, reject) => {
|
||||
init.signal?.addEventListener('abort', () => reject(init.signal?.reason))
|
||||
}),
|
||||
)
|
||||
|
||||
const response = await split({ text: TEXT })
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toEqual({
|
||||
items: ['dos litros de leche descremada', 'una docena de huevos', 'bolsas de residuos'],
|
||||
})
|
||||
expect(JSON.stringify(warnings)).toContain('timeout')
|
||||
// The transcript itself is never logged.
|
||||
expect(JSON.stringify(warnings)).not.toContain('leche')
|
||||
})
|
||||
|
||||
it('falls back when the model is rate limited (429)', async () => {
|
||||
mockFetch(async () => new Response('quota', { status: 429 }))
|
||||
|
||||
const response = await split({ text: 'pan y queso' })
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toEqual({ items: ['pan', 'queso'] })
|
||||
expect(JSON.stringify(warnings)).toContain('rate-limited')
|
||||
})
|
||||
|
||||
it('falls back when the model answers invalid JSON', async () => {
|
||||
mockFetch(async () => modelAnswer('Perdón, no entendí.'))
|
||||
|
||||
const response = await split({ text: 'pan, queso' })
|
||||
|
||||
expect(await response.json()).toEqual({ items: ['pan', 'queso'] })
|
||||
expect(JSON.stringify(warnings)).toContain('invalid-json')
|
||||
})
|
||||
|
||||
it('falls back without calling the model when there is no API key', async () => {
|
||||
delete process.env.GEMINI_API_KEY
|
||||
const fetchMock = mockFetch(async () => modelAnswer('[]'))
|
||||
|
||||
const response = await split({ text: 'pan' })
|
||||
|
||||
expect(await response.json()).toEqual({ items: ['pan'] })
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects an empty text with a 422', async () => {
|
||||
const fetchMock = mockFetch(async () => modelAnswer('[]'))
|
||||
|
||||
const response = await split({ text: ' ' })
|
||||
|
||||
expect(response.status).toBe(422)
|
||||
expect(response.headers.get('content-type')).toContain('application/problem+json')
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('truncates the text to 500 characters', async () => {
|
||||
const fetchMock = mockFetch(async () => modelAnswer('["pan"]'))
|
||||
|
||||
await split({ text: 'a'.repeat(800) })
|
||||
|
||||
const sent = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))
|
||||
expect(sent.contents.at(-1).parts[0].text).toHaveLength(500)
|
||||
})
|
||||
})
|
||||
23
apps/api/src/modules/voice/split/route.ts
Normal file
23
apps/api/src/modules/voice/split/route.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Hono } from 'hono'
|
||||
|
||||
import { requireSession } from '@/lib/auth-session'
|
||||
import { GeminiClient } from '@/lib/gemini'
|
||||
import { resultJson } from '@/lib/result-json'
|
||||
import { validate } from '@/lib/validate'
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
import { SplitVoiceSchema } from './schema'
|
||||
import { SplitVoiceText } from './use-case'
|
||||
|
||||
/** POST /voice/split — splits a dictated sentence into one string per item. */
|
||||
export const splitVoiceRoute = new Hono<AppEnv>().post(
|
||||
'/split',
|
||||
requireSession,
|
||||
validate.json(SplitVoiceSchema),
|
||||
async (c) => {
|
||||
const { text } = c.req.valid('json')
|
||||
const result = await new SplitVoiceText(new GeminiClient(), c.get('logger')).execute({ text })
|
||||
|
||||
return resultJson(c, result)
|
||||
},
|
||||
)
|
||||
13
apps/api/src/modules/voice/split/schema.ts
Normal file
13
apps/api/src/modules/voice/split/schema.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { VOICE_TEXT_MAX_LENGTH } from '@superlist/shared'
|
||||
import { z } from 'zod'
|
||||
|
||||
/** Body of `POST /voice/split`. Longer transcripts are cut to `VOICE_TEXT_MAX_LENGTH`. */
|
||||
export const SplitVoiceSchema = z.object({
|
||||
text: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, 'El texto no puede estar vacío')
|
||||
.transform((text) => text.slice(0, VOICE_TEXT_MAX_LENGTH)),
|
||||
})
|
||||
|
||||
export type SplitVoiceInput = z.infer<typeof SplitVoiceSchema>
|
||||
54
apps/api/src/modules/voice/split/use-case.ts
Normal file
54
apps/api/src/modules/voice/split/use-case.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import {
|
||||
Ok,
|
||||
type ProblemDetails,
|
||||
type Result,
|
||||
VOICE_TEXT_MAX_LENGTH,
|
||||
type VoiceSplitResponse,
|
||||
} from '@superlist/shared'
|
||||
|
||||
import { GeminiError, type TextGenerator } from '@/lib/gemini'
|
||||
import type { Logger } from '@/lib/logger'
|
||||
|
||||
import { cleanItems, fallbackSplit, parseModelItems } from './items'
|
||||
import { buildSplitPrompt } from './prompt'
|
||||
|
||||
/**
|
||||
* Splits a dictated sentence into one string per item ("dos litros de leche y doce
|
||||
* huevos" → ["2 l de leche", "12 huevos"]), asking the model first. The model only
|
||||
* splits and normalizes; the web app reads each string with its usual parser.
|
||||
*
|
||||
* It never fails because of the model: when the model is not configured, times out,
|
||||
* is rate limited or answers something that is not an array of strings, the text is
|
||||
* split on commas, semicolons, " y " and " e " instead, and the reason is logged
|
||||
* (never the transcript).
|
||||
*/
|
||||
export class SplitVoiceText {
|
||||
constructor(
|
||||
private readonly model: TextGenerator,
|
||||
private readonly logger: Pick<Logger, 'warn'>,
|
||||
) {}
|
||||
|
||||
async execute(input: { text: string }): Promise<Result<VoiceSplitResponse, ProblemDetails>> {
|
||||
const text = input.text.trim().slice(0, VOICE_TEXT_MAX_LENGTH)
|
||||
if (!text) return Ok({ items: [] })
|
||||
|
||||
let answer: string
|
||||
try {
|
||||
answer = await this.model.generate(buildSplitPrompt(text))
|
||||
} catch (error) {
|
||||
return this.fallback(text, error instanceof GeminiError ? error.reason : 'unexpected-error')
|
||||
}
|
||||
|
||||
const items = parseModelItems(answer)
|
||||
if (items === null) return this.fallback(text, 'invalid-json')
|
||||
if (items.length === 0) return this.fallback(text, 'no-items')
|
||||
|
||||
return Ok({ items: cleanItems(items) })
|
||||
}
|
||||
|
||||
private fallback(text: string, reason: string): Result<VoiceSplitResponse, ProblemDetails> {
|
||||
this.logger.warn({ reason, textLength: text.length }, 'voice split: using the fallback split')
|
||||
|
||||
return Ok({ items: fallbackSplit(text) })
|
||||
}
|
||||
}
|
||||
@@ -1 +1,4 @@
|
||||
VITE_API_URL="http://localhost:4100"
|
||||
# Optional. Vite proxies /api/* to http://localhost:4100 in dev, so leave this
|
||||
# unset unless the frontend must call the API on a different origin (the client
|
||||
# always appends /api to it).
|
||||
# VITE_API_URL=""
|
||||
|
||||
23
apps/web/Dockerfile
Normal file
23
apps/web/Dockerfile
Normal file
@@ -0,0 +1,23 @@
|
||||
# Build context is the repository root (Bun workspace monorepo).
|
||||
FROM oven/bun:1.4.0 AS build
|
||||
WORKDIR /app
|
||||
|
||||
# Manifests first so `bun install` only reruns when the lockfile changes.
|
||||
COPY package.json bun.lock bunfig.toml ./
|
||||
COPY apps/api/package.json apps/api/package.json
|
||||
COPY apps/web/package.json apps/web/package.json
|
||||
COPY packages/shared/package.json packages/shared/package.json
|
||||
RUN bun install --frozen-lockfile
|
||||
|
||||
COPY . .
|
||||
# Empty by default: in production the SPA and the API share one origin and the
|
||||
# browser calls `/api/*` (nginx proxies it). Set the build arg to point the
|
||||
# frontend at a different API origin.
|
||||
ARG VITE_API_URL=""
|
||||
ENV VITE_API_URL=$VITE_API_URL
|
||||
RUN cd apps/web && bun run build
|
||||
|
||||
FROM nginx:alpine AS runtime
|
||||
COPY apps/web/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /app/apps/web/dist /usr/share/nginx/html
|
||||
EXPOSE 80
|
||||
@@ -3,12 +3,14 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1.0, viewport-fit=cover"
|
||||
/>
|
||||
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#ffffff" />
|
||||
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#0a0a0a" />
|
||||
<!-- Set from the resolved theme (script below and `theme-provider.tsx`), not with
|
||||
`media` queries: those follow the OS and ignore the theme picked in the app. -->
|
||||
<meta name="theme-color" content="#f9f8f5" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||
@@ -27,6 +29,9 @@
|
||||
stored === 'dark' || (stored !== 'light' && matchMedia('(prefers-color-scheme: dark)').matches)
|
||||
document.documentElement.classList.toggle('dark', dark)
|
||||
document.documentElement.style.colorScheme = dark ? 'dark' : 'light'
|
||||
document
|
||||
.querySelector('meta[name="theme-color"]')
|
||||
.setAttribute('content', dark ? '#0f1411' : '#f9f8f5')
|
||||
})()
|
||||
</script>
|
||||
</head>
|
||||
|
||||
55
apps/web/nginx.conf
Normal file
55
apps/web/nginx.conf
Normal file
@@ -0,0 +1,55 @@
|
||||
# Serves the built SPA and proxies /api/* to the Bun API container.
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
gzip on;
|
||||
gzip_types text/css application/javascript application/json image/svg+xml;
|
||||
|
||||
# Docker's embedded DNS. Proxying through a variable makes nginx re-resolve
|
||||
# the API on every TTL instead of pinning the IPs it saw at startup, so a
|
||||
# redeployed API container (new IP) is picked up without restarting nginx.
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
|
||||
# API proxy: no path rewrite, /api/* reaches the API as-is (proxy_pass with a
|
||||
# variable and no URI forwards the original request URI). `superlist-api` is
|
||||
# the API's alias on the stack-private network (see docker-compose.yml).
|
||||
# `proxy_buffering off` and the long read timeout keep the SSE streams
|
||||
# (/lists/:id/events) flowing in realtime instead of being batched or cut off.
|
||||
location /api/ {
|
||||
set $api_upstream http://superlist-api:4100;
|
||||
proxy_pass $api_upstream;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 1h;
|
||||
proxy_send_timeout 1h;
|
||||
}
|
||||
|
||||
# PWA: hashed build output is safe to cache forever, the service worker and
|
||||
# the app shell must always be revalidated so new releases reach clients.
|
||||
location /assets/ {
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
location = /sw.js {
|
||||
add_header Cache-Control "no-cache";
|
||||
}
|
||||
|
||||
location = /index.html {
|
||||
add_header Cache-Control "no-cache";
|
||||
}
|
||||
|
||||
# SPA fallback so deep links (/lists/:id, /invitations, ...) work on reload.
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,6 @@
|
||||
"@tanstack/react-query": "^5.104.2",
|
||||
"@tanstack/react-query-devtools": "^5.104.2",
|
||||
"@tanstack/react-router": "^1.170.42",
|
||||
"@tanstack/react-table": "^9.3.1",
|
||||
"better-auth": "^1.7.7",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
@@ -32,6 +31,7 @@
|
||||
"recharts": "^3.10.1",
|
||||
"sonner": "^2.0.8",
|
||||
"tailwind-merge": "^3.7.0",
|
||||
"workbox-window": "^7.4.1",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -48,6 +48,7 @@
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.3.0",
|
||||
"vite-plugin-pwa": "^2.0.0",
|
||||
"vitest": "^5.0.4"
|
||||
}
|
||||
}
|
||||
|
||||
BIN
apps/web/public/apple-touch-icon.png
Normal file
BIN
apps/web/public/apple-touch-icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.1 KiB |
6
apps/web/public/favicon.svg
Normal file
6
apps/web/public/favicon.svg
Normal file
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-label="Superlist">
|
||||
<rect width="512" height="512" rx="116" fill="#287c39"/>
|
||||
<path d="M190 206c0-58 26-86 66-86s66 28 66 86" fill="none" stroke="#faf9f6" stroke-width="26" stroke-linecap="round"/>
|
||||
<path d="M150 196h212l20 196H130z" fill="#faf9f6" stroke="#faf9f6" stroke-width="44" stroke-linejoin="round"/>
|
||||
<path d="M198 300l42 42 78-80" fill="none" stroke="#287c39" stroke-width="34" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 552 B |
BIN
apps/web/public/maskable-512x512.png
Normal file
BIN
apps/web/public/maskable-512x512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
8
apps/web/public/maskable.svg
Normal file
8
apps/web/public/maskable.svg
Normal file
@@ -0,0 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-label="Superlist">
|
||||
<rect width="512" height="512" fill="#287c39"/>
|
||||
<g transform="translate(256 262) scale(0.78) translate(-256 -262)">
|
||||
<path d="M190 206c0-58 26-86 66-86s66 28 66 86" fill="none" stroke="#faf9f6" stroke-width="26" stroke-linecap="round"/>
|
||||
<path d="M150 196h212l20 196H130z" fill="#faf9f6" stroke="#faf9f6" stroke-width="44" stroke-linejoin="round"/>
|
||||
<path d="M198 300l42 42 78-80" fill="none" stroke="#287c39" stroke-width="34" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 620 B |
BIN
apps/web/public/pwa-192x192.png
Normal file
BIN
apps/web/public/pwa-192x192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 7.4 KiB |
BIN
apps/web/public/pwa-512x512.png
Normal file
BIN
apps/web/public/pwa-512x512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 22 KiB |
50
apps/web/src/components/app-logo.tsx
Normal file
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>
|
||||
)
|
||||
}
|
||||
42
apps/web/src/components/install-prompt.tsx
Normal file
42
apps/web/src/components/install-prompt.tsx
Normal file
@@ -0,0 +1,42 @@
|
||||
import { DownloadIcon, SmartphoneIcon, XIcon } from 'lucide-react'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useInstallPrompt } from '@/hooks/use-install-prompt'
|
||||
|
||||
export function InstallPrompt() {
|
||||
const { visible, canInstall, needsManualInstructions, install, dismiss } = useInstallPrompt()
|
||||
|
||||
if (!visible) return null
|
||||
|
||||
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="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">
|
||||
{needsManualInstructions ? (
|
||||
<SmartphoneIcon className="size-4" />
|
||||
) : (
|
||||
<DownloadIcon className="size-4" />
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium">Instalar Superlist</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{needsManualInstructions
|
||||
? 'Toca Compartir y luego «Añadir a pantalla de inicio».'
|
||||
: 'Añádela a tu pantalla de inicio para usarla como una app.'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{canInstall && (
|
||||
<Button size="sm" onClick={install}>
|
||||
Instalar
|
||||
</Button>
|
||||
)}
|
||||
<Button size="icon-sm" variant="ghost" aria-label="Cerrar" onClick={dismiss}>
|
||||
<XIcon className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
63
apps/web/src/components/items/bought-item-list.tsx
Normal file
63
apps/web/src/components/items/bought-item-list.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { CheckIcon, ChevronDownIcon } from 'lucide-react'
|
||||
|
||||
import { Card } from '@/components/ui/card'
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
|
||||
import type { useUpdateItem } from '@/hooks/use-items'
|
||||
|
||||
import { ItemRow } from './item-row'
|
||||
|
||||
type BoughtItemListProps = {
|
||||
items: ListItem[]
|
||||
updateItem: ReturnType<typeof useUpdateItem>
|
||||
savingIds: string[]
|
||||
onEdit: (item: ListItem) => void
|
||||
onMove: (item: ListItem) => void
|
||||
onDelete: (item: ListItem) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapsible "Comprados (N)" section at the end of the list, folded by default so
|
||||
* the pending items stay in focus. Tapping an item here un-buys it and it returns
|
||||
* to the pending list.
|
||||
*/
|
||||
export function BoughtItemList({
|
||||
items,
|
||||
updateItem,
|
||||
savingIds,
|
||||
onEdit,
|
||||
onMove,
|
||||
onDelete,
|
||||
}: BoughtItemListProps) {
|
||||
return (
|
||||
<Collapsible asChild>
|
||||
<section className="border-border overflow-hidden rounded-xl border border-dashed">
|
||||
<CollapsibleTrigger className="group text-muted-foreground hover:text-foreground focus-visible:ring-ring/50 flex min-h-12 w-full items-center gap-3 px-4 py-3 text-left transition-colors outline-none focus-visible:ring-3">
|
||||
<CheckIcon className="text-primary size-4" strokeWidth={2.5} aria-hidden />
|
||||
<span className="flex-1 text-base">Comprados ({items.length})</span>
|
||||
<ChevronDownIcon
|
||||
className="size-5 transition-transform group-data-[state=open]:rotate-180"
|
||||
aria-hidden
|
||||
/>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<Card className="gap-0 rounded-none border-x-0 border-b-0 py-0 shadow-none">
|
||||
<ul className="divide-y">
|
||||
{items.map((item) => (
|
||||
<ItemRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
updateItem={updateItem}
|
||||
isSaving={savingIds.includes(item.id)}
|
||||
onEdit={() => onEdit(item)}
|
||||
onMove={() => onMove(item)}
|
||||
onDelete={() => onDelete(item)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
</Card>
|
||||
</CollapsibleContent>
|
||||
</section>
|
||||
</Collapsible>
|
||||
)
|
||||
}
|
||||
@@ -1,15 +1,28 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { PlusIcon } from 'lucide-react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { Loader2Icon, MicIcon, PlusIcon } from 'lucide-react'
|
||||
import { type ClipboardEvent, useEffect, useState } from 'react'
|
||||
import { useForm, useWatch } from 'react-hook-form'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ItemInputPreview } from '@/components/items/item-input-preview'
|
||||
import { Field, FieldError } from '@/components/ui/field'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { useCreateItem } from '@/hooks/use-items'
|
||||
import {
|
||||
InputGroup,
|
||||
InputGroupAddon,
|
||||
InputGroupButton,
|
||||
InputGroupInput,
|
||||
} from '@/components/ui/input-group'
|
||||
import { itemLimitError, readItems, useAddItems } from '@/hooks/use-add-items'
|
||||
import { useDictation } from '@/hooks/use-dictation'
|
||||
import { useKeyboardDictation } from '@/hooks/use-keyboard-dictation'
|
||||
import { isPlainItem } from '@/lib/natural-input/parse-item'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
// The input may hold several items ("leche, pan y 2 pascualinas" or a pasted list);
|
||||
// each one is checked against the API limits once the text is read.
|
||||
const createItemSchema = z.object({
|
||||
name: z.string().trim().min(1, 'Escribe un artículo').max(120, 'Máximo 120 caracteres'),
|
||||
// Not called `name`: iOS offers to autofill a contact into an input named that way.
|
||||
entry: z.string().trim().min(1, 'Escribe un artículo').max(2000, 'Máximo 2000 caracteres'),
|
||||
})
|
||||
|
||||
type CreateItemValues = z.infer<typeof createItemSchema>
|
||||
@@ -20,36 +33,225 @@ type CreateItemFormProps = {
|
||||
autoFocus?: boolean
|
||||
}
|
||||
|
||||
/** Input to add an item to a list. Submits with Enter or the button. */
|
||||
/** The input carries this id so it can be focused from outside the form (e.g. by the nav). */
|
||||
const NEW_ITEM_INPUT_ID = 'new-item-input'
|
||||
|
||||
/**
|
||||
* Puts the cursor in the "add an item" input when the home page is already the one on
|
||||
* screen (the route does not remount, so nothing else would move the focus). When the
|
||||
* user is navigating *to* the home page this is a no-op: the input takes the focus as
|
||||
* soon as it mounts, through `autoFocus`. Either way, tapping "Inicio" always ends with
|
||||
* the focus in the input — and never with the focus on another page's input.
|
||||
*
|
||||
* @param pathname the route the link was clicked from, so only the home input is focused.
|
||||
*/
|
||||
export function focusNewItemInput(pathname: string): void {
|
||||
if (pathname !== '/') return
|
||||
refocusNewItemInput()
|
||||
}
|
||||
|
||||
/** Puts the cursor back in the "add an item" input of the page on screen, if it has one. */
|
||||
export function refocusNewItemInput(): void {
|
||||
document.getElementById(NEW_ITEM_INPUT_ID)?.focus()
|
||||
}
|
||||
|
||||
/**
|
||||
* Input to add items to a list. Submits with Enter or the "+" button. The text is read
|
||||
* as natural language ("400 de jamon", "Queso crema. Solo Tregar", "leche, pan y
|
||||
* 2 pascualinas"), previewed while typing, and an item already pending is added to
|
||||
* instead of repeated.
|
||||
*
|
||||
* The microphone dictates instead: the transcript is split into items by the API (with
|
||||
* AI) and each one goes through this same flow. "Deshacer" removes the whole dictation.
|
||||
*/
|
||||
export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProps) {
|
||||
const createItem = useCreateItem(listId)
|
||||
// The text the user asked to add as typed; editing it brings the reading back.
|
||||
const [literalText, setLiteralText] = useState<string | null>(null)
|
||||
|
||||
const form = useForm<CreateItemValues>({
|
||||
resolver: zodResolver(createItemSchema),
|
||||
defaultValues: { name: '' },
|
||||
defaultValues: { entry: '' },
|
||||
})
|
||||
|
||||
const onSubmit = form.handleSubmit((values) => {
|
||||
createItem.mutate(values, { onSuccess: () => form.reset() })
|
||||
const text = useWatch({ control: form.control, name: 'entry' })
|
||||
const literal = literalText !== null && literalText === text
|
||||
|
||||
const restoreText = (source: string, message: string) => {
|
||||
const current = form.getValues('entry').trim()
|
||||
form.setValue('entry', current ? `${current}; ${source}` : source)
|
||||
form.setError('entry', { message })
|
||||
}
|
||||
|
||||
// A failed item comes back to the input, and so does a dictation that breaks the limits.
|
||||
const { existing, addItems, addDictation, processing } = useAddItems(listId, {
|
||||
onItemFailed: restoreText,
|
||||
onDictationRejected: (transcript, message) => {
|
||||
form.setValue('entry', transcript)
|
||||
form.setError('entry', { message })
|
||||
},
|
||||
})
|
||||
|
||||
const dictation = useDictation({ onTranscript: (transcript) => onTranscript(transcript) })
|
||||
// The keyboard's own microphone (the only one in the installed iOS app) just writes
|
||||
// text: once it has been quiet for a few seconds, that text is added as a dictation.
|
||||
const keyboardDictation = useKeyboardDictation({
|
||||
onIdle: () => {
|
||||
const dictated = form.getValues('entry').trim()
|
||||
if (dictated && !dictation.listening && !processing) onTranscript(dictated)
|
||||
},
|
||||
})
|
||||
const dictating = dictation.listening || processing
|
||||
|
||||
// The partial transcript is shown in the input while the user talks.
|
||||
useEffect(() => {
|
||||
if (dictation.listening) form.setValue('entry', dictation.interim)
|
||||
}, [dictation.listening, dictation.interim, form])
|
||||
|
||||
const preview = readItems(text, literal, existing)
|
||||
const showPreview =
|
||||
!dictating &&
|
||||
text.trim() !== '' &&
|
||||
(literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate))
|
||||
|
||||
// The input clears at once (items are added optimistically) so several items can be
|
||||
// typed in a row; if a request fails its text comes back with the error.
|
||||
const onSubmit = form.handleSubmit((values) => {
|
||||
keyboardDictation.cancel()
|
||||
const toAdd = readItems(values.entry, literal, existing)
|
||||
|
||||
const limitError = toAdd.map(itemLimitError).find(Boolean)
|
||||
if (limitError) {
|
||||
form.setError('entry', { message: limitError })
|
||||
return
|
||||
}
|
||||
|
||||
form.reset()
|
||||
setLiteralText(null)
|
||||
form.setFocus('entry')
|
||||
|
||||
addItems(toAdd)
|
||||
})
|
||||
|
||||
/** A dictation clears the input and goes through `addDictation`. */
|
||||
const onTranscript = (transcript: string) => {
|
||||
keyboardDictation.cancel()
|
||||
form.reset()
|
||||
setLiteralText(null)
|
||||
void addDictation(transcript)
|
||||
}
|
||||
|
||||
// An <input> drops line breaks, so a pasted list keeps one item per line as "; ".
|
||||
const onPaste = (event: ClipboardEvent<HTMLInputElement>) => {
|
||||
const pasted = event.clipboardData.getData('text')
|
||||
if (!/[\r\n]/.test(pasted)) return
|
||||
|
||||
event.preventDefault()
|
||||
const input = event.currentTarget
|
||||
const start = input.selectionStart ?? input.value.length
|
||||
const end = input.selectionEnd ?? start
|
||||
const lines = pasted
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean)
|
||||
.join('; ')
|
||||
|
||||
form.setValue('entry', input.value.slice(0, start) + lines + input.value.slice(end), {
|
||||
shouldDirty: true,
|
||||
})
|
||||
}
|
||||
|
||||
const micLabel = processing
|
||||
? 'Procesando el dictado'
|
||||
: dictation.listening
|
||||
? 'Dejar de escuchar'
|
||||
: 'Dictar productos'
|
||||
|
||||
return (
|
||||
<form onSubmit={onSubmit} className="flex items-start gap-2">
|
||||
<Field className="flex-1" data-invalid={!!form.formState.errors.name}>
|
||||
<Input
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
// Enter while dictating ends the dictation: what was heard goes through its flow.
|
||||
if (!dictation.listening) return onSubmit(event)
|
||||
event.preventDefault()
|
||||
dictation.stop()
|
||||
}}
|
||||
>
|
||||
<Field data-invalid={!!form.formState.errors.entry}>
|
||||
<InputGroup className="bg-card h-14 rounded-full shadow-xs dark:bg-card">
|
||||
<InputGroupAddon className="pl-1.5">
|
||||
<InputGroupButton
|
||||
type="submit"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="Agregar"
|
||||
disabled={dictating}
|
||||
className="text-muted-foreground hover:text-foreground size-11 rounded-full"
|
||||
// Tapping the button must not steal the focus from the input: on mobile that
|
||||
// would close the keyboard between one item and the next.
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
>
|
||||
<PlusIcon className="size-5" strokeWidth={2.5} />
|
||||
</InputGroupButton>
|
||||
</InputGroupAddon>
|
||||
<InputGroupInput
|
||||
id={NEW_ITEM_INPUT_ID}
|
||||
aria-label="Nuevo artículo"
|
||||
aria-invalid={!!form.formState.errors.entry}
|
||||
aria-describedby={dictation.error ? 'dictation-error' : undefined}
|
||||
autoComplete="off"
|
||||
placeholder="Añade un artículo…"
|
||||
placeholder={
|
||||
dictation.listening ? 'Escuchando…' : 'Agregar… ej: 400 g de jamón. Feteado fino'
|
||||
}
|
||||
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>
|
||||
|
||||
<Button type="submit" disabled={createItem.isPending}>
|
||||
<PlusIcon />
|
||||
{createItem.isPending ? 'Agregando…' : 'Agregar'}
|
||||
</Button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
88
apps/web/src/components/items/dictate-items-button.tsx
Normal file
88
apps/web/src/components/items/dictate-items-button.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import { Loader2Icon, MicIcon, SquareIcon } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useAddItems } from '@/hooks/use-add-items'
|
||||
import { DICTATION_MESSAGES, useMicrophoneDictation } from '@/hooks/use-microphone-dictation'
|
||||
|
||||
type DictateItemsButtonProps = {
|
||||
listId: string
|
||||
}
|
||||
|
||||
/**
|
||||
* "Dictar ítems" for an empty list: listens until the user stops it and adds what was
|
||||
* said through the same flow as the input's microphone (split by the API, undoable).
|
||||
*/
|
||||
export function DictateItemsButton({ listId }: DictateItemsButtonProps) {
|
||||
const [message, setMessage] = useState<string | null>(null)
|
||||
const { addDictation, processing } = useAddItems(listId, {
|
||||
onItemFailed: (source, detail) => toast.error(`No pudimos añadir «${source}»: ${detail}`),
|
||||
onDictationRejected: (_, detail) => setMessage(detail),
|
||||
})
|
||||
|
||||
const dictation = useMicrophoneDictation({
|
||||
onPhrases: async (phrases) => {
|
||||
const understood = await addDictation(phrases.join('\n'))
|
||||
if (understood === 0) setMessage(DICTATION_MESSAGES.empty)
|
||||
},
|
||||
onError: setMessage,
|
||||
})
|
||||
|
||||
const listening = dictation.status === 'listening'
|
||||
const busy = dictation.status === 'requesting' || processing
|
||||
|
||||
const label = processing
|
||||
? 'Procesando el dictado'
|
||||
: dictation.status === 'requesting'
|
||||
? 'Pidiendo acceso al micrófono'
|
||||
: listening
|
||||
? 'Detener dictado'
|
||||
: 'Dictar ítems'
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant={listening ? 'default' : 'secondary'}
|
||||
aria-label={label}
|
||||
aria-pressed={listening}
|
||||
disabled={busy}
|
||||
className="relative rounded-full"
|
||||
onClick={() => {
|
||||
setMessage(null)
|
||||
if (listening) dictation.stop()
|
||||
else dictation.start()
|
||||
}}
|
||||
>
|
||||
{busy ? (
|
||||
<Loader2Icon className="animate-spin" />
|
||||
) : listening ? (
|
||||
<SquareIcon className="fill-current" />
|
||||
) : (
|
||||
<MicIcon />
|
||||
)}
|
||||
{listening ? 'Detener dictado' : 'Dictar ítems'}
|
||||
</Button>
|
||||
|
||||
<div aria-live="polite" className="flex flex-col items-center gap-1 text-sm">
|
||||
{listening && (
|
||||
<p className="text-primary flex items-center gap-2 font-medium">
|
||||
<span className="relative flex size-2.5" aria-hidden="true">
|
||||
<span className="bg-primary absolute inline-flex size-full rounded-full opacity-75 motion-safe:animate-ping" />
|
||||
<span className="bg-primary relative inline-flex size-2.5 rounded-full" />
|
||||
</span>
|
||||
Micrófono activo, te escuchamos
|
||||
</p>
|
||||
)}
|
||||
{listening && dictation.heard && (
|
||||
<p className="text-muted-foreground max-w-xs">{dictation.heard}</p>
|
||||
)}
|
||||
{listening && !dictation.heard && (
|
||||
<p className="text-muted-foreground">Di «nuevo ítem» o haz una pausa entre artículos.</p>
|
||||
)}
|
||||
{message && !listening && <p className="text-destructive max-w-xs">{message}</p>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
55
apps/web/src/components/items/item-input-preview.tsx
Normal file
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,19 +1,62 @@
|
||||
import { CheckIcon, ShoppingBasketIcon } from 'lucide-react'
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { ShoppingBasketIcon } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useItems } from '@/hooks/use-items'
|
||||
import {
|
||||
useDeleteItem,
|
||||
useItems,
|
||||
usePendingDeletions,
|
||||
usePendingItemUpdates,
|
||||
useUpdateItem,
|
||||
} from '@/hooks/use-items'
|
||||
import { useListEvents } from '@/hooks/use-list-events'
|
||||
import { useToday } from '@/hooks/use-today'
|
||||
import { ApiError } from '@/lib/api-client'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { splitItems } from '@/lib/items'
|
||||
|
||||
import { BoughtItemList } from './bought-item-list'
|
||||
import { DictateItemsButton } from './dictate-items-button'
|
||||
import { ItemRow } from './item-row'
|
||||
import { ItemSheet } from './item-sheet'
|
||||
import { MoveItemDialog } from './move-item-dialog'
|
||||
|
||||
type ItemListProps = {
|
||||
listId: string
|
||||
}
|
||||
|
||||
/** Items loaded from the API, pending ones first. */
|
||||
/**
|
||||
* Items loaded from the API, pending ones first. Tapping an item marks it as
|
||||
* bought; bought items move to a collapsible "Comprados (N)" section at the end
|
||||
* and are only shown on the day they were bought.
|
||||
*/
|
||||
export function ItemList({ listId }: ItemListProps) {
|
||||
const { data: items, isPending, error } = useItems(listId)
|
||||
const updateItem = useUpdateItem(listId)
|
||||
const savingIds = usePendingItemUpdates(listId)
|
||||
const deleteItem = useDeleteItem(listId)
|
||||
// Just-deleted items stay hidden while they can still be restored.
|
||||
const deletingIds = usePendingDeletions()
|
||||
const today = useToday()
|
||||
// The item whose edit sheet is open, by id so the sheet shows its live values.
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
// The item whose "move to another list" dialog is open.
|
||||
const [movingItem, setMovingItem] = useState<ListItem | null>(null)
|
||||
|
||||
const handleDelete = (item: ListItem) => {
|
||||
setEditingId((current) => (current === item.id ? null : current))
|
||||
deleteItem(item)
|
||||
}
|
||||
|
||||
const openMoveDialog = (item: ListItem) => {
|
||||
setEditingId((current) => (current === item.id ? null : current))
|
||||
setMovingItem(item)
|
||||
}
|
||||
|
||||
// Live updates: another member adds or buys an item and this list refreshes.
|
||||
useListEvents(listId)
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
@@ -38,7 +81,15 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
)
|
||||
}
|
||||
|
||||
if (items.length === 0) {
|
||||
const { pending, boughtToday } = splitItems(
|
||||
items.filter((item) => !deletingIds.has(item.id)),
|
||||
today,
|
||||
)
|
||||
|
||||
const editingItem =
|
||||
items.find((item) => item.id === editingId && !deletingIds.has(item.id)) ?? null
|
||||
|
||||
if (pending.length === 0 && boughtToday.length === 0) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center gap-3 py-10 text-center">
|
||||
@@ -51,43 +102,50 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
Usa el campo de arriba para añadir tu primer artículo.
|
||||
</p>
|
||||
</div>
|
||||
<DictateItemsButton listId={listId} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="flex flex-col gap-2">
|
||||
{items.map((item) => (
|
||||
<li key={item.id}>
|
||||
<Card>
|
||||
<CardContent className="flex items-center gap-3 p-3">
|
||||
<span
|
||||
className={cn(
|
||||
'flex size-5 shrink-0 items-center justify-center rounded-full border',
|
||||
item.completed
|
||||
? 'bg-primary text-primary-foreground border-primary'
|
||||
: 'border-muted-foreground/40 text-transparent',
|
||||
)}
|
||||
aria-hidden
|
||||
>
|
||||
<CheckIcon className="size-3" />
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
'min-w-0 flex-1 truncate',
|
||||
item.completed && 'text-muted-foreground line-through',
|
||||
)}
|
||||
>
|
||||
{item.name}
|
||||
</span>
|
||||
{item.quantity && (
|
||||
<span className="text-muted-foreground shrink-0 text-sm">{item.quantity}</span>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</li>
|
||||
<div className="flex flex-col gap-4">
|
||||
{pending.length > 0 && (
|
||||
<Card className="py-0">
|
||||
<ul className="divide-y">
|
||||
{pending.map((item) => (
|
||||
<ItemRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
updateItem={updateItem}
|
||||
isSaving={savingIds.includes(item.id)}
|
||||
onEdit={() => setEditingId(item.id)}
|
||||
onMove={() => openMoveDialog(item)}
|
||||
onDelete={() => handleDelete(item)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{boughtToday.length > 0 && (
|
||||
<BoughtItemList
|
||||
items={boughtToday}
|
||||
updateItem={updateItem}
|
||||
savingIds={savingIds}
|
||||
onEdit={(item) => setEditingId(item.id)}
|
||||
onMove={openMoveDialog}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
)}
|
||||
|
||||
<ItemSheet
|
||||
item={editingItem}
|
||||
updateItem={updateItem}
|
||||
onClose={() => setEditingId(null)}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
<MoveItemDialog listId={listId} item={movingItem} onClose={() => setMovingItem(null)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
234
apps/web/src/components/items/item-row.tsx
Normal file
234
apps/web/src/components/items/item-row.tsx
Normal file
@@ -0,0 +1,234 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { CheckIcon, FolderInputIcon, PencilIcon, Trash2Icon } from 'lucide-react'
|
||||
import { type PointerEvent, useRef, useState } from 'react'
|
||||
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuTrigger,
|
||||
} from '@/components/ui/context-menu'
|
||||
import { isOptimisticItem, type useUpdateItem } from '@/hooks/use-items'
|
||||
import { quantityLabel } from '@/lib/items'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export type ItemRowProps = {
|
||||
item: ListItem
|
||||
updateItem: ReturnType<typeof useUpdateItem>
|
||||
/** This item's bought state is being saved; only this row waits for it. */
|
||||
isSaving: boolean
|
||||
/** Opens the edit sheet for this item. */
|
||||
onEdit: () => void
|
||||
/** Opens the "move to another list" dialog for this item. */
|
||||
onMove: () => void
|
||||
/** Deletes the item (it can be undone for a few seconds). */
|
||||
onDelete: () => void
|
||||
}
|
||||
|
||||
/** Horizontal drag (px) that turns a touch on the row into "edit the item". */
|
||||
const EDIT_THRESHOLD = 48
|
||||
|
||||
/** A longer drag (px) that turns it into "move the item to another list". */
|
||||
const MOVE_THRESHOLD = 120
|
||||
|
||||
/**
|
||||
* Drag (px) to the right that turns a touch into "delete the item". Longer than
|
||||
* the edit swipe because it is destructive (even if it can be undone).
|
||||
*/
|
||||
const DELETE_THRESHOLD = 96
|
||||
|
||||
/** What releasing the finger does, decided by how far the row was dragged. */
|
||||
type SwipeAction = 'edit' | 'move' | 'delete'
|
||||
|
||||
/**
|
||||
* How far the row is drawn for a finger `dx` px away: it follows the finger up
|
||||
* to the furthest threshold on that side and then resists, capped a bit past it
|
||||
* so the row never leaves the card. Negative is to the left.
|
||||
*/
|
||||
function dragOffset(dx: number): number {
|
||||
const limit = dx < 0 ? MOVE_THRESHOLD : DELETE_THRESHOLD
|
||||
const distance = Math.abs(dx)
|
||||
const resisted = distance <= limit ? distance : limit + (distance - limit) / 3
|
||||
|
||||
return Math.sign(dx) * Math.min(resisted, limit * 1.25)
|
||||
}
|
||||
|
||||
function swipeAction(dx: number): SwipeAction | null {
|
||||
if (dx < -MOVE_THRESHOLD) return 'move'
|
||||
if (dx < -EDIT_THRESHOLD) return 'edit'
|
||||
if (dx > DELETE_THRESHOLD) return 'delete'
|
||||
return null
|
||||
}
|
||||
|
||||
/** A single item row inside a grouped card: tapping it toggles its bought state. */
|
||||
export function ItemRow({ item, updateItem, isSaving, onEdit, onMove, onDelete }: ItemRowProps) {
|
||||
const [dragX, setDragX] = useState(0)
|
||||
const swipeStart = useRef<{ x: number; y: number } | null>(null)
|
||||
// Set once a drag passes a threshold: releasing the finger then runs that
|
||||
// action, and the click that the touch may fire right after is ignored.
|
||||
const swiped = useRef<SwipeAction | null>(null)
|
||||
const [action, setAction] = useState<SwipeAction | null>(null)
|
||||
|
||||
// A placeholder has no server id yet, so it cannot be toggled or edited.
|
||||
const editable = !isSaving && !isOptimisticItem(item)
|
||||
const quantity = quantityLabel(item.quantity)
|
||||
|
||||
const handlePointerDown = (event: PointerEvent<HTMLButtonElement>) => {
|
||||
// Mice use the right-click menu; only touch drags are tracked here.
|
||||
swiped.current = null
|
||||
if (!editable || event.pointerType === 'mouse') return
|
||||
swipeStart.current = { x: event.clientX, y: event.clientY }
|
||||
}
|
||||
|
||||
const handlePointerMove = (event: PointerEvent<HTMLButtonElement>) => {
|
||||
const start = swipeStart.current
|
||||
if (!start) return
|
||||
|
||||
const dx = event.clientX - start.x
|
||||
const dy = event.clientY - start.y
|
||||
// While the movement is mostly vertical the user is scrolling the list,
|
||||
// so no gesture is decided yet (and `touch-pan-y` lets the page scroll).
|
||||
if (!swiped.current && Math.abs(dx) <= Math.abs(dy)) return
|
||||
|
||||
setDragX(dragOffset(dx))
|
||||
swiped.current = swipeAction(dx)
|
||||
setAction(swiped.current)
|
||||
}
|
||||
|
||||
const handlePointerUp = () => {
|
||||
const released = swipeStart.current !== null ? swiped.current : null
|
||||
swipeStart.current = null
|
||||
setDragX(0)
|
||||
setAction(null)
|
||||
if (released === 'edit') onEdit()
|
||||
if (released === 'move') onMove()
|
||||
if (released === 'delete') onDelete()
|
||||
}
|
||||
|
||||
const handlePointerCancel = () => {
|
||||
swipeStart.current = null
|
||||
swiped.current = null
|
||||
setDragX(0)
|
||||
setAction(null)
|
||||
}
|
||||
|
||||
const dragging = swipeStart.current !== null && dragX !== 0
|
||||
|
||||
return (
|
||||
<li>
|
||||
<div className="relative overflow-hidden">
|
||||
{dragX > 0 && (
|
||||
<div
|
||||
className={cn(
|
||||
'absolute inset-y-0 left-0 flex items-center justify-center transition-colors',
|
||||
// Past the threshold the background turns solid: releasing deletes.
|
||||
action === 'delete'
|
||||
? 'bg-destructive text-white'
|
||||
: 'bg-destructive/15 text-destructive',
|
||||
)}
|
||||
style={{ width: dragX }}
|
||||
aria-hidden
|
||||
>
|
||||
<Trash2Icon className="size-5" />
|
||||
</div>
|
||||
)}
|
||||
{dragX < 0 && (
|
||||
<div
|
||||
className={cn(
|
||||
'absolute inset-y-0 right-0 flex items-center justify-center transition-colors',
|
||||
// Past the move threshold the background changes, so the user
|
||||
// knows releasing now moves the item instead of editing it.
|
||||
action === 'move'
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-primary/15 text-primary',
|
||||
)}
|
||||
style={{ width: -dragX }}
|
||||
aria-hidden
|
||||
>
|
||||
{action === 'move' ? (
|
||||
<FolderInputIcon className="size-5" />
|
||||
) : (
|
||||
<PencilIcon className="size-5" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild disabled={!editable}>
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={item.completed}
|
||||
disabled={!editable}
|
||||
onClick={() => {
|
||||
if (swiped.current) {
|
||||
swiped.current = null
|
||||
return
|
||||
}
|
||||
|
||||
updateItem.mutate({ itemId: item.id, completed: !item.completed })
|
||||
}}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerUp}
|
||||
onPointerCancel={handlePointerCancel}
|
||||
style={dragX !== 0 ? { transform: `translateX(${dragX}px)` } : undefined}
|
||||
className={cn(
|
||||
'bg-card hover:bg-muted/50 focus-visible:bg-muted/50 relative flex w-full cursor-pointer touch-pan-y items-center gap-4 px-4 py-3.5 text-left outline-none disabled:cursor-default disabled:opacity-60',
|
||||
// Follows the finger while dragged, then snaps back on release.
|
||||
dragging
|
||||
? 'transition-colors'
|
||||
: 'transition-[background-color,transform] duration-200 motion-reduce:transition-colors',
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'flex size-6 shrink-0 items-center justify-center rounded-full border-[1.5px] transition-colors',
|
||||
item.completed
|
||||
? 'bg-primary text-primary-foreground border-primary'
|
||||
: 'border-muted-foreground/45 text-transparent',
|
||||
)}
|
||||
aria-hidden
|
||||
>
|
||||
<CheckIcon className="size-3.5" strokeWidth={3} />
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-1 flex-col">
|
||||
<span
|
||||
className={cn(
|
||||
'truncate text-base',
|
||||
item.completed && 'text-muted-foreground line-through',
|
||||
)}
|
||||
>
|
||||
{item.name}
|
||||
</span>
|
||||
{item.notes && (
|
||||
<span className="text-muted-foreground truncate text-sm">{item.notes}</span>
|
||||
)}
|
||||
</span>
|
||||
{quantity && (
|
||||
<span className="bg-accent text-accent-foreground shrink-0 rounded-md px-2 py-0.5 text-sm font-semibold">
|
||||
{quantity}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</ContextMenuTrigger>
|
||||
{/* Right-click is the desktop equivalent of the swipes. */}
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onSelect={onEdit}>
|
||||
<PencilIcon />
|
||||
Editar
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={onMove}>
|
||||
<FolderInputIcon />
|
||||
Mover a otra lista…
|
||||
</ContextMenuItem>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem variant="destructive" onSelect={onDelete}>
|
||||
<Trash2Icon />
|
||||
Eliminar
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
245
apps/web/src/components/items/item-sheet.tsx
Normal file
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
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
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
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>
|
||||
)
|
||||
}
|
||||
@@ -1,42 +1,83 @@
|
||||
import { useRouterState } from '@tanstack/react-router'
|
||||
import { SearchIcon } from 'lucide-react'
|
||||
import type { ShoppingListSummary } from '@superlist/shared'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Link, useMatch, useRouterState } from '@tanstack/react-router'
|
||||
import { ArrowLeftIcon, SettingsIcon } from 'lucide-react'
|
||||
|
||||
import { ListSwitcher } from '@/components/layout/list-switcher'
|
||||
import { sectionTitle } from '@/components/layout/nav-items'
|
||||
import { ThemeToggle } from '@/components/theme-toggle'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { SidebarTrigger } from '@/components/ui/sidebar'
|
||||
import { listQueryOptions } from '@/hooks/use-list'
|
||||
import { listsQueryOptions, pickPrimaryList } from '@/hooks/use-lists'
|
||||
|
||||
function titleFor(pathname: string) {
|
||||
if (pathname === '/') return 'Panel'
|
||||
if (pathname.startsWith('/lists')) return 'Listas'
|
||||
if (pathname.startsWith('/tasks')) return 'Tareas'
|
||||
if (pathname.startsWith('/settings')) return 'Ajustes'
|
||||
return 'Superlist'
|
||||
}
|
||||
type HeaderList = Pick<ShoppingListSummary, 'id' | 'name' | 'role' | 'isPrimary'>
|
||||
|
||||
export function AppHeader() {
|
||||
const pathname = useRouterState({ select: (state) => state.location.pathname })
|
||||
const title = titleFor(pathname)
|
||||
const listMatch = useMatch({ from: '/_authenticated/lists/$listId/', shouldThrow: false })
|
||||
const homeMatch = useMatch({ from: '/_authenticated/', shouldThrow: false })
|
||||
const listId = listMatch?.params.listId
|
||||
|
||||
// The list pages carry their name, badges and actions here instead of in the body;
|
||||
// both route loaders have already cached the data, so these don't add requests.
|
||||
const { data: openList } = useQuery({
|
||||
...listQueryOptions(listId ?? ''),
|
||||
enabled: Boolean(listId),
|
||||
})
|
||||
const { data: lists } = useQuery({ ...listsQueryOptions(), enabled: Boolean(homeMatch) })
|
||||
const list: HeaderList | undefined = listId
|
||||
? openList
|
||||
: homeMatch && lists
|
||||
? pickPrimaryList(lists)
|
||||
: undefined
|
||||
|
||||
return (
|
||||
<header className="bg-background/95 supports-[backdrop-filter]:bg-background/60 sticky top-0 z-10 flex h-16 shrink-0 items-center gap-2 border-b backdrop-blur">
|
||||
<div className="flex w-full items-center gap-2 px-4">
|
||||
<SidebarTrigger className="-ml-1" />
|
||||
<Separator orientation="vertical" className="mr-2 h-4" />
|
||||
<h1 className="truncate text-sm font-medium">{title}</h1>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
className="text-muted-foreground hover:bg-accent hover:text-accent-foreground mr-1 hidden items-center gap-2 rounded-md border px-3 py-1.5 text-xs md:flex"
|
||||
<div className="flex w-full min-w-0 items-center gap-2 px-4">
|
||||
<SidebarTrigger className="-ml-1 hidden md:inline-flex" />
|
||||
<Separator orientation="vertical" className="mr-2 hidden h-4 md:block" />
|
||||
{list ? (
|
||||
<ListHeading list={list} showBack={Boolean(listId)} />
|
||||
) : (
|
||||
<h1 className="truncate text-sm font-medium">{sectionTitle(pathname)}</h1>
|
||||
)}
|
||||
<div className="ml-auto flex shrink-0 items-center gap-1">
|
||||
{list && (
|
||||
<Button variant="outline" size="sm" className="h-11 min-w-11" asChild>
|
||||
<Link
|
||||
to="/lists/$listId/settings"
|
||||
params={{ listId: list.id }}
|
||||
aria-label="Gestionar la lista"
|
||||
>
|
||||
<SearchIcon className="size-3.5" />
|
||||
Buscar
|
||||
<kbd className="bg-muted text-muted-foreground rounded px-1.5 py-0.5 font-mono text-[10px]">
|
||||
⌘K
|
||||
</kbd>
|
||||
</button>
|
||||
<SettingsIcon className="size-4" />
|
||||
<span className="hidden sm:inline">Gestionar</span>
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
||||
function ListHeading({ list, showBack }: { list: HeaderList; showBack: boolean }) {
|
||||
return (
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
{showBack && (
|
||||
<Button variant="ghost" size="icon" className="-ml-2 size-11 shrink-0" asChild>
|
||||
<Link to="/lists" aria-label="Volver a listas">
|
||||
<ArrowLeftIcon className="size-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
<ListSwitcher list={list} />
|
||||
<Badge variant="secondary" className="hidden shrink-0 sm:inline-flex">
|
||||
{list.role === 'owner' ? 'Propietario' : 'Colaborador'}
|
||||
</Badge>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Link, useRouterState } from '@tanstack/react-router'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { HomeIcon, ListTodoIcon, SettingsIcon, ShoppingCartIcon } from 'lucide-react'
|
||||
|
||||
import { AppLogo } from '@/components/app-logo'
|
||||
import { focusNewItemInput } from '@/components/items/create-item-form'
|
||||
import { isNavItemActive, NAV_ITEMS } from '@/components/layout/nav-items'
|
||||
import { NavUser } from '@/components/layout/nav-user'
|
||||
import {
|
||||
Sidebar,
|
||||
@@ -16,24 +16,6 @@ import {
|
||||
SidebarRail,
|
||||
} from '@/components/ui/sidebar'
|
||||
|
||||
type NavItem = {
|
||||
title: string
|
||||
to: string
|
||||
icon: LucideIcon
|
||||
}
|
||||
|
||||
const NAV_ITEMS: NavItem[] = [
|
||||
{ title: 'Principal', to: '/', icon: HomeIcon },
|
||||
{ title: 'Listas', to: '/lists', icon: ShoppingCartIcon },
|
||||
{ title: 'Tareas', to: '/tasks', icon: ListTodoIcon },
|
||||
{ title: 'Ajustes', to: '/settings', icon: SettingsIcon },
|
||||
]
|
||||
|
||||
function isActive(pathname: string, to: string) {
|
||||
if (to === '/') return pathname === '/'
|
||||
return pathname === to || pathname.startsWith(`${to}/`)
|
||||
}
|
||||
|
||||
export function AppSidebar() {
|
||||
const pathname = useRouterState({ select: (state) => state.location.pathname })
|
||||
|
||||
@@ -43,10 +25,8 @@ export function AppSidebar() {
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton size="lg" asChild>
|
||||
<Link to="/">
|
||||
<div className="bg-primary text-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg text-sm font-semibold">
|
||||
SL
|
||||
</div>
|
||||
<Link to="/" onClick={() => focusNewItemInput(pathname)}>
|
||||
<AppLogo className="size-8 rounded-lg" />
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<span className="truncate font-medium">Superlist</span>
|
||||
<span className="text-muted-foreground truncate text-xs">Listas compartidas</span>
|
||||
@@ -59,16 +39,19 @@ export function AppSidebar() {
|
||||
|
||||
<SidebarContent>
|
||||
<SidebarGroup>
|
||||
<SidebarGroupLabel>Plataforma</SidebarGroupLabel>
|
||||
<SidebarGroupLabel>Navegación</SidebarGroupLabel>
|
||||
<SidebarMenu>
|
||||
{NAV_ITEMS.map((item) => (
|
||||
<SidebarMenuItem key={item.to}>
|
||||
<SidebarMenuButton
|
||||
asChild
|
||||
isActive={isActive(pathname, item.to)}
|
||||
isActive={isNavItemActive(pathname, item.to)}
|
||||
tooltip={item.title}
|
||||
>
|
||||
<Link to={item.to}>
|
||||
<Link
|
||||
to={item.to}
|
||||
onClick={item.to === '/' ? () => focusNewItemInput(pathname) : undefined}
|
||||
>
|
||||
<item.icon />
|
||||
<span>{item.title}</span>
|
||||
</Link>
|
||||
|
||||
38
apps/web/src/components/layout/bottom-nav.tsx
Normal file
38
apps/web/src/components/layout/bottom-nav.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
import { Link, useRouterState } from '@tanstack/react-router'
|
||||
|
||||
import { focusNewItemInput } from '@/components/items/create-item-form'
|
||||
import { isNavItemActive, NAV_ITEMS } from '@/components/layout/nav-items'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export function BottomNav() {
|
||||
const pathname = useRouterState({ select: (state) => state.location.pathname })
|
||||
|
||||
return (
|
||||
<footer className="fixed inset-x-0 bottom-0 z-30 border-t bg-background/95 supports-[backdrop-filter]:bg-background/60 backdrop-blur md:hidden pb-[env(safe-area-inset-bottom)]">
|
||||
<nav className="mx-auto flex h-18 max-w-lg items-center justify-around px-2">
|
||||
{NAV_ITEMS.map((item) => {
|
||||
const active = isNavItemActive(pathname, item.to)
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={item.to}
|
||||
to={item.to}
|
||||
onClick={item.to === '/' ? () => focusNewItemInput(pathname) : undefined}
|
||||
aria-current={active ? 'page' : undefined}
|
||||
className={cn(
|
||||
'relative flex flex-col items-center gap-1 rounded-md px-3 py-1.5 text-xs transition-colors',
|
||||
active ? 'text-primary font-medium' : 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<item.icon className="size-5" />
|
||||
<span>{item.title}</span>
|
||||
{active && (
|
||||
<span className="bg-primary absolute -bottom-1 size-1 rounded-full" aria-hidden />
|
||||
)}
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</nav>
|
||||
</footer>
|
||||
)
|
||||
}
|
||||
95
apps/web/src/components/layout/list-switcher.tsx
Normal file
95
apps/web/src/components/layout/list-switcher.tsx
Normal file
@@ -0,0 +1,95 @@
|
||||
import type { ShoppingListSummary } from '@superlist/shared'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { CheckIcon, ChevronDownIcon, ListIcon, StarIcon } from 'lucide-react'
|
||||
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { itemsQueryOptions } from '@/hooks/use-items'
|
||||
import { useLists } from '@/hooks/use-lists'
|
||||
import { useToday } from '@/hooks/use-today'
|
||||
import { splitItems } from '@/lib/items'
|
||||
|
||||
type ListSwitcherProps = {
|
||||
list: Pick<ShoppingListSummary, 'id' | 'name'>
|
||||
}
|
||||
|
||||
/**
|
||||
* The open list's name with a "▾" that opens the user's lists (the same ones the
|
||||
* "Listas" tab shows), plus "X pendientes · Y comprados" below it. The primary list
|
||||
* opens on the home page, the others on their own page.
|
||||
*/
|
||||
export function ListSwitcher({ list }: ListSwitcherProps) {
|
||||
const { data: lists } = useLists()
|
||||
|
||||
return (
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<DropdownMenu>
|
||||
<h1 className="flex min-w-0">
|
||||
<DropdownMenuTrigger className="focus-visible:ring-ring/50 -ml-1 flex min-h-11 min-w-0 items-center gap-1 rounded-lg px-1 text-left text-xl leading-tight font-bold outline-none focus-visible:ring-3">
|
||||
<span className="truncate">{list.name}</span>
|
||||
<ChevronDownIcon className="size-5 shrink-0" aria-hidden />
|
||||
<span className="sr-only">: cambiar de lista</span>
|
||||
</DropdownMenuTrigger>
|
||||
</h1>
|
||||
<DropdownMenuContent align="start" className="w-64">
|
||||
<DropdownMenuLabel>Mis listas</DropdownMenuLabel>
|
||||
{lists?.map((option) => (
|
||||
<DropdownMenuItem key={option.id} asChild className="min-h-11">
|
||||
{option.isPrimary ? (
|
||||
<Link to="/">
|
||||
<ListOption list={option} current={option.id === list.id} />
|
||||
</Link>
|
||||
) : (
|
||||
<Link to="/lists/$listId" params={{ listId: option.id }}>
|
||||
<ListOption list={option} current={option.id === list.id} />
|
||||
</Link>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild className="min-h-11">
|
||||
<Link to="/lists">
|
||||
<ListIcon />
|
||||
Ver todas las listas
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<ListCounts listId={list.id} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ListOption({ list, current }: { list: ShoppingListSummary; current: boolean }) {
|
||||
return (
|
||||
<>
|
||||
<span className="min-w-0 flex-1 truncate">{list.name}</span>
|
||||
{list.isPrimary && <StarIcon aria-label="Principal" className="text-muted-foreground" />}
|
||||
{current && <CheckIcon aria-label="Lista actual" className="text-primary" />}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** "6 pendientes · 2 comprados", from the items query the page already loads. */
|
||||
function ListCounts({ listId }: { listId: string }) {
|
||||
const { data: items } = useQuery(itemsQueryOptions(listId))
|
||||
const today = useToday()
|
||||
|
||||
if (!items) return null
|
||||
|
||||
const { pending, boughtToday } = splitItems(items, today)
|
||||
|
||||
return (
|
||||
<p className="text-muted-foreground truncate text-sm leading-tight">
|
||||
{pending.length} {pending.length === 1 ? 'pendiente' : 'pendientes'} · {boughtToday.length}{' '}
|
||||
{boughtToday.length === 1 ? 'comprado' : 'comprados'}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
25
apps/web/src/components/layout/nav-items.ts
Normal file
25
apps/web/src/components/layout/nav-items.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { HomeIcon, SettingsIcon, ShoppingCartIcon } from 'lucide-react'
|
||||
|
||||
type NavItem = {
|
||||
title: string
|
||||
to: '/' | '/lists' | '/settings'
|
||||
icon: LucideIcon
|
||||
}
|
||||
|
||||
/** The app's sections, shared by the sidebar (desktop), the bottom nav (mobile) and the header. */
|
||||
export const NAV_ITEMS: NavItem[] = [
|
||||
{ title: 'Inicio', to: '/', icon: HomeIcon },
|
||||
{ title: 'Listas', to: '/lists', icon: ShoppingCartIcon },
|
||||
{ title: 'Ajustes', to: '/settings', icon: SettingsIcon },
|
||||
]
|
||||
|
||||
export function isNavItemActive(pathname: string, to: NavItem['to']) {
|
||||
if (to === '/') return pathname === '/'
|
||||
return pathname === to || pathname.startsWith(`${to}/`)
|
||||
}
|
||||
|
||||
/** Title of the section the pathname belongs to, for the header. */
|
||||
export function sectionTitle(pathname: string) {
|
||||
return NAV_ITEMS.find((item) => isNavItemActive(pathname, item.to))?.title ?? 'Superlist'
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { ChevronsUpDownIcon, LogOutIcon, UserIcon } from 'lucide-react'
|
||||
import { ChevronsUpDownIcon, LogOutIcon, SettingsIcon } from 'lucide-react'
|
||||
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
|
||||
import {
|
||||
@@ -78,8 +78,8 @@ export function NavUser() {
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem onClick={() => void navigate({ to: '/settings' })}>
|
||||
<UserIcon />
|
||||
Cuenta
|
||||
<SettingsIcon />
|
||||
Ajustes
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
@@ -16,6 +16,9 @@ type ThemeContextValue = {
|
||||
const STORAGE_KEY = 'superlist-theme'
|
||||
const DARK_QUERY = '(prefers-color-scheme: dark)'
|
||||
|
||||
/** Browser chrome color (the iOS status bar) per theme. Keep in sync with `index.html`. */
|
||||
const THEME_COLORS: Record<ResolvedTheme, string> = { light: '#f9f8f5', dark: '#0f1411' }
|
||||
|
||||
/**
|
||||
* This theme handling is hand-rolled on purpose. Libraries such as `next-themes`
|
||||
* avoid the pre-paint flash by rendering a `<script>` from React, but React 19
|
||||
@@ -44,6 +47,15 @@ function systemTheme(): ResolvedTheme {
|
||||
return window.matchMedia(DARK_QUERY).matches ? 'dark' : 'light'
|
||||
}
|
||||
|
||||
function resolveTheme(theme: Theme): ResolvedTheme {
|
||||
return theme === 'system' ? systemTheme() : theme
|
||||
}
|
||||
|
||||
/** iOS home-screen app (`navigator.standalone` only exists in iOS Safari). */
|
||||
function isIosStandalone() {
|
||||
return 'standalone' in navigator && navigator.standalone === true
|
||||
}
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const [theme, setThemeState] = useState<Theme>(readStoredTheme)
|
||||
const [systemDark, setSystemDark] = useState(() => systemTheme() === 'dark')
|
||||
@@ -60,16 +72,27 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const root = document.documentElement
|
||||
root.classList.toggle('dark', resolvedTheme === 'dark')
|
||||
root.style.colorScheme = resolvedTheme
|
||||
document
|
||||
.querySelector('meta[name="theme-color"]')
|
||||
?.setAttribute('content', THEME_COLORS[resolvedTheme])
|
||||
}, [resolvedTheme])
|
||||
|
||||
const setTheme = useCallback((next: Theme) => {
|
||||
const setTheme = useCallback(
|
||||
(next: Theme) => {
|
||||
setThemeState(next)
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, next)
|
||||
} catch {
|
||||
// Ignore storage failures: the theme still applies for this session.
|
||||
}
|
||||
}, [])
|
||||
|
||||
// An installed iOS app only reads `theme-color` when the page loads, so
|
||||
// the status bar keeps the old color until a reload. The stored theme is
|
||||
// applied again before the first paint by the script in `index.html`.
|
||||
if (isIosStandalone() && resolveTheme(next) !== resolvedTheme) window.location.reload()
|
||||
},
|
||||
[resolvedTheme],
|
||||
)
|
||||
|
||||
const value = useMemo(
|
||||
() => ({ theme, resolvedTheme, setTheme }),
|
||||
|
||||
@@ -2,38 +2,45 @@ import { MonitorIcon, MoonIcon, SunIcon } from 'lucide-react'
|
||||
|
||||
import { useTheme } from '@/components/theme-provider'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const OPTIONS = [
|
||||
{ value: 'light', label: 'Claro', icon: SunIcon },
|
||||
{ value: 'dark', label: 'Oscuro', icon: MoonIcon },
|
||||
{ value: 'system', label: 'Sistema', icon: MonitorIcon },
|
||||
{ value: 'light', label: 'Claro', icon: SunIcon, out: '-rotate-90' },
|
||||
{ value: 'dark', label: 'Oscuro', icon: MoonIcon, out: 'rotate-90' },
|
||||
{ value: 'system', label: 'Sistema', icon: MonitorIcon, out: 'rotate-90' },
|
||||
] as const
|
||||
|
||||
type Option = (typeof OPTIONS)[number]
|
||||
|
||||
function nextOption(current: Option['value']): Option {
|
||||
const index = OPTIONS.findIndex((option) => option.value === current)
|
||||
return OPTIONS[(index + 1) % OPTIONS.length]
|
||||
}
|
||||
|
||||
export function ThemeToggle() {
|
||||
const { setTheme } = useTheme()
|
||||
const { theme, setTheme } = useTheme()
|
||||
|
||||
const current = OPTIONS.find((option) => option.value === theme) ?? OPTIONS[2]
|
||||
const next = nextOption(current.value)
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" aria-label="Cambiar tema">
|
||||
<SunIcon className="size-4 scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
|
||||
<MoonIcon className="absolute size-4 scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{OPTIONS.map(({ value, label, icon: Icon }) => (
|
||||
<DropdownMenuItem key={value} onClick={() => setTheme(value)}>
|
||||
<Icon />
|
||||
{label}
|
||||
</DropdownMenuItem>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="relative size-11"
|
||||
aria-label={`Tema: ${current.label} — cambiar a ${next.label}`}
|
||||
onClick={() => setTheme(next.value)}
|
||||
>
|
||||
{OPTIONS.map(({ value, icon: Icon, out }) => (
|
||||
<Icon
|
||||
key={value}
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
'absolute size-4 transition-all',
|
||||
value === current.value ? 'scale-100 rotate-0' : `scale-0 ${out}`,
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
19
apps/web/src/components/ui/collapsible.tsx
Normal file
19
apps/web/src/components/ui/collapsible.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import { Collapsible as CollapsiblePrimitive } from 'radix-ui'
|
||||
|
||||
function Collapsible({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
|
||||
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
|
||||
}
|
||||
|
||||
function CollapsibleTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
|
||||
return <CollapsiblePrimitive.CollapsibleTrigger data-slot="collapsible-trigger" {...props} />
|
||||
}
|
||||
|
||||
function CollapsibleContent({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
|
||||
return <CollapsiblePrimitive.CollapsibleContent data-slot="collapsible-content" {...props} />
|
||||
}
|
||||
|
||||
export { Collapsible, CollapsibleContent, CollapsibleTrigger }
|
||||
244
apps/web/src/components/ui/context-menu.tsx
Normal file
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
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
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
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 }
|
||||
@@ -1,88 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { cn } from 'cn'
|
||||
import * as React from 'react'
|
||||
|
||||
function Table({ className, ...props }: React.ComponentProps<'table'>) {
|
||||
return (
|
||||
<div data-slot="table-container" className="relative w-full overflow-x-auto">
|
||||
<table
|
||||
data-slot="table"
|
||||
className={cn('w-full caption-bottom text-sm', className)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TableHeader({ className, ...props }: React.ComponentProps<'thead'>) {
|
||||
return <thead data-slot="table-header" className={cn('[&_tr]:border-b', className)} {...props} />
|
||||
}
|
||||
|
||||
function TableBody({ className, ...props }: React.ComponentProps<'tbody'>) {
|
||||
return (
|
||||
<tbody
|
||||
data-slot="table-body"
|
||||
className={cn('[&_tr:last-child]:border-0', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableFooter({ className, ...props }: React.ComponentProps<'tfoot'>) {
|
||||
return (
|
||||
<tfoot
|
||||
data-slot="table-footer"
|
||||
className={cn('border-t bg-muted/50 font-medium [&>tr]:last:border-b-0', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableRow({ className, ...props }: React.ComponentProps<'tr'>) {
|
||||
return (
|
||||
<tr
|
||||
data-slot="table-row"
|
||||
className={cn(
|
||||
'border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableHead({ className, ...props }: React.ComponentProps<'th'>) {
|
||||
return (
|
||||
<th
|
||||
data-slot="table-head"
|
||||
className={cn(
|
||||
'h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCell({ className, ...props }: React.ComponentProps<'td'>) {
|
||||
return (
|
||||
<td
|
||||
data-slot="table-cell"
|
||||
className={cn('p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCaption({ className, ...props }: React.ComponentProps<'caption'>) {
|
||||
return (
|
||||
<caption
|
||||
data-slot="table-caption"
|
||||
className={cn('mt-4 text-sm text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow }
|
||||
171
apps/web/src/hooks/use-add-items.ts
Normal file
171
apps/web/src/hooks/use-add-items.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { useRef } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import type { PreviewItem } from '@/components/items/item-input-preview'
|
||||
import {
|
||||
isOptimisticItem,
|
||||
useCreateItem,
|
||||
useItems,
|
||||
useRemoveItems,
|
||||
useUpdateItem,
|
||||
} from '@/hooks/use-items'
|
||||
import { useVoiceSplit } from '@/hooks/use-voice-split'
|
||||
import { ApiError } from '@/lib/api-client'
|
||||
import { findDuplicate, mergeBatch, mergeInto } from '@/lib/natural-input/merge'
|
||||
import { literalItem, parseItemInput } from '@/lib/natural-input/parse-item'
|
||||
|
||||
/** How long the "Deshacer" of a dictation stays on screen. */
|
||||
const DICTATION_UNDO_MS = 8000
|
||||
|
||||
/** Why a read item cannot be sent as is, mirroring the API limits, or `null`. */
|
||||
export function itemLimitError(item: PreviewItem): string | null {
|
||||
if (item.name.length > 120) return `«${item.name.slice(0, 20)}…»: máximo 120 caracteres`
|
||||
if ((item.quantity?.length ?? 0) > 40) return `«${item.name}»: la cantidad es demasiado larga`
|
||||
if ((item.notes?.length ?? 0) > 280) return `«${item.name}»: la nota es demasiado larga`
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** The items `text` adds, each with the pending item it repeats, if any. */
|
||||
export function readItems(text: string, literal: boolean, existing: ListItem[]): PreviewItem[] {
|
||||
if (!text.trim()) return []
|
||||
|
||||
const items = literal ? [literalItem(text)] : mergeBatch(parseItemInput(text))
|
||||
|
||||
return items.map((item) => ({ ...item, duplicate: findDuplicate(existing, item.name) }))
|
||||
}
|
||||
|
||||
/** What adding a batch of items did, so a dictation can be undone. */
|
||||
type AddedItems = {
|
||||
/** Ids of the items created (failed ones are left out). */
|
||||
created: Promise<string[]>
|
||||
/** The previous quantity/notes of the pending items that were added to. */
|
||||
merged: { itemId: string; quantity: string | null; notes: string | null }[]
|
||||
}
|
||||
|
||||
type UseAddItemsOptions = {
|
||||
/** An item could not be created: `source` is the text it was read from. */
|
||||
onItemFailed: (source: string, message: string) => void
|
||||
/** A dictation was not added because an item breaks the API limits. */
|
||||
onDictationRejected: (transcript: string, message: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds items to a list the way the "add an item" input does: an item already pending is
|
||||
* added to instead of repeated, and a dictation is split into items by the API (with AI)
|
||||
* and can be undone as a whole.
|
||||
*/
|
||||
export function useAddItems(
|
||||
listId: string,
|
||||
{ onItemFailed, onDictationRejected }: UseAddItemsOptions,
|
||||
) {
|
||||
const createItem = useCreateItem(listId)
|
||||
const updateItem = useUpdateItem(listId)
|
||||
const removeItems = useRemoveItems(listId)
|
||||
const voiceSplit = useVoiceSplit()
|
||||
const { data: items } = useItems(listId)
|
||||
// Placeholders have no server id yet, so they cannot be added to.
|
||||
const existing = (items ?? []).filter((item) => !isOptimisticItem(item))
|
||||
// A dictation finishes after a request: by then the list may have changed.
|
||||
const existingRef = useRef(existing)
|
||||
existingRef.current = existing
|
||||
|
||||
/** Adds the items, or adds to the pending ones they repeat. */
|
||||
const addItems = (toAdd: PreviewItem[]): AddedItems => {
|
||||
const created: Promise<string | null>[] = []
|
||||
const merged: AddedItems['merged'] = []
|
||||
|
||||
for (const item of toAdd) {
|
||||
if (item.duplicate) {
|
||||
const patch = mergeInto(item.duplicate, item)
|
||||
if (patch.quantity !== undefined || patch.notes !== undefined) {
|
||||
updateItem.mutate({ itemId: item.duplicate.id, ...patch })
|
||||
merged.push({
|
||||
itemId: item.duplicate.id,
|
||||
quantity: item.duplicate.quantity,
|
||||
notes: item.duplicate.notes,
|
||||
})
|
||||
}
|
||||
toast(
|
||||
patch.quantity
|
||||
? `Se sumó a «${item.duplicate.name}» (${patch.quantity})`
|
||||
: `«${item.duplicate.name}» ya está en la lista`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
created.push(
|
||||
createItem
|
||||
.mutateAsync({
|
||||
name: item.name,
|
||||
quantity: item.quantity ?? undefined,
|
||||
notes: item.notes ?? undefined,
|
||||
})
|
||||
.then(
|
||||
(createdItem) => createdItem.id,
|
||||
(error) => {
|
||||
onItemFailed(
|
||||
item.source,
|
||||
error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos añadir el artículo.',
|
||||
)
|
||||
return null
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
created: Promise.all(created).then((ids) => ids.filter((id): id is string => id !== null)),
|
||||
merged,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The API splits the transcript into one string per item and each one is read by the
|
||||
* usual parser. If the request fails, the transcript is read as typed text when it is
|
||||
* already split into lines, and added as a single item otherwise.
|
||||
*
|
||||
* @returns how many items were understood (0 when the dictation had none).
|
||||
*/
|
||||
const addDictation = async (transcript: string): Promise<number> => {
|
||||
let toAdd: PreviewItem[]
|
||||
try {
|
||||
const { items: spoken } = await voiceSplit.mutateAsync({ text: transcript })
|
||||
toAdd = readItems(spoken.join('; '), false, existingRef.current)
|
||||
} catch {
|
||||
toAdd = readItems(transcript, !/[;\n]/.test(transcript), existingRef.current)
|
||||
}
|
||||
|
||||
if (toAdd.length === 0) return 0
|
||||
|
||||
const limitError = toAdd.map(itemLimitError).find(Boolean)
|
||||
if (limitError) {
|
||||
onDictationRejected(transcript, limitError)
|
||||
return toAdd.length
|
||||
}
|
||||
|
||||
const { created, merged } = addItems(toAdd)
|
||||
const createdIds = await created
|
||||
const count = createdIds.length + merged.length
|
||||
if (count === 0) return toAdd.length
|
||||
|
||||
toast(`Se ${count === 1 ? 'agregó 1 producto' : `agregaron ${count} productos`}`, {
|
||||
// Longer than a plain toast: the user has to check what was understood first.
|
||||
duration: DICTATION_UNDO_MS,
|
||||
action: {
|
||||
label: 'Deshacer',
|
||||
onClick: () => {
|
||||
void removeItems(createdIds)
|
||||
for (const previous of merged) updateItem.mutate(previous)
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return toAdd.length
|
||||
}
|
||||
|
||||
return { existing, addItems, addDictation, processing: voiceSplit.isPending }
|
||||
}
|
||||
136
apps/web/src/hooks/use-dictation.ts
Normal file
136
apps/web/src/hooks/use-dictation.ts
Normal file
@@ -0,0 +1,136 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
import {
|
||||
getSpeechRecognition as getBrowserSpeechRecognition,
|
||||
isIosStandalone,
|
||||
type SpeechRecognitionConstructor,
|
||||
} from '@/lib/speech-recognition'
|
||||
|
||||
/** Errors that only mean "nothing was said" or "we stopped it": not worth telling. */
|
||||
const IGNORED_ERRORS = new Set(['no-speech', 'aborted'])
|
||||
|
||||
const ERROR_MESSAGES: Record<string, string> = {
|
||||
'not-allowed': 'Permite el acceso al micrófono para dictar.',
|
||||
'service-not-allowed': 'El dictado no está disponible en este navegador.',
|
||||
'audio-capture': 'No encontramos un micrófono.',
|
||||
network: 'Sin conexión para reconocer la voz.',
|
||||
}
|
||||
|
||||
/**
|
||||
* The browser's speech recognition, or `null` when there is none. An iOS home-screen
|
||||
* app exposes `webkitSpeechRecognition` but it does not work there, so it counts as
|
||||
* unsupported (the keyboard's own dictation still works).
|
||||
*/
|
||||
function getSpeechRecognition(): SpeechRecognitionConstructor | null {
|
||||
if (typeof window === 'undefined' || isIosStandalone()) return null
|
||||
|
||||
return getBrowserSpeechRecognition()
|
||||
}
|
||||
|
||||
type UseDictationOptions = {
|
||||
/** Called once with the whole transcript when the user stops talking. */
|
||||
onTranscript: (transcript: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Quiet time after the last words heard that ends the dictation. Safari on iOS keeps
|
||||
* listening long after the user stops talking even with `continuous = false`, so the
|
||||
* phrase is delivered once nothing new has been heard for this long.
|
||||
*/
|
||||
export const DICTATION_SILENCE_MS = 3000
|
||||
|
||||
/** A recognition in progress: `finish` delivers what was heard, `cancel` drops it. */
|
||||
type DictationSession = { finish: () => void; cancel: () => void }
|
||||
|
||||
/**
|
||||
* Dictation with the Web Speech API in Argentine Spanish: one phrase per `start()`
|
||||
* (`continuous = false`), with the partial transcript in `interim` while the user
|
||||
* talks. The phrase is delivered when the browser ends the recognition, when the user
|
||||
* stops it, or after `DICTATION_SILENCE_MS` without new words, whichever comes first.
|
||||
* `no-speech` and `aborted` are ignored; any other error is in `error`.
|
||||
*/
|
||||
export function useDictation({ onTranscript }: UseDictationOptions) {
|
||||
const [supported] = useState(() => getSpeechRecognition() !== null)
|
||||
const [listening, setListening] = useState(false)
|
||||
const [interim, setInterim] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const sessionRef = useRef<DictationSession | null>(null)
|
||||
const onTranscriptRef = useRef(onTranscript)
|
||||
|
||||
useEffect(() => {
|
||||
onTranscriptRef.current = onTranscript
|
||||
})
|
||||
|
||||
// Leaving the page stops listening, without delivering a transcript.
|
||||
useEffect(() => () => sessionRef.current?.cancel(), [])
|
||||
|
||||
const start = useCallback(() => {
|
||||
const SpeechRecognition = getSpeechRecognition()
|
||||
if (!SpeechRecognition || sessionRef.current) return
|
||||
|
||||
const recognition = new SpeechRecognition()
|
||||
recognition.lang = 'es-AR'
|
||||
recognition.interimResults = true
|
||||
recognition.continuous = false
|
||||
recognition.maxAlternatives = 1
|
||||
|
||||
let transcript = ''
|
||||
let failed = false
|
||||
let done = false
|
||||
let silenceTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
// Runs once, whatever ends the dictation first; aborting afterwards only fires an
|
||||
// ignored `aborted` error and an `onend` that finds the session already done.
|
||||
const end = (deliver: boolean) => {
|
||||
if (done) return
|
||||
done = true
|
||||
clearTimeout(silenceTimer)
|
||||
sessionRef.current = null
|
||||
setListening(false)
|
||||
setInterim('')
|
||||
recognition.abort()
|
||||
if (deliver && transcript && !failed) onTranscriptRef.current(transcript)
|
||||
}
|
||||
|
||||
recognition.onresult = (event) => {
|
||||
// The results hold the whole phrase so far: final parts plus the guess in progress.
|
||||
transcript = Array.from(event.results, (result) => result[0].transcript)
|
||||
.join('')
|
||||
.trim()
|
||||
setInterim(transcript)
|
||||
|
||||
clearTimeout(silenceTimer)
|
||||
silenceTimer = setTimeout(() => end(true), DICTATION_SILENCE_MS)
|
||||
}
|
||||
|
||||
recognition.onerror = (event) => {
|
||||
if (IGNORED_ERRORS.has(event.error)) return
|
||||
failed = true
|
||||
setError(ERROR_MESSAGES[event.error] ?? 'No pudimos reconocer la voz.')
|
||||
}
|
||||
|
||||
// Some browsers (iOS Safari) end without marking the last result as final, so
|
||||
// whatever was heard by then is the transcript.
|
||||
recognition.onend = () => end(true)
|
||||
|
||||
setError(null)
|
||||
setInterim('')
|
||||
|
||||
try {
|
||||
recognition.start()
|
||||
} catch {
|
||||
setError('No pudimos empezar a escuchar.')
|
||||
return
|
||||
}
|
||||
|
||||
sessionRef.current = { finish: () => end(true), cancel: () => end(false) }
|
||||
setListening(true)
|
||||
}, [])
|
||||
|
||||
/** Stops listening right away; what was heard so far is still delivered. */
|
||||
const stop = useCallback(() => sessionRef.current?.finish(), [])
|
||||
|
||||
const clearError = useCallback(() => setError(null), [])
|
||||
|
||||
return { supported, listening, interim, error, start, stop, clearError }
|
||||
}
|
||||
111
apps/web/src/hooks/use-install-prompt.ts
Normal file
111
apps/web/src/hooks/use-install-prompt.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import * as React from 'react'
|
||||
|
||||
/**
|
||||
* `beforeinstallprompt` is still non-standard, so TypeScript has no DOM type
|
||||
* for it. This is the subset of the event we use.
|
||||
*/
|
||||
interface BeforeInstallPromptEvent extends Event {
|
||||
readonly platforms: string[]
|
||||
readonly userChoice: Promise<{ outcome: 'accepted' | 'dismissed'; platform: string }>
|
||||
prompt(): Promise<void>
|
||||
}
|
||||
|
||||
const DISMISSED_KEY = 'superlist-install-dismissed'
|
||||
|
||||
function readDismissed() {
|
||||
try {
|
||||
return localStorage.getItem(DISMISSED_KEY) === '1'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function isStandalone() {
|
||||
if (typeof window === 'undefined') return false
|
||||
const navigatorWithStandalone = navigator as Navigator & { standalone?: boolean }
|
||||
return (
|
||||
window.matchMedia('(display-mode: standalone)').matches ||
|
||||
navigatorWithStandalone.standalone === true
|
||||
)
|
||||
}
|
||||
|
||||
function isIosSafari() {
|
||||
if (typeof navigator === 'undefined') return false
|
||||
const ua = navigator.userAgent
|
||||
const isIos = /iphone|ipad|ipod/i.test(ua)
|
||||
// On iOS only Safari can add apps to the home screen, and it never fires
|
||||
// `beforeinstallprompt`, so we detect it to show manual instructions.
|
||||
const isSafari = /safari/i.test(ua) && !/crios|fxios|edgios/i.test(ua)
|
||||
return isIos && isSafari
|
||||
}
|
||||
|
||||
export type InstallPromptState = {
|
||||
/** We can trigger the native install dialog. */
|
||||
canInstall: boolean
|
||||
/** iOS Safari: no native prompt, show "Compartir → Añadir a pantalla de inicio". */
|
||||
needsManualInstructions: boolean
|
||||
/** The app is already running as an installed PWA. */
|
||||
isInstalled: boolean
|
||||
/** The user dismissed the banner before (persisted). */
|
||||
isDismissed: boolean
|
||||
install: () => Promise<void>
|
||||
dismiss: () => void
|
||||
/** Show the banner: installable or needing instructions, and not dismissed/installed. */
|
||||
visible: boolean
|
||||
}
|
||||
|
||||
export function useInstallPrompt(): InstallPromptState {
|
||||
const [deferredPrompt, setDeferredPrompt] = React.useState<BeforeInstallPromptEvent | null>(null)
|
||||
const [isInstalled, setIsInstalled] = React.useState(isStandalone)
|
||||
const [isDismissed, setIsDismissed] = React.useState(readDismissed)
|
||||
const [isIos] = React.useState(isIosSafari)
|
||||
|
||||
React.useEffect(() => {
|
||||
const onBeforeInstallPrompt = (event: Event) => {
|
||||
// Stop Chrome from showing its own mini-infobar so we control the banner.
|
||||
event.preventDefault()
|
||||
setDeferredPrompt(event as BeforeInstallPromptEvent)
|
||||
}
|
||||
|
||||
const onInstalled = () => {
|
||||
setDeferredPrompt(null)
|
||||
setIsInstalled(true)
|
||||
}
|
||||
|
||||
window.addEventListener('beforeinstallprompt', onBeforeInstallPrompt)
|
||||
window.addEventListener('appinstalled', onInstalled)
|
||||
return () => {
|
||||
window.removeEventListener('beforeinstallprompt', onBeforeInstallPrompt)
|
||||
window.removeEventListener('appinstalled', onInstalled)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const install = React.useCallback(async () => {
|
||||
if (!deferredPrompt) return
|
||||
await deferredPrompt.prompt()
|
||||
const { outcome } = await deferredPrompt.userChoice
|
||||
if (outcome === 'accepted') setDeferredPrompt(null)
|
||||
}, [deferredPrompt])
|
||||
|
||||
const dismiss = React.useCallback(() => {
|
||||
setIsDismissed(true)
|
||||
try {
|
||||
localStorage.setItem(DISMISSED_KEY, '1')
|
||||
} catch {
|
||||
// Storage can be unavailable (private mode); the banner just comes back.
|
||||
}
|
||||
}, [])
|
||||
|
||||
const canInstall = deferredPrompt !== null
|
||||
const needsManualInstructions = isIos && !deferredPrompt && !isInstalled
|
||||
|
||||
return {
|
||||
canInstall,
|
||||
needsManualInstructions,
|
||||
isInstalled,
|
||||
isDismissed,
|
||||
install,
|
||||
dismiss,
|
||||
visible: !isInstalled && !isDismissed && (canInstall || needsManualInstructions),
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,22 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
queryOptions,
|
||||
useMutation,
|
||||
useMutationState,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
} from '@tanstack/react-query'
|
||||
import { useSyncExternalStore } from 'react'
|
||||
|
||||
import { apiFetch } from '@/lib/api-client'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { ApiError, apiFetch } from '@/lib/api-client'
|
||||
import {
|
||||
DELETE_UNDO_MS,
|
||||
getPendingDeletions,
|
||||
scheduleDeletion,
|
||||
subscribePendingDeletions,
|
||||
} from '@/lib/pending-deletions'
|
||||
|
||||
export const itemsQueryOptions = (listId: string) =>
|
||||
queryOptions({
|
||||
@@ -13,8 +28,17 @@ export function useItems(listId: string) {
|
||||
return useQuery(itemsQueryOptions(listId))
|
||||
}
|
||||
|
||||
/** Prefix of the temporary ids given to items that are still being created. */
|
||||
const OPTIMISTIC_ID_PREFIX = 'optimistic-'
|
||||
|
||||
/** Whether the item is a placeholder whose `POST` has not been answered yet. */
|
||||
export function isOptimisticItem(item: ListItem): boolean {
|
||||
return item.id.startsWith(OPTIMISTIC_ID_PREFIX)
|
||||
}
|
||||
|
||||
export function useCreateItem(listId: string) {
|
||||
const queryClient = useQueryClient()
|
||||
const { queryKey } = itemsQueryOptions(listId)
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (input: { name: string; quantity?: string; notes?: string }) =>
|
||||
@@ -22,6 +46,251 @@ export function useCreateItem(listId: string) {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] }),
|
||||
// The item shows up right away; the POST response then swaps the placeholder
|
||||
// for the real row, so no refetch of the whole list is needed (other members
|
||||
// still get it through the SSE stream).
|
||||
onMutate: async (input) => {
|
||||
await queryClient.cancelQueries({ queryKey })
|
||||
|
||||
const now = new Date().toISOString()
|
||||
const optimistic: ListItem = {
|
||||
id: `${OPTIMISTIC_ID_PREFIX}${crypto.randomUUID()}`,
|
||||
listId,
|
||||
name: input.name.trim(),
|
||||
completed: false,
|
||||
boughtAt: null,
|
||||
quantity: input.quantity?.trim() || null,
|
||||
notes: input.notes?.trim() || null,
|
||||
order: 0,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
|
||||
queryClient.setQueryData(queryKey, (items) => items && [...items, optimistic])
|
||||
|
||||
return { optimisticId: optimistic.id }
|
||||
},
|
||||
onSuccess: (created, _input, context) => {
|
||||
queryClient.setQueryData(queryKey, (items) =>
|
||||
items?.map((item) => (item.id === context.optimisticId ? created : item)),
|
||||
)
|
||||
},
|
||||
// Only this placeholder is removed, so other in-flight additions survive.
|
||||
onError: (_error, _input, context) => {
|
||||
queryClient.setQueryData(queryKey, (items) =>
|
||||
items?.filter((item) => item.id !== context?.optimisticId),
|
||||
)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type UpdateItemInput = {
|
||||
itemId: string
|
||||
/** New name; omitted to leave it untouched. */
|
||||
name?: string
|
||||
/** New bought state; omitted when only the details are being changed. */
|
||||
completed?: boolean
|
||||
/** New quantity (`null` clears it); omitted to leave it untouched. */
|
||||
quantity?: string | null
|
||||
/** New notes (`null` clears them); omitted to leave them untouched. */
|
||||
notes?: string | null
|
||||
}
|
||||
|
||||
const updateItemMutationKey = (listId: string) => ['lists', listId, 'items', 'update']
|
||||
|
||||
export function useUpdateItem(listId: string) {
|
||||
const queryClient = useQueryClient()
|
||||
const { queryKey } = itemsQueryOptions(listId)
|
||||
const mutationKey = updateItemMutationKey(listId)
|
||||
|
||||
return useMutation({
|
||||
mutationKey,
|
||||
mutationFn: (input: UpdateItemInput) => {
|
||||
const body: {
|
||||
name?: string
|
||||
completed?: boolean
|
||||
quantity?: string | null
|
||||
notes?: string | null
|
||||
} = {}
|
||||
if (input.name !== undefined) body.name = input.name
|
||||
if (input.completed !== undefined) body.completed = input.completed
|
||||
if (input.quantity !== undefined) body.quantity = input.quantity
|
||||
if (input.notes !== undefined) body.notes = input.notes
|
||||
|
||||
return apiFetch<ListItem>(`/lists/${listId}/items/${input.itemId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
},
|
||||
onMutate: async ({ itemId, name, completed, quantity, notes }) => {
|
||||
// Cancel the outgoing refetch so it cannot overwrite our optimistic one.
|
||||
await queryClient.cancelQueries({ queryKey })
|
||||
|
||||
const previous = queryClient.getQueryData(queryKey)?.find((item) => item.id === itemId)
|
||||
|
||||
queryClient.setQueryData(queryKey, (items) =>
|
||||
items?.map((item) => {
|
||||
if (item.id !== itemId) return item
|
||||
|
||||
return {
|
||||
...item,
|
||||
...(name !== undefined ? { name: name.trim() } : {}),
|
||||
...(completed !== undefined
|
||||
? { completed, boughtAt: completed ? new Date().toISOString() : null }
|
||||
: {}),
|
||||
...(quantity !== undefined ? { quantity: quantity?.trim() || null } : {}),
|
||||
...(notes !== undefined ? { notes: notes?.trim() || null } : {}),
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
return { previous }
|
||||
},
|
||||
// Only this item is rolled back, so other toggles in flight keep their state.
|
||||
onError: (error, _variables, context) => {
|
||||
toast.error(
|
||||
error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos guardar el cambio.',
|
||||
)
|
||||
|
||||
const previous = context?.previous
|
||||
if (!previous) return
|
||||
|
||||
queryClient.setQueryData(queryKey, (items) =>
|
||||
items?.map((item) => (item.id === previous.id ? previous : item)),
|
||||
)
|
||||
},
|
||||
// Several items can be toggled in a row: refetch once the last one settles, so an
|
||||
// early refetch cannot bring back the server state of a toggle still in flight.
|
||||
onSettled: () => {
|
||||
if (queryClient.isMutating({ mutationKey }) === 1) {
|
||||
return queryClient.invalidateQueries({ queryKey })
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** Ids of the items of a list whose bought state is being saved right now. */
|
||||
export function usePendingItemUpdates(listId: string): string[] {
|
||||
return useMutationState({
|
||||
filters: { mutationKey: updateItemMutationKey(listId), status: 'pending' },
|
||||
select: (mutation) => (mutation.state.variables as UpdateItemInput).itemId,
|
||||
})
|
||||
}
|
||||
|
||||
type MoveItemInput = {
|
||||
itemId: string
|
||||
targetListId: string
|
||||
/** Name of the target list, only used for the confirmation toast. */
|
||||
targetListName: string
|
||||
}
|
||||
|
||||
export function useMoveItem(listId: string) {
|
||||
const queryClient = useQueryClient()
|
||||
const { queryKey } = itemsQueryOptions(listId)
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ itemId, targetListId }: MoveItemInput) =>
|
||||
apiFetch<ListItem>(`/lists/${listId}/items/${itemId}/move`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ targetListId }),
|
||||
}),
|
||||
// The item leaves this list right away; the user stays on it.
|
||||
onMutate: async ({ itemId }) => {
|
||||
await queryClient.cancelQueries({ queryKey })
|
||||
|
||||
const items = queryClient.getQueryData(queryKey)
|
||||
const index = items?.findIndex((item) => item.id === itemId) ?? -1
|
||||
const previous = index >= 0 ? items?.[index] : undefined
|
||||
|
||||
queryClient.setQueryData(queryKey, (current) => current?.filter((item) => item.id !== itemId))
|
||||
|
||||
return { previous, index }
|
||||
},
|
||||
onSuccess: (_moved, { targetListId, targetListName }) => {
|
||||
toast.success(`Movido a «${targetListName}»`)
|
||||
return queryClient.invalidateQueries({ queryKey: itemsQueryOptions(targetListId).queryKey })
|
||||
},
|
||||
// The item goes back to where it was, so the list does not jump around.
|
||||
onError: (error, _variables, context) => {
|
||||
toast.error(
|
||||
error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos mover el artículo.',
|
||||
)
|
||||
|
||||
const previous = context?.previous
|
||||
if (!previous) return
|
||||
|
||||
queryClient.setQueryData(queryKey, (items) => {
|
||||
if (!items || items.some((item) => item.id === previous.id)) return items
|
||||
const next = [...items]
|
||||
next.splice(Math.min(context.index, next.length), 0, previous)
|
||||
return next
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** Ids of the items hidden because they were just deleted (they can still come back). */
|
||||
export function usePendingDeletions(): ReadonlySet<string> {
|
||||
return useSyncExternalStore(subscribePendingDeletions, getPendingDeletions)
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an item with a few seconds to undo it: the row disappears at once,
|
||||
* a toast offers "Deshacer" and the `DELETE` is only sent once that time is
|
||||
* over, so undoing never has to recreate anything.
|
||||
*/
|
||||
export function useDeleteItem(listId: string) {
|
||||
const queryClient = useQueryClient()
|
||||
const { queryKey } = itemsQueryOptions(listId)
|
||||
|
||||
return (item: ListItem) => {
|
||||
const undo = scheduleDeletion(item.id, async ({ keepalive }) => {
|
||||
try {
|
||||
await apiFetch<void>(`/lists/${listId}/items/${item.id}`, { method: 'DELETE', keepalive })
|
||||
queryClient.setQueryData(queryKey, (items) =>
|
||||
items?.filter((current) => current.id !== item.id),
|
||||
)
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos eliminar el artículo.',
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
toast(`«${item.name}» eliminado`, {
|
||||
duration: DELETE_UNDO_MS,
|
||||
action: { label: 'Deshacer', onClick: undo },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes items right away, without the undo window of `useDeleteItem`: used to undo a
|
||||
* dictation, which is itself the undo. The rows leave the list at once.
|
||||
*/
|
||||
export function useRemoveItems(listId: string) {
|
||||
const queryClient = useQueryClient()
|
||||
const { queryKey } = itemsQueryOptions(listId)
|
||||
|
||||
return async (itemIds: string[]) => {
|
||||
const ids = new Set(itemIds)
|
||||
queryClient.setQueryData(queryKey, (items) => items?.filter((item) => !ids.has(item.id)))
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
itemIds.map((itemId) =>
|
||||
apiFetch<void>(`/lists/${listId}/items/${itemId}`, { method: 'DELETE' }),
|
||||
),
|
||||
)
|
||||
|
||||
if (results.some((result) => result.status === 'rejected')) {
|
||||
toast.error('No pudimos quitar todos los artículos.')
|
||||
await queryClient.invalidateQueries({ queryKey })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
29
apps/web/src/hooks/use-keyboard-dictation.test.ts
Normal file
29
apps/web/src/hooks/use-keyboard-dictation.test.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { isDictatedInput } from './use-keyboard-dictation'
|
||||
|
||||
describe('isDictatedInput', () => {
|
||||
it('takes words or phrases written without a key press as dictation', () => {
|
||||
expect(isDictatedInput({ inputType: 'insertText', data: 'Yogur', msSinceKeydown: 5000 })).toBe(
|
||||
true,
|
||||
)
|
||||
expect(
|
||||
isDictatedInput({ inputType: 'insertReplacementText', data: null, msSinceKeydown: 5000 }),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('does not take typing as dictation', () => {
|
||||
expect(isDictatedInput({ inputType: 'insertText', data: 'Yogur', msSinceKeydown: 10 })).toBe(
|
||||
false,
|
||||
)
|
||||
expect(isDictatedInput({ inputType: 'insertText', data: 'y', msSinceKeydown: 5000 })).toBe(
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
it('never takes pastes, drops or deletions as dictation', () => {
|
||||
for (const inputType of ['insertFromPaste', 'insertFromDrop', 'deleteContentBackward']) {
|
||||
expect(isDictatedInput({ inputType, data: 'leche y pan', msSinceKeydown: 5000 })).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
92
apps/web/src/hooks/use-keyboard-dictation.ts
Normal file
92
apps/web/src/hooks/use-keyboard-dictation.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import { type FormEvent, type KeyboardEvent, useCallback, useEffect, useRef } from 'react'
|
||||
|
||||
/** Quiet time after the keyboard's dictation last wrote into the input before it is added. */
|
||||
export const KEYBOARD_DICTATION_IDLE_MS = 3000
|
||||
|
||||
/** How close to a key press an input event must be to count as typed. */
|
||||
const KEYDOWN_WINDOW_MS = 100
|
||||
|
||||
/** Insertions that are never dictation (pasting or dropping text, deleting). */
|
||||
const NOT_DICTATION = /^(insertFromPaste|insertFromDrop|delete)/
|
||||
|
||||
/**
|
||||
* Whether an input event looks like the system keyboard's dictation writing into the
|
||||
* field: text that arrives without a key press, several characters at once (dictation
|
||||
* writes word by word or a whole phrase) or as a replacement of what it wrote before.
|
||||
* Tapping a keyboard suggestion looks the same, which is the price of the guess.
|
||||
*/
|
||||
export function isDictatedInput(event: {
|
||||
inputType: string
|
||||
data: string | null
|
||||
msSinceKeydown: number
|
||||
}): boolean {
|
||||
if (NOT_DICTATION.test(event.inputType)) return false
|
||||
if (event.msSinceKeydown < KEYDOWN_WINDOW_MS) return false
|
||||
if (event.inputType === 'insertReplacementText') return true
|
||||
|
||||
return event.inputType === 'insertText' && (event.data?.trim().length ?? 0) > 1
|
||||
}
|
||||
|
||||
type UseKeyboardDictationOptions = {
|
||||
/** Called with the input's text once the dictation has been quiet for a while. */
|
||||
onIdle: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* The installed iOS app has no speech recognition, so people dictate with the
|
||||
* keyboard's microphone, which only writes text into the input. This notices text that
|
||||
* arrives that way and calls `onIdle` once nothing new has arrived for
|
||||
* `KEYBOARD_DICTATION_IDLE_MS`, so it is added without pressing Enter. Typing a key
|
||||
* cancels it: from then on the text is the user's to submit.
|
||||
*/
|
||||
export function useKeyboardDictation({ onIdle }: UseKeyboardDictationOptions) {
|
||||
const lastKeydown = useRef(0)
|
||||
const dictated = useRef(false)
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
|
||||
const onIdleRef = useRef(onIdle)
|
||||
|
||||
useEffect(() => {
|
||||
onIdleRef.current = onIdle
|
||||
})
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
clearTimeout(timer.current)
|
||||
dictated.current = false
|
||||
}, [])
|
||||
|
||||
useEffect(() => cancel, [cancel])
|
||||
|
||||
const onKeyDown = useCallback(
|
||||
(_event: KeyboardEvent<HTMLInputElement>) => {
|
||||
lastKeydown.current = performance.now()
|
||||
cancel()
|
||||
},
|
||||
[cancel],
|
||||
)
|
||||
|
||||
const onInput = useCallback((event: FormEvent<HTMLInputElement>) => {
|
||||
const native = event.nativeEvent as InputEvent
|
||||
const inputType = native.inputType ?? ''
|
||||
|
||||
const looksDictated = isDictatedInput({
|
||||
inputType,
|
||||
data: native.data ?? null,
|
||||
msSinceKeydown: performance.now() - lastKeydown.current,
|
||||
})
|
||||
|
||||
// Once dictation started, any later update without a key press (corrections,
|
||||
// composition) keeps it going; a paste or a deletion stops it.
|
||||
if (looksDictated) dictated.current = true
|
||||
else if (NOT_DICTATION.test(inputType)) dictated.current = false
|
||||
|
||||
clearTimeout(timer.current)
|
||||
if (!dictated.current) return
|
||||
|
||||
timer.current = setTimeout(() => {
|
||||
dictated.current = false
|
||||
onIdleRef.current()
|
||||
}, KEYBOARD_DICTATION_IDLE_MS)
|
||||
}, [])
|
||||
|
||||
return { onKeyDown, onInput, cancel }
|
||||
}
|
||||
47
apps/web/src/hooks/use-list-events.ts
Normal file
47
apps/web/src/hooks/use-list-events.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect } from 'react'
|
||||
|
||||
import { apiBaseUrl } from '@/lib/api-client'
|
||||
import { LIST_EVENT_TYPES, queryKeysForListEvent } from '@/lib/list-events'
|
||||
|
||||
/**
|
||||
* Subscribes to a list's SSE stream (`GET /lists/:listId/events`) and refreshes
|
||||
* the affected queries whenever another member adds or buys an item, invites
|
||||
* somebody or renames the list — so the page updates without a reload.
|
||||
*
|
||||
* The session cookie is sent via `withCredentials`. `EventSource` reconnects on
|
||||
* its own; a `ready` event is emitted on every (re)connection, used here to
|
||||
* reconcile anything missed while disconnected.
|
||||
*/
|
||||
export function useListEvents(listId: string) {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
useEffect(() => {
|
||||
const source = new EventSource(`${apiBaseUrl}/lists/${listId}/events`, {
|
||||
withCredentials: true,
|
||||
})
|
||||
|
||||
const onReady = () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] })
|
||||
}
|
||||
|
||||
source.addEventListener('ready', onReady)
|
||||
|
||||
const listeners = LIST_EVENT_TYPES.map((type) => {
|
||||
const listener = () => {
|
||||
for (const queryKey of queryKeysForListEvent(type, listId)) {
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
}
|
||||
}
|
||||
|
||||
source.addEventListener(type, listener)
|
||||
return { type, listener }
|
||||
})
|
||||
|
||||
return () => {
|
||||
source.removeEventListener('ready', onReady)
|
||||
for (const { type, listener } of listeners) source.removeEventListener(type, listener)
|
||||
source.close()
|
||||
}
|
||||
}, [listId, queryClient])
|
||||
}
|
||||
@@ -13,6 +13,11 @@ export function useLists() {
|
||||
return useQuery(listsQueryOptions())
|
||||
}
|
||||
|
||||
/** The list a user lands on: their primary one, falling back to the first. */
|
||||
export function pickPrimaryList(lists: ShoppingListSummary[]): ShoppingListSummary | undefined {
|
||||
return lists.find((list) => list.isPrimary) ?? lists[0]
|
||||
}
|
||||
|
||||
export function useCreateList() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
|
||||
154
apps/web/src/hooks/use-microphone-dictation.ts
Normal file
154
apps/web/src/hooks/use-microphone-dictation.ts
Normal file
@@ -0,0 +1,154 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { splitDictation } from '@/lib/natural-input/dictation'
|
||||
import { getSpeechRecognition, type SpeechRecognitionLike } from '@/lib/speech-recognition'
|
||||
|
||||
export const DICTATION_MESSAGES = {
|
||||
denied: 'No tenemos permiso para usar el micrófono. Habilítalo en los ajustes del navegador.',
|
||||
unavailable: 'No encontramos un micrófono disponible.',
|
||||
unsupported:
|
||||
'Este navegador no permite dictar. Puedes usar el micrófono del teclado en el campo de arriba.',
|
||||
empty: 'No escuchamos ningún artículo. Inténtalo de nuevo.',
|
||||
failed: 'Ocurrió un error al reconocer la voz. Inténtalo de nuevo.',
|
||||
} as const
|
||||
|
||||
/** Recognition errors with a message of their own; any other one is `failed`. */
|
||||
const RECOGNITION_ERRORS: Record<string, string | null> = {
|
||||
'not-allowed': DICTATION_MESSAGES.denied,
|
||||
'service-not-allowed': DICTATION_MESSAGES.unsupported,
|
||||
'audio-capture': DICTATION_MESSAGES.unavailable,
|
||||
// Silence just ends with no phrases; a stop of ours is not an error.
|
||||
'no-speech': null,
|
||||
aborted: null,
|
||||
}
|
||||
|
||||
/** What `getUserMedia` rejects with, as one of the messages. */
|
||||
function microphoneError(error: unknown): string {
|
||||
const name = error instanceof DOMException ? error.name : ''
|
||||
if (name === 'NotAllowedError' || name === 'SecurityError') return DICTATION_MESSAGES.denied
|
||||
|
||||
return DICTATION_MESSAGES.unavailable
|
||||
}
|
||||
|
||||
type DictationStatus = 'idle' | 'requesting' | 'listening'
|
||||
|
||||
type UseMicrophoneDictationOptions = {
|
||||
/** The phrases dictated, one per item said, when the dictation ends with some. */
|
||||
onPhrases: (phrases: string[]) => void
|
||||
/** Why the dictation did not deliver anything, in Spanish. */
|
||||
onError: (message: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Dictation of several items in a row with the Web Speech API (`webkitSpeechRecognition`
|
||||
* in Safari), in Argentine Spanish. `start()` must run inside a click handler: it asks
|
||||
* for the microphone right there, then listens until the user calls `stop()` or the
|
||||
* browser ends the recognition. Pauses, line breaks and "nuevo ítem" separate phrases
|
||||
* (`splitDictation`).
|
||||
*
|
||||
* The microphone stream is only used to ask for the permission: its tracks are stopped
|
||||
* as soon as it arrives (even after an unmount), before the recognition opens its own
|
||||
* capture. Unmounting aborts the recognition.
|
||||
*/
|
||||
export function useMicrophoneDictation({ onPhrases, onError }: UseMicrophoneDictationOptions) {
|
||||
const [status, setStatus] = useState<DictationStatus>('idle')
|
||||
// What has been heard so far, shown while listening.
|
||||
const [heard, setHeard] = useState('')
|
||||
const callbacksRef = useRef({ onPhrases, onError })
|
||||
// Ends the dictation in progress: `true` delivers what was heard, `false` drops it.
|
||||
const endRef = useRef<((deliver: boolean) => void) | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
callbacksRef.current = { onPhrases, onError }
|
||||
})
|
||||
|
||||
useEffect(() => () => endRef.current?.(false), [])
|
||||
|
||||
const start = useCallback(() => {
|
||||
if (endRef.current) return
|
||||
|
||||
const SpeechRecognition = getSpeechRecognition()
|
||||
if (!SpeechRecognition) {
|
||||
callbacksRef.current.onError(DICTATION_MESSAGES.unsupported)
|
||||
return
|
||||
}
|
||||
|
||||
let recognition: SpeechRecognitionLike | null = null
|
||||
let segments: string[] = []
|
||||
let failure: string | null = null
|
||||
let done = false
|
||||
|
||||
const end = (deliver: boolean) => {
|
||||
if (done) return
|
||||
done = true
|
||||
endRef.current = null
|
||||
// Aborting afterwards only fires an ignored `aborted` and an `onend` that finds it done.
|
||||
recognition?.abort()
|
||||
setStatus('idle')
|
||||
setHeard('')
|
||||
// Stopped while the permission was being asked: there is nothing to tell.
|
||||
if (!deliver || (!recognition && !failure)) return
|
||||
|
||||
const phrases = splitDictation(segments)
|
||||
if (failure) callbacksRef.current.onError(failure)
|
||||
else if (phrases.length === 0) callbacksRef.current.onError(DICTATION_MESSAGES.empty)
|
||||
else callbacksRef.current.onPhrases(phrases)
|
||||
}
|
||||
|
||||
const listen = () => {
|
||||
recognition = new SpeechRecognition()
|
||||
recognition.lang = 'es-AR'
|
||||
recognition.interimResults = true
|
||||
recognition.continuous = true
|
||||
recognition.maxAlternatives = 1
|
||||
|
||||
// Each result is a stretch of speech between pauses; the last one may still change.
|
||||
recognition.onresult = (event) => {
|
||||
segments = Array.from(event.results, (result) => result[0].transcript)
|
||||
setHeard(splitDictation(segments).join(' · '))
|
||||
}
|
||||
|
||||
recognition.onerror = (event) => {
|
||||
const message = RECOGNITION_ERRORS[event.error]
|
||||
if (message === null) return
|
||||
failure = message ?? DICTATION_MESSAGES.failed
|
||||
}
|
||||
|
||||
recognition.onend = () => end(true)
|
||||
|
||||
try {
|
||||
recognition.start()
|
||||
setStatus('listening')
|
||||
} catch {
|
||||
failure = DICTATION_MESSAGES.failed
|
||||
end(true)
|
||||
}
|
||||
}
|
||||
|
||||
endRef.current = end
|
||||
setStatus('requesting')
|
||||
|
||||
// Without `getUserMedia` (e.g. outside HTTPS) the recognition asks for the microphone itself.
|
||||
if (!navigator.mediaDevices?.getUserMedia) {
|
||||
listen()
|
||||
return
|
||||
}
|
||||
|
||||
// Called right in the click, before any `await`, so Safari treats it as the user's.
|
||||
navigator.mediaDevices.getUserMedia({ audio: true }).then(
|
||||
(stream) => {
|
||||
for (const track of stream.getTracks()) track.stop()
|
||||
if (!done) listen()
|
||||
},
|
||||
(error: unknown) => {
|
||||
failure = microphoneError(error)
|
||||
end(true)
|
||||
},
|
||||
)
|
||||
}, [])
|
||||
|
||||
/** Stops listening; what was heard so far is delivered. */
|
||||
const stop = useCallback(() => endRef.current?.(true), [])
|
||||
|
||||
return { status, heard, start, stop }
|
||||
}
|
||||
35
apps/web/src/hooks/use-today.ts
Normal file
35
apps/web/src/hooks/use-today.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
/** Milliseconds until the next local midnight, plus a small buffer. */
|
||||
function msUntilNextLocalDay(now: Date): number {
|
||||
const nextMidnight = new Date(now)
|
||||
nextMidnight.setHours(24, 0, 0, 0)
|
||||
|
||||
return nextMidnight.getTime() - now.getTime() + 5_000
|
||||
}
|
||||
|
||||
/**
|
||||
* The current date, refreshed when the local day changes (via a timer set to
|
||||
* the next midnight) and when the tab regains focus. Components selling a
|
||||
* "today only" view use it so bought items disappear once the day rolls over
|
||||
* even if the page has been open all night.
|
||||
*/
|
||||
export function useToday(): Date {
|
||||
const [today, setToday] = useState(() => new Date())
|
||||
|
||||
useEffect(() => {
|
||||
const refresh = () => setToday(new Date())
|
||||
|
||||
const timer = setTimeout(refresh, msUntilNextLocalDay(new Date()))
|
||||
window.addEventListener('focus', refresh)
|
||||
document.addEventListener('visibilitychange', refresh)
|
||||
|
||||
return () => {
|
||||
clearTimeout(timer)
|
||||
window.removeEventListener('focus', refresh)
|
||||
document.removeEventListener('visibilitychange', refresh)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return today
|
||||
}
|
||||
20
apps/web/src/hooks/use-voice-split.ts
Normal file
20
apps/web/src/hooks/use-voice-split.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import type { VoiceSplitRequest, VoiceSplitResponse } from '@superlist/shared'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
|
||||
import { apiFetch } from '@/lib/api-client'
|
||||
|
||||
/**
|
||||
* Asks the API to split a dictated sentence into one string per item, each written the
|
||||
* way the item parser reads typed text. The API never fails because of the model (it
|
||||
* falls back to splitting on commas and "y"), so an error here means the request did not
|
||||
* get through.
|
||||
*/
|
||||
export function useVoiceSplit() {
|
||||
return useMutation({
|
||||
mutationFn: (input: VoiceSplitRequest) =>
|
||||
apiFetch<VoiceSplitResponse>('/voice/split', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
})
|
||||
}
|
||||
@@ -49,72 +49,74 @@
|
||||
}
|
||||
|
||||
:root {
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.87 0 0);
|
||||
--chart-2: oklch(0.556 0 0);
|
||||
--chart-3: oklch(0.439 0 0);
|
||||
--chart-4: oklch(0.371 0 0);
|
||||
--chart-5: oklch(0.269 0 0);
|
||||
--radius: 0.625rem;
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
/* Warm paper background, white cards and a grocery green as the accent. */
|
||||
--background: oklch(0.982 0.004 91);
|
||||
--foreground: oklch(0.17 0.005 90);
|
||||
--card: oklch(0.997 0.002 91);
|
||||
--card-foreground: oklch(0.17 0.005 90);
|
||||
--popover: oklch(0.997 0.002 91);
|
||||
--popover-foreground: oklch(0.17 0.005 90);
|
||||
--primary: oklch(0.52 0.13 147);
|
||||
--primary-foreground: oklch(0.99 0.01 147);
|
||||
--secondary: oklch(0.95 0.007 91);
|
||||
--secondary-foreground: oklch(0.24 0.005 90);
|
||||
--muted: oklch(0.95 0.007 91);
|
||||
--muted-foreground: oklch(0.52 0.008 90);
|
||||
--accent: oklch(0.94 0.025 147);
|
||||
--accent-foreground: oklch(0.36 0.09 147);
|
||||
--destructive: oklch(0.577 0.215 27.325);
|
||||
--border: oklch(0.915 0.007 91);
|
||||
--input: oklch(0.9 0.008 91);
|
||||
--ring: oklch(0.52 0.13 147);
|
||||
--chart-1: oklch(0.52 0.13 147);
|
||||
--chart-2: oklch(0.65 0.13 150);
|
||||
--chart-3: oklch(0.75 0.12 85);
|
||||
--chart-4: oklch(0.6 0.12 45);
|
||||
--chart-5: oklch(0.45 0.05 200);
|
||||
--radius: 0.875rem;
|
||||
--sidebar: oklch(0.97 0.005 91);
|
||||
--sidebar-foreground: oklch(0.17 0.005 90);
|
||||
--sidebar-primary: oklch(0.52 0.13 147);
|
||||
--sidebar-primary-foreground: oklch(0.99 0.01 147);
|
||||
--sidebar-accent: oklch(0.94 0.025 147);
|
||||
--sidebar-accent-foreground: oklch(0.36 0.09 147);
|
||||
--sidebar-border: oklch(0.915 0.007 91);
|
||||
--sidebar-ring: oklch(0.52 0.13 147);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
/* Deep green-tinted charcoal; the green is lifted so it reads on dark. */
|
||||
--background: oklch(0.165 0.008 155);
|
||||
--foreground: oklch(0.95 0.006 95);
|
||||
--card: oklch(0.21 0.01 155);
|
||||
--card-foreground: oklch(0.95 0.006 95);
|
||||
--popover: oklch(0.23 0.01 155);
|
||||
--popover-foreground: oklch(0.95 0.006 95);
|
||||
--primary: oklch(0.72 0.16 148);
|
||||
--primary-foreground: oklch(0.2 0.04 150);
|
||||
--secondary: oklch(0.26 0.01 155);
|
||||
--secondary-foreground: oklch(0.95 0.006 95);
|
||||
--muted: oklch(0.255 0.01 155);
|
||||
--muted-foreground: oklch(0.7 0.012 120);
|
||||
--accent: oklch(0.3 0.045 150);
|
||||
--accent-foreground: oklch(0.88 0.08 148);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
--chart-1: oklch(0.87 0 0);
|
||||
--chart-2: oklch(0.556 0 0);
|
||||
--chart-3: oklch(0.439 0 0);
|
||||
--chart-4: oklch(0.371 0 0);
|
||||
--chart-5: oklch(0.269 0 0);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
--border: oklch(1 0 0 / 9%);
|
||||
--input: oklch(1 0 0 / 14%);
|
||||
--ring: oklch(0.72 0.16 148);
|
||||
--chart-1: oklch(0.72 0.16 148);
|
||||
--chart-2: oklch(0.62 0.13 150);
|
||||
--chart-3: oklch(0.8 0.12 85);
|
||||
--chart-4: oklch(0.7 0.12 45);
|
||||
--chart-5: oklch(0.65 0.06 200);
|
||||
--sidebar: oklch(0.19 0.009 155);
|
||||
--sidebar-foreground: oklch(0.95 0.006 95);
|
||||
--sidebar-primary: oklch(0.72 0.16 148);
|
||||
--sidebar-primary-foreground: oklch(0.2 0.04 150);
|
||||
--sidebar-accent: oklch(0.3 0.045 150);
|
||||
--sidebar-accent-foreground: oklch(0.88 0.08 148);
|
||||
--sidebar-border: oklch(1 0 0 / 9%);
|
||||
--sidebar-ring: oklch(0.72 0.16 148);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
import { PROBLEM_CONTENT_TYPE, type ProblemDetails } from '@superlist/shared'
|
||||
|
||||
const baseUrl = import.meta.env.VITE_API_URL ?? 'http://localhost:4100'
|
||||
/**
|
||||
* Base URL of the API. Also used to open the SSE streams (`list-events`).
|
||||
*
|
||||
* Empty by default: the API is reached through the `/api` prefix on the same
|
||||
* origin (Vite proxies it in dev, nginx in production). Set `VITE_API_URL` to
|
||||
* point at another origin — the `/api` suffix is always appended to it.
|
||||
*/
|
||||
const origin = import.meta.env.VITE_API_URL || ''
|
||||
|
||||
export const apiBaseUrl = `${origin}/api`
|
||||
|
||||
/** Error thrown when the API answers with a RFC 9457 Problem Details payload. */
|
||||
export class ApiError extends Error {
|
||||
@@ -34,7 +43,7 @@ export async function readProblem(response: Response): Promise<ProblemDetails> {
|
||||
|
||||
/** Thin `fetch` wrapper: JSON by default, sessions enabled, problems as errors. */
|
||||
export async function apiFetch<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
const response = await fetch(`${baseUrl}${path}`, {
|
||||
const response = await fetch(`${apiBaseUrl}${path}`, {
|
||||
credentials: 'include',
|
||||
...init,
|
||||
headers: {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user