feat: add collaborative shopping lists with items and invitations
Some checks failed
CI / Verify (push) Has been cancelled

API: lists, items and invitations modules (list, create, get, update,
set-primary, items create/list, invitation create/accept/list-pending),
BetterAuth session helper, list membership, mailer and Prisma schema plus
migrations.

Web: lists overview, list detail (items) and list management (settings)
views, item and invitation forms/hooks, sign-up and invitation accept pages.

Shared: shopping list DTOs.

Tooling: ignore the generated TanStack Router cache (apps/web/.tanstack).
This commit is contained in:
Jose Selesan
2026-10-16 10:12:11 -03:00
parent 964a3c7217
commit 6aa86a3b68
81 changed files with 3476 additions and 269 deletions

View File

@@ -0,0 +1,55 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { PlusIcon } from 'lucide-react'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { Button } from '@/components/ui/button'
import { Field, FieldError } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { useCreateItem } from '@/hooks/use-items'
const createItemSchema = z.object({
name: z.string().trim().min(1, 'Escribe un artículo').max(120, 'Máximo 120 caracteres'),
})
type CreateItemValues = z.infer<typeof createItemSchema>
type CreateItemFormProps = {
listId: string
/** Focus the input when the form mounts, so the user can type right away. */
autoFocus?: boolean
}
/** Input to add an item to a list. Submits with Enter or the button. */
export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProps) {
const createItem = useCreateItem(listId)
const form = useForm<CreateItemValues>({
resolver: zodResolver(createItemSchema),
defaultValues: { name: '' },
})
const onSubmit = form.handleSubmit((values) => {
createItem.mutate(values, { onSuccess: () => form.reset() })
})
return (
<form onSubmit={onSubmit} className="flex items-start gap-2">
<Field className="flex-1" data-invalid={!!form.formState.errors.name}>
<Input
aria-label="Nuevo artículo"
autoComplete="off"
placeholder="Añade un artículo…"
autoFocus={autoFocus}
{...form.register('name')}
/>
<FieldError errors={[form.formState.errors.name]} />
</Field>
<Button type="submit" disabled={createItem.isPending}>
<PlusIcon />
{createItem.isPending ? 'Agregando…' : 'Agregar'}
</Button>
</form>
)
}

View File

@@ -0,0 +1,93 @@
import { CheckIcon, ShoppingBasketIcon } from 'lucide-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 { ApiError } from '@/lib/api-client'
import { cn } from '@/lib/utils'
type ItemListProps = {
listId: string
}
/** Items loaded from the API, pending ones first. */
export function ItemList({ listId }: ItemListProps) {
const { data: items, isPending, error } = useItems(listId)
if (error) {
return (
<Alert variant="destructive">
<AlertTitle>No pudimos cargar los artículos</AlertTitle>
<AlertDescription>
{error instanceof ApiError
? (error.problem.detail ?? error.problem.title)
: 'Inténtalo de nuevo en unos segundos.'}
</AlertDescription>
</Alert>
)
}
if (isPending) {
return (
<div className="flex flex-col gap-2">
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
</div>
)
}
if (items.length === 0) {
return (
<Card>
<CardContent className="flex flex-col items-center gap-3 py-10 text-center">
<div className="bg-muted text-muted-foreground flex size-12 items-center justify-center rounded-full">
<ShoppingBasketIcon className="size-6" />
</div>
<div>
<p className="font-medium">La lista está vacía</p>
<p className="text-muted-foreground text-sm">
Usa el campo de arriba para añadir tu primer artículo.
</p>
</div>
</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>
))}
</ul>
)
}

View File

