feat/observability #4

Merged
jselesan merged 2 commits from feat/observability into main 2026-11-25 12:28:17 +00:00
49 changed files with 2156 additions and 151 deletions
Showing only changes of commit b9c6ab92e3 - Show all commits

View File

@@ -0,0 +1,7 @@
-- AlterTable
ALTER TABLE "shopping_list_members" ADD COLUMN "icon" TEXT,
ADD COLUMN "is_pinned" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "pinned_order" INTEGER;
-- CreateIndex
CREATE INDEX "shopping_list_members_user_id_is_pinned_idx" ON "shopping_list_members"("user_id", "is_pinned");

View File

@@ -168,11 +168,18 @@ model ShoppingListMember {
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
role ListRole @default(collaborator)
isPrimary Boolean @default(false) @map("is_primary")
/// Per user: the list is pinned to the always-visible bar (at most 4 per user).
isPinned Boolean @default(false) @map("is_pinned")
/// Position among the user's pinned lists (pin order); null when not pinned.
pinnedOrder Int? @map("pinned_order")
/// Per user: key of the icon chosen for the list (see `LIST_ICONS` in `@superlist/shared`).
icon String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@unique([listId, userId])
@@index([userId, isPrimary])
@@index([userId, isPinned])
@@map("shopping_list_members")
}

View File

