Compare commits

...

3 Commits

Author SHA1 Message Date
Jose Selesan
debf3b2728 feat(web): UI quick wins for items, navigation and settings
- Toggling an item only disables that row, so several items can be
  marked in a row; failures roll back just that item and show a toast,
  and the list refetches once the last toggle settles.
- Sidebar, bottom nav and header share one set of sections
  (Inicio / Listas / Ajustes); the bottom nav drops the duplicated
  "Cuenta" link and the header drops the non-functional search button.
- Settings: the name is saved through BetterAuth, the email is shown
  read-only, and the fake notification switches are replaced by a real
  theme picker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:52:08 -03:00
Jose Selesan
bba10361f0 feat: show list name on header 2026-10-19 12:46:40 -03:00
Jose Selesan
c374db1616 feat: Enahnce add item delay 2026-10-19 12:26:21 -03:00
15 changed files with 378 additions and 267 deletions

View File

@@ -14,6 +14,15 @@ export const auth = betterAuth({
baseURL: process.env.BETTER_AUTH_URL, baseURL: process.env.BETTER_AUTH_URL,
secret: process.env.BETTER_AUTH_SECRET, secret: process.env.BETTER_AUTH_SECRET,
trustedOrigins, 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: { emailAndPassword: {
enabled: true, enabled: true,
minPasswordLength: 8, minPasswordLength: 8,

View File

@@ -9,6 +9,7 @@ import { ItemRow } from './item-row'
type BoughtItemListProps = { type BoughtItemListProps = {
items: ListItem[] items: ListItem[]
updateItem: ReturnType<typeof useUpdateItem> updateItem: ReturnType<typeof useUpdateItem>
savingIds: string[]
} }
/** /**
@@ -16,7 +17,7 @@ type BoughtItemListProps = {
* default so marking an item visibly moves it down; the user can fold it. * default so marking an item visibly moves it down; the user can fold it.
* Tapping an item here un-buys it and it returns to the pending list. * Tapping an item here un-buys it and it returns to the pending list.
*/ */
export function BoughtItemList({ items, updateItem }: BoughtItemListProps) { export function BoughtItemList({ items, updateItem, savingIds }: BoughtItemListProps) {
return ( return (
<Collapsible defaultOpen> <Collapsible defaultOpen>
<CollapsibleTrigger className="group flex w-full items-center gap-1.5 py-1 text-left"> <CollapsibleTrigger className="group flex w-full items-center gap-1.5 py-1 text-left">
@@ -27,7 +28,12 @@ export function BoughtItemList({ items, updateItem }: BoughtItemListProps) {
<CollapsibleContent> <CollapsibleContent>
<ul className="flex flex-col gap-2 pt-2"> <ul className="flex flex-col gap-2 pt-2">
{items.map((item) => ( {items.map((item) => (
<ItemRow key={item.id} item={item} updateItem={updateItem} /> <ItemRow
key={item.id}
item={item}
updateItem={updateItem}
isSaving={savingIds.includes(item.id)}
/>
))} ))}
</ul> </ul>
</CollapsibleContent> </CollapsibleContent>

View File

@@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button'
import { Field, FieldError } from '@/components/ui/field' import { Field, FieldError } from '@/components/ui/field'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import { useCreateItem } from '@/hooks/use-items' import { useCreateItem } from '@/hooks/use-items'
import { ApiError } from '@/lib/api-client'
const createItemSchema = z.object({ const createItemSchema = z.object({
name: z.string().trim().min(1, 'Escribe un artículo').max(120, 'Máximo 120 caracteres'), name: z.string().trim().min(1, 'Escribe un artículo').max(120, 'Máximo 120 caracteres'),
@@ -34,6 +35,11 @@ const NEW_ITEM_INPUT_ID = 'new-item-input'
*/ */
export function focusNewItemInput(pathname: string): void { export function focusNewItemInput(pathname: string): void {
if (pathname !== '/') return 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() document.getElementById(NEW_ITEM_INPUT_ID)?.focus()
} }
@@ -46,8 +52,21 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
defaultValues: { name: '' }, defaultValues: { name: '' },
}) })
// The input clears at once (the item is added optimistically) so several items
// can be typed in a row; if the request fails the text comes back with the error.
const onSubmit = form.handleSubmit((values) => { const onSubmit = form.handleSubmit((values) => {
createItem.mutate(values, { onSuccess: () => form.reset() }) form.reset()
createItem.mutate(values, {
onError: (error) => {
form.setValue('name', values.name)
form.setError('name', {
message:
error instanceof ApiError
? (error.problem.detail ?? error.problem.title)
: 'No pudimos añadir el artículo.',
})
},
})
}) })
return ( return (
@@ -64,9 +83,9 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
<FieldError errors={[form.formState.errors.name]} /> <FieldError errors={[form.formState.errors.name]} />
</Field> </Field>
<Button type="submit" disabled={createItem.isPending}> <Button type="submit">
<PlusIcon /> <PlusIcon />
{createItem.isPending ? 'Agregando…' : 'Agregar'} Agregar
</Button> </Button>
</form> </form>
) )

View File

@@ -4,7 +4,7 @@ import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Card, CardContent } from '@/components/ui/card' import { Card, CardContent } from '@/components/ui/card'
import { Separator } from '@/components/ui/separator' import { Separator } from '@/components/ui/separator'
import { Skeleton } from '@/components/ui/skeleton' import { Skeleton } from '@/components/ui/skeleton'
import { useItems, useUpdateItem } from '@/hooks/use-items' import { useItems, usePendingItemUpdates, useUpdateItem } from '@/hooks/use-items'
import { useListEvents } from '@/hooks/use-list-events' import { useListEvents } from '@/hooks/use-list-events'
import { useToday } from '@/hooks/use-today' import { useToday } from '@/hooks/use-today'
import { ApiError } from '@/lib/api-client' import { ApiError } from '@/lib/api-client'
@@ -25,6 +25,7 @@ type ItemListProps = {
export function ItemList({ listId }: ItemListProps) { export function ItemList({ listId }: ItemListProps) {
const { data: items, isPending, error } = useItems(listId) const { data: items, isPending, error } = useItems(listId)
const updateItem = useUpdateItem(listId) const updateItem = useUpdateItem(listId)
const savingIds = usePendingItemUpdates(listId)
const today = useToday() const today = useToday()
// Live updates: another member adds or buys an item and this list refreshes. // Live updates: another member adds or buys an item and this list refreshes.
@@ -78,7 +79,12 @@ export function ItemList({ listId }: ItemListProps) {
{pending.length > 0 && ( {pending.length > 0 && (
<ul className="flex flex-col gap-2"> <ul className="flex flex-col gap-2">
{pending.map((item) => ( {pending.map((item) => (
<ItemRow key={item.id} item={item} updateItem={updateItem} /> <ItemRow
key={item.id}
item={item}
updateItem={updateItem}
isSaving={savingIds.includes(item.id)}
/>
))} ))}
</ul> </ul>
)} )}
@@ -86,7 +92,7 @@ export function ItemList({ listId }: ItemListProps) {
{boughtToday.length > 0 && ( {boughtToday.length > 0 && (
<> <>
{pending.length > 0 && <Separator className="mt-2" />} {pending.length > 0 && <Separator className="mt-2" />}
<BoughtItemList items={boughtToday} updateItem={updateItem} /> <BoughtItemList items={boughtToday} updateItem={updateItem} savingIds={savingIds} />
</> </>
)} )}
</div> </div>

View File

@@ -1,17 +1,20 @@
import type { ListItem } from '@superlist/shared' import type { ListItem } from '@superlist/shared'
import { CheckIcon } from 'lucide-react' import { CheckIcon } from 'lucide-react'
import { refocusNewItemInput } from '@/components/items/create-item-form'
import { Card, CardContent } from '@/components/ui/card' import { Card, CardContent } from '@/components/ui/card'
import type { useUpdateItem } from '@/hooks/use-items' import { isOptimisticItem, type useUpdateItem } from '@/hooks/use-items'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
type ItemRowProps = { type ItemRowProps = {
item: ListItem item: ListItem
updateItem: ReturnType<typeof useUpdateItem> updateItem: ReturnType<typeof useUpdateItem>
/** This item's bought state is being saved; only this row waits for it. */
isSaving: boolean
} }
/** A single item row: tapping it toggles its bought state. */ /** A single item row: tapping it toggles its bought state. */
export function ItemRow({ item, updateItem }: ItemRowProps) { export function ItemRow({ item, updateItem, isSaving }: ItemRowProps) {
return ( return (
<li> <li>
<Card> <Card>
@@ -19,8 +22,13 @@ export function ItemRow({ item, updateItem }: ItemRowProps) {
<button <button
type="button" type="button"
aria-pressed={item.completed} aria-pressed={item.completed}
disabled={updateItem.isPending} // A placeholder has no server id yet, so it cannot be toggled.
onClick={() => updateItem.mutate({ itemId: item.id, completed: !item.completed })} disabled={isSaving || isOptimisticItem(item)}
onClick={() => {
updateItem.mutate({ itemId: item.id, completed: !item.completed })
// Back to the input, so the next item can be typed right away.
refocusNewItemInput()
}}
className="flex w-full cursor-pointer items-center gap-3 p-3 text-left disabled:cursor-default disabled:opacity-60" className="flex w-full cursor-pointer items-center gap-3 p-3 text-left disabled:cursor-default disabled:opacity-60"
> >
<span <span

View File

@@ -1,41 +1,79 @@
import { useRouterState } from '@tanstack/react-router' import type { ShoppingListSummary } from '@superlist/shared'
import { SearchIcon } from 'lucide-react' import { useQuery } from '@tanstack/react-query'
import { Link, useMatch, useRouterState } from '@tanstack/react-router'
import { ArrowLeftIcon, SettingsIcon } from 'lucide-react'
import { sectionTitle } from '@/components/layout/nav-items'
import { ThemeToggle } from '@/components/theme-toggle' import { ThemeToggle } from '@/components/theme-toggle'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Separator } from '@/components/ui/separator' import { Separator } from '@/components/ui/separator'
import { SidebarTrigger } from '@/components/ui/sidebar' import { SidebarTrigger } from '@/components/ui/sidebar'
import { listQueryOptions } from '@/hooks/use-list'
import { listsQueryOptions, pickPrimaryList } from '@/hooks/use-lists'
function titleFor(pathname: string) { type HeaderList = Pick<ShoppingListSummary, 'id' | 'name' | 'role' | 'isPrimary'>
if (pathname === '/') return 'Panel'
if (pathname.startsWith('/lists')) return 'Listas'
if (pathname.startsWith('/settings')) return 'Ajustes'
return 'Superlist'
}
export function AppHeader() { export function AppHeader() {
const pathname = useRouterState({ select: (state) => state.location.pathname }) 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 ( 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"> <header className="bg-background/95 supports-[backdrop-filter]:bg-background/60 sticky top-0 z-10 flex h-16 shrink-0 items-center gap-2 border-b backdrop-blur">
<div className="flex w-full items-center gap-2 px-4"> <div className="flex w-full min-w-0 items-center gap-2 px-4">
<SidebarTrigger className="-ml-1 hidden md:inline-flex" /> <SidebarTrigger className="-ml-1 hidden md:inline-flex" />
<Separator orientation="vertical" className="mr-2 h-4" /> <Separator orientation="vertical" className="mr-2 hidden h-4 md:block" />
<h1 className="truncate text-sm font-medium">{title}</h1> {list ? (
<div className="ml-auto flex items-center gap-1"> <ListHeading list={list} showBack={Boolean(listId)} />
<button ) : (
type="button" <h1 className="truncate text-sm font-medium">{sectionTitle(pathname)}</h1>
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="ml-auto flex shrink-0 items-center gap-1">
<SearchIcon className="size-3.5" /> {list && (
Buscar <Button variant="outline" size="sm" asChild>
<kbd className="bg-muted text-muted-foreground rounded px-1.5 py-0.5 font-mono text-[10px]"> <Link to="/lists/$listId/settings" params={{ listId: list.id }}>
⌘K <SettingsIcon className="size-4" />
</kbd> <span className="hidden sm:inline">Gestionar</span>
</button> </Link>
</Button>
)}
<ThemeToggle /> <ThemeToggle />
</div> </div>
</div> </div>
</header> </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-8 shrink-0" asChild>
<Link to="/lists" aria-label="Volver a listas">
<ArrowLeftIcon className="size-4" />
</Link>
</Button>
)}
<h1 className="truncate text-sm font-medium">{list.name}</h1>
{list.isPrimary && <Badge className="shrink-0">Principal</Badge>}
<Badge variant="secondary" className="hidden shrink-0 sm:inline-flex">
{list.role === 'owner' ? 'Propietario' : 'Colaborador'}
</Badge>
</div>
)
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,15 @@
import type { ListItem } from '@superlist/shared' 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 { apiFetch } from '@/lib/api-client' import { toast } from 'sonner'
import { ApiError, apiFetch } from '@/lib/api-client'
export const itemsQueryOptions = (listId: string) => export const itemsQueryOptions = (listId: string) =>
queryOptions({ queryOptions({
@@ -13,8 +21,17 @@ export function useItems(listId: string) {
return useQuery(itemsQueryOptions(listId)) 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) { export function useCreateItem(listId: string) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const { queryKey } = itemsQueryOptions(listId)
return useMutation({ return useMutation({
mutationFn: (input: { name: string; quantity?: string; notes?: string }) => mutationFn: (input: { name: string; quantity?: string; notes?: string }) =>
@@ -22,16 +39,56 @@ export function useCreateItem(listId: string) {
method: 'POST', method: 'POST',
body: JSON.stringify(input), 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; completed: boolean }
const updateItemMutationKey = (listId: string) => ['lists', listId, 'items', 'update']
export function useUpdateItem(listId: string) { export function useUpdateItem(listId: string) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const queryKey = ['lists', listId, 'items'] const { queryKey } = itemsQueryOptions(listId)
const mutationKey = updateItemMutationKey(listId)
return useMutation({ return useMutation({
mutationFn: (input: { itemId: string; completed: boolean }) => mutationKey,
mutationFn: (input: UpdateItemInput) =>
apiFetch<ListItem>(`/lists/${listId}/items/${input.itemId}`, { apiFetch<ListItem>(`/lists/${listId}/items/${input.itemId}`, {
method: 'PATCH', method: 'PATCH',
body: JSON.stringify({ completed: input.completed }), body: JSON.stringify({ completed: input.completed }),
@@ -40,9 +97,9 @@ export function useUpdateItem(listId: string) {
// Cancel the outgoing refetch so it cannot overwrite our optimistic one. // Cancel the outgoing refetch so it cannot overwrite our optimistic one.
await queryClient.cancelQueries({ queryKey }) await queryClient.cancelQueries({ queryKey })
const previous = queryClient.getQueriesData<ListItem[]>({ queryKey }) const previous = queryClient.getQueryData(queryKey)?.find((item) => item.id === itemId)
queryClient.setQueriesData<ListItem[]>({ queryKey }, (items) => queryClient.setQueryData(queryKey, (items) =>
items?.map((item) => items?.map((item) =>
item.id === itemId item.id === itemId
? { ...item, completed, boughtAt: completed ? new Date().toISOString() : null } ? { ...item, completed, boughtAt: completed ? new Date().toISOString() : null }
@@ -52,11 +109,35 @@ export function useUpdateItem(listId: string) {
return { previous } return { previous }
}, },
onError: (_error, _variables, context) => { // Only this item is rolled back, so other toggles in flight keep their state.
context?.previous.forEach(([key, items]) => { onError: (error, _variables, context) => {
queryClient.setQueryData(key, items) toast.error(
}) error instanceof ApiError
? (error.problem.detail ?? error.problem.title)
: 'No pudimos guardar el cambio.',
)
const previous = context?.previous
if (!previous) return
queryClient.setQueryData(queryKey, (items) =>
items?.map((item) => (item.id === previous.id ? previous : item)),
)
},
// Several items can be toggled in a row: refetch once the last one settles, so an
// early refetch cannot bring back the server state of a toggle still in flight.
onSettled: () => {
if (queryClient.isMutating({ mutationKey }) === 1) {
return queryClient.invalidateQueries({ queryKey })
}
}, },
onSettled: () => queryClient.invalidateQueries({ queryKey }), })
}
/** Ids of the items of a list whose bought state is being saved right now. */
export function usePendingItemUpdates(listId: string): string[] {
return useMutationState({
filters: { mutationKey: updateItemMutationKey(listId), status: 'pending' },
select: (mutation) => (mutation.state.variables as UpdateItemInput).itemId,
}) })
} }

View File

@@ -13,6 +13,11 @@ export function useLists() {
return useQuery(listsQueryOptions()) 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() { export function useCreateList() {
const queryClient = useQueryClient() const queryClient = useQueryClient()

View File

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

View File

@@ -1,11 +1,8 @@
import { createFileRoute, Link } from '@tanstack/react-router' import { createFileRoute } from '@tanstack/react-router'
import { ArrowLeftIcon, SettingsIcon } from 'lucide-react'
import { CreateItemForm } from '@/components/items/create-item-form' import { CreateItemForm } from '@/components/items/create-item-form'
import { ItemList } from '@/components/items/item-list' import { ItemList } from '@/components/items/item-list'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert' 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 { Skeleton } from '@/components/ui/skeleton'
import { itemsQueryOptions } from '@/hooks/use-items' import { itemsQueryOptions } from '@/hooks/use-items'
import { listQueryOptions, useList } from '@/hooks/use-list' import { listQueryOptions, useList } from '@/hooks/use-list'
@@ -43,7 +40,6 @@ function ListItemsPage() {
if (isPending || !list) { if (isPending || !list) {
return ( return (
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4"> <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-10 w-full" />
<Skeleton className="h-12 w-full" /> <Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" /> <Skeleton className="h-12 w-full" />
@@ -53,31 +49,6 @@ function ListItemsPage() {
return ( return (
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4 md:gap-6"> <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 /> <CreateItemForm listId={list.id} autoFocus />
<ItemList listId={list.id} /> <ItemList listId={list.id} />

View File

@@ -1,113 +1,27 @@
import { zodResolver } from '@hookform/resolvers/zod' import { zodResolver } from '@hookform/resolvers/zod'
import { createFileRoute, useNavigate } from '@tanstack/react-router' import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useState } from 'react' import { MonitorIcon, MoonIcon, SunIcon } from 'lucide-react'
import { useForm } from 'react-hook-form' import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import { z } from 'zod' import { z } from 'zod'
import { type Theme, useTheme } from '@/components/theme-provider'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field' import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch' import { authClient, signOut, useSession } from '@/lib/auth-client'
import { signOut, useSession } from '@/lib/auth-client'
export const Route = createFileRoute('/_authenticated/settings')({ export const Route = createFileRoute('/_authenticated/settings')({
component: SettingsPage, component: SettingsPage,
}) })
const profileSchema = z.object({
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>
function SettingsPage() { function SettingsPage() {
const { data: session } = useSession()
const navigate = useNavigate() const navigate = useNavigate()
const [saved, setSaved] = useState(false)
const form = useForm<ProfileValues>({
resolver: zodResolver(profileSchema),
defaultValues: {
name: session?.user.name ?? '',
email: session?.user.email ?? '',
},
})
return ( return (
<div className="grid max-w-3xl gap-4 md:gap-6"> <div className="mx-auto grid w-full max-w-2xl gap-4 md:gap-6">
<Card> <ProfileCard />
<CardHeader> <AppearanceCard />
<CardTitle>Perfil</CardTitle>
<CardDescription>Así es como te verán las demás personas.</CardDescription>
</CardHeader>
<CardContent>
<form
onSubmit={form.handleSubmit(() => {
// Wire this to a `PATCH /users/me` feature on the API.
setSaved(true)
})}
>
<FieldGroup>
<Field data-invalid={!!form.formState.errors.name}>
<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">Correo electrónico</FieldLabel>
<Input
id="email"
type="email"
placeholder="ada@ejemplo.com"
{...form.register('email')}
/>
<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}>
Guardar cambios
</Button>
{saved && (
<span className="text-muted-foreground text-sm">Guardado localmente.</span>
)}
</div>
</FieldGroup>
</form>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Apariencia</CardTitle>
<CardDescription>Notificaciones y preferencias de visualización.</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{[
{
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>
<p className="text-sm font-medium">{option.label}</p>
<p className="text-muted-foreground text-sm">{option.hint}</p>
</div>
<Switch defaultChecked aria-label={option.label} />
</div>
))}
</CardContent>
</Card>
<Card> <Card>
<CardHeader> <CardHeader>
@@ -129,3 +43,103 @@ function SettingsPage() {
</div> </div>
) )
} }
const profileSchema = z.object({
name: z.string().trim().min(1, 'El nombre es obligatorio').max(80, 'Máximo 80 caracteres'),
})
type ProfileValues = z.infer<typeof profileSchema>
function ProfileCard() {
const { data: session } = useSession()
const form = useForm<ProfileValues>({
resolver: zodResolver(profileSchema),
defaultValues: { name: session?.user.name ?? '' },
})
const onSubmit = form.handleSubmit(async (values) => {
const { error } = await authClient.updateUser({ name: values.name })
if (error) {
toast.error(error.message ?? 'No pudimos guardar tu nombre.')
return
}
form.reset(values)
toast.success('Nombre actualizado.')
})
return (
<Card>
<CardHeader>
<CardTitle>Perfil</CardTitle>
<CardDescription>Así te ven las personas con las que compartes listas.</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={onSubmit}>
<FieldGroup>
<Field data-invalid={!!form.formState.errors.name}>
<FieldLabel htmlFor="name">Nombre</FieldLabel>
<Input id="name" autoComplete="name" {...form.register('name')} />
<FieldError errors={[form.formState.errors.name]} />
</Field>
<Field>
<FieldLabel htmlFor="email">Correo electrónico</FieldLabel>
<Input id="email" type="email" value={session?.user.email ?? ''} readOnly disabled />
<FieldDescription>
Lo usas para iniciar sesión y recibir invitaciones.
</FieldDescription>
</Field>
<Button
type="submit"
className="w-full sm:w-auto sm:self-start"
disabled={!form.formState.isDirty || form.formState.isSubmitting}
>
{form.formState.isSubmitting ? 'Guardando…' : 'Guardar cambios'}
</Button>
</FieldGroup>
</form>
</CardContent>
</Card>
)
}
const THEME_OPTIONS: { value: Theme; label: string; icon: typeof SunIcon }[] = [
{ value: 'light', label: 'Claro', icon: SunIcon },
{ value: 'dark', label: 'Oscuro', icon: MoonIcon },
{ value: 'system', label: 'Sistema', icon: MonitorIcon },
]
function AppearanceCard() {
const { theme, setTheme } = useTheme()
return (
<Card>
<CardHeader>
<CardTitle>Apariencia</CardTitle>
<CardDescription>Elige el tema de la app en este dispositivo.</CardDescription>
</CardHeader>
<CardContent>
<fieldset className="grid grid-cols-3 gap-2">
<legend className="sr-only">Tema</legend>
{THEME_OPTIONS.map((option) => (
<Button
key={option.value}
type="button"
variant={theme === option.value ? 'default' : 'outline'}
aria-pressed={theme === option.value}
onClick={() => setTheme(option.value)}
className="h-auto flex-col gap-1.5 py-3"
>
<option.icon className="size-5" />
{option.label}
</Button>
))}
</fieldset>
</CardContent>
</Card>
)
}