@@ -1,34 +1,35 @@
import { useRouterState } from '@tanstack/react-router'
import { SearchIcon } from 'lucide-react'
import { ThemeToggle } from '@/components/theme-toggle'
import { Separator } from '@/components/ui/separator'
import { SidebarTrigger } from '@/components/ui/sidebar'
function usePageTitle() {
const pathname = useRouterState({ select: (state) => state.location.pathname })
if (pathname === '/') return 'Dashboard'
const segment = pathname.split('/').filter(Boolean).at(0) ?? ''
return segment.charAt(0).toUpperCase() + segment.slice(1)
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'
}
export function AppHeader() {
const title = usePageTitle()
const pathname = useRouterState({ select: (state) => state.location.pathname })
const title = titleFor(pathname)
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="text-sm font-medium">{title}</h1>
<h1 className="truncate text-sm font-medium">{title}</h1>
<div className="ml-auto flex items-center gap-1">
<button
type="button"
className="text-muted-foreground hover:bg-accent hover:text-accent-foreground mr-1 hidden items-center gap-2 rounded-md border px-3 py-1.5 text-xs md:flex"
>
<SearchIcon className="size-3.5" />
Search
Buscar
<kbd className="bg-muted text-muted-foreground rounded px-1.5 py-0.5 font-mono text-[10px]">
⌘K
</kbd>

View File

@@ -1,6 +1,6 @@
import { Link, useRouterState } from '@tanstack/react-router'
import type { LucideIcon } from 'lucide-react'
import { LayoutDashboardIcon, ListTodoIcon, SettingsIcon } from 'lucide-react'
import { HomeIcon, ListTodoIcon, SettingsIcon, ShoppingCartIcon } from 'lucide-react'
import { NavUser } from '@/components/layout/nav-user'
import {
@@ -23,11 +23,17 @@ type NavItem = {
}
const NAV_ITEMS: NavItem[] = [
{ title: 'Dashboard', to: '/', icon: LayoutDashboardIcon },
{ title: 'Tasks', to: '/tasks', icon: ListTodoIcon },
{ title: 'Settings', to: '/settings', icon: SettingsIcon },
{ 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,7 +49,7 @@ export function AppSidebar() {
</div>
<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">Admin</span>
<span className="text-muted-foreground truncate text-xs">Listas compartidas</span>
</div>
</Link>
</SidebarMenuButton>
@@ -53,11 +59,15 @@ export function AppSidebar() {
<SidebarContent>
<SidebarGroup>
<SidebarGroupLabel>Platform</SidebarGroupLabel>
<SidebarGroupLabel>Plataforma</SidebarGroupLabel>
<SidebarMenu>
{NAV_ITEMS.map((item) => (
<SidebarMenuItem key={item.to}>
<SidebarMenuButton asChild isActive={pathname === item.to} tooltip={item.title}>
<SidebarMenuButton
asChild
isActive={isActive(pathname, item.to)}
tooltip={item.title}
>
<Link to={item.to}>
<item.icon />
<span>{item.title}</span>

View File

@@ -35,7 +35,7 @@ export function NavUser() {
const navigate = useNavigate()
const user = session?.user
const name = user?.name ?? 'Signed out'
const name = user?.name ?? 'Sin sesión'
const email = user?.email ?? ''
return (
@@ -79,7 +79,7 @@ export function NavUser() {
<DropdownMenuGroup>
<DropdownMenuItem onClick={() => void navigate({ to: '/settings' })}>
<UserIcon />
Account
Cuenta
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
@@ -90,7 +90,7 @@ export function NavUser() {
}}
>
<LogOutIcon />
Sign out
Cerrar sesión
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>

View File

@@ -0,0 +1,81 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { useCreateList } from '@/hooks/use-lists'
import { ApiError } from '@/lib/api-client'
const createListSchema = z.object({
name: z.string().trim().min(1, 'El nombre es obligatorio').max(80, 'Máximo 80 caracteres'),
})
type CreateListValues = z.infer<typeof createListSchema>
type CreateListFormProps = {
onCreated?: () => void
}
/** Inline form to create a shopping list. Used by the lists page. */
export function CreateListForm({ onCreated }: CreateListFormProps) {
const [error, setError] = useState<string | null>(null)
const createList = useCreateList()
const form = useForm<CreateListValues>({
resolver: zodResolver(createListSchema),
defaultValues: { name: '' },
})
const onSubmit = form.handleSubmit((values) => {
setError(null)
createList.mutate(values, {
onSuccess: () => {
form.reset()
onCreated?.()
},
onError: (mutationError) => {
setError(
mutationError instanceof ApiError
? (mutationError.problem.detail ?? mutationError.problem.title)
: 'No pudimos crear la lista.',
)
},
})
})
return (
<form onSubmit={onSubmit} className="flex flex-col gap-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<FieldGroup>
<Field data-invalid={!!form.formState.errors.name}>
<FieldLabel htmlFor="list-name">Nombre de la lista</FieldLabel>
<Input
id="list-name"
placeholder="Compra semanal"
autoComplete="off"
{...form.register('name')}
/>
<FieldError errors={[form.formState.errors.name]} />
</Field>
<Button
type="submit"
className="w-full sm:w-auto sm:self-start"
disabled={createList.isPending}
>
{createList.isPending ? 'Creando…' : 'Crear lista'}
</Button>
</FieldGroup>
</form>
)
}

View File

@@ -0,0 +1,55 @@
import type { ShoppingListSummary } from '@superlist/shared'
import { Link } from '@tanstack/react-router'
import { SettingsIcon, StarIcon, UsersIcon } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { useSetPrimaryList } from '@/hooks/use-lists'
type ListCardProps = {
list: ShoppingListSummary
}
/** A single list in the lists overview. Tapping it opens the list's items. */
export function ListCard({ list }: ListCardProps) {
const setPrimary = useSetPrimaryList()
return (
<Card>
<CardContent className="flex items-center gap-1 p-4">
<Link to="/lists/$listId" params={{ listId: list.id }} className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate font-medium">{list.name}</span>
{list.isPrimary && <Badge>Principal</Badge>}
</div>
<div className="text-muted-foreground mt-1 flex items-center gap-3 text-xs">
<span className="flex items-center gap-1">
<UsersIcon className="size-3.5" />
{list.memberCount} {list.memberCount === 1 ? 'persona' : 'personas'}
</span>
<span>{list.role === 'owner' ? 'Propietario' : 'Colaborador'}</span>
</div>
</Link>
{!list.isPrimary && (
<Button
variant="ghost"
size="icon"
aria-label={`Marcar ${list.name} como lista principal`}
disabled={setPrimary.isPending}
onClick={() => setPrimary.mutate(list.id)}
>
<StarIcon className="size-4" />
</Button>
)}
<Button variant="ghost" size="icon" aria-label={`Editar o configurar ${list.name}`} asChild>
<Link to="/lists/$listId/settings" params={{ listId: list.id }}>
<SettingsIcon className="size-4" />
</Link>
</Button>
</CardContent>
</Card>
)
}

View File

@@ -1,11 +1,84 @@
import { ThemeProvider as NextThemesProvider } from 'next-themes'
import type { ComponentProps } from 'react'
import type { ReactNode } from 'react'
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
/** Wraps `next-themes` so the theme is toggled by a class on `<html>`. */
export function ThemeProvider({ children, ...props }: ComponentProps<typeof NextThemesProvider>) {
return (
<NextThemesProvider attribute="class" enableSystem disableTransitionOnChange {...props}>
{children}
</NextThemesProvider>
)
export type Theme = 'light' | 'dark' | 'system'
type ResolvedTheme = Exclude<Theme, 'system'>
type ThemeContextValue = {
/** The preference the user picked, `system` included. */
theme: Theme
/** The preference already resolved against the OS setting. */
resolvedTheme: ResolvedTheme
setTheme: (theme: Theme) => void
}
const STORAGE_KEY = 'superlist-theme'
const DARK_QUERY = '(prefers-color-scheme: dark)'
/**
* 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
* never executes scripts rendered by components (it even logs a warning). Since
* this app is client-rendered, the flash is prevented by the static script in
* `index.html`, which runs before React mounts and uses this same storage key
* and `.dark` class.
*/
const ThemeContext = createContext<ThemeContextValue>({
theme: 'system',
resolvedTheme: 'light',
setTheme: () => {},
})
function readStoredTheme(): Theme {
try {
const stored = window.localStorage.getItem(STORAGE_KEY)
if (stored === 'light' || stored === 'dark' || stored === 'system') return stored
} catch {
// Storage can be unavailable (private mode, blocked cookies); fall back to system.
}
return 'system'
}
function systemTheme(): ResolvedTheme {
return window.matchMedia(DARK_QUERY).matches ? 'dark' : 'light'
}
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setThemeState] = useState<Theme>(readStoredTheme)
const [systemDark, setSystemDark] = useState(() => systemTheme() === 'dark')
const resolvedTheme: ResolvedTheme = theme === 'system' ? (systemDark ? 'dark' : 'light') : theme
useEffect(() => {
const media = window.matchMedia(DARK_QUERY)
const onChange = (event: MediaQueryListEvent) => setSystemDark(event.matches)
media.addEventListener('change', onChange)
return () => media.removeEventListener('change', onChange)
}, [])
useEffect(() => {
const root = document.documentElement
root.classList.toggle('dark', resolvedTheme === 'dark')
root.style.colorScheme = resolvedTheme
}, [resolvedTheme])
const setTheme = useCallback((next: Theme) => {
setThemeState(next)
try {
window.localStorage.setItem(STORAGE_KEY, next)
} catch {
// Ignore storage failures: the theme still applies for this session.
}
}, [])
const value = useMemo(
() => ({ theme, resolvedTheme, setTheme }),
[theme, resolvedTheme, setTheme],
)
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
}
export function useTheme() {
return useContext(ThemeContext)
}

View File

@@ -1,6 +1,6 @@
import { MonitorIcon, MoonIcon, SunIcon } from 'lucide-react'
import { useTheme } from 'next-themes'
import { useTheme } from '@/components/theme-provider'
import { Button } from '@/components/ui/button'
import {
DropdownMenu,
@@ -10,9 +10,9 @@ import {
} from '@/components/ui/dropdown-menu'
const OPTIONS = [
{ value: 'light', label: 'Light', icon: SunIcon },
{ value: 'dark', label: 'Dark', icon: MoonIcon },
{ value: 'system', label: 'System', icon: MonitorIcon },
{ value: 'light', label: 'Claro', icon: SunIcon },
{ value: 'dark', label: 'Oscuro', icon: MoonIcon },
{ value: 'system', label: 'Sistema', icon: MonitorIcon },
] as const
export function ThemeToggle() {
@@ -21,7 +21,7 @@ export function ThemeToggle() {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" aria-label="Toggle theme">
<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>

View File

@@ -5,8 +5,8 @@ import {
OctagonXIcon,
TriangleAlertIcon,
} from 'lucide-react'
import { useTheme } from 'next-themes'
import { Toaster as Sonner, type ToasterProps } from 'sonner'
import { useTheme } from '@/components/theme-provider'
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = 'system' } = useTheme()

View File

@@ -0,0 +1,41 @@
import type {
AcceptInvitationResult,
CreateInvitationResult,
PendingInvitation,
} from '@superlist/shared'
import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { apiFetch } from '@/lib/api-client'
export const pendingInvitationsQueryOptions = () =>
queryOptions({
queryKey: ['invitations', 'pending'],
queryFn: () => apiFetch<PendingInvitation[]>('/invitations/pending'),
})
export function usePendingInvitations() {
return useQuery(pendingInvitationsQueryOptions())
}
export function useCreateInvitation(listId: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (input: { email: string }) =>
apiFetch<CreateInvitationResult>('/invitations', {
method: 'POST',
body: JSON.stringify({ listId, email: input.email }),
}),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists', listId] }),
})
}
export function useAcceptInvitation() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (token: string) =>
apiFetch<AcceptInvitationResult>(`/invitations/${token}/accept`, { method: 'POST' }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists'] }),
})
}

View File

@@ -0,0 +1,27 @@
import type { ListItem } from '@superlist/shared'
import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { apiFetch } from '@/lib/api-client'
export const itemsQueryOptions = (listId: string) =>
queryOptions({
queryKey: ['lists', listId, 'items'],
queryFn: () => apiFetch<ListItem[]>(`/lists/${listId}/items`),
})
export function useItems(listId: string) {
return useQuery(itemsQueryOptions(listId))
}
export function useCreateItem(listId: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (input: { name: string; quantity?: string; notes?: string }) =>
apiFetch<ListItem>(`/lists/${listId}/items`, {
method: 'POST',
body: JSON.stringify(input),
}),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] }),
})
}

View File

@@ -0,0 +1,14 @@
import type { ShoppingListDetail } from '@superlist/shared'
import { queryOptions, useQuery } from '@tanstack/react-query'
import { apiFetch } from '@/lib/api-client'
export const listQueryOptions = (listId: string) =>
queryOptions({
queryKey: ['lists', listId],
queryFn: () => apiFetch<ShoppingListDetail>(`/lists/${listId}`),
})
export function useList(listId: string) {
return useQuery(listQueryOptions(listId))
}

View File

@@ -0,0 +1,49 @@
import type { ShoppingListSummary } from '@superlist/shared'
import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { apiFetch } from '@/lib/api-client'
export const listsQueryOptions = () =>
queryOptions({
queryKey: ['lists'],
queryFn: () => apiFetch<ShoppingListSummary[]>('/lists'),
})
export function useLists() {
return useQuery(listsQueryOptions())
}
export function useCreateList() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (input: { name: string }) =>
apiFetch<ShoppingListSummary>('/lists', {
method: 'POST',
body: JSON.stringify(input),
}),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists'] }),
})
}
export function useRenameList(listId: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (input: { name: string }) =>
apiFetch<ShoppingListSummary>(`/lists/${listId}`, {
method: 'PATCH',
body: JSON.stringify(input),
}),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists'] }),
})
}
export function useSetPrimaryList() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (listId: string) => apiFetch<void>(`/lists/${listId}/primary`, { method: 'POST' }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists'] }),
})
}

