// 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 }[] } /** The card with this id, or the card that holds the link with this id. */ const cardOf = (cards: TCard[], id: string) => cards.find((c) => c.id === id || c.links.some((l) => l.id === id)) /** While dragging: a link that hovers over another card moves into that card. */ export function moveOver( cards: TCard[], linkId: string, overId: string ): TCard[] { const from = cardOf(cards, linkId) const to = cardOf(cards, overId) const link = from?.links.find((l) => l.id === linkId) if (!from || !to || !link || from === to) return cards // over a link: take its place. Over the card itself: go to the end. const overIndex = to.links.findIndex((l) => l.id === overId) const at = overIndex < 0 ? to.links.length : overIndex return cards.map((c) => c === from ? { ...c, links: c.links.filter((l) => l !== link) } : c === to ? { ...c, links: [...c.links.slice(0, at), link, ...c.links.slice(at)] } : c ) } /** While dragging a card: it takes the place of the card it hovers over. */ export function moveCard( 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( cards: TCard[], linkId: string, overId: string ): TCard[] { const moved = moveOver(cards, linkId, overId) if (moved !== cards) return moved // it changed cards, that put it in place const card = cardOf(cards, linkId) const from = card?.links.findIndex((l) => l.id === linkId) ?? -1 const to = card?.links.findIndex((l) => l.id === overId) ?? -1 if (!card || from < 0 || to < 0 || from === to) return cards const links = [...card.links] links.splice(to, 0, ...links.splice(from, 1)) return cards.map((c) => (c === card ? { ...c, links } : c)) } /** 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) }))