@@ -33,12 +33,14 @@ function createDb({
name: input.data.name,
createdAt: new Date('2026-10-15T00:00:00.000Z'),
updatedAt: new Date('2026-10-15T00:00:00.000Z'),
_count: { members: membershipsOnCreate },
_count: { members: membershipsOnCreate, items: 0 },
members: [
{
id: 'member-1',
role: 'owner',
isPrimary: input.data.members.create.isPrimary,
isPinned: false,
icon: null,
},
],
}
@@ -65,6 +67,9 @@ describe('CreateShoppingList', () => {
name: 'Compra semanal',
role: 'owner',
isPrimary: true,
isPinned: false,
icon: null,
pendingCount: 0,
memberCount: 1,
createdAt: '2026-10-15T00:00:00.000Z',
updatedAt: '2026-10-15T00:00:00.000Z',

View File

@@ -2,7 +2,7 @@ import { Ok, type ProblemDetails, type Result, type ShoppingListSummary } from '
import type { Database } from '@/lib/prisma'
import { toSummary } from '../serialize'
import { summaryCountInclude, toSummary } from '../serialize'
/** Creates a shopping list owned by the user. The first list becomes primary. */
export class CreateShoppingList {
@@ -29,7 +29,7 @@ export class CreateShoppingList {
},
},
include: {
_count: { select: { members: true } },
...summaryCountInclude,
members: { where: { userId: input.userId } },
},
})
@@ -44,6 +44,8 @@ export class CreateShoppingList {
toSummary({
role: membership.role,
isPrimary: membership.isPrimary,
isPinned: membership.isPinned,
icon: membership.icon,
list: {
id: list.id,
name: list.name,

View File

@@ -7,6 +7,7 @@ import { listEventsRoute } from './events/route'
import { getListRoute } from './get/route'
import { listItemsModule } from './items'
import { listListsRoute } from './list/route'
import { updateListPreferencesRoute } from './preferences/route'
import { setPrimaryListRoute } from './set-primary/route'
import { updateListRoute } from './update/route'
@@ -17,5 +18,6 @@ export const listsModule = new Hono<AppEnv>()
.route('/', getListRoute)
.route('/', updateListRoute)
.route('/', setPrimaryListRoute)
.route('/', updateListPreferencesRoute)
.route('/:listId/items', listItemsModule)
.route('/:listId/events', listEventsRoute)

View File

@@ -0,0 +1,60 @@
import { describe, expect, it } from 'bun:test'
import type { Database } from '@/lib/prisma'
import { ListShoppingLists } from './use-case'
describe('ListShoppingLists', () => {
it('returns the pending count and the user preferences of each list', async () => {
const queries: unknown[] = []
const db = {
shoppingListMember: {
findMany: async (args: unknown) => {
queries.push(args)
return [
{
role: 'owner',
isPrimary: false,
isPinned: true,
icon: 'unknown-icon',
list: {
id: 'list-1',
name: 'Verdulería',
createdAt: new Date('2026-11-01T00:00:00.000Z'),
updatedAt: new Date('2026-11-02T00:00:00.000Z'),
_count: { members: 1, items: 4 },
},
},
]
},
},
}
const result = await new ListShoppingLists(db as unknown as Database).execute({
userId: 'user-1',
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
expect(result.value).toEqual([
{
id: 'list-1',
name: 'Verdulería',
role: 'owner',
isPrimary: false,
isPinned: true,
icon: null,
pendingCount: 4,
memberCount: 1,
createdAt: '2026-11-01T00:00:00.000Z',
updatedAt: '2026-11-02T00:00:00.000Z',
},
])
expect(queries[0]).toMatchObject({
include: {
list: { include: { _count: { select: { items: { where: { completed: false } } } } } },
},
})
})
})

View File

@@ -2,27 +2,27 @@ import { Ok, type ProblemDetails, type Result, type ShoppingListSummary } from '
import type { Database } from '@/lib/prisma'
/** Lists every shopping list the user belongs to (owned or shared). */
import { summaryCountInclude, toSummary } from '../serialize'
/**
* Lists every shopping list the user belongs to (owned or shared): the primary
* one first, then the pinned ones in pin order, then the rest, newest first.
*/
export class ListShoppingLists {
constructor(private readonly db: Database) {}
async execute(input: { userId: string }): Promise<Result<ShoppingListSummary[], ProblemDetails>> {
const memberships = await this.db.shoppingListMember.findMany({
where: { userId: input.userId },
include: { list: { include: { _count: { select: { members: true } } } } },
orderBy: [{ isPrimary: 'desc' }, { list: { createdAt: 'desc' } }],
include: { list: { include: summaryCountInclude } },
orderBy: [
{ isPrimary: 'desc' },
{ isPinned: 'desc' },
{ pinnedOrder: { sort: 'asc', nulls: 'last' } },
{ list: { createdAt: 'desc' } },
],
})
const lists = memberships.map((membership) => ({
id: membership.list.id,
name: membership.list.name,
role: membership.role,
isPrimary: membership.isPrimary,
memberCount: membership.list._count.members,
createdAt: membership.list.createdAt.toISOString(),
updatedAt: membership.list.updatedAt.toISOString(),
}))
return Ok(lists)
return Ok(memberships.map(toSummary))
}
}

View File

@@ -0,0 +1,30 @@
import { Hono } from 'hono'
import { requireSession } from '@/lib/auth-session'
import { prisma } from '@/lib/prisma'
import { resultJson } from '@/lib/result-json'
import { validate } from '@/lib/validate'
import type { AppEnv } from '@/types'
import { ListParamsSchema } from '../schema'
import { UpdateListPreferencesSchema } from './schema'
import { UpdateListPreferences } from './use-case'
/** PATCH /lists/:listId/preferences — pins the list or changes its icon (per user). */
export const updateListPreferencesRoute = new Hono<AppEnv>().patch(
'/:listId/preferences',
requireSession,
validate.param(ListParamsSchema),
validate.json(UpdateListPreferencesSchema),
async (c) => {
const { listId } = c.req.valid('param')
const body = c.req.valid('json')
const result = await new UpdateListPreferences(prisma).execute({
listId,
userId: c.get('user').id,
...body,
})
return resultJson(c, result)
},
)

View File

@@ -0,0 +1,14 @@
import { ListIconSchema } from '@superlist/shared'
import { z } from 'zod'
/** Body of `PATCH /lists/:listId/preferences`: the user's own settings for the list. */
export const UpdateListPreferencesSchema = z
.object({
isPinned: z.boolean().optional(),
icon: ListIconSchema.nullable().optional(),
})
.refine((body) => body.isPinned !== undefined || body.icon !== undefined, {
message: 'Indica al menos una preferencia para actualizar',
})
export type UpdateListPreferencesInput = z.infer<typeof UpdateListPreferencesSchema>

View File

@@ -0,0 +1,147 @@
import { describe, expect, it } from 'bun:test'
import type { Database } from '@/lib/prisma'
import { UpdateListPreferences } from './use-case'
type Membership = {
role: 'owner' | 'collaborator'
isPrimary: boolean
isPinned: boolean
icon: string | null
}
function createDb({
membership,
pinnedCount = 0,
maxPinnedOrder = null,
}: {
membership: Membership | null
pinnedCount?: number
maxPinnedOrder?: number | null
}) {
const updates: Array<{ data: Record<string, unknown> }> = []
const tx = {
shoppingListMember: {
findUnique: async () => membership,
aggregate: async () => ({
_count: { _all: pinnedCount },
_max: { pinnedOrder: maxPinnedOrder },
}),
update: async (args: { data: Record<string, unknown> }) => {
updates.push(args)
return {
...membership,
...args.data,
list: {
id: 'list-1',
name: 'Casa de fin de semana',
createdAt: new Date('2026-11-01T00:00:00.000Z'),
updatedAt: new Date('2026-11-01T00:00:00.000Z'),
_count: { members: 2, items: 3 },
},
}
},
},
}
const db = { $transaction: async (fn: (client: typeof tx) => unknown) => fn(tx) }
return { db: db as unknown as Database, updates }
}
const collaborator: Membership = {
role: 'collaborator',
isPrimary: false,
isPinned: false,
icon: null,
}
describe('UpdateListPreferences', () => {
it('answers 404 when the user does not belong to the list', async () => {
const { db, updates } = createDb({ membership: null })
const result = await new UpdateListPreferences(db).execute({
listId: 'list-1',
userId: 'user-1',
isPinned: true,
})
expect(result.ok).toBe(false)
if (result.ok) throw new Error('expected the use case to fail')
expect(result.error.status).toBe(404)
expect(updates).toHaveLength(0)
})
it('pins the list after the last pinned one and returns its pending count', async () => {
const { db, updates } = createDb({
membership: collaborator,
pinnedCount: 2,
maxPinnedOrder: 5,
})
const result = await new UpdateListPreferences(db).execute({
listId: 'list-1',
userId: 'user-1',
isPinned: true,
icon: 'park',
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
expect(updates[0]?.data).toEqual({ isPinned: true, pinnedOrder: 6, icon: 'park' })
expect(result.value).toMatchObject({
isPinned: true,
icon: 'park',
pendingCount: 3,
memberCount: 2,
})
})
it('refuses to pin more than four lists', async () => {
const { db, updates } = createDb({
membership: collaborator,
pinnedCount: 4,
maxPinnedOrder: 4,
})
const result = await new UpdateListPreferences(db).execute({
listId: 'list-1',
userId: 'user-1',
isPinned: true,
})
expect(result.ok).toBe(false)
if (result.ok) throw new Error('expected the use case to fail')
expect(result.error.status).toBe(409)
expect(updates).toHaveLength(0)
})
it('unpins the list and clears its position', async () => {
const { db, updates } = createDb({ membership: { ...collaborator, isPinned: true } })
const result = await new UpdateListPreferences(db).execute({
listId: 'list-1',
userId: 'user-1',
isPinned: false,
})
expect(result.ok).toBe(true)
expect(updates[0]?.data).toEqual({ isPinned: false, pinnedOrder: null })
})
it('changes only the icon of an already pinned list', async () => {
const { db, updates } = createDb({
membership: { ...collaborator, isPinned: true, icon: 'carrot' },
})
const result = await new UpdateListPreferences(db).execute({
listId: 'list-1',
userId: 'user-1',
isPinned: true,
icon: null,
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
expect(updates[0]?.data).toEqual({ icon: null })
expect(result.value.icon).toBeNull()
})
})

View File

@@ -0,0 +1,76 @@
import {
Failure,
type ListIcon,
MAX_PINNED_LISTS,
Ok,
type ProblemDetails,
problems,
type Result,
type ShoppingListSummary,
} from '@superlist/shared'
import type { Database } from '@/lib/prisma'
import { summaryCountInclude, toSummary } from '../serialize'
/**
* Updates the user's own settings for a list: whether it is pinned to the
* always-visible bar and which icon it shows. Any member may do it, because
* the settings are per user (like the primary list), not shared with the list.
*/
export class UpdateListPreferences {
constructor(private readonly db: Database) {}
async execute(input: {
listId: string
userId: string
isPinned?: boolean
icon?: ListIcon | null
}): Promise<Result<ShoppingListSummary, ProblemDetails>> {
const where = { listId_userId: { listId: input.listId, userId: input.userId } }
return this.db.$transaction(async (tx) => {
const membership = await tx.shoppingListMember.findUnique({ where })
if (!membership) {
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
}
const data: { isPinned?: boolean; pinnedOrder?: number | null; icon?: ListIcon | null } = {}
if (input.icon !== undefined) data.icon = input.icon
if (input.isPinned === true && !membership.isPinned) {
const pinned = await tx.shoppingListMember.aggregate({
where: { userId: input.userId, isPinned: true },
_count: { _all: true },
_max: { pinnedOrder: true },
})
if (pinned._count._all >= MAX_PINNED_LISTS) {
return Failure(
problems.conflict(
`Puedes fijar hasta ${MAX_PINNED_LISTS} listas. Desfija otra para fijar esta.`,
),
)
}
data.isPinned = true
data.pinnedOrder = (pinned._max.pinnedOrder ?? 0) + 1
}
if (input.isPinned === false && membership.isPinned) {
data.isPinned = false
data.pinnedOrder = null
}
const updated = await tx.shoppingListMember.update({
where,
data,
include: { list: { include: summaryCountInclude } },
})
return Ok(toSummary(updated))
})
}
}

View File

@@ -1,4 +1,17 @@
import type { ListMember, ShoppingListDetail, ShoppingListSummary } from '@superlist/shared'
import {
type ListIcon,
ListIconSchema,
type ListMember,
type ShoppingListDetail,
type ShoppingListSummary,
} from '@superlist/shared'
/** Reads a stored icon key; unknown keys (e.g. one removed from the set) fall back to none. */
export function toListIcon(icon: string | null): ListIcon | null {
const parsed = ListIconSchema.safeParse(icon)
return parsed.success ? parsed.data : null
}
type ListRow = {
id: string
@@ -10,16 +23,29 @@ type ListRow = {
type MemberRow = {
role: 'owner' | 'collaborator'
isPrimary: boolean
list: ListRow & { _count: { members: number } }
isPinned: boolean
icon: string | null
list: ListRow & { _count: { members: number; items: number } }
}
/** Maps a membership (with its list and member count) to the summary DTO. */
/**
* Prisma `include` for a summary: the member count plus the pending items
* (`items` counts only the ones not bought yet).
*/
export const summaryCountInclude = {
_count: { select: { members: true, items: { where: { completed: false } } } },
} as const
/** Maps a membership (with its list, member and pending counts) to the summary DTO. */
export function toSummary(member: MemberRow): ShoppingListSummary {
return {
id: member.list.id,
name: member.list.name,
role: member.role,
isPrimary: member.isPrimary,
isPinned: member.isPinned,
icon: toListIcon(member.icon),
pendingCount: member.list._count.items,
memberCount: member.list._count.members,
createdAt: member.list.createdAt.toISOString(),
updatedAt: member.list.updatedAt.toISOString(),
@@ -29,6 +55,8 @@ export function toSummary(member: MemberRow): ShoppingListSummary {
type DetailRow = {
role: 'owner' | 'collaborator'
isPrimary: boolean
isPinned: boolean
icon: string | null
list: ListRow & {
members: Array<{
id: string
@@ -65,6 +93,8 @@ export function toDetail(member: DetailRow): ShoppingListDetail {
name: member.list.name,
role: member.role,
isPrimary: member.isPrimary,
isPinned: member.isPinned,
icon: toListIcon(member.icon),
members,
invitations: member.list.invitations.map((invitation) => ({
id: invitation.id,

View File

@@ -10,6 +10,8 @@ import {
import { type ListEvents, listEvents } from '@/lib/events'
import type { Database } from '@/lib/prisma'
import { summaryCountInclude, toSummary } from '../serialize'
/** Renames a list. Only the owner (`role: owner`) may do it. */
export class UpdateShoppingList {
constructor(
@@ -37,19 +39,11 @@ export class UpdateShoppingList {
const list = await this.db.shoppingList.update({
where: { id: input.listId },
data: { name: input.name },
include: { _count: { select: { members: true } } },
include: summaryCountInclude,
})
this.events.publish({ type: 'list.updated', listId: list.id, name: list.name })
return Ok({
id: list.id,
name: list.name,
role: membership.role,
isPrimary: membership.isPrimary,
memberCount: list._count.members,
createdAt: list.createdAt.toISOString(),
updatedAt: list.updatedAt.toISOString(),
})
return Ok(toSummary({ ...membership, list }))
}
}

View File

@@ -9,7 +9,7 @@ export function InstallPrompt() {
if (!visible) return null
return (
<div className="fixed inset-x-0 bottom-0 z-40 px-3 pb-[calc(4.75rem+env(safe-area-inset-bottom))] md:left-auto md:right-4 md:max-w-md md:px-4 md:pb-4">
<div className="fixed inset-x-0 bottom-0 z-40 px-3 pb-[calc(var(--bottom-nav-height,4.5rem)+0.25rem+env(safe-area-inset-bottom))] md:left-auto md:right-4 md:max-w-md md:px-4 md:pb-4">
<div className="bg-card shadow-lg border rounded-xl p-3 flex items-center gap-3 w-full">
<div className="bg-primary/10 text-primary rounded-lg p-2">
{needsManualInstructions ? (

View File

@@ -57,7 +57,7 @@ export function DictateFab({ listId }: DictateFabProps) {
aria-label="Dictar ítems"
aria-haspopup="dialog"
aria-expanded={open}
className="fixed right-4 bottom-[calc(4.5rem+env(safe-area-inset-bottom)+0.75rem)] z-40 size-14 rounded-full shadow-lg md:right-6 md:bottom-6"
className="fixed right-4 bottom-[calc(var(--bottom-nav-height,4.5rem)+env(safe-area-inset-bottom)+0.75rem)] z-40 size-14 rounded-full shadow-lg md:right-6 md:bottom-6"
onClick={() => {
setOpen(true)
// Called right in the click, before any state update, so the browser still

View File

@@ -3,6 +3,7 @@ import { AppLogo } from '@/components/app-logo'
import { focusNewItemInput } from '@/components/items/create-item-form'
import { isNavItemActive, NAV_ITEMS } from '@/components/layout/nav-items'
import { NavUser } from '@/components/layout/nav-user'
import { PinnedListsSidebarGroup } from '@/components/layout/pinned-lists'
import {
Sidebar,
SidebarContent,
@@ -60,6 +61,7 @@ export function AppSidebar() {
))}
</SidebarMenu>
</SidebarGroup>
<PinnedListsSidebarGroup />
</SidebarContent>
<SidebarFooter>

View File

@@ -2,6 +2,7 @@ import { Link, useRouterState } from '@tanstack/react-router'
import { focusNewItemInput } from '@/components/items/create-item-form'
import { isNavItemActive, NAV_ITEMS } from '@/components/layout/nav-items'
import { PinnedListsBar } from '@/components/layout/pinned-lists'
import { cn } from '@/lib/utils'
export function BottomNav() {
@@ -9,6 +10,7 @@ export function BottomNav() {
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)]">
<PinnedListsBar />
<nav className="mx-auto flex h-18 max-w-lg items-center justify-around px-2">
{NAV_ITEMS.map((item) => {
const active = isNavItemActive(pathname, item.to)

View File

@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query'
import { Link } from '@tanstack/react-router'
import { CheckIcon, ChevronDownIcon, ListIcon, StarIcon } from 'lucide-react'
import { ListGlyph } from '@/components/lists/list-glyph'
import {
DropdownMenu,
DropdownMenuContent,
@@ -27,12 +28,14 @@ type ListSwitcherProps = {
*/
export function ListSwitcher({ list }: ListSwitcherProps) {
const { data: lists } = useLists()
const icon = lists?.find((option) => option.id === list.id)?.icon
return (
<div className="flex min-w-0 flex-col">
<DropdownMenu>
<h1 className="flex min-w-0">
<DropdownMenuTrigger className="focus-visible:ring-ring/50 -ml-1 flex min-h-11 min-w-0 items-center gap-1 rounded-lg px-1 text-left text-xl leading-tight font-bold outline-none focus-visible:ring-3">
{icon && <ListGlyph list={{ name: list.name, icon }} className="mr-1" />}
<span className="truncate">{list.name}</span>
<ChevronDownIcon className="size-5 shrink-0" aria-hidden />
<span className="sr-only">: cambiar de lista</span>
@@ -70,6 +73,7 @@ export function ListSwitcher({ list }: ListSwitcherProps) {
function ListOption({ list, current }: { list: ShoppingListSummary; current: boolean }) {
return (
<>
<ListGlyph list={list} className="text-muted-foreground size-4" />
<span className="min-w-0 flex-1 truncate">{list.name}</span>
{list.isPrimary && <StarIcon aria-label="Principal" className="text-muted-foreground" />}
{current && <CheckIcon aria-label="Lista actual" className="text-primary" />}

View File

@@ -0,0 +1,183 @@
import type { ShoppingListSummary } from '@superlist/shared'
import { Link, useRouterState } from '@tanstack/react-router'
import { CheckIcon } from 'lucide-react'
import type { ComponentProps } from 'react'
import { ListGlyph } from '@/components/lists/list-glyph'
import {
SidebarGroup,
SidebarGroupLabel,
SidebarMenu,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
} from '@/components/ui/sidebar'
import { pickPrimaryList, useLists, usePinnedLists } from '@/hooks/use-lists'
import { usePendingCount } from '@/hooks/use-pending-count'
import { cn } from '@/lib/utils'
/** The list the current page shows: the primary one on `/`, the one in the URL under `/lists/:id`. */
function useCurrentListId(): string | undefined {
const pathname = useRouterState({ select: (state) => state.location.pathname })
const { data: lists } = useLists()
if (pathname === '/') return lists ? pickPrimaryList(lists)?.id : undefined
return /^\/lists\/([^/]+)/.exec(pathname)?.[1]
}
function pendingLabel(list: ShoppingListSummary, count: number) {
return `${list.name}: ${count === 0 ? 'nada pendiente' : `${count} ${count === 1 ? 'pendiente' : 'pendientes'}`}`
}
/** Opens a list where the app expects it: the primary one on the home page, the rest on their own page. */
function PinnedListLink({
list,
className,
children,
...props
}: ComponentProps<'a'> & { list: ShoppingListSummary }) {
return list.isPrimary ? (
<Link to="/" className={className} {...props}>
{children}
</Link>
) : (
<Link to="/lists/$listId" params={{ listId: list.id }} className={className} {...props}>
{children}
</Link>
)
}
/**
* Mobile: the pinned lists as chips above the bottom navigation, each with its
* icon and the number of items still to buy, so the other lists stay in sight
* while shopping from one. Renders nothing when no list is pinned.
*
* It is exactly 4.5rem tall (as the navigation itself), which is what the
* authenticated layout adds to `--bottom-nav-height` while lists are pinned.
*/
export function PinnedListsBar() {
const pinned = usePinnedLists()
const currentListId = useCurrentListId()
if (pinned.length === 0) return null
return (
<nav aria-label="Listas fijadas" className="mx-auto max-w-lg px-3 pt-2.5">
<ul className="bg-muted/60 flex gap-1 rounded-2xl border p-1">
{pinned.map((list) => (
<li key={list.id} className="min-w-0 flex-1">
<PinnedChip list={list} current={list.id === currentListId} />
</li>
))}
</ul>
</nav>
)
}
function PinnedChip({ list, current }: { list: ShoppingListSummary; current: boolean }) {
const count = usePendingCount(list)
return (
<PinnedListLink
list={list}
aria-current={current ? 'page' : undefined}
aria-label={pendingLabel(list, count)}
className={cn(
'relative flex h-13 flex-col items-center justify-center gap-0.5 rounded-xl px-1 text-[11px] leading-tight transition-colors',
current
? 'bg-background text-foreground font-medium shadow-xs'
: count > 0
? 'text-foreground hover:bg-background/60'
: 'text-muted-foreground hover:bg-background/60',
)}
>
<span className="relative">
<ListGlyph list={list} />
<PendingBadge count={count} current={current} className="absolute -top-1.5 left-3.5" />
</span>
<span className="w-full truncate text-center">{list.name}</span>
</PinnedListLink>
)
}
function PendingBadge({
count,
current,
className,
}: {
count: number
current: boolean
className?: string
}) {
if (count === 0) {
return (
<span
aria-hidden
className={cn(
'bg-muted text-muted-foreground flex size-4 items-center justify-center rounded-full border',
className,
)}
>
<CheckIcon className="size-2.5" />
</span>
)
}
return (
<span
aria-hidden
className={cn(
'flex h-4.5 min-w-4.5 items-center justify-center rounded-full px-1 text-[10px] font-semibold tabular-nums',
// The open list is already in front of the user; the others are the ones to remember.
current ? 'bg-primary text-primary-foreground' : 'bg-destructive text-white',
className,
)}
>
{count > 99 ? '99+' : count}
</span>
)
}
/** Desktop: the pinned lists as a sidebar group, with the pending count (a dot when collapsed). */
export function PinnedListsSidebarGroup() {
const pinned = usePinnedLists()
const currentListId = useCurrentListId()
if (pinned.length === 0) return null
return (
<SidebarGroup>
<SidebarGroupLabel>Fijadas</SidebarGroupLabel>
<SidebarMenu>
{pinned.map((list) => (
<PinnedSidebarItem key={list.id} list={list} current={list.id === currentListId} />
))}
</SidebarMenu>
</SidebarGroup>
)
}
function PinnedSidebarItem({ list, current }: { list: ShoppingListSummary; current: boolean }) {
const count = usePendingCount(list)
return (
<SidebarMenuItem>
<SidebarMenuButton asChild isActive={current} tooltip={pendingLabel(list, count)}>
<PinnedListLink list={list}>
<ListGlyph list={list} className="size-4" />
<span>{list.name}</span>
{count > 0 && !current && (
<span
aria-hidden
className="bg-destructive absolute top-1 right-1 hidden size-2 rounded-full group-data-[collapsible=icon]:block"
/>
)}
</PinnedListLink>
</SidebarMenuButton>
<SidebarMenuBadge className={cn(count > 0 && !current && 'text-destructive')}>
{count === 0 ? <CheckIcon className="size-3.5" aria-label="Nada pendiente" /> : count}
</SidebarMenuBadge>
</SidebarMenuItem>
)
}

View File

@@ -1,11 +1,13 @@
import type { ShoppingListSummary } from '@superlist/shared'
import { MAX_PINNED_LISTS } from '@superlist/shared'
import { Link } from '@tanstack/react-router'
import { SettingsIcon, StarIcon, UsersIcon } from 'lucide-react'
import { PinIcon, PinOffIcon, SettingsIcon, StarIcon, UsersIcon } from 'lucide-react'
import { ListGlyph } from '@/components/lists/list-glyph'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { useSetPrimaryList } from '@/hooks/use-lists'
import { usePinnedLists, useSetPrimaryList, useUpdateListPreferences } from '@/hooks/use-lists'
type ListCardProps = {
list: ShoppingListSummary
@@ -18,20 +20,34 @@ export function ListCard({ list }: ListCardProps) {
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
to="/lists/$listId"
params={{ listId: list.id }}
className="flex min-w-0 flex-1 items-center gap-3"
>
<span className="bg-muted text-muted-foreground flex size-10 shrink-0 items-center justify-center rounded-lg">
<ListGlyph list={list} />
</span>
<span className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate font-medium">{list.name}</span>
{list.isPrimary && <Badge>Principal</Badge>}
</div>
<div className="text-muted-foreground mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-xs whitespace-nowrap">
<span className="flex items-center gap-1">
<UsersIcon className="size-3.5" />
{list.memberCount} {list.memberCount === 1 ? 'persona' : 'personas'}
</span>
<span>{list.role === 'owner' ? 'Propietario' : 'Colaborador'}</span>
<span>
{list.pendingCount} {list.pendingCount === 1 ? 'pendiente' : 'pendientes'}
</span>
</div>
</span>
</Link>
<PinButton list={list} />
{!list.isPrimary && (
<Button
variant="ghost"
@@ -53,3 +69,24 @@ export function ListCard({ list }: ListCardProps) {
</Card>
)
}
/** Pins or unpins the list to the always-visible bar (disabled once the limit is reached). */
function PinButton({ list }: ListCardProps) {
const updatePreferences = useUpdateListPreferences(list.id)
const pinnedCount = usePinnedLists().length
const limitReached = !list.isPinned && pinnedCount >= MAX_PINNED_LISTS
return (
<Button
variant="ghost"
size="icon"
aria-pressed={list.isPinned}
aria-label={list.isPinned ? `Desfijar ${list.name}` : `Fijar ${list.name} en la barra`}
title={limitReached ? `Puedes fijar hasta ${MAX_PINNED_LISTS} listas` : undefined}
disabled={limitReached || updatePreferences.isPending}
onClick={() => updatePreferences.mutate({ isPinned: !list.isPinned })}
>
{list.isPinned ? <PinOffIcon className="size-4" /> : <PinIcon className="size-4" />}
</Button>
)
}

View File

@@ -0,0 +1,29 @@
import type { ShoppingListSummary } from '@superlist/shared'
import { LIST_ICON_OPTIONS } from '@/lib/list-icons'
import { cn } from '@/lib/utils'
type ListGlyphProps = {
list: Pick<ShoppingListSummary, 'name' | 'icon'>
className?: string
}
/** The icon the user picked for a list, or the first letter of its name when there is none. */
export function ListGlyph({ list, className }: ListGlyphProps) {
if (list.icon) {
const { icon: Icon } = LIST_ICON_OPTIONS[list.icon]
return <Icon aria-hidden className={cn('size-5 shrink-0', className)} />
}
return (
<span
aria-hidden
className={cn(
'flex size-5 shrink-0 items-center justify-center text-sm leading-none font-semibold uppercase',
className,
)}
>
{list.name.trim().charAt(0) || '?'}
</span>
)
}

View File

@@ -0,0 +1,94 @@
import { LIST_ICONS, MAX_PINNED_LISTS, type ShoppingListDetail } from '@superlist/shared'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Switch } from '@/components/ui/switch'
import { usePinnedLists, useUpdateListPreferences } from '@/hooks/use-lists'
import { ApiError } from '@/lib/api-client'
import { LIST_ICON_OPTIONS } from '@/lib/list-icons'
import { cn } from '@/lib/utils'
type ListPreferencesCardProps = {
list: Pick<ShoppingListDetail, 'id' | 'name' | 'isPinned' | 'icon'>
}
/**
* The user's own settings for a list: pin it to the always-visible bar and pick
* its icon. Every member has their own, so it is shown to collaborators too.
*/
export function ListPreferencesCard({ list }: ListPreferencesCardProps) {
const updatePreferences = useUpdateListPreferences(list.id)
const pinnedCount = usePinnedLists().length
const pinLimitReached = !list.isPinned && pinnedCount >= MAX_PINNED_LISTS
const error = updatePreferences.error
return (
<Card>
<CardHeader>
<CardTitle className="text-base">Acceso rápido</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-5">
{error && (
<Alert variant="destructive">
<AlertDescription>
{error instanceof ApiError
? (error.problem.detail ?? error.problem.title)
: 'No pudimos guardar el cambio.'}
</AlertDescription>
</Alert>
)}
<label htmlFor="pin-list" className="flex items-start gap-3">
<span className="min-w-0 flex-1">
<span className="block text-sm font-medium">Fijar en la barra</span>
<span className="text-muted-foreground block text-sm">
{pinLimitReached
? `Ya tienes ${MAX_PINNED_LISTS} listas fijadas. Desfija otra para fijar esta.`
: `Siempre visible con sus pendientes, en cualquier pantalla. Hasta ${MAX_PINNED_LISTS} listas.`}
</span>
</span>
<Switch
id="pin-list"
className="mt-1"
checked={list.isPinned}
disabled={pinLimitReached}
onCheckedChange={(checked) => updatePreferences.mutate({ isPinned: checked })}
/>
</label>
<fieldset className="flex flex-col gap-2">
<legend className="mb-2 text-sm font-medium">Ícono</legend>
<div className="grid grid-cols-6 gap-2 sm:grid-cols-9">
{LIST_ICONS.map((key) => {
const { icon: Icon, label } = LIST_ICON_OPTIONS[key]
const selected = list.icon === key
return (
<button
key={key}
type="button"
aria-pressed={selected}
aria-label={label}
title={label}
// Tapping the selected icon again clears it (back to the initial).
onClick={() => updatePreferences.mutate({ icon: selected ? null : key })}
className={cn(
'focus-visible:ring-ring/50 flex aspect-square min-h-11 items-center justify-center rounded-lg border outline-none transition-colors focus-visible:ring-3',
selected
? 'border-primary bg-primary/10 text-primary border-2'
: 'text-muted-foreground hover:bg-muted hover:text-foreground',
)}
>
<Icon className="size-5" />
</button>
)
})}
</div>
<p className="text-muted-foreground text-xs">
Sin ícono se muestra la inicial: «{list.name.trim().charAt(0).toUpperCase()}».
</p>
</fieldset>
</CardContent>
</Card>
)
}

View File

@@ -1,4 +1,8 @@
import type { ShoppingListSummary } from '@superlist/shared'
import type {
ShoppingListDetail,
ShoppingListSummary,
UpdateListPreferencesRequest,
} from '@superlist/shared'
import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { apiFetch } from '@/lib/api-client'
@@ -18,6 +22,61 @@ export function pickPrimaryList(lists: ShoppingListSummary[]): ShoppingListSumma
return lists.find((list) => list.isPrimary) ?? lists[0]
}
/** The lists pinned to the always-visible bar, in the API's order. */
export function pickPinnedLists(lists: ShoppingListSummary[]): ShoppingListSummary[] {
return lists.filter((list) => list.isPinned)
}
export function usePinnedLists(): ShoppingListSummary[] {
const { data: lists } = useLists()
return lists ? pickPinnedLists(lists) : []
}
/**
* Pins/unpins a list or changes its icon (the user's own settings). The change is
* applied to the cached lists and list detail right away and rolled back if the
* API refuses it (e.g. a fifth pinned list).
*/
export function useUpdateListPreferences(listId: string) {
const queryClient = useQueryClient()
const listsKey = listsQueryOptions().queryKey
const detailKey = ['lists', listId]
return useMutation({
mutationFn: (input: UpdateListPreferencesRequest) =>
apiFetch<ShoppingListSummary>(`/lists/${listId}/preferences`, {
method: 'PATCH',
body: JSON.stringify(input),
}),
onMutate: async (input) => {
await queryClient.cancelQueries({ queryKey: listsKey, exact: true })
await queryClient.cancelQueries({ queryKey: detailKey, exact: true })
const previousLists = queryClient.getQueryData<ShoppingListSummary[]>(listsKey)
const previousDetail = queryClient.getQueryData<ShoppingListDetail>(detailKey)
queryClient.setQueryData<ShoppingListSummary[]>(listsKey, (lists) =>
lists?.map((list) => (list.id === listId ? { ...list, ...input } : list)),
)
queryClient.setQueryData<ShoppingListDetail>(detailKey, (detail) =>
detail ? { ...detail, ...input } : detail,
)
return { previousLists, previousDetail }
},
onError: (_error, _input, context) => {
queryClient.setQueryData(listsKey, context?.previousLists)
queryClient.setQueryData(detailKey, context?.previousDetail)
},
// `exact`: only the collection and this list's detail, not every list's items.
onSettled: () =>
Promise.all([
queryClient.invalidateQueries({ queryKey: listsKey, exact: true }),
queryClient.invalidateQueries({ queryKey: detailKey, exact: true }),
]),
})
}
export function useCreateList() {
const queryClient = useQueryClient()

View File

@@ -0,0 +1,22 @@
import type { ShoppingListSummary } from '@superlist/shared'
import { useQuery } from '@tanstack/react-query'
import { itemsQueryOptions, usePendingDeletions } from '@/hooks/use-items'
import { useListEvents } from '@/hooks/use-list-events'
import { countPendingItems } from '@/lib/items'
/**
* Items still to buy in a list, kept live from any page: it reads the list's
* items (so optimistic changes and deletions waiting for undo count the same as
* on the list itself) and follows its SSE stream, shared with any other
* subscriber of that list. Until the items load it falls back to the count
* the lists endpoint returned.
*/
export function usePendingCount(list: Pick<ShoppingListSummary, 'id' | 'pendingCount'>): number {
const { data: items } = useQuery(itemsQueryOptions(list.id))
const deletingIds = usePendingDeletions()
useListEvents(list.id)
return items ? countPendingItems(items, deletingIds) : list.pendingCount
}

View File

@@ -0,0 +1,45 @@
import type { ListIcon } from '@superlist/shared'
import {
AppleIcon,
BabyIcon,
BeefIcon,
CarrotIcon,
CroissantIcon,
DogIcon,
FishIcon,
GiftIcon,
HammerIcon,
HouseIcon,
type LucideIcon,
MilkIcon,
ParkIcon,
PillIcon,
ShirtIcon,
ShoppingCartIcon,
TreesIcon,
WineIcon,
} from 'lucide-react'
/**
* The icons a list can show, in picker order. Keys come from `LIST_ICONS` in
* `@superlist/shared` (the API validates them); the labels are for screen readers.
*/
export const LIST_ICON_OPTIONS: Record<ListIcon, { icon: LucideIcon; label: string }> = {
'shopping-cart': { icon: ShoppingCartIcon, label: 'Carrito' },
carrot: { icon: CarrotIcon, label: 'Zanahoria' },
apple: { icon: AppleIcon, label: 'Manzana' },
house: { icon: HouseIcon, label: 'Casa' },
trees: { icon: TreesIcon, label: 'Árboles' },
park: { icon: ParkIcon, label: 'Parque' },
beef: { icon: BeefIcon, label: 'Carne' },
fish: { icon: FishIcon, label: 'Pescado' },
milk: { icon: MilkIcon, label: 'Leche' },
croissant: { icon: CroissantIcon, label: 'Panadería' },
wine: { icon: WineIcon, label: 'Bebidas' },
pill: { icon: PillIcon, label: 'Farmacia' },
baby: { icon: BabyIcon, label: 'Bebé' },
dog: { icon: DogIcon, label: 'Mascotas' },
shirt: { icon: ShirtIcon, label: 'Ropa' },
hammer: { icon: HammerIcon, label: 'Ferretería' },
gift: { icon: GiftIcon, label: 'Regalos' },
}

View File

@@ -6,6 +6,7 @@ import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { ListPreferencesCard } from '@/components/lists/list-preferences-card'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { Badge } from '@/components/ui/badge'
@@ -77,6 +78,8 @@ function ListSettingsPage() {
{!list.isPrimary && <SetPrimaryButton listId={list.id} />}
<ListPreferencesCard list={list} />
{list.role === 'owner' && <RenameListCard list={list} />}
{list.role === 'owner' && <InviteCollaboratorCard listId={list.id} />}

View File

@@ -1,4 +1,5 @@
import { createFileRoute, Outlet, redirect } from '@tanstack/react-router'
import type { CSSProperties } from 'react'
import { AppBadge } from '@/components/app-badge'
import { InstallPrompt } from '@/components/install-prompt'
import { AppHeader } from '@/components/layout/app-header'
@@ -6,6 +7,7 @@ import { AppSidebar } from '@/components/layout/app-sidebar'
import { BottomNav } from '@/components/layout/bottom-nav'
import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar'
import { Skeleton } from '@/components/ui/skeleton'
import { usePinnedLists } from '@/hooks/use-lists'
import { authClient, useSession } from '@/lib/auth-client'
export const Route = createFileRoute('/_authenticated')({
@@ -36,13 +38,26 @@ function AuthenticatedLayout() {
return <SessionLoading />
}
return <AuthenticatedShell />
}
/** Split from the layout so the lists query only runs once the session is known. */
function AuthenticatedShell() {
// Height of the mobile bottom navigation, which grows by the pinned lists bar.
// Everything placed above it (page padding, install prompt, dictation button)
// reads this variable instead of a fixed offset.
const hasPinnedLists = usePinnedLists().length > 0
const shellStyle = {
'--bottom-nav-height': hasPinnedLists ? '9rem' : '4.5rem',
} as CSSProperties
return (
<SidebarProvider>
<SidebarProvider style={shellStyle}>
<AppBadge />
<AppSidebar />
<SidebarInset>
<AppHeader />
<div className="flex flex-1 flex-col gap-4 p-4 pb-[calc(5rem+env(safe-area-inset-bottom))] md:gap-6 md:p-6 md:pb-6">
<div className="flex flex-1 flex-col gap-4 p-4 pb-[calc(var(--bottom-nav-height)+0.5rem+env(safe-area-inset-bottom))] md:gap-6 md:p-6 md:pb-6">
<Outlet />
</div>
<BottomNav />

View File

@@ -3,8 +3,47 @@
* and the web app consumes them, so they live here instead of being duplicated.
*/
import { z } from 'zod'
export type ListRole = 'owner' | 'collaborator'
/**
* Icons a user can give a list (keys of lucide icons). The web app maps each key
* to its component; the API only validates the key.
*/
export const LIST_ICONS = [
'shopping-cart',
'carrot',
'apple',
'house',
'trees',
'park',
'beef',
'fish',
'milk',
'croissant',
'wine',
'pill',
'baby',
'dog',
'shirt',
'hammer',
'gift',
] as const
export const ListIconSchema = z.enum(LIST_ICONS)
export type ListIcon = (typeof LIST_ICONS)[number]
/** Most lists a user can pin to the always-visible bar. */
export const MAX_PINNED_LISTS = 4
/** Body of `PATCH /lists/:listId/preferences` (per-user settings of a list). */
export type UpdateListPreferencesRequest = {
isPinned?: boolean
icon?: ListIcon | null
}
export type InvitationStatus = 'pending' | 'accepted' | 'revoked' | 'expired'
/** A member of a list, as seen in the list detail. */
@@ -26,6 +65,12 @@ export type ShoppingListSummary = {
name: string
role: ListRole
isPrimary: boolean
/** Per user: pinned to the always-visible bar. */
isPinned: boolean
/** Per user: icon chosen for the list, `null` to show its initial. */
icon: ListIcon | null
/** Items not bought yet. */
pendingCount: number
memberCount: number
createdAt: string
updatedAt: string
@@ -37,6 +82,8 @@ export type ShoppingListDetail = {
name: string
role: ListRole
isPrimary: boolean
isPinned: boolean
icon: ListIcon | null
members: ListMember[]
invitations: ListInvitation[]
createdAt: string