feat(lists): pin lists with an icon and a live pending badge

Each member can pin up to four lists and pick an icon for them (per-user
settings on shopping_list_members, PATCH /api/lists/:listId/preferences).
Pinned lists stay visible with their pending count, kept live over each
list's SSE stream: a chip bar above the bottom nav on mobile and a "Fijadas"
group in the sidebar on desktop. GET /api/lists now returns pendingCount,
isPinned and icon.

The page padding, install prompt and dictation button now read
--bottom-nav-height, which grows with the pinned bar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-11-25 09:24:13 -03:00
parent dd9cf4ce43
commit b9c6ab92e3
28 changed files with 965 additions and 49 deletions

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 }))
}
}