add ability to move cards
This commit is contained in:
+110
-44
@@ -8,7 +8,6 @@ import {
|
||||
TouchSensor,
|
||||
closestCenter,
|
||||
pointerWithin,
|
||||
useDroppable,
|
||||
useSensor,
|
||||
useSensors,
|
||||
} from "@dnd-kit/core"
|
||||
@@ -21,13 +20,14 @@ import {
|
||||
SortableContext,
|
||||
rectSortingStrategy,
|
||||
sortableKeyboardCoordinates,
|
||||
useSortable,
|
||||
} from "@dnd-kit/sortable"
|
||||
import { Plus } from "lucide-react"
|
||||
import { GripVertical, Plus } from "lucide-react"
|
||||
import { glass } from "@/components/glass"
|
||||
import { LinkTile, TileFace } from "@/components/link-tile"
|
||||
import type { HomeLink } from "@/components/link-tile"
|
||||
import { moveLinks } from "@/lib/dashboard.functions"
|
||||
import { drop, moveOver, order } from "@/lib/layout"
|
||||
import { saveLayout } from "@/lib/dashboard.functions"
|
||||
import { drop, moveCard, moveOver, order } from "@/lib/layout"
|
||||
import { Button } from "@/vendor/collabry/components/Button/Button"
|
||||
import { cn } from "@/vendor/collabry/lib/cn"
|
||||
|
||||
@@ -39,20 +39,25 @@ type Handlers = {
|
||||
onEditCard: (card: DashCard) => void
|
||||
}
|
||||
|
||||
/** The cards with their links. Links can be dragged inside a card and between cards. */
|
||||
/**
|
||||
* The cards with their links. Links can be dragged inside a card and between cards,
|
||||
* cards by their title bar.
|
||||
*/
|
||||
export function CardGrid({
|
||||
cards: saved,
|
||||
onAddCard,
|
||||
...handlers
|
||||
}: { cards: DashCard[]; onAddCard: () => void } & Handlers) {
|
||||
const router = useRouter()
|
||||
// the layout while a link is dragged, and until the server has stored it
|
||||
// the layout while a link or a card is dragged, and until the server has stored it
|
||||
const [dragged, setDragged] = useState<DashCard[] | null>(null)
|
||||
const [activeId, setActiveId] = useState<UniqueIdentifier | null>(null)
|
||||
const drags = useRef(0)
|
||||
const cards = dragged ?? saved
|
||||
const links = cards.flatMap((c) => c.links)
|
||||
const active = links.find((l) => l.id === activeId)
|
||||
const activeCard = cards.find((c) => c.id === activeId)
|
||||
const isCard = (id: UniqueIdentifier) => cards.some((c) => c.id === id)
|
||||
|
||||
const sensors = useSensors(
|
||||
// a few pixels of slack, so a plain click still opens the link
|
||||
@@ -82,10 +87,17 @@ export function CardGrid({
|
||||
),
|
||||
})
|
||||
const cardArgs = only(cards.map((c) => c.id))
|
||||
// the keyboard has no pointer: take the nearest card then
|
||||
const hit = pointerWithin(cardArgs).at(0) ?? closestCenter(cardArgs).at(0)
|
||||
const dragsCard = isCard(args.active.id)
|
||||
// The keyboard has no pointer: take the nearest card then. A dragged card waits
|
||||
// while the pointer is between cards: the nearest one could swap it back and forth.
|
||||
const hit =
|
||||
pointerWithin(cardArgs).at(0) ??
|
||||
(dragsCard && args.pointerCoordinates
|
||||
? undefined
|
||||
: closestCenter(cardArgs).at(0))
|
||||
const card = cards.find((c) => c.id === hit?.id)
|
||||
if (!hit || !card) return []
|
||||
if (dragsCard) return [hit]
|
||||
const nearest = closestCenter(only(card.links.map((l) => l.id)))
|
||||
return nearest.length ? nearest : [hit]
|
||||
}
|
||||
@@ -97,7 +109,7 @@ export function CardGrid({
|
||||
setDragged(next)
|
||||
const drag = drags.current
|
||||
// on failure the reload below puts the links back where they were
|
||||
await moveLinks({ data: { cards: order(next) } }).catch(() => {})
|
||||
await saveLayout({ data: { cards: order(next) } }).catch(() => {})
|
||||
await router.invalidate()
|
||||
// a newer drag owns the layout by now
|
||||
if (drags.current === drag) setDragged(null)
|
||||
@@ -110,12 +122,18 @@ export function CardGrid({
|
||||
cards.find((c) => c.id === id || c.links.some((l) => l.id === id))?.name
|
||||
const announcements: Announcements = {
|
||||
onDragStart: ({ active: a }) => `Picked up ${name(a.id)}.`,
|
||||
onDragOver: ({ active: a, over }) =>
|
||||
over ? `${name(a.id)} is in ${cardName(over.id)}.` : undefined,
|
||||
onDragOver: ({ active: a, over }) => {
|
||||
if (!over || over.id === a.id) return
|
||||
return isCard(a.id)
|
||||
? `${name(a.id)} took the place of ${name(over.id)}.`
|
||||
: `${name(a.id)} is in ${cardName(over.id)}.`
|
||||
},
|
||||
onDragEnd: ({ active: a, over }) =>
|
||||
over
|
||||
? `${name(a.id)} was put down in ${cardName(over.id)}.`
|
||||
: `${name(a.id)} was put back.`,
|
||||
isCard(a.id)
|
||||
? `${name(a.id)} was put down.`
|
||||
: over
|
||||
? `${name(a.id)} was put down in ${cardName(over.id)}.`
|
||||
: `${name(a.id)} was put back.`,
|
||||
onDragCancel: ({ active: a }) => `${name(a.id)} was put back.`,
|
||||
}
|
||||
|
||||
@@ -132,7 +150,10 @@ export function CardGrid({
|
||||
setDragged(cards)
|
||||
}}
|
||||
onDragOver={({ active: a, over }) => {
|
||||
if (over) setDragged(moveOver(cards, String(a.id), String(over.id)))
|
||||
if (!over) return
|
||||
// each of the two leaves the other kind of drag alone
|
||||
const [id, overId] = [String(a.id), String(over.id)]
|
||||
setDragged(moveCard(moveOver(cards, id, overId), id, overId))
|
||||
}}
|
||||
onDragEnd={({ active: a, over }) =>
|
||||
finish(over ? drop(cards, String(a.id), String(over.id)) : cards)
|
||||
@@ -142,18 +163,22 @@ export function CardGrid({
|
||||
setDragged(null)
|
||||
}}
|
||||
>
|
||||
{/* cards in a row share a height, so their edges line up */}
|
||||
<div className="flex w-full max-w-6xl flex-wrap justify-center gap-4">
|
||||
{cards.map((card) => (
|
||||
<CardPanel
|
||||
key={card.id}
|
||||
card={card}
|
||||
// the card the dragged link would land in
|
||||
target={card.links.some((l) => l.id === activeId)}
|
||||
{...handlers}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{/* A dragged card moves in the list itself (onDragOver), so no strategy shifts
|
||||
the others: cards differ in size, and a shifted one would not fit its slot. */}
|
||||
<SortableContext items={cards.map((c) => c.id)} strategy={() => null}>
|
||||
{/* cards in a row share a height, so their edges line up */}
|
||||
<div className="flex w-full max-w-6xl flex-wrap justify-center gap-4">
|
||||
{cards.map((card) => (
|
||||
<CardPanel
|
||||
key={card.id}
|
||||
card={card}
|
||||
// the card the dragged link would land in
|
||||
target={card.links.some((l) => l.id === activeId)}
|
||||
{...handlers}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</SortableContext>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="mt-4 rounded-full text-white/60 hover:bg-white/10 hover:text-white"
|
||||
@@ -162,17 +187,46 @@ export function CardGrid({
|
||||
<Plus className="size-4" /> New card
|
||||
</Button>
|
||||
<DragOverlay>
|
||||
{active && (
|
||||
{/* one expression: an array of two empty ones would still count as a child */}
|
||||
{active ? (
|
||||
<TileFace
|
||||
link={active}
|
||||
className="cursor-grabbing rounded-2xl bg-white/15 shadow-2xl"
|
||||
/>
|
||||
) : (
|
||||
activeCard && <CardFace card={activeCard} />
|
||||
)}
|
||||
</DragOverlay>
|
||||
</DndContext>
|
||||
)
|
||||
}
|
||||
|
||||
// 6rem is a tile's width. On a narrow screen fewer columns fit: they stay
|
||||
// centered in the card, and a last row that is not full starts at the left.
|
||||
const tiles =
|
||||
"mx-auto grid max-w-full grid-cols-[repeat(auto-fill,6rem)] justify-center gap-y-2"
|
||||
/** One column per link, at most 8. An empty card is as wide as two links. */
|
||||
const tilesWidth = (card: DashCard) => ({
|
||||
width: `${(Math.min(card.links.length, 8) || 2) * 6}rem`,
|
||||
})
|
||||
|
||||
/** What follows the pointer while a card is dragged: the card without its buttons. */
|
||||
function CardFace({ card }: { card: DashCard }) {
|
||||
return (
|
||||
// the overlay is as large as the card, h-full fills it for an empty card too
|
||||
<div className={cn(glass, "h-full cursor-grabbing rounded-3xl p-2")}>
|
||||
<div className="h-10 truncate pr-3.5 pl-5 text-sm leading-10 font-bold text-white/70">
|
||||
{card.name}
|
||||
</div>
|
||||
<div style={tilesWidth(card)} className={tiles}>
|
||||
{card.links.map((link) => (
|
||||
<TileFace key={link.id} link={link} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CardPanel({
|
||||
card,
|
||||
target,
|
||||
@@ -181,11 +235,16 @@ function CardPanel({
|
||||
onEditCard,
|
||||
}: { card: DashCard; target: boolean } & Handlers) {
|
||||
const titleId = useId()
|
||||
const { setNodeRef } = useDroppable({ id: card.id })
|
||||
// one column per link, at most 8. An empty card is as wide as two links.
|
||||
const columns = Math.min(card.links.length, 8) || 2
|
||||
// `card` tells the link tiles that a card is dragged, see LinkTile
|
||||
const { setNodeRef, setActivatorNodeRef, attributes, listeners, isDragging } =
|
||||
useSortable({ id: card.id, data: { card: true } })
|
||||
const subtle =
|
||||
"rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-white/60"
|
||||
// shown on hover, always on touch
|
||||
const action = cn(
|
||||
subtle,
|
||||
"grid size-7 flex-none place-items-center text-white/70 opacity-0 transition-opacity group-hover/card:opacity-100 hover:bg-white/10 hover:text-white focus-visible:opacity-100 pointer-coarse:opacity-100"
|
||||
)
|
||||
return (
|
||||
<section
|
||||
ref={setNodeRef}
|
||||
@@ -193,11 +252,16 @@ function CardPanel({
|
||||
className={cn(
|
||||
glass,
|
||||
"group/card max-w-full rounded-3xl p-2 transition-colors",
|
||||
target && "border-white/30"
|
||||
target && "border-white/30",
|
||||
isDragging && "opacity-40"
|
||||
)}
|
||||
>
|
||||
{/* the title starts where the first icon does, the plus ends where the last one does */}
|
||||
<header className="flex h-10 min-w-48 items-center gap-2 pr-3.5 pl-5">
|
||||
{/* The title starts where the first icon does, the plus ends where the last one does.
|
||||
The whole bar drags the card. The keyboard picks it up on the grip only. */}
|
||||
<header
|
||||
{...listeners}
|
||||
className="flex h-10 min-w-48 cursor-grab touch-manipulation items-center gap-2 pr-3.5 pl-5 select-none [-webkit-touch-callout:none]"
|
||||
>
|
||||
<h2 id={titleId} className="m-0 min-w-0 text-sm">
|
||||
<button
|
||||
type="button"
|
||||
@@ -211,14 +275,21 @@ function CardPanel({
|
||||
{card.name}
|
||||
</button>
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
ref={setActivatorNodeRef}
|
||||
{...attributes}
|
||||
aria-label={`Move ${card.name}`}
|
||||
title="Drag to move this card"
|
||||
className={cn(action, "ml-auto cursor-grab")}
|
||||
>
|
||||
<GripVertical className="size-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Add a link to ${card.name}`}
|
||||
onClick={() => onAddLink(card)}
|
||||
className={cn(
|
||||
subtle,
|
||||
"ml-auto grid size-7 flex-none place-items-center text-white/70 opacity-0 transition-opacity group-hover/card:opacity-100 hover:bg-white/10 hover:text-white focus-visible:opacity-100 pointer-coarse:opacity-100"
|
||||
)}
|
||||
className={action}
|
||||
>
|
||||
<Plus className="size-4" />
|
||||
</button>
|
||||
@@ -227,12 +298,7 @@ function CardPanel({
|
||||
items={card.links.map((l) => l.id)}
|
||||
strategy={rectSortingStrategy}
|
||||
>
|
||||
{/* 6rem is a tile's width. On a narrow screen fewer columns fit: they stay
|
||||
centered in the card, and a last row that is not full starts at the left. */}
|
||||
<div
|
||||
style={{ width: `${columns * 6}rem` }}
|
||||
className="mx-auto grid max-w-full grid-cols-[repeat(auto-fill,6rem)] justify-center gap-y-2"
|
||||
>
|
||||
<div style={tilesWidth(card)} className={tiles}>
|
||||
{card.links.map((link) => (
|
||||
<LinkTile
|
||||
key={link.id}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { useDndContext } from "@dnd-kit/core"
|
||||
import { useSortable } from "@dnd-kit/sortable"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import { Pencil } from "lucide-react"
|
||||
@@ -85,6 +86,8 @@ export function LinkTile({
|
||||
link: HomeLink
|
||||
onEdit: () => void
|
||||
}) {
|
||||
// while a card is dragged, the arrow keys go from card to card, not through the links
|
||||
const cardDragged = !!useDndContext().active?.data.current?.card
|
||||
const {
|
||||
attributes,
|
||||
listeners,
|
||||
@@ -92,7 +95,7 @@ export function LinkTile({
|
||||
transform,
|
||||
transition,
|
||||
isDragging,
|
||||
} = useSortable({ id: link.id })
|
||||
} = useSortable({ id: link.id, disabled: { droppable: cardDragged } })
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
|
||||
@@ -106,6 +106,8 @@ export const card = pgTable(
|
||||
dashboardId: uuid("dashboard_id")
|
||||
.notNull()
|
||||
.references(() => dashboard.id, { onDelete: "cascade" }),
|
||||
// order on the dashboard
|
||||
position: integer("position").notNull().default(0),
|
||||
name: text("name").notNull(),
|
||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||
},
|
||||
|
||||
@@ -85,7 +85,8 @@ export const getDashboard = createServerFn({ method: "GET" })
|
||||
.select({ id: card.id, name: card.name })
|
||||
.from(card)
|
||||
.where(and(eq(card.userId, userId), eq(card.dashboardId, dashboardId)))
|
||||
.orderBy(asc(card.createdAt)),
|
||||
// cards that were never moved all have position 0: oldest first
|
||||
.orderBy(asc(card.position), asc(card.createdAt)),
|
||||
db
|
||||
.select({
|
||||
id: link.id,
|
||||
@@ -173,7 +174,13 @@ export const saveCard = createServerFn({ method: "POST" })
|
||||
.where(and(eq(card.id, id), eq(card.userId, user.id)))
|
||||
} else {
|
||||
await requireDashboard(user.id, dashboardId)
|
||||
await db.insert(card).values({ name, dashboardId, userId: user.id })
|
||||
await db.insert(card).values({
|
||||
name,
|
||||
dashboardId,
|
||||
userId: user.id,
|
||||
// after the last card of the dashboard
|
||||
position: sql`(select coalesce(max(${card.position}) + 1, 0) from ${card} where ${card.dashboardId} = ${dashboardId})`,
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
@@ -217,8 +224,8 @@ export const deleteCard = createServerFn({ method: "POST" })
|
||||
.where(and(eq(card.id, data.id), eq(card.userId, user.id)))
|
||||
})
|
||||
|
||||
/** Stores the result of a drag: for each card, its links in order. */
|
||||
export const moveLinks = createServerFn({ method: "POST" })
|
||||
/** Stores the result of a drag: the cards in order and, for each card, its links in order. */
|
||||
export const saveLayout = createServerFn({ method: "POST" })
|
||||
.validator(
|
||||
z.object({
|
||||
cards: z
|
||||
@@ -234,15 +241,20 @@ export const moveLinks = createServerFn({ method: "POST" })
|
||||
.from(card)
|
||||
.where(and(eq(card.userId, user.id), inArray(card.id, cardIds)))
|
||||
if (owned.length !== cardIds.length) throw new Error("Unknown card")
|
||||
// shortcut: one UPDATE per link, fine for a few hundred links; switch to a
|
||||
// single UPDATE ... FROM (VALUES ...) if a save gets slow
|
||||
// shortcut: one UPDATE per card and link, fine for a few hundred links; switch
|
||||
// to a single UPDATE ... FROM (VALUES ...) if a save gets slow
|
||||
await db.transaction(async (tx) => {
|
||||
for (const c of data.cards)
|
||||
for (const [at, c] of data.cards.entries()) {
|
||||
await tx
|
||||
.update(card)
|
||||
.set({ position: at })
|
||||
.where(and(eq(card.id, c.id), eq(card.userId, user.id)))
|
||||
for (const [position, id] of c.linkIds.entries())
|
||||
await tx
|
||||
.update(link)
|
||||
.set({ cardId: c.id, position })
|
||||
.where(and(eq(link.id, id), eq(link.userId, user.id)))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
+13
-1
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { drop, moveOver, order } from "./layout.ts"
|
||||
import { drop, moveCard, moveOver, order } from "./layout.ts"
|
||||
|
||||
const cards = () => [
|
||||
{ id: "apps", links: [{ id: "a" }, { id: "b" }, { id: "c" }] },
|
||||
@@ -31,6 +31,18 @@ test("a link dropped on a card goes to its end", () => {
|
||||
assert.deepEqual(ids(drop(cards(), "a", "empty")), ["bc", "x", "a"])
|
||||
})
|
||||
|
||||
test("a card takes the place of the card it is over, with its links", () => {
|
||||
assert.deepEqual(ids(moveCard(cards(), "apps", "empty")), ["x", "", "abc"])
|
||||
assert.deepEqual(ids(moveCard(cards(), "empty", "apps")), ["", "abc", "x"])
|
||||
})
|
||||
|
||||
test("a card over itself, or a link over a card, moves no card", () => {
|
||||
const before = cards()
|
||||
assert.equal(moveCard(before, "apps", "apps"), before)
|
||||
assert.equal(moveCard(before, "a", "web"), before)
|
||||
assert.equal(drop(before, "apps", "web"), before)
|
||||
})
|
||||
|
||||
test("unknown ids change nothing", () => {
|
||||
const before = cards()
|
||||
assert.equal(drop(before, "nope", "x"), before)
|
||||
|
||||
+16
-2
@@ -1,4 +1,4 @@
|
||||
// Where links sit in their cards. Pure, so drag and drop can be tested without a browser.
|
||||
// Where the cards sit, and the links in them. Pure, so drag and drop can be tested without a browser.
|
||||
|
||||
type Card = { id: string; links: { id: string }[] }
|
||||
|
||||
@@ -28,6 +28,20 @@ export function moveOver<TCard extends Card>(
|
||||
)
|
||||
}
|
||||
|
||||
/** While dragging a card: it takes the place of the card it hovers over. */
|
||||
export function moveCard<TCard extends Card>(
|
||||
cards: TCard[],
|
||||
cardId: string,
|
||||
overId: string
|
||||
): TCard[] {
|
||||
const from = cards.findIndex((c) => c.id === cardId)
|
||||
const to = cards.findIndex((c) => c.id === overId)
|
||||
if (from < 0 || to < 0 || from === to) return cards
|
||||
const next = [...cards]
|
||||
next.splice(to, 0, ...next.splice(from, 1))
|
||||
return next
|
||||
}
|
||||
|
||||
/** On drop: the link takes the place of the link it was dropped on. */
|
||||
export function drop<TCard extends Card>(
|
||||
cards: TCard[],
|
||||
@@ -45,6 +59,6 @@ export function drop<TCard extends Card>(
|
||||
return cards.map((c) => (c === card ? { ...c, links } : c))
|
||||
}
|
||||
|
||||
/** What the server stores: per card, its link ids in order. */
|
||||
/** What the server stores: the cards in order and, per card, its link ids in order. */
|
||||
export const order = (cards: Card[]) =>
|
||||
cards.map((c) => ({ id: c.id, linkIds: c.links.map((l) => l.id) }))
|
||||
|
||||
Reference in New Issue
Block a user