Compare commits
2 Commits
86d4796d88
...
eb1f6cb2a9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb1f6cb2a9 | ||
|
|
feb8df14c0 |
27
apps/api/src/modules/lists/items/delete/route.ts
Normal file
27
apps/api/src/modules/lists/items/delete/route.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { Hono } from 'hono'
|
||||
|
||||
import { requireSession } from '@/lib/auth-session'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { resultJson } from '@/lib/result-json'
|
||||
import { validate } from '@/lib/validate'
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
import { ItemParamsSchema } from '../update/schema'
|
||||
import { DeleteItem } from './use-case'
|
||||
|
||||
/** DELETE /lists/:listId/items/:itemId — deletes an item from a list the user belongs to. */
|
||||
export const deleteItemRoute = new Hono<AppEnv>().delete(
|
||||
'/:itemId',
|
||||
requireSession,
|
||||
validate.param(ItemParamsSchema),
|
||||
async (c) => {
|
||||
const { listId, itemId } = c.req.valid('param')
|
||||
const result = await new DeleteItem(prisma).execute({
|
||||
listId,
|
||||
itemId,
|
||||
userId: c.get('user').id,
|
||||
})
|
||||
|
||||
return resultJson(c, result, { status: 204 })
|
||||
},
|
||||
)
|
||||
75
apps/api/src/modules/lists/items/delete/use-case.test.ts
Normal file
75
apps/api/src/modules/lists/items/delete/use-case.test.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
import type { ListEvent } from '@superlist/shared'
|
||||
|
||||
import { ListEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
import { DeleteItem } from './use-case'
|
||||
|
||||
function createDb(options: { membership: unknown; item: { id: string } | null }) {
|
||||
const deletes: unknown[] = []
|
||||
|
||||
const db = {
|
||||
shoppingListMember: {
|
||||
findUnique: async () => options.membership,
|
||||
},
|
||||
listItem: {
|
||||
findFirst: async () => options.item,
|
||||
delete: async (args: unknown) => {
|
||||
deletes.push(args)
|
||||
return options.item
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return { db: db as unknown as Database, deletes }
|
||||
}
|
||||
|
||||
function createBus() {
|
||||
const events = new ListEvents()
|
||||
const published: ListEvent[] = []
|
||||
events.subscribe('list-1', (event) => published.push(event))
|
||||
|
||||
return { events, published }
|
||||
}
|
||||
|
||||
const input = { listId: 'list-1', itemId: 'item-1', userId: 'user-1' }
|
||||
|
||||
describe('DeleteItem', () => {
|
||||
it('answers 404 when the user does not belong to the list', async () => {
|
||||
const { db, deletes } = createDb({ membership: null, item: { id: 'item-1' } })
|
||||
const { events, published } = createBus()
|
||||
const result = await new DeleteItem(db, events).execute(input)
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(404)
|
||||
expect(deletes).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('answers 404 when the item does not belong to the list', async () => {
|
||||
const { db, deletes } = createDb({ membership: { role: 'owner' }, item: null })
|
||||
const { events, published } = createBus()
|
||||
const result = await new DeleteItem(db, events).execute(input)
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(404)
|
||||
expect(deletes).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('deletes the item and publishes item.removed', async () => {
|
||||
const { db, deletes } = createDb({
|
||||
membership: { role: 'collaborator' },
|
||||
item: { id: 'item-1' },
|
||||
})
|
||||
const { events, published } = createBus()
|
||||
const result = await new DeleteItem(db, events).execute(input)
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(deletes).toEqual([{ where: { id: 'item-1' } }])
|
||||
expect(published).toEqual([{ type: 'item.removed', listId: 'list-1', itemId: 'item-1' }])
|
||||
})
|
||||
})
|
||||
42
apps/api/src/modules/lists/items/delete/use-case.ts
Normal file
42
apps/api/src/modules/lists/items/delete/use-case.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { Failure, Ok, type ProblemDetails, problems, type Result } from '@superlist/shared'
|
||||
|
||||
import { type ListEvents, listEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
type DeleteItemFields = {
|
||||
listId: string
|
||||
itemId: string
|
||||
userId: string
|
||||
}
|
||||
|
||||
/** Deletes an item from a list. Only members can do it. */
|
||||
export class DeleteItem {
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly events: ListEvents = listEvents,
|
||||
) {}
|
||||
|
||||
async execute(input: DeleteItemFields): Promise<Result<void, ProblemDetails>> {
|
||||
const membership = await this.db.shoppingListMember.findUnique({
|
||||
where: { listId_userId: { listId: input.listId, userId: input.userId } },
|
||||
})
|
||||
|
||||
if (!membership) {
|
||||
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
|
||||
}
|
||||
|
||||
const item = await this.db.listItem.findFirst({
|
||||
where: { id: input.itemId, shoppingListId: input.listId },
|
||||
})
|
||||
|
||||
if (!item) {
|
||||
return Failure(problems.notFound('El artículo no existe en esta lista.'))
|
||||
}
|
||||
|
||||
await this.db.listItem.delete({ where: { id: item.id } })
|
||||
|
||||
this.events.publish({ type: 'item.removed', listId: input.listId, itemId: item.id })
|
||||
|
||||
return Ok(undefined)
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,9 @@ import { Hono } from 'hono'
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
import { createItemRoute } from './create/route'
|
||||
import { deleteItemRoute } from './delete/route'
|
||||
import { listItemsRoute } from './list/route'
|
||||
import { moveItemRoute } from './move/route'
|
||||
import { updateItemRoute } from './update/route'
|
||||
|
||||
/** `items` sub-module of `lists`: mounted at `/lists/:listId/items`. */
|
||||
@@ -11,3 +13,5 @@ export const listItemsModule = new Hono<AppEnv>()
|
||||
.route('/', listItemsRoute)
|
||||
.route('/', createItemRoute)
|
||||
.route('/', updateItemRoute)
|
||||
.route('/', moveItemRoute)
|
||||
.route('/', deleteItemRoute)
|
||||
|
||||
31
apps/api/src/modules/lists/items/move/route.ts
Normal file
31
apps/api/src/modules/lists/items/move/route.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { Hono } from 'hono'
|
||||
|
||||
import { requireSession } from '@/lib/auth-session'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { resultJson } from '@/lib/result-json'
|
||||
import { validate } from '@/lib/validate'
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
import { ItemParamsSchema } from '../update/schema'
|
||||
import { MoveItemSchema } from './schema'
|
||||
import { MoveItem } from './use-case'
|
||||
|
||||
/** POST /lists/:listId/items/:itemId/move — moves an item to another list of the user. */
|
||||
export const moveItemRoute = new Hono<AppEnv>().post(
|
||||
'/:itemId/move',
|
||||
requireSession,
|
||||
validate.param(ItemParamsSchema),
|
||||
validate.json(MoveItemSchema),
|
||||
async (c) => {
|
||||
const { listId, itemId } = c.req.valid('param')
|
||||
const { targetListId } = c.req.valid('json')
|
||||
const result = await new MoveItem(prisma).execute({
|
||||
listId,
|
||||
itemId,
|
||||
userId: c.get('user').id,
|
||||
targetListId,
|
||||
})
|
||||
|
||||
return resultJson(c, result)
|
||||
},
|
||||
)
|
||||
8
apps/api/src/modules/lists/items/move/schema.ts
Normal file
8
apps/api/src/modules/lists/items/move/schema.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
/** Body of `POST /lists/:listId/items/:itemId/move`. */
|
||||
export const MoveItemSchema = z.object({
|
||||
targetListId: z.uuid('El identificador de la lista de destino no es válido'),
|
||||
})
|
||||
|
||||
export type MoveItemInput = z.infer<typeof MoveItemSchema>
|
||||
141
apps/api/src/modules/lists/items/move/use-case.test.ts
Normal file
141
apps/api/src/modules/lists/items/move/use-case.test.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
import type { ListEvent } from '@superlist/shared'
|
||||
|
||||
import { ListEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
import { MoveItem } from './use-case'
|
||||
|
||||
type ItemRow = {
|
||||
id: string
|
||||
shoppingListId: string
|
||||
name: string
|
||||
completed: boolean
|
||||
boughtAt: Date | null
|
||||
quantity: string | null
|
||||
notes: string | null
|
||||
order: number
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
const now = new Date('2026-10-20T10:00:00.000Z')
|
||||
|
||||
const item: ItemRow = {
|
||||
id: 'item-1',
|
||||
shoppingListId: 'list-1',
|
||||
name: 'Leche',
|
||||
completed: false,
|
||||
boughtAt: null,
|
||||
quantity: '1 L',
|
||||
notes: 'sin lactosa',
|
||||
order: 0,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
|
||||
function createDb(options: { memberOf: string[]; item: ItemRow | null }) {
|
||||
const updates: unknown[] = []
|
||||
|
||||
const db = {
|
||||
shoppingListMember: {
|
||||
findUnique: async (args: { where: { listId_userId: { listId: string } } }) =>
|
||||
options.memberOf.includes(args.where.listId_userId.listId) ? { role: 'owner' } : null,
|
||||
},
|
||||
listItem: {
|
||||
findFirst: async () => options.item,
|
||||
update: async (args: { data: Partial<ItemRow> }) => {
|
||||
updates.push(args)
|
||||
return { ...options.item, ...args.data } as ItemRow
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return { db: db as unknown as Database, updates }
|
||||
}
|
||||
|
||||
function createBus() {
|
||||
const events = new ListEvents()
|
||||
const published: ListEvent[] = []
|
||||
events.subscribe('list-1', (event) => published.push(event))
|
||||
events.subscribe('list-2', (event) => published.push(event))
|
||||
|
||||
return { events, published }
|
||||
}
|
||||
|
||||
const input = { listId: 'list-1', itemId: 'item-1', userId: 'user-1', targetListId: 'list-2' }
|
||||
|
||||
describe('MoveItem', () => {
|
||||
it('answers 400 when the target is the same list', async () => {
|
||||
const { db, updates } = createDb({ memberOf: ['list-1'], item })
|
||||
const { events, published } = createBus()
|
||||
const result = await new MoveItem(db, events).execute({ ...input, targetListId: 'list-1' })
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(400)
|
||||
expect(updates).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('answers 404 when the user does not belong to the source list', async () => {
|
||||
const { db, updates } = createDb({ memberOf: ['list-2'], item })
|
||||
const { events, published } = createBus()
|
||||
const result = await new MoveItem(db, events).execute(input)
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(404)
|
||||
expect(updates).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('answers 404 when the user does not belong to the target list', async () => {
|
||||
const { db, updates } = createDb({ memberOf: ['list-1'], item })
|
||||
const { events, published } = createBus()
|
||||
const result = await new MoveItem(db, events).execute(input)
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(404)
|
||||
expect(result.error.detail).toBe('La lista de destino no existe o no tienes acceso.')
|
||||
expect(updates).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('answers 404 when the item does not belong to the source list', async () => {
|
||||
const { db, updates } = createDb({ memberOf: ['list-1', 'list-2'], item: null })
|
||||
const { events, published } = createBus()
|
||||
const result = await new MoveItem(db, events).execute(input)
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(404)
|
||||
expect(updates).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('moves the item, keeping its details, and notifies both lists', async () => {
|
||||
const { db, updates } = createDb({ memberOf: ['list-1', 'list-2'], item })
|
||||
const { events, published } = createBus()
|
||||
const result = await new MoveItem(db, events).execute(input)
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||
|
||||
expect(updates).toEqual([{ where: { id: 'item-1' }, data: { shoppingListId: 'list-2' } }])
|
||||
expect(result.value).toMatchObject({
|
||||
id: 'item-1',
|
||||
listId: 'list-2',
|
||||
name: 'Leche',
|
||||
quantity: '1 L',
|
||||
notes: 'sin lactosa',
|
||||
completed: false,
|
||||
})
|
||||
|
||||
expect(published).toEqual([
|
||||
{ type: 'item.removed', listId: 'list-1', itemId: 'item-1' },
|
||||
{ type: 'item.created', listId: 'list-2', item: result.value },
|
||||
])
|
||||
})
|
||||
})
|
||||
72
apps/api/src/modules/lists/items/move/use-case.ts
Normal file
72
apps/api/src/modules/lists/items/move/use-case.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import {
|
||||
Failure,
|
||||
type ListItem,
|
||||
Ok,
|
||||
type ProblemDetails,
|
||||
problems,
|
||||
type Result,
|
||||
} from '@superlist/shared'
|
||||
|
||||
import { type ListEvents, listEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
import { toListItem } from '../serialize'
|
||||
|
||||
type MoveItemFields = {
|
||||
listId: string
|
||||
itemId: string
|
||||
userId: string
|
||||
targetListId: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves an item to another list, keeping its name, quantity, notes and bought
|
||||
* state. The user has to be a member of both lists.
|
||||
*/
|
||||
export class MoveItem {
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly events: ListEvents = listEvents,
|
||||
) {}
|
||||
|
||||
async execute(input: MoveItemFields): Promise<Result<ListItem, ProblemDetails>> {
|
||||
if (input.targetListId === input.listId) {
|
||||
return Failure(problems.badRequest('El artículo ya está en esa lista.'))
|
||||
}
|
||||
|
||||
const membership = await this.db.shoppingListMember.findUnique({
|
||||
where: { listId_userId: { listId: input.listId, userId: input.userId } },
|
||||
})
|
||||
|
||||
if (!membership) {
|
||||
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
|
||||
}
|
||||
|
||||
const targetMembership = await this.db.shoppingListMember.findUnique({
|
||||
where: { listId_userId: { listId: input.targetListId, userId: input.userId } },
|
||||
})
|
||||
|
||||
if (!targetMembership) {
|
||||
return Failure(problems.notFound('La lista de destino no existe o no tienes acceso.'))
|
||||
}
|
||||
|
||||
const item = await this.db.listItem.findFirst({
|
||||
where: { id: input.itemId, shoppingListId: input.listId },
|
||||
})
|
||||
|
||||
if (!item) {
|
||||
return Failure(problems.notFound('El artículo no existe en esta lista.'))
|
||||
}
|
||||
|
||||
const moved = await this.db.listItem.update({
|
||||
where: { id: item.id },
|
||||
data: { shoppingListId: input.targetListId },
|
||||
})
|
||||
|
||||
const dto = toListItem(moved)
|
||||
this.events.publish({ type: 'item.removed', listId: input.listId, itemId: item.id })
|
||||
this.events.publish({ type: 'item.created', listId: input.targetListId, item: dto })
|
||||
|
||||
return Ok(dto)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ type BoughtItemListProps = {
|
||||
savingIds: string[]
|
||||
/** The editing state of each row, owned by the parent so only one row edits at a time. */
|
||||
editingProps: (itemId: string) => Pick<ItemRowProps, 'editing' | 'onEditingChange'>
|
||||
onMove: (item: ListItem) => void
|
||||
onDelete: (item: ListItem) => void
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -25,6 +27,8 @@ export function BoughtItemList({
|
||||
updateItem,
|
||||
savingIds,
|
||||
editingProps,
|
||||
onMove,
|
||||
onDelete,
|
||||
}: BoughtItemListProps) {
|
||||
return (
|
||||
<Collapsible defaultOpen asChild>
|
||||
@@ -42,6 +46,8 @@ export function BoughtItemList({
|
||||
updateItem={updateItem}
|
||||
isSaving={savingIds.includes(item.id)}
|
||||
{...editingProps(item.id)}
|
||||
onMove={() => onMove(item)}
|
||||
onDelete={() => onDelete(item)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { ShoppingBasketIcon } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useItems, usePendingItemUpdates, useUpdateItem } from '@/hooks/use-items'
|
||||
import {
|
||||
useDeleteItem,
|
||||
useItems,
|
||||
usePendingDeletions,
|
||||
usePendingItemUpdates,
|
||||
useUpdateItem,
|
||||
} from '@/hooks/use-items'
|
||||
import { useListEvents } from '@/hooks/use-list-events'
|
||||
import { useToday } from '@/hooks/use-today'
|
||||
import { ApiError } from '@/lib/api-client'
|
||||
@@ -12,6 +19,7 @@ import { splitItems } from '@/lib/items'
|
||||
|
||||
import { BoughtItemList } from './bought-item-list'
|
||||
import { ItemRow } from './item-row'
|
||||
import { MoveItemDialog } from './move-item-dialog'
|
||||
|
||||
type ItemListProps = {
|
||||
listId: string
|
||||
@@ -26,9 +34,24 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
const { data: items, isPending, error } = useItems(listId)
|
||||
const updateItem = useUpdateItem(listId)
|
||||
const savingIds = usePendingItemUpdates(listId)
|
||||
const deleteItem = useDeleteItem(listId)
|
||||
// Just-deleted items stay hidden while they can still be restored.
|
||||
const deletingIds = usePendingDeletions()
|
||||
const today = useToday()
|
||||
// Only one row shows its inline editor at a time: opening another closes it.
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
// The item whose "move to another list" dialog is open.
|
||||
const [movingItem, setMovingItem] = useState<ListItem | null>(null)
|
||||
|
||||
const handleDelete = (item: ListItem) => {
|
||||
setEditingId((current) => (current === item.id ? null : current))
|
||||
deleteItem(item)
|
||||
}
|
||||
|
||||
const openMoveDialog = (item: ListItem) => {
|
||||
setEditingId((current) => (current === item.id ? null : current))
|
||||
setMovingItem(item)
|
||||
}
|
||||
|
||||
const editingProps = (itemId: string) => ({
|
||||
editing: editingId === itemId,
|
||||
@@ -62,7 +85,10 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
)
|
||||
}
|
||||
|
||||
const { pending, boughtToday } = splitItems(items, today)
|
||||
const { pending, boughtToday } = splitItems(
|
||||
items.filter((item) => !deletingIds.has(item.id)),
|
||||
today,
|
||||
)
|
||||
|
||||
if (pending.length === 0 && boughtToday.length === 0) {
|
||||
return (
|
||||
@@ -94,6 +120,8 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
updateItem={updateItem}
|
||||
isSaving={savingIds.includes(item.id)}
|
||||
{...editingProps(item.id)}
|
||||
onMove={() => openMoveDialog(item)}
|
||||
onDelete={() => handleDelete(item)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
@@ -106,8 +134,12 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
updateItem={updateItem}
|
||||
savingIds={savingIds}
|
||||
editingProps={editingProps}
|
||||
onMove={openMoveDialog}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
)}
|
||||
|
||||
<MoveItemDialog listId={listId} item={movingItem} onClose={() => setMovingItem(null)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { CheckIcon, PencilIcon } from 'lucide-react'
|
||||
import { CheckIcon, FolderInputIcon, PencilIcon, Trash2Icon } from 'lucide-react'
|
||||
import { type PointerEvent, useRef, useState } from 'react'
|
||||
import { flushSync } from 'react-dom'
|
||||
|
||||
import { ItemEditor } from '@/components/items/item-editor'
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuTrigger,
|
||||
} from '@/components/ui/context-menu'
|
||||
import { isOptimisticItem, type useUpdateItem } from '@/hooks/use-items'
|
||||
import { quantityLabel } from '@/lib/items'
|
||||
import { cn } from '@/lib/utils'
|
||||
@@ -16,35 +23,67 @@ export type ItemRowProps = {
|
||||
/** The inline editor of this row is open (only one row edits at a time). */
|
||||
editing: boolean
|
||||
onEditingChange: (editing: boolean) => void
|
||||
/** Opens the "move to another list" dialog for this item. */
|
||||
onMove: () => void
|
||||
/** Deletes the item (it can be undone for a few seconds). */
|
||||
onDelete: () => void
|
||||
}
|
||||
|
||||
/** Horizontal drag (px) that turns a touch on the row into "edit the item". */
|
||||
const SWIPE_THRESHOLD = 48
|
||||
const EDIT_THRESHOLD = 48
|
||||
|
||||
/** Furthest the row slides while dragged, so it never leaves the card. */
|
||||
const MAX_DRAG = SWIPE_THRESHOLD * 1.5
|
||||
/** A longer drag (px) that turns it into "move the item to another list". */
|
||||
const MOVE_THRESHOLD = 120
|
||||
|
||||
/**
|
||||
* How far the row is drawn for a finger `dx` px to the left: it follows the
|
||||
* finger up to the threshold and then resists, capped at `MAX_DRAG`.
|
||||
* Drag (px) to the right that turns a touch into "delete the item". Longer than
|
||||
* the edit swipe because it is destructive (even if it can be undone).
|
||||
*/
|
||||
const DELETE_THRESHOLD = 96
|
||||
|
||||
/** What releasing the finger does, decided by how far the row was dragged. */
|
||||
type SwipeAction = 'edit' | 'move' | 'delete'
|
||||
|
||||
/**
|
||||
* How far the row is drawn for a finger `dx` px away: it follows the finger up
|
||||
* to the furthest threshold on that side and then resists, capped a bit past it
|
||||
* so the row never leaves the card. Negative is to the left.
|
||||
*/
|
||||
function dragOffset(dx: number): number {
|
||||
if (dx >= 0) return 0
|
||||
const distance = -dx
|
||||
const resisted =
|
||||
distance <= SWIPE_THRESHOLD ? distance : SWIPE_THRESHOLD + (distance - SWIPE_THRESHOLD) / 3
|
||||
const limit = dx < 0 ? MOVE_THRESHOLD : DELETE_THRESHOLD
|
||||
const distance = Math.abs(dx)
|
||||
const resisted = distance <= limit ? distance : limit + (distance - limit) / 3
|
||||
|
||||
return -Math.min(resisted, MAX_DRAG)
|
||||
return Math.sign(dx) * Math.min(resisted, limit * 1.25)
|
||||
}
|
||||
|
||||
function swipeAction(dx: number): SwipeAction | null {
|
||||
if (dx < -MOVE_THRESHOLD) return 'move'
|
||||
if (dx < -EDIT_THRESHOLD) return 'edit'
|
||||
if (dx > DELETE_THRESHOLD) return 'delete'
|
||||
return null
|
||||
}
|
||||
|
||||
/** A single item row inside a grouped card: tapping it toggles its bought state. */
|
||||
export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }: ItemRowProps) {
|
||||
export function ItemRow({
|
||||
item,
|
||||
updateItem,
|
||||
isSaving,
|
||||
editing,
|
||||
onEditingChange,
|
||||
onMove,
|
||||
onDelete,
|
||||
}: ItemRowProps) {
|
||||
const [dragX, setDragX] = useState(0)
|
||||
const swipeStart = useRef<{ x: number; y: number } | null>(null)
|
||||
// Set once a drag passes the threshold: releasing the finger then opens the
|
||||
// editor, and the click that the touch may fire right after is ignored.
|
||||
const swiped = useRef(false)
|
||||
// Set once a drag passes a threshold: releasing the finger then runs that
|
||||
// action, and the click that the touch may fire right after is ignored.
|
||||
const swiped = useRef<SwipeAction | null>(null)
|
||||
const [action, setAction] = useState<SwipeAction | null>(null)
|
||||
const quantityInputRef = useRef<HTMLInputElement>(null)
|
||||
// "Editar" was picked in the context menu: the editor's input takes the focus
|
||||
// once the menu closes, since the menu keeps it while it is open.
|
||||
const focusEditorOnMenuClose = useRef(false)
|
||||
|
||||
// A placeholder has no server id yet, so it cannot be toggled or edited.
|
||||
const editable = !isSaving && !isOptimisticItem(item)
|
||||
@@ -61,8 +100,8 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }
|
||||
}
|
||||
|
||||
const handlePointerDown = (event: PointerEvent<HTMLButtonElement>) => {
|
||||
// Mice edit through right-click; only touch drags are tracked here.
|
||||
swiped.current = false
|
||||
// Mice use the right-click menu; only touch drags are tracked here.
|
||||
swiped.current = null
|
||||
if (!editable || event.pointerType === 'mouse') return
|
||||
swipeStart.current = { x: event.clientX, y: event.clientY }
|
||||
}
|
||||
@@ -78,20 +117,25 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }
|
||||
if (!swiped.current && Math.abs(dx) <= Math.abs(dy)) return
|
||||
|
||||
setDragX(dragOffset(dx))
|
||||
swiped.current = dx < -SWIPE_THRESHOLD
|
||||
swiped.current = swipeAction(dx)
|
||||
setAction(swiped.current)
|
||||
}
|
||||
|
||||
const handlePointerUp = () => {
|
||||
const shouldOpen = swipeStart.current !== null && swiped.current
|
||||
const released = swipeStart.current !== null ? swiped.current : null
|
||||
swipeStart.current = null
|
||||
setDragX(0)
|
||||
if (shouldOpen) openEditor()
|
||||
setAction(null)
|
||||
if (released === 'edit') openEditor()
|
||||
if (released === 'move') onMove()
|
||||
if (released === 'delete') onDelete()
|
||||
}
|
||||
|
||||
const handlePointerCancel = () => {
|
||||
swipeStart.current = null
|
||||
swiped.current = false
|
||||
swiped.current = null
|
||||
setDragX(0)
|
||||
setAction(null)
|
||||
}
|
||||
|
||||
const dragging = swipeStart.current !== null && dragX !== 0
|
||||
@@ -99,15 +143,43 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }
|
||||
return (
|
||||
<li>
|
||||
<div className="relative overflow-hidden">
|
||||
{dragX !== 0 && (
|
||||
{dragX > 0 && (
|
||||
<div
|
||||
className="bg-primary/15 text-primary absolute inset-y-0 right-0 flex items-center justify-center"
|
||||
className={cn(
|
||||
'absolute inset-y-0 left-0 flex items-center justify-center transition-colors',
|
||||
// Past the threshold the background turns solid: releasing deletes.
|
||||
action === 'delete'
|
||||
? 'bg-destructive text-white'
|
||||
: 'bg-destructive/15 text-destructive',
|
||||
)}
|
||||
style={{ width: dragX }}
|
||||
aria-hidden
|
||||
>
|
||||
<Trash2Icon className="size-5" />
|
||||
</div>
|
||||
)}
|
||||
{dragX < 0 && (
|
||||
<div
|
||||
className={cn(
|
||||
'absolute inset-y-0 right-0 flex items-center justify-center transition-colors',
|
||||
// Past the move threshold the background changes, so the user
|
||||
// knows releasing now moves the item instead of editing it.
|
||||
action === 'move'
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-primary/15 text-primary',
|
||||
)}
|
||||
style={{ width: -dragX }}
|
||||
aria-hidden
|
||||
>
|
||||
{action === 'move' ? (
|
||||
<FolderInputIcon className="size-5" />
|
||||
) : (
|
||||
<PencilIcon className="size-5" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild disabled={!editable}>
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={item.completed}
|
||||
@@ -115,7 +187,7 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }
|
||||
disabled={!editable}
|
||||
onClick={() => {
|
||||
if (swiped.current) {
|
||||
swiped.current = false
|
||||
swiped.current = null
|
||||
return
|
||||
}
|
||||
|
||||
@@ -125,12 +197,6 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerUp}
|
||||
onPointerCancel={handlePointerCancel}
|
||||
// Right-click is the desktop equivalent of the swipe: edit the item.
|
||||
onContextMenu={(event) => {
|
||||
if (!editable) return
|
||||
event.preventDefault()
|
||||
openEditor()
|
||||
}}
|
||||
style={dragX !== 0 ? { transform: `translateX(${dragX}px)` } : undefined}
|
||||
className={cn(
|
||||
'bg-card hover:bg-muted/50 focus-visible:bg-muted/50 relative flex w-full cursor-pointer touch-pan-y items-center gap-4 px-4 py-3.5 text-left outline-none disabled:cursor-default disabled:opacity-60',
|
||||
@@ -164,8 +230,40 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }
|
||||
<span className="text-muted-foreground truncate text-sm">{item.notes}</span>
|
||||
)}
|
||||
</span>
|
||||
{quantity && <span className="text-muted-foreground shrink-0 text-sm">{quantity}</span>}
|
||||
{quantity && (
|
||||
<span className="text-muted-foreground shrink-0 text-sm">{quantity}</span>
|
||||
)}
|
||||
</button>
|
||||
</ContextMenuTrigger>
|
||||
{/* Right-click is the desktop equivalent of the swipes. */}
|
||||
<ContextMenuContent
|
||||
onCloseAutoFocus={(event) => {
|
||||
if (!focusEditorOnMenuClose.current) return
|
||||
focusEditorOnMenuClose.current = false
|
||||
event.preventDefault()
|
||||
quantityInputRef.current?.focus()
|
||||
}}
|
||||
>
|
||||
<ContextMenuItem
|
||||
onSelect={() => {
|
||||
focusEditorOnMenuClose.current = true
|
||||
onEditingChange(true)
|
||||
}}
|
||||
>
|
||||
<PencilIcon />
|
||||
Editar
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={onMove}>
|
||||
<FolderInputIcon />
|
||||
Mover a otra lista…
|
||||
</ContextMenuItem>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem variant="destructive" onSelect={onDelete}>
|
||||
<Trash2Icon />
|
||||
Eliminar
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
</div>
|
||||
{editing && (
|
||||
<ItemEditor
|
||||
|
||||
94
apps/web/src/components/items/move-item-dialog.tsx
Normal file
94
apps/web/src/components/items/move-item-dialog.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { ChevronRightIcon, ListIcon } from 'lucide-react'
|
||||
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useMoveItem } from '@/hooks/use-items'
|
||||
import { useLists } from '@/hooks/use-lists'
|
||||
import { ApiError } from '@/lib/api-client'
|
||||
|
||||
type MoveItemDialogProps = {
|
||||
listId: string
|
||||
/** The item being moved; `null` keeps the dialog closed. */
|
||||
item: ListItem | null
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets the user pick another of their lists for an item. Picking one moves the
|
||||
* item there and closes the dialog; the user stays on the current list.
|
||||
*/
|
||||
export function MoveItemDialog({ listId, item, onClose }: MoveItemDialogProps) {
|
||||
const { data: lists, isPending, error } = useLists()
|
||||
const moveItem = useMoveItem(listId)
|
||||
|
||||
const targets = lists?.filter((list) => list.id !== listId) ?? []
|
||||
|
||||
return (
|
||||
<Dialog open={item !== null} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Mover a otra lista</DialogTitle>
|
||||
<DialogDescription>
|
||||
{item ? `Elige a qué lista quieres mover «${item.name}».` : null}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{error ? (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>
|
||||
{error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos cargar tus listas.'}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : isPending ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Skeleton className="h-11 w-full" />
|
||||
<Skeleton className="h-11 w-full" />
|
||||
</div>
|
||||
) : targets.length === 0 ? (
|
||||
<p className="text-muted-foreground text-sm">
|
||||
No tienes otras listas.{' '}
|
||||
<Link to="/lists" className="text-primary underline-offset-4 hover:underline">
|
||||
Crea una
|
||||
</Link>{' '}
|
||||
para poder mover artículos.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="-mx-2 flex flex-col">
|
||||
{targets.map((list) => (
|
||||
<li key={list.id}>
|
||||
<button
|
||||
type="button"
|
||||
className="hover:bg-muted focus-visible:bg-muted flex w-full items-center gap-3 rounded-md px-2 py-3 text-left outline-none transition-colors"
|
||||
onClick={() => {
|
||||
if (!item) return
|
||||
moveItem.mutate({
|
||||
itemId: item.id,
|
||||
targetListId: list.id,
|
||||
targetListName: list.name,
|
||||
})
|
||||
onClose()
|
||||
}}
|
||||
>
|
||||
<ListIcon className="text-muted-foreground size-5 shrink-0" />
|
||||
<span className="min-w-0 flex-1 truncate text-base">{list.name}</span>
|
||||
<ChevronRightIcon className="text-muted-foreground size-4 shrink-0" />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
244
apps/web/src/components/ui/context-menu.tsx
Normal file
244
apps/web/src/components/ui/context-menu.tsx
Normal file
@@ -0,0 +1,244 @@
|
||||
import { cn } from 'cn'
|
||||
import { CheckIcon, ChevronRightIcon } from 'lucide-react'
|
||||
import { ContextMenu as ContextMenuPrimitive } from 'radix-ui'
|
||||
import * as React from 'react'
|
||||
|
||||
function ContextMenu({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
||||
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuTrigger({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Trigger
|
||||
data-slot="context-menu-trigger"
|
||||
className={cn('select-none', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
||||
return <ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuPortal({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
||||
return <ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuSub({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
||||
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
||||
return <ContextMenuPrimitive.RadioGroup data-slot="context-menu-radio-group" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Content> & {
|
||||
side?: 'top' | 'right' | 'bottom' | 'left'
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal>
|
||||
<ContextMenuPrimitive.Content
|
||||
data-slot="context-menu-content"
|
||||
className={cn(
|
||||
'z-50 max-h-(--radix-context-menu-content-available-height) min-w-36 origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</ContextMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = 'default',
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: 'default' | 'destructive'
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Item
|
||||
data-slot="context-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"group/context-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 focus:*:[svg]:text-accent-foreground data-[variant=destructive]:*:[svg]:text-destructive",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubTrigger
|
||||
data-slot="context-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto" />
|
||||
</ContextMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubContent
|
||||
data-slot="context-menu-sub-content"
|
||||
className={cn(
|
||||
'z-50 min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-lg border bg-popover p-1 text-popover-foreground shadow-lg duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.CheckboxItem
|
||||
data-slot="context-menu-checkbox-item"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute right-2">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioItem
|
||||
data-slot="context-menu-radio-item"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute right-2">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Label
|
||||
data-slot="context-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
'px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Separator
|
||||
data-slot="context-menu-separator"
|
||||
className={cn('-mx-1 my-1 h-px bg-border', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) {
|
||||
return (
|
||||
<span
|
||||
data-slot="context-menu-shortcut"
|
||||
className={cn(
|
||||
'ml-auto text-xs tracking-widest text-muted-foreground group-focus/context-menu-item:text-accent-foreground',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
ContextMenu,
|
||||
ContextMenuCheckboxItem,
|
||||
ContextMenuContent,
|
||||
ContextMenuGroup,
|
||||
ContextMenuItem,
|
||||
ContextMenuLabel,
|
||||
ContextMenuPortal,
|
||||
ContextMenuRadioGroup,
|
||||
ContextMenuRadioItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuShortcut,
|
||||
ContextMenuSub,
|
||||
ContextMenuSubContent,
|
||||
ContextMenuSubTrigger,
|
||||
ContextMenuTrigger,
|
||||
}
|
||||
@@ -6,10 +6,17 @@ import {
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
} from '@tanstack/react-query'
|
||||
import { useSyncExternalStore } from 'react'
|
||||
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { ApiError, apiFetch } from '@/lib/api-client'
|
||||
import {
|
||||
DELETE_UNDO_MS,
|
||||
getPendingDeletions,
|
||||
scheduleDeletion,
|
||||
subscribePendingDeletions,
|
||||
} from '@/lib/pending-deletions'
|
||||
|
||||
export const itemsQueryOptions = (listId: string) =>
|
||||
queryOptions({
|
||||
@@ -162,3 +169,94 @@ export function usePendingItemUpdates(listId: string): string[] {
|
||||
select: (mutation) => (mutation.state.variables as UpdateItemInput).itemId,
|
||||
})
|
||||
}
|
||||
|
||||
type MoveItemInput = {
|
||||
itemId: string
|
||||
targetListId: string
|
||||
/** Name of the target list, only used for the confirmation toast. */
|
||||
targetListName: string
|
||||
}
|
||||
|
||||
export function useMoveItem(listId: string) {
|
||||
const queryClient = useQueryClient()
|
||||
const { queryKey } = itemsQueryOptions(listId)
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ itemId, targetListId }: MoveItemInput) =>
|
||||
apiFetch<ListItem>(`/lists/${listId}/items/${itemId}/move`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ targetListId }),
|
||||
}),
|
||||
// The item leaves this list right away; the user stays on it.
|
||||
onMutate: async ({ itemId }) => {
|
||||
await queryClient.cancelQueries({ queryKey })
|
||||
|
||||
const items = queryClient.getQueryData(queryKey)
|
||||
const index = items?.findIndex((item) => item.id === itemId) ?? -1
|
||||
const previous = index >= 0 ? items?.[index] : undefined
|
||||
|
||||
queryClient.setQueryData(queryKey, (current) => current?.filter((item) => item.id !== itemId))
|
||||
|
||||
return { previous, index }
|
||||
},
|
||||
onSuccess: (_moved, { targetListId, targetListName }) => {
|
||||
toast.success(`Movido a «${targetListName}»`)
|
||||
return queryClient.invalidateQueries({ queryKey: itemsQueryOptions(targetListId).queryKey })
|
||||
},
|
||||
// The item goes back to where it was, so the list does not jump around.
|
||||
onError: (error, _variables, context) => {
|
||||
toast.error(
|
||||
error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos mover el artículo.',
|
||||
)
|
||||
|
||||
const previous = context?.previous
|
||||
if (!previous) return
|
||||
|
||||
queryClient.setQueryData(queryKey, (items) => {
|
||||
if (!items || items.some((item) => item.id === previous.id)) return items
|
||||
const next = [...items]
|
||||
next.splice(Math.min(context.index, next.length), 0, previous)
|
||||
return next
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** Ids of the items hidden because they were just deleted (they can still come back). */
|
||||
export function usePendingDeletions(): ReadonlySet<string> {
|
||||
return useSyncExternalStore(subscribePendingDeletions, getPendingDeletions)
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an item with a few seconds to undo it: the row disappears at once,
|
||||
* a toast offers "Deshacer" and the `DELETE` is only sent once that time is
|
||||
* over, so undoing never has to recreate anything.
|
||||
*/
|
||||
export function useDeleteItem(listId: string) {
|
||||
const queryClient = useQueryClient()
|
||||
const { queryKey } = itemsQueryOptions(listId)
|
||||
|
||||
return (item: ListItem) => {
|
||||
const undo = scheduleDeletion(item.id, async ({ keepalive }) => {
|
||||
try {
|
||||
await apiFetch<void>(`/lists/${listId}/items/${item.id}`, { method: 'DELETE', keepalive })
|
||||
queryClient.setQueryData(queryKey, (items) =>
|
||||
items?.filter((current) => current.id !== item.id),
|
||||
)
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos eliminar el artículo.',
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
toast(`«${item.name}» eliminado`, {
|
||||
duration: DELETE_UNDO_MS,
|
||||
action: { label: 'Deshacer', onClick: undo },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { QueryKey } from '@tanstack/react-query'
|
||||
export const LIST_EVENT_TYPES: readonly ListEventType[] = [
|
||||
'item.created',
|
||||
'item.updated',
|
||||
'item.removed',
|
||||
'invitation.created',
|
||||
'member.added',
|
||||
'list.updated',
|
||||
@@ -19,6 +20,7 @@ export function queryKeysForListEvent(type: ListEventType, listId: string): Quer
|
||||
switch (type) {
|
||||
case 'item.created':
|
||||
case 'item.updated':
|
||||
case 'item.removed':
|
||||
return [['lists', listId, 'items']]
|
||||
case 'invitation.created':
|
||||
case 'member.added':
|
||||
|
||||
67
apps/web/src/lib/pending-deletions.test.ts
Normal file
67
apps/web/src/lib/pending-deletions.test.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import {
|
||||
DELETE_UNDO_MS,
|
||||
flushPendingDeletions,
|
||||
getPendingDeletions,
|
||||
scheduleDeletion,
|
||||
} from './pending-deletions'
|
||||
|
||||
describe('pending deletions', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('hides the item and sends the delete once the undo window is over', async () => {
|
||||
const commit = vi.fn(async () => {})
|
||||
scheduleDeletion('item-1', commit)
|
||||
|
||||
expect(getPendingDeletions().has('item-1')).toBe(true)
|
||||
await vi.advanceTimersByTimeAsync(DELETE_UNDO_MS - 1)
|
||||
expect(commit).not.toHaveBeenCalled()
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(commit).toHaveBeenCalledWith({ keepalive: false })
|
||||
expect(getPendingDeletions().has('item-1')).toBe(false)
|
||||
})
|
||||
|
||||
it('undo restores the item and never sends the delete', async () => {
|
||||
const commit = vi.fn(async () => {})
|
||||
const undo = scheduleDeletion('item-2', commit)
|
||||
|
||||
undo()
|
||||
expect(getPendingDeletions().has('item-2')).toBe(false)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(DELETE_UNDO_MS)
|
||||
expect(commit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows the item again when the delete fails', async () => {
|
||||
const commit = vi.fn(async (_init: { keepalive: boolean }) => {
|
||||
throw new Error('offline')
|
||||
})
|
||||
scheduleDeletion('item-3', (init) => commit(init).catch(() => {}))
|
||||
|
||||
await vi.advanceTimersByTimeAsync(DELETE_UNDO_MS)
|
||||
expect(commit).toHaveBeenCalledOnce()
|
||||
expect(getPendingDeletions().has('item-3')).toBe(false)
|
||||
})
|
||||
|
||||
it('flushes waiting deletions right away with keepalive', async () => {
|
||||
const commit = vi.fn(async () => {})
|
||||
scheduleDeletion('item-4', commit)
|
||||
|
||||
flushPendingDeletions()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(commit).toHaveBeenCalledWith({ keepalive: true })
|
||||
expect(getPendingDeletions().has('item-4')).toBe(false)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(DELETE_UNDO_MS)
|
||||
expect(commit).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
90
apps/web/src/lib/pending-deletions.ts
Normal file
90
apps/web/src/lib/pending-deletions.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
/** How long a deleted item can still be restored before its `DELETE` is sent. */
|
||||
export const DELETE_UNDO_MS = 3000
|
||||
|
||||
/** Sends the `DELETE`; `keepalive` is set when the page is going away. */
|
||||
type Commit = (init: { keepalive: boolean }) => Promise<void>
|
||||
|
||||
type PendingDeletion = {
|
||||
/** Pending until the `DELETE` is sent; `undefined` once it is in flight. */
|
||||
timer: ReturnType<typeof setTimeout> | undefined
|
||||
commit: Commit
|
||||
}
|
||||
|
||||
/**
|
||||
* Items the user deleted, still hidden while they can be restored or while
|
||||
* their `DELETE` is in flight. It lives outside React so navigating away does
|
||||
* not cancel a deletion; rows are filtered out at render time, so a refetch
|
||||
* in the meantime cannot bring them back.
|
||||
*/
|
||||
const pending = new Map<string, PendingDeletion>()
|
||||
const listeners = new Set<() => void>()
|
||||
let snapshot: ReadonlySet<string> = new Set()
|
||||
|
||||
function emit() {
|
||||
snapshot = new Set(pending.keys())
|
||||
for (const listener of listeners) listener()
|
||||
}
|
||||
|
||||
/** `useSyncExternalStore` subscription. */
|
||||
export function subscribePendingDeletions(listener: () => void): () => void {
|
||||
listeners.add(listener)
|
||||
return () => listeners.delete(listener)
|
||||
}
|
||||
|
||||
/** Ids of the items hidden because they are being deleted (a stable snapshot). */
|
||||
export function getPendingDeletions(): ReadonlySet<string> {
|
||||
return snapshot
|
||||
}
|
||||
|
||||
async function run(itemId: string, keepalive: boolean) {
|
||||
const entry = pending.get(itemId)
|
||||
if (!entry) return
|
||||
|
||||
clearTimeout(entry.timer)
|
||||
entry.timer = undefined
|
||||
|
||||
try {
|
||||
await entry.commit({ keepalive })
|
||||
} finally {
|
||||
// On success the commit already dropped the item from the cache; on
|
||||
// failure the row comes back.
|
||||
pending.delete(itemId)
|
||||
emit()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hides the item and sends its `DELETE` after `DELETE_UNDO_MS`. Returns the
|
||||
* undo function, which only works while the `DELETE` has not been sent.
|
||||
*/
|
||||
export function scheduleDeletion(itemId: string, commit: Commit): () => void {
|
||||
if (!pending.has(itemId)) {
|
||||
pending.set(itemId, {
|
||||
timer: setTimeout(() => void run(itemId, false), DELETE_UNDO_MS),
|
||||
commit,
|
||||
})
|
||||
emit()
|
||||
}
|
||||
|
||||
return () => {
|
||||
const entry = pending.get(itemId)
|
||||
if (!entry?.timer) return
|
||||
|
||||
clearTimeout(entry.timer)
|
||||
pending.delete(itemId)
|
||||
emit()
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends every deletion still waiting, without waiting for the undo window. */
|
||||
export function flushPendingDeletions(): void {
|
||||
for (const [itemId, entry] of pending) {
|
||||
if (entry.timer) void run(itemId, true)
|
||||
}
|
||||
}
|
||||
|
||||
// Closing the tab or the installed app must not lose a deletion: `keepalive`
|
||||
// lets the request outlive the page.
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('pagehide', flushPendingDeletions)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import type { ListItem } from './shopping-list'
|
||||
export type ListEventType =
|
||||
| 'item.created'
|
||||
| 'item.updated'
|
||||
| 'item.removed'
|
||||
| 'invitation.created'
|
||||
| 'member.added'
|
||||
| 'list.updated'
|
||||
@@ -15,6 +16,8 @@ export type ListEventType =
|
||||
*/
|
||||
export type ListEvent =
|
||||
| { type: 'item.created' | 'item.updated'; listId: string; item: ListItem }
|
||||
/** The item left this list (it was moved to another one). */
|
||||
| { type: 'item.removed'; listId: string; itemId: string }
|
||||
| { type: 'invitation.created'; listId: string; email: string }
|
||||
| { type: 'member.added'; listId: string; userId: string }
|
||||
| { type: 'list.updated'; listId: string; name: string }
|
||||
|
||||
Reference in New Issue
Block a user