View File

@@ -1,5 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
@@ -12,18 +12,22 @@ import { Input } from '@/components/ui/input'
import { signIn } from '@/lib/auth-client'
export const Route = createFileRoute('/(auth)/sign-in')({
validateSearch: (search: Record<string, unknown>): { redirect?: string } => ({
redirect: typeof search.redirect === 'string' ? search.redirect : undefined,
}),
component: SignInPage,
})
const signInSchema = z.object({
email: z.email('Enter a valid email address'),
password: z.string().min(8, 'Passwords are at least 8 characters long'),
email: z.email('Introduce un correo electrónico válido'),
password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'),
})
type SignInValues = z.infer<typeof signInSchema>
function SignInPage() {
const navigate = useNavigate()
const { redirect } = Route.useSearch()
const [error, setError] = useState<string | null>(null)
const form = useForm<SignInValues>({
@@ -37,7 +41,12 @@ function SignInPage() {
const { error: signInError } = await signIn.email(values)
if (signInError) {
setError(signInError.message ?? 'Could not sign you in')
setError(signInError.message ?? 'No pudimos iniciar tu sesión')
return
}
if (redirect) {
window.location.assign(redirect)
return
}
@@ -48,33 +57,33 @@ function SignInPage() {
<div className="flex min-h-svh items-center justify-center p-6">
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle>Sign in</CardTitle>
<CardDescription>Use your Superlist account to continue.</CardDescription>
<CardTitle>Iniciar sesión</CardTitle>
<CardDescription>Usa tu cuenta de Superlist para continuar.</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={onSubmit} className="flex flex-col gap-6">
{error && (
<Alert variant="destructive">
<AlertTitle>Sign in failed</AlertTitle>
<AlertTitle>No pudimos iniciar tu sesión</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<FieldGroup>
<Field data-invalid={!!form.formState.errors.email}>
<FieldLabel htmlFor="email">Email</FieldLabel>
<FieldLabel htmlFor="email">Correo electrónico</FieldLabel>
<Input
id="email"
type="email"
autoComplete="email"
placeholder="ada@example.com"
placeholder="ada@ejemplo.com"
{...form.register('email')}
/>
<FieldError errors={[form.formState.errors.email]} />
</Field>
<Field data-invalid={!!form.formState.errors.password}>
<FieldLabel htmlFor="password">Password</FieldLabel>
<FieldLabel htmlFor="password">Contraseña</FieldLabel>
<Input
id="password"
type="password"
@@ -85,9 +94,20 @@ function SignInPage() {
</Field>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? 'Signing in…' : 'Sign in'}
{form.formState.isSubmitting ? 'Iniciando sesión…' : 'Iniciar sesión'}
</Button>
</FieldGroup>
<p className="text-muted-foreground text-center text-sm">
¿Todavía no tienes cuenta?{' '}
<Link
to="/sign-up"
search={redirect ? { redirect } : {}}
className="text-foreground font-medium underline-offset-4 hover:underline"
>
Crea una
</Link>
</p>
</form>
</CardContent>
</Card>

View File

@@ -0,0 +1,128 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { signUp } from '@/lib/auth-client'
export const Route = createFileRoute('/(auth)/sign-up')({
validateSearch: (search: Record<string, unknown>): { redirect?: string } => ({
redirect: typeof search.redirect === 'string' ? search.redirect : undefined,
}),
component: SignUpPage,
})
const signUpSchema = z.object({
name: z.string().trim().min(1, 'Escribe tu nombre').max(80),
email: z.email('Introduce un correo electrónico válido'),
password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'),
})
type SignUpValues = z.infer<typeof signUpSchema>
function SignUpPage() {
const navigate = useNavigate()
const { redirect } = Route.useSearch()
const [error, setError] = useState<string | null>(null)
const form = useForm<SignUpValues>({
resolver: zodResolver(signUpSchema),
defaultValues: { name: '', email: '', password: '' },
})
const onSubmit = form.handleSubmit(async (values) => {
setError(null)
const { error: signUpError } = await signUp.email(values)
if (signUpError) {
setError(signUpError.message ?? 'No pudimos crear tu cuenta')
return
}
if (redirect) {
window.location.assign(redirect)
return
}
await navigate({ to: '/' })
})
return (
<div className="flex min-h-svh items-center justify-center p-6">
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle>Crear cuenta</CardTitle>
<CardDescription>Empieza a compartir tus listas de compras.</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={onSubmit} className="flex flex-col gap-6">
{error && (
<Alert variant="destructive">
<AlertTitle>No pudimos crear tu cuenta</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<FieldGroup>
<Field data-invalid={!!form.formState.errors.name}>
<FieldLabel htmlFor="name">Nombre</FieldLabel>
<Input
id="name"
autoComplete="name"
placeholder="Ada Lovelace"
{...form.register('name')}
/>
<FieldError errors={[form.formState.errors.name]} />
</Field>
<Field data-invalid={!!form.formState.errors.email}>
<FieldLabel htmlFor="email">Correo electrónico</FieldLabel>
<Input
id="email"
type="email"
autoComplete="email"
placeholder="ada@ejemplo.com"
{...form.register('email')}
/>
<FieldError errors={[form.formState.errors.email]} />
</Field>
<Field data-invalid={!!form.formState.errors.password}>
<FieldLabel htmlFor="password">Contraseña</FieldLabel>
<Input
id="password"
type="password"
autoComplete="new-password"
{...form.register('password')}
/>
<FieldError errors={[form.formState.errors.password]} />
</Field>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? 'Creando cuenta…' : 'Crear cuenta'}
</Button>
</FieldGroup>
<p className="text-muted-foreground text-center text-sm">
¿Ya tienes cuenta?{' '}
<Link
to="/sign-in"
search={redirect ? { redirect } : {}}
className="text-foreground font-medium underline-offset-4 hover:underline"
>
Inicia sesión
</Link>
</p>
</form>
</CardContent>
</Card>
</div>
)
}

View File

@@ -30,7 +30,7 @@ export const Route = createRootRouteWithContext<RouterContext>()({
function RootLayout() {
return (
<ThemeProvider defaultTheme="system" storageKey="superlist-theme">
<ThemeProvider>
<TooltipProvider delayDuration={200}>
<Outlet />
<Toaster richColors position="top-right" />
@@ -45,9 +45,9 @@ function NotFound() {
return (
<div className="flex min-h-svh flex-col items-center justify-center gap-4 p-6 text-center">
<p className="text-muted-foreground text-sm font-medium">404</p>
<h1 className="text-2xl font-semibold">This page does not exist</h1>
<h1 className="text-2xl font-semibold">Esta página no existe</h1>
<Button asChild>
<Link to="/">Back to dashboard</Link>
<Link to="/">Volver al inicio</Link>
</Button>
</div>
)

View File

@@ -1,160 +1,98 @@
import { createFileRoute } from '@tanstack/react-router'
import { ActivityIcon, CircleCheckIcon, ServerIcon, UsersIcon } from 'lucide-react'
import { Area, AreaChart, CartesianGrid, ResponsiveContainer, XAxis, YAxis } from 'recharts'
import type { ShoppingListSummary } from '@superlist/shared'
import { createFileRoute, Link } from '@tanstack/react-router'
import { PlusIcon, ShoppingCartIcon } from 'lucide-react'
import { CreateItemForm } from '@/components/items/create-item-form'
import { ItemList } from '@/components/items/item-list'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { useHealth } from '@/hooks/use-health'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { listsQueryOptions, useLists } from '@/hooks/use-lists'
import { ApiError } from '@/lib/api-client'
const TRAFFIC = [
{ day: 'Mon', requests: 420 },
{ day: 'Tue', requests: 512 },
{ day: 'Wed', requests: 388 },
{ day: 'Thu', requests: 640 },
{ day: 'Fri', requests: 731 },
{ day: 'Sat', requests: 254 },
{ day: 'Sun', requests: 198 },
]
export const Route = createFileRoute('/_authenticated/')({
component: DashboardPage,
loader: ({ context }) => context.queryClient.ensureQueryData(listsQueryOptions()),
component: HomePage,
})
function DashboardPage() {
/** The list a user lands on: their primary one, falling back to the first. */
function pickPrimaryList(lists: ShoppingListSummary[]): ShoppingListSummary | undefined {
return lists.find((list) => list.isPrimary) ?? lists[0]
}
function HomePage() {
const { data: lists, isPending, error } = useLists()
if (error) {
return (
<div className="mx-auto w-full max-w-2xl">
<Alert variant="destructive">
<AlertTitle>No pudimos cargar tu lista</AlertTitle>
<AlertDescription>
{error instanceof ApiError
? (error.problem.detail ?? error.problem.title)
: 'Inténtalo de nuevo en unos segundos.'}
</AlertDescription>
</Alert>
</div>
)
}
if (isPending || !lists) {
return (
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4">
<Skeleton className="h-8 w-48" />
<Skeleton className="h-10 w-full" />
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
</div>
)
}
const primaryList = pickPrimaryList(lists)
if (!primaryList) {
return <NoLists />
}
return (
<div className="flex flex-col gap-4 md:gap-6">
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
<StatCard title="Users" value="2,481" description="+12% vs last month" icon={UsersIcon} />
<StatCard title="Active lists" value="318" description="+4 this week" icon={ActivityIcon} />
<StatCard
title="Tasks done"
value="9,204"
description="+18% vs last month"
icon={CircleCheckIcon}
/>
<ApiStatusCard />
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4 md:gap-6">
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-lg font-semibold">{primaryList.name}</h1>
{primaryList.isPrimary && <Badge>Principal</Badge>}
</div>
<div className="grid gap-4 lg:grid-cols-2">
<Card>
<CardHeader>
<CardTitle>Requests</CardTitle>
<CardDescription>API requests over the last 7 days</CardDescription>
</CardHeader>
<CardContent className="h-72 pl-0">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={TRAFFIC} margin={{ left: 12, right: 12, top: 8 }}>
<defs>
<linearGradient id="fillRequests" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="var(--color-primary)" stopOpacity={0.7} />
<stop offset="95%" stopColor="var(--color-primary)" stopOpacity={0.05} />
</linearGradient>
</defs>
<CartesianGrid vertical={false} strokeDasharray="3 3" />
<XAxis dataKey="day" tickLine={false} axisLine={false} />
<YAxis tickLine={false} axisLine={false} width={40} />
<Area
dataKey="requests"
type="monotone"
stroke="var(--color-primary)"
fill="url(#fillRequests)"
strokeWidth={2}
/>
</AreaChart>
</ResponsiveContainer>
</CardContent>
</Card>
<CreateItemForm listId={primaryList.id} />
<Card>
<CardHeader>
<CardTitle>Recent activity</CardTitle>
<CardDescription>What your team has been doing</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{[
{ who: 'Ada Lovelace', what: 'created list "Q4 roadmap"', when: '2h ago' },
{ who: 'Alan Turing', what: 'completed 12 tasks', when: '5h ago' },
{ who: 'Grace Hopper', what: 'invited 3 teammates', when: 'yesterday' },
{ who: 'Linus Torvalds', what: 'archived "Sprint 41"', when: '2 days ago' },
].map((item) => (
<div key={item.what} className="flex items-start gap-3">
<div className="bg-muted text-muted-foreground flex size-9 shrink-0 items-center justify-center rounded-full text-xs font-medium">
{item.who.slice(0, 2).toUpperCase()}
</div>
<div className="flex-1 text-sm">
<p>
<span className="font-medium">{item.who}</span> {item.what}
</p>
<p className="text-muted-foreground text-xs">{item.when}</p>
</div>
</div>
))}
</CardContent>
</Card>
</div>
<ItemList listId={primaryList.id} />
</div>
)
}
function StatCard({
title,
value,
description,
icon: Icon,
}: {
title: string
value: string
description: string
icon: typeof UsersIcon
}) {
function NoLists() {
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">{title}</CardTitle>
<Icon className="text-muted-foreground size-4" />
</CardHeader>
<CardContent>
<div className="text-2xl font-semibold">{value}</div>
<p className="text-muted-foreground text-xs">{description}</p>
</CardContent>
</Card>
)
}
/** Pings `GET /health` through TanStack Query, proving the API wiring works. */
function ApiStatusCard() {
const { data, isPending, error } = useHealth()
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">API</CardTitle>
<ServerIcon className="text-muted-foreground size-4" />
</CardHeader>
<CardContent>
{isPending && <div className="text-2xl font-semibold">…</div>}
{data && (
<>
<div className="text-2xl font-semibold">
<Badge variant="secondary">online</Badge>
</div>
<p className="text-muted-foreground text-xs">up {data.uptimeSeconds}s</p>
</>
)}
{error && (
<>
<div className="text-2xl font-semibold">
<Badge variant="destructive">offline</Badge>
</div>
<p className="text-muted-foreground truncate text-xs">
{error instanceof ApiError
? (error.problem.detail ?? error.message)
: 'API unreachable'}
<div className="mx-auto w-full max-w-2xl">
<Card>
<CardContent className="flex flex-col items-center gap-3 py-10 text-center">
<div className="bg-muted text-muted-foreground flex size-12 items-center justify-center rounded-full">
<ShoppingCartIcon className="size-6" />
</div>
<div>
<p className="font-medium">Todavía no tienes listas</p>
<p className="text-muted-foreground text-sm">
Crea tu primera lista para empezar a añadir artículos.
</p>
</>
)}
</CardContent>
</Card>
</div>
<Button asChild>
<Link to="/lists">
<PlusIcon className="size-4" />
Crear lista
</Link>
</Button>
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,86 @@
import { createFileRoute, Link } from '@tanstack/react-router'
import { ArrowLeftIcon, SettingsIcon } from 'lucide-react'
import { CreateItemForm } from '@/components/items/create-item-form'
import { ItemList } from '@/components/items/item-list'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { itemsQueryOptions } from '@/hooks/use-items'
import { listQueryOptions, useList } from '@/hooks/use-list'
import { ApiError } from '@/lib/api-client'
export const Route = createFileRoute('/_authenticated/lists/$listId/')({
loader: ({ context, params }) =>
Promise.all([
context.queryClient.ensureQueryData(listQueryOptions(params.listId)),
context.queryClient.ensureQueryData(itemsQueryOptions(params.listId)),
]),
component: ListItemsPage,
})
function problemMessage(error: unknown, fallback: string) {
return error instanceof ApiError ? (error.problem.detail ?? error.problem.title) : fallback
}
/** A list's items: the default view when a list is opened from the overview. */
function ListItemsPage() {
const { listId } = Route.useParams()
const { data: list, isPending, error } = useList(listId)
if (error) {
return (
<div className="mx-auto w-full max-w-2xl">
<Alert variant="destructive">
<AlertTitle>No pudimos abrir la lista</AlertTitle>
<AlertDescription>{problemMessage(error, 'Inténtalo de nuevo.')}</AlertDescription>
</Alert>
</div>
)
}
if (isPending || !list) {
return (
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4">
<Skeleton className="h-8 w-48" />
<Skeleton className="h-10 w-full" />
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
</div>
)
}
return (
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4 md:gap-6">
<div className="flex flex-col gap-2">
<Link
to="/lists"
className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-sm"
>
<ArrowLeftIcon className="size-4" />
Listas
</Link>
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-lg font-semibold break-words">{list.name}</h1>
{list.isPrimary && <Badge>Principal</Badge>}
<Badge variant="secondary">
{list.role === 'owner' ? 'Propietario' : 'Colaborador'}
</Badge>
</div>
<Button variant="outline" size="sm" asChild>
<Link to="/lists/$listId/settings" params={{ listId: list.id }}>
<SettingsIcon className="size-4" />
Gestionar
</Link>
</Button>
</div>
</div>
<CreateItemForm listId={list.id} autoFocus />
<ItemList listId={list.id} />
</div>
)
}

View File

@@ -0,0 +1,300 @@
import { zodResolver } from '@hookform/resolvers/zod'
import type { ListMember, ShoppingListDetail } from '@superlist/shared'
import { createFileRoute, Link } from '@tanstack/react-router'
import { ArrowLeftIcon, CheckIcon, MailIcon, StarIcon, UserPlusIcon } from 'lucide-react'
import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { Skeleton } from '@/components/ui/skeleton'
import { useCreateInvitation } from '@/hooks/use-invitations'
import { listQueryOptions, useList } from '@/hooks/use-list'
import { useRenameList, useSetPrimaryList } from '@/hooks/use-lists'
import { ApiError } from '@/lib/api-client'
export const Route = createFileRoute('/_authenticated/lists/$listId/settings')({
loader: ({ context, params }) =>
context.queryClient.ensureQueryData(listQueryOptions(params.listId)),
component: ListSettingsPage,
})
function problemMessage(error: unknown, fallback: string) {
return error instanceof ApiError ? (error.problem.detail ?? error.problem.title) : fallback
}
function ListSettingsPage() {
const { listId } = Route.useParams()
const { data: list, isPending, error } = useList(listId)
if (error) {
return (
<div className="mx-auto w-full max-w-2xl">
<Alert variant="destructive">
<AlertTitle>No pudimos abrir la lista</AlertTitle>
<AlertDescription>{problemMessage(error, 'Inténtalo de nuevo.')}</AlertDescription>
</Alert>
</div>
)
}
if (isPending || !list) {
return (
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4">
<Skeleton className="h-8 w-48" />
<Skeleton className="h-32 w-full" />
<Skeleton className="h-32 w-full" />
</div>
)
}
return (
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4 md:gap-6">
<div className="flex flex-col gap-2">
<Link
to="/lists/$listId"
params={{ listId: list.id }}
className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-sm"
>
<ArrowLeftIcon className="size-4" />
{list.name}
</Link>
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-lg font-semibold break-words">Gestionar lista</h1>
<Badge variant="secondary">{list.role === 'owner' ? 'Propietario' : 'Colaborador'}</Badge>
</div>
</div>
{!list.isPrimary && <SetPrimaryButton listId={list.id} />}
{list.role === 'owner' && <RenameListCard list={list} />}
{list.role === 'owner' && <InviteCollaboratorCard listId={list.id} />}
<MembersCard members={list.members} />
{list.invitations.length > 0 && <PendingInvitationsCard list={list} />}
</div>
)
}
function SetPrimaryButton({ listId }: { listId: string }) {
const setPrimary = useSetPrimaryList()
return (
<Button
variant="outline"
className="w-full sm:w-auto sm:self-start"
disabled={setPrimary.isPending}
onClick={() => setPrimary.mutate(listId)}
>
<StarIcon className="size-4" />
{setPrimary.isPending ? 'Marcando…' : 'Marcar como lista principal'}
</Button>
)
}
const renameSchema = z.object({
name: z.string().trim().min(1, 'El nombre es obligatorio').max(80, 'Máximo 80 caracteres'),
})
function RenameListCard({ list }: { list: ShoppingListDetail }) {
const [saved, setSaved] = useState(false)
const renameList = useRenameList(list.id)
const form = useForm<z.infer<typeof renameSchema>>({
resolver: zodResolver(renameSchema),
defaultValues: { name: list.name },
})
const onSubmit = form.handleSubmit((values) => {
setSaved(false)
renameList.mutate(values, { onSuccess: () => setSaved(true) })
})
return (
<Card>
<CardHeader>
<CardTitle className="text-base">Nombre de la lista</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={onSubmit} className="flex flex-col gap-4">
{renameList.error && (
<Alert variant="destructive">
<AlertDescription>
{problemMessage(renameList.error, 'No pudimos renombrar la lista.')}
</AlertDescription>
</Alert>
)}
<FieldGroup>
<Field data-invalid={!!form.formState.errors.name}>
<FieldLabel htmlFor="rename-list">Nombre</FieldLabel>
<Input id="rename-list" {...form.register('name')} />
<FieldError errors={[form.formState.errors.name]} />
</Field>
<div className="flex items-center gap-3">
<Button type="submit" className="w-full sm:w-auto" disabled={renameList.isPending}>
{renameList.isPending ? 'Guardando…' : 'Guardar'}
</Button>
{saved && (
<span className="text-muted-foreground inline-flex items-center gap-1 text-sm">
<CheckIcon className="size-4" />
Guardado
</span>
)}
</div>
</FieldGroup>
</form>
</CardContent>
</Card>
)
}
const inviteSchema = z.object({
email: z.email('Introduce un correo electrónico válido'),
})
function InviteCollaboratorCard({ listId }: { listId: string }) {
const [message, setMessage] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
const createInvitation = useCreateInvitation(listId)
const form = useForm<z.infer<typeof inviteSchema>>({
resolver: zodResolver(inviteSchema),
defaultValues: { email: '' },
})
const onSubmit = form.handleSubmit((values) => {
setMessage(null)
setError(null)
createInvitation.mutate(values, {
onSuccess: (result) => {
form.reset()
setMessage(
result.status === 'added'
? `${result.email} ya tenía cuenta y ahora colabora en la lista.`
: `Invitación enviada a ${result.email}.`,
)
},
onError: (mutationError) => {
setError(problemMessage(mutationError, 'No pudimos enviar la invitación.'))
},
})
})
return (
<Card>
<CardHeader>
<CardTitle className="text-base">Invitar a colaborar</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={onSubmit} className="flex flex-col gap-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{message && (
<Alert>
<AlertDescription>{message}</AlertDescription>
</Alert>
)}
<FieldGroup>
<Field data-invalid={!!form.formState.errors.email}>
<FieldLabel htmlFor="invite-email">Correo electrónico</FieldLabel>
<Input
id="invite-email"
type="email"
placeholder="persona@ejemplo.com"
autoComplete="off"
{...form.register('email')}
/>
<FieldError errors={[form.formState.errors.email]} />
</Field>
<Button
type="submit"
className="w-full sm:w-auto sm:self-start"
disabled={createInvitation.isPending}
>
<UserPlusIcon className="size-4" />
{createInvitation.isPending ? 'Enviando…' : 'Enviar invitación'}
</Button>
</FieldGroup>
</form>
</CardContent>
</Card>
)
}
function initials(name: string) {
return (
name
.split(' ')
.map((part) => part[0])
.filter(Boolean)
.slice(0, 2)
.join('')
.toUpperCase() || '?'
)
}
function MembersCard({ members }: { members: ListMember[] }) {
return (
<Card>
<CardHeader>
<CardTitle className="text-base">Colaboradores ({members.length})</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3">
{members.map((member) => (
<div key={member.id} className="flex items-center gap-3">
<Avatar className="size-9">
<AvatarFallback>{initials(member.user.name)}</AvatarFallback>
</Avatar>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{member.user.name}</p>
<p className="text-muted-foreground truncate text-xs">{member.user.email}</p>
</div>
{member.role === 'owner' && <Badge variant="secondary">Propietario</Badge>}
</div>
))}
</CardContent>
</Card>
)
}
function PendingInvitationsCard({ list }: { list: ShoppingListDetail }) {
return (
<Card>
<CardHeader>
<CardTitle className="text-base">Invitaciones pendientes</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3">
{list.invitations.map((invitation) => (
<div key={invitation.id} className="flex items-center gap-3">
<div className="bg-muted text-muted-foreground flex size-9 items-center justify-center rounded-full">
<MailIcon className="size-4" />
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{invitation.email}</p>
<p className="text-muted-foreground text-xs">
Caduca el {new Date(invitation.expiresAt).toLocaleDateString('es')}
</p>
</div>
<Badge variant="outline">Pendiente</Badge>
</div>
))}
</CardContent>
</Card>
)
}

View File

@@ -0,0 +1,87 @@
import { createFileRoute } from '@tanstack/react-router'
import { PlusIcon, ShoppingCartIcon } from 'lucide-react'
import { useState } from 'react'
import { CreateListForm } from '@/components/lists/create-list-form'
import { ListCard } from '@/components/lists/list-card'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { listsQueryOptions, useLists } from '@/hooks/use-lists'
import { ApiError } from '@/lib/api-client'
export const Route = createFileRoute('/_authenticated/lists/')({
loader: ({ context }) => context.queryClient.ensureQueryData(listsQueryOptions()),
component: ListsPage,
})
function ListsPage() {
const [showCreate, setShowCreate] = useState(false)
const { data: lists, isPending, error } = useLists()
return (
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4 md:gap-6">
<div className="flex items-center justify-between gap-2">
<div>
<h1 className="text-lg font-semibold">Listas de compras</h1>
<p className="text-muted-foreground text-sm">
Tuyas y las que compartes con otras personas.
</p>
</div>
<Button size="sm" onClick={() => setShowCreate((open) => !open)} aria-expanded={showCreate}>
<PlusIcon className="size-4" />
Nueva
</Button>
</div>
{showCreate && (
<Card>
<CardContent className="p-4">
<CreateListForm onCreated={() => setShowCreate(false)} />
</CardContent>
</Card>
)}
{error ? (
<Alert variant="destructive">
<AlertTitle>No pudimos cargar tus listas</AlertTitle>
<AlertDescription>
{error instanceof ApiError
? (error.problem.detail ?? error.problem.title)
: 'Inténtalo de nuevo en unos segundos.'}
</AlertDescription>
</Alert>
) : isPending ? (
<div className="flex flex-col gap-3">
<Skeleton className="h-20 w-full" />
<Skeleton className="h-20 w-full" />
</div>
) : lists && lists.length > 0 ? (
<div className="flex flex-col gap-3">
{lists.map((list) => (
<ListCard key={list.id} list={list} />
))}
</div>
) : (
<Card>
<CardContent className="flex flex-col items-center gap-3 py-10 text-center">
<div className="bg-muted text-muted-foreground flex size-12 items-center justify-center rounded-full">
<ShoppingCartIcon className="size-6" />
</div>
<div>
<p className="font-medium">Todavía no tienes listas</p>
<p className="text-muted-foreground text-sm">
Crea tu primera lista para empezar a organizar tus compras.
</p>
</div>
<Button onClick={() => setShowCreate(true)}>
<PlusIcon className="size-4" />
Crear lista
</Button>
</CardContent>
</Card>
)}
</div>
)
}

View File

@@ -1,4 +1,4 @@
import { createFileRoute, Navigate, Outlet } from '@tanstack/react-router'
import { createFileRoute, Navigate, Outlet, useRouterState } from '@tanstack/react-router'
import { AppHeader } from '@/components/layout/app-header'
import { AppSidebar } from '@/components/layout/app-sidebar'
@@ -13,17 +13,18 @@ export const Route = createFileRoute('/_authenticated')({
/**
* Layout for every authenticated page. The session lives in BetterAuth (Hono
* API); while it resolves we render a loader, and without a session we bounce
* the user to `/sign-in`.
* the user to `/sign-in`, keeping the current URL so we can return after login.
*/
function AuthenticatedLayout() {
const { data: session, isPending } = useSession()
const href = useRouterState({ select: (state) => state.location.href })
if (isPending) {
return <SessionLoading />
}
if (!session) {
return <Navigate to="/sign-in" replace />
return <Navigate to="/sign-in" search={{ redirect: href }} replace />
}
return (

View File

@@ -16,8 +16,8 @@ export const Route = createFileRoute('/_authenticated/settings')({
})
const profileSchema = z.object({
name: z.string().min(1, 'Name is required').max(80),
email: z.email('Enter a valid email address'),
name: z.string().min(1, 'El nombre es obligatorio').max(80),
email: z.email('Introduce un correo electrónico válido'),
})
type ProfileValues = z.infer<typeof profileSchema>
@@ -38,8 +38,8 @@ function SettingsPage() {
<div className="grid max-w-3xl gap-4 md:gap-6">
<Card>
<CardHeader>
<CardTitle>Profile</CardTitle>
<CardDescription>This is how other people will see you.</CardDescription>
<CardTitle>Perfil</CardTitle>
<CardDescription>Así es como te verán las demás personas.</CardDescription>
</CardHeader>
<CardContent>
<form
@@ -50,28 +50,30 @@ function SettingsPage() {
>
<FieldGroup>
<Field data-invalid={!!form.formState.errors.name}>
<FieldLabel htmlFor="name">Name</FieldLabel>
<FieldLabel htmlFor="name">Nombre</FieldLabel>
<Input id="name" placeholder="Ada Lovelace" {...form.register('name')} />
<FieldError errors={[form.formState.errors.name]} />
</Field>
<Field data-invalid={!!form.formState.errors.email}>
<FieldLabel htmlFor="email">Email</FieldLabel>
<FieldLabel htmlFor="email">Correo electrónico</FieldLabel>
<Input
id="email"
type="email"
placeholder="ada@example.com"
placeholder="ada@ejemplo.com"
{...form.register('email')}
/>
<FieldDescription>We only use it to sign you in.</FieldDescription>
<FieldDescription>Solo lo usamos para iniciar tu sesión.</FieldDescription>
<FieldError errors={[form.formState.errors.email]} />
</Field>
<div className="flex items-center gap-4">
<Button type="submit" disabled={form.formState.isSubmitting}>
Save changes
Guardar cambios
</Button>
{saved && <span className="text-muted-foreground text-sm">Saved locally.</span>}
{saved && (
<span className="text-muted-foreground text-sm">Guardado localmente.</span>
)}
</div>
</FieldGroup>
</form>
@@ -80,13 +82,21 @@ function SettingsPage() {
<Card>
<CardHeader>
<CardTitle>Appearance</CardTitle>
<CardDescription>Notifications and display preferences.</CardDescription>
<CardTitle>Apariencia</CardTitle>
<CardDescription>Notificaciones y preferencias de visualización.</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{[
{ id: 'digest', label: 'Weekly digest', hint: 'A summary of your lists every Monday.' },
{ id: 'mentions', label: 'Mentions', hint: 'Ping me when someone mentions my name.' },
{
id: 'digest',
label: 'Resumen semanal',
hint: 'Un resumen de tus listas cada lunes.',
},
{
id: 'mentions',
label: 'Menciones',
hint: 'Avísame cuando alguien mencione mi nombre.',
},
].map((option) => (
<div key={option.id} className="flex items-center justify-between gap-4">
<div>

View File

@@ -22,17 +22,37 @@ export const Route = createFileRoute('/_authenticated/tasks')({
type Task = {
title: string
list: string
status: 'todo' | 'in progress' | 'done'
priority: 'low' | 'medium' | 'high'
status: 'pendiente' | 'en curso' | 'hecha'
priority: 'baja' | 'media' | 'alta'
}
const TASKS: Task[] = [
{ title: 'Design onboarding flow', list: 'Q4 roadmap', status: 'in progress', priority: 'high' },
{ title: 'Write API docs', list: 'Docs', status: 'todo', priority: 'medium' },
{ title: 'Review Prisma migrations', list: 'Backend', status: 'todo', priority: 'high' },
{ title: 'Ship dark mode', list: 'Design system', status: 'done', priority: 'low' },
{ title: 'Migrate to Turborepo', list: 'Infra', status: 'done', priority: 'medium' },
{ title: 'Add e2e smoke test', list: 'Quality', status: 'in progress', priority: 'low' },
{
title: 'Diseñar el flujo de registro',
list: 'Hoja de ruta Q4',
status: 'en curso',
priority: 'alta',
},
{
title: 'Escribir la documentación de la API',
list: 'Docs',
status: 'pendiente',
priority: 'media',
},
{
title: 'Revisar migraciones de Prisma',
list: 'Backend',
status: 'pendiente',
priority: 'alta',
},
{
title: 'Publicar el modo oscuro',
list: 'Sistema de diseño',
status: 'hecha',
priority: 'baja',
},
{ title: 'Migrar a Turborepo', list: 'Infra', status: 'hecha', priority: 'media' },
{ title: 'Añadir prueba e2e', list: 'Calidad', status: 'en curso', priority: 'baja' },
]
// `tableFeatures` and the columns live at module scope so row models stay stable.
@@ -40,16 +60,16 @@ const features = tableFeatures({})
const columnHelper = createColumnHelper<typeof features, Task>()
const columns = columnHelper.columns([
columnHelper.accessor('title', { header: 'Task' }),
columnHelper.accessor('list', { header: 'List' }),
columnHelper.accessor('status', { header: 'Status' }),
columnHelper.accessor('priority', { header: 'Priority' }),
columnHelper.accessor('title', { header: 'Tarea' }),
columnHelper.accessor('list', { header: 'Lista' }),
columnHelper.accessor('status', { header: 'Estado' }),
columnHelper.accessor('priority', { header: 'Prioridad' }),
])
const STATUS_VARIANT = {
todo: 'outline',
'in progress': 'secondary',
done: 'default',
pendiente: 'outline',
'en curso': 'secondary',
hecha: 'default',
} as const
function TasksPage() {
@@ -68,21 +88,21 @@ function TasksPage() {
return (
<Card>
<CardHeader>
<CardTitle>Tasks</CardTitle>
<CardDescription>Every task across your lists.</CardDescription>
<CardTitle>Tareas</CardTitle>
<CardDescription>Todas las tareas de tus listas.</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="relative max-w-sm">
<div className="relative w-full sm:max-w-sm">
<SearchIcon className="text-muted-foreground absolute top-2.5 left-2.5 size-4" />
<Input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder="Filter tasks…"
placeholder="Filtrar tareas…"
className="pl-8"
/>
</div>
<div className="rounded-md border">
<div className="overflow-x-auto rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
@@ -102,7 +122,7 @@ function TasksPage() {
colSpan={columns.length}
className="text-muted-foreground h-24 text-center"
>
No tasks match your filter.
Ninguna tarea coincide con el filtro.
</TableCell>
</TableRow>
)}

View File

@@ -0,0 +1,131 @@
import type { AcceptInvitationResult } from '@superlist/shared'
import { createFileRoute, Link } from '@tanstack/react-router'
import { CheckCircle2Icon, Loader2Icon, XCircleIcon } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { useAcceptInvitation } from '@/hooks/use-invitations'
import { ApiError } from '@/lib/api-client'
import { useSession } from '@/lib/auth-client'
export const Route = createFileRoute('/invitations/$token')({
component: AcceptInvitationPage,
})
function problemMessage(error: unknown, fallback: string) {
return error instanceof ApiError ? (error.problem.detail ?? error.problem.title) : fallback
}
function AcceptInvitationPage() {
const { token } = Route.useParams()
const { data: session, isPending } = useSession()
return (
<div className="flex min-h-svh items-center justify-center p-6">
<Card className="w-full max-w-sm">
{isPending ? (
<CardContent className="flex items-center justify-center gap-2 py-10">
<Loader2Icon className="size-4 animate-spin" />
<span className="text-muted-foreground text-sm">Cargando…</span>
</CardContent>
) : session ? (
<AcceptInvitation token={token} />
) : (
<SignedOut token={token} />
)}
</Card>
</div>
)
}
function SignedOut({ token }: { token: string }) {
const redirect = `/invitations/${token}`
return (
<>
<CardHeader>
<CardTitle>Te invitaron a una lista</CardTitle>
<CardDescription>
Inicia sesión o crea una cuenta con tu correo para unirte a la lista compartida.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<Button asChild>
<Link to="/sign-up" search={{ redirect }}>
Crear cuenta
</Link>
</Button>
<Button variant="outline" asChild>
<Link to="/sign-in" search={{ redirect }}>
Iniciar sesión
</Link>
</Button>
</CardContent>
</>
)
}
function AcceptInvitation({ token }: { token: string }) {
const { mutate } = useAcceptInvitation()
const [result, setResult] = useState<AcceptInvitationResult | null>(null)
const [error, setError] = useState<string | null>(null)
const started = useRef(false)
useEffect(() => {
if (started.current) return
started.current = true
mutate(token, {
onSuccess: (accepted) => setResult(accepted),
onError: (mutationError) =>
setError(problemMessage(mutationError, 'No pudimos aceptar la invitación.')),
})
}, [mutate, token])
if (result) {
return (
<>
<CardHeader>
<CheckCircle2Icon className="text-primary size-8" />
<CardTitle>Invitación aceptada</CardTitle>
<CardDescription>Ya formas parte de «{result.listName}».</CardDescription>
</CardHeader>
<CardContent>
<Button className="w-full" asChild>
<Link to="/lists/$listId" params={{ listId: result.listId }}>
Ir a la lista
</Link>
</Button>
</CardContent>
</>
)
}
if (error) {
return (
<>
<CardHeader>
<XCircleIcon className="text-destructive size-8" />
<CardTitle>No pudimos aceptar la invitación</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
<Button variant="outline" asChild>
<Link to="/lists">Ver mis listas</Link>
</Button>
</CardContent>
</>
)
}
return (
<CardContent className="flex items-center justify-center gap-2 py-10">
<Loader2Icon className="size-4 animate-spin" />
<span className="text-muted-foreground text-sm">Aceptando invitación…</span>
</CardContent>
)
}