| 1 | import { closestCenter, type CollisionDetection, type Modifier } from "@dnd-kit/core"; |
| 2 | import { verticalListSortingStrategy, type SortingStrategy } from "@dnd-kit/sortable"; |
| 3 | import { |
| 4 | resolveSidebarDropTarget, |
| 5 | sidebarListItemId, |
| 6 | sidebarMarkerId, |
| 7 | type SidebarListItem, |
| 8 | type SidebarListMarker, |
| 9 | type SidebarSection, |
| 10 | } from "./Sidebar.logic"; |
| 11 | |
| 12 | const stationary = { x: 0, y: 0, scaleX: 1, scaleY: 1 }; |
| 13 | const hidden = { ...stationary, scaleY: 0 }; |
| 14 | type ThreadItem = Extract<SidebarListItem, { kind: "thread" }>; |
| 15 | type Layout = Parameters<SortingStrategy>[0]; |
| 16 | const isShelfHeader = (item: SidebarListItem | undefined) => |
| 17 | item?.kind === "marker" && |
| 18 | (item.marker === "working-header" || |
| 19 | item.marker === "snoozed-header" || |
| 20 | item.marker === "settled-header"); |
| 21 | |
| 22 | /** Keep the lifted card below the Pins label, including when Pins is empty. |
| 23 | * The container rect follows scrolling; the offset is measured once at pickup. */ |
| 24 | export function restrictBelowSidebarLabel( |
| 25 | { transform, containerNodeRect, draggingNodeRect }: Parameters<Modifier>[0], |
| 26 | offset: number, |
| 27 | ) { |
| 28 | if (!containerNodeRect || !draggingNodeRect) return transform; |
| 29 | const minimumY = containerNodeRect.top + offset - draggingNodeRect.top; |
| 30 | return transform.y < minimumY ? { ...transform, y: minimumY } : transform; |
| 31 | } |
| 32 | |
| 33 | /** Reject the nearest unsupported target without selecting another section. |
| 34 | * Recreate this detector when drop eligibility changes. */ |
| 35 | export function createSidebarCollisionDetection( |
| 36 | isValidTarget: (id: string) => boolean, |
| 37 | options: { |
| 38 | items?: readonly SidebarListItem[]; |
| 39 | activationY?: number | null; |
| 40 | } = {}, |
| 41 | ): CollisionDetection { |
| 42 | const validity = new Map<string, boolean>(); |
| 43 | const sections = new Map<string, SidebarSection | null>(); |
| 44 | let previousPointerY = options.activationY; |
| 45 | let boundarySection: "pinned" | "active" | undefined; |
| 46 | return (args) => { |
| 47 | let collisions = closestCenter(args); |
| 48 | const pointer = args.pointerCoordinates; |
| 49 | const items = options.items; |
| 50 | const source = items?.find((item) => item.kind === "thread" && item.key === args.active.id); |
| 51 | const boundary = args.droppableContainers |
| 52 | .find((container) => container.id === sidebarMarkerId("pinned-divider")) |
| 53 | ?.node.current?.querySelector(".sidebar-drag-boundary-label") |
| 54 | ?.getBoundingClientRect(); |
| 55 | if (items && boundary && source?.kind === "thread" && pointer) { |
| 56 | boundarySection ??= source.section === "pinned" ? "pinned" : "active"; |
| 57 | // Use the visible divider row, including its sortable translation. |
| 58 | // Only pointer movement can change sections: opening the destination |
| 59 | // moves this row, but must not toggle a stationary gesture back. |
| 60 | const previousY = previousPointerY ?? pointer.y; |
| 61 | previousPointerY = pointer.y; |
| 62 | if (pointer.x >= boundary.left && pointer.x <= boundary.right) { |
| 63 | if (pointer.y < previousY && pointer.y <= boundary.bottom) boundarySection = "pinned"; |
| 64 | else if (pointer.y > previousY && pointer.y >= boundary.top) boundarySection = "active"; |
| 65 | const nextHeader = (["working-header", "snoozed-header", "settled-header"] as const) |
| 66 | .map((marker) => |
| 67 | args.droppableContainers.find((container) => container.id === sidebarMarkerId(marker)), |
| 68 | ) |
| 69 | .find((container) => container !== undefined); |
| 70 | const activeBottom = nextHeader?.node.current?.getBoundingClientRect().top; |
| 71 | if (boundarySection === "pinned" || (activeBottom != null && pointer.y < activeBottom)) { |
| 72 | const target = collisions.find((collision) => { |
| 73 | const id = String(collision.id); |
| 74 | if (!sections.has(id)) { |
| 75 | sections.set( |
| 76 | id, |
| 77 | resolveSidebarDropTarget(items, String(args.active.id), id)?.section ?? null, |
| 78 | ); |
| 79 | } |
| 80 | return sections.get(id) === boundarySection; |
| 81 | }); |
| 82 | if (target) |
| 83 | collisions = [target, ...collisions.filter((collision) => collision !== target)]; |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | const nearest = collisions[0]; |
| 88 | if (!nearest || nearest.id === args.active.id) { |
| 89 | return collisions; |
| 90 | } |
| 91 | const id = String(nearest.id); |
| 92 | const valid = validity.get(id) ?? isValidTarget(id); |
| 93 | validity.set(id, valid); |
| 94 | return valid ? collisions : collisions.filter((collision) => collision.id === args.active.id); |
| 95 | }; |
| 96 | } |
| 97 | |
| 98 | /** Preview the committed section layout without moving or mounting DOM nodes. |
| 99 | * A zero scaleY marks rows/markers to hide while retaining their measured nodes. */ |
| 100 | export function createSidebarSortingStrategy(input: { |
| 101 | items: readonly SidebarListItem[]; |
| 102 | /** Suspend the reorder preview while the thread is dragged out as context. */ |
| 103 | enabled?: boolean; |
| 104 | settledOrder: readonly string[]; |
| 105 | /** Time-ordered inbox (Working beta): where the lifted row would land. */ |
| 106 | activeOrder?: readonly string[]; |
| 107 | settledExpanded: boolean; |
| 108 | settledVisibleCount?: number; |
| 109 | routeThreadKey?: string | null; |
| 110 | snoozedThreadCount?: number; |
| 111 | cardHeight?: number; |
| 112 | slimHeight?: number; |
| 113 | /** Space each pinned boundary opens for its label while dragging. The |
| 114 | * markers stay zero height at rest, so nothing is reserved until pickup. */ |
| 115 | boundaryLabelHeight?: number; |
| 116 | }): SortingStrategy { |
| 117 | if (input.enabled === false) return () => stationary; |
| 118 | const { items } = input; |
| 119 | const indices = new Map(items.map((item, index) => [sidebarListItemId(item), index])); |
| 120 | let previous: Pick<Layout, "rects" | "activeIndex" | "overIndex"> | undefined; |
| 121 | let transforms: ReturnType<SortingStrategy>[] | null = []; |
| 122 | |
| 123 | function project({ rects, activeIndex, overIndex }: Layout) { |
| 124 | const active = items[activeIndex]; |
| 125 | const over = items[overIndex] ?? active; |
| 126 | if (active?.kind !== "thread" || !over || !rects[0]) return []; |
| 127 | const target = resolveSidebarDropTarget(items, active.key, sidebarListItemId(over)); |
| 128 | if (!target) return []; |
| 129 | const groups: Record<SidebarSection, ThreadItem[]> = { |
| 130 | pinned: [], |
| 131 | active: [], |
| 132 | working: [], |
| 133 | snoozed: [], |
| 134 | settled: [], |
| 135 | }; |
| 136 | let cardHeight = input.cardHeight; |
| 137 | let slimHeight = input.slimHeight; |
| 138 | let headerScale: number | undefined; |
| 139 | for (const [index, item] of items.entries()) { |
| 140 | if (item.kind === "marker") { |
| 141 | if (isShelfHeader(item)) { |
| 142 | const height = rects[index]?.height; |
| 143 | if (height) headerScale ??= height / 32; |
| 144 | } |
| 145 | continue; |
| 146 | } |
| 147 | if (item.section === "pinned" || item.section === "active" || item.section === "working") |
| 148 | cardHeight ??= rects[index]?.height; |
| 149 | else slimHeight ??= rects[index]?.height; |
| 150 | if (item.key !== active.key) groups[item.section].push(item); |
| 151 | } |
| 152 | // Cards are 4.875rem + 0.25rem padding; slim rows/placeholders are h-9. |
| 153 | const scale = |
| 154 | slimHeight !== undefined ? slimHeight / 36 : (headerScale ?? (cardHeight ?? 82) / 82); |
| 155 | cardHeight ??= 82 * scale; |
| 156 | slimHeight ??= 36 * scale; |
| 157 | const labelHeight = (input.boundaryLabelHeight ?? 0) * scale; |
| 158 | const group = groups[target.section]; |
| 159 | const order = |
| 160 | target.section === "pinned" |
| 161 | ? target.pinnedOrder |
| 162 | : target.section === "settled" |
| 163 | ? input.settledOrder |
| 164 | : (input.activeOrder ?? target.activeOrder); |
| 165 | const ranks = new Map(order.map((key, index) => [key, index])); |
| 166 | const rank = ranks.get(active.key) ?? Number.POSITIVE_INFINITY; |
| 167 | const index = group.findIndex( |
| 168 | (item) => (ranks.get(item.key) ?? Number.POSITIVE_INFINITY) > rank, |
| 169 | ); |
| 170 | group.splice(index < 0 ? group.length : index, 0, { ...active, section: target.section }); |
| 171 | const settledOrder = ( |
| 172 | input.settledOrder.length > 0 ? input.settledOrder : groups.settled.map((item) => item.key) |
| 173 | ).filter((key) => key !== active.key || target.section === "settled"); |
| 174 | const visible = input.settledExpanded |
| 175 | ? settledOrder.slice(0, input.settledVisibleCount ?? settledOrder.length) |
| 176 | : []; |
| 177 | const routeKey = input.routeThreadKey; |
| 178 | if (routeKey && settledOrder.includes(routeKey) && !visible.includes(routeKey)) { |
| 179 | visible.push(routeKey); |
| 180 | } |
| 181 | groups.settled = visible.map((key) => ({ kind: "thread", key, section: "settled" })); |
| 182 | const projected: SidebarListItem[] = []; |
| 183 | const marker = (name: SidebarListMarker) => projected.push({ kind: "marker", marker: name }); |
| 184 | const section = (name: "active" | "settled") => { |
| 185 | if (groups[name].length > 0) projected.push(...groups[name]); |
| 186 | else marker(`${name}-placeholder`); |
| 187 | }; |
| 188 | marker("pinned-header"); |
| 189 | projected.push(...groups.pinned); |
| 190 | marker("pinned-divider"); |
| 191 | section("active"); |
| 192 | if (items.some((item) => item.kind === "marker" && item.marker === "working-header")) { |
| 193 | marker("working-header"); |
| 194 | projected.push(...groups.working); |
| 195 | } |
| 196 | if ( |
| 197 | groups.snoozed.length > 0 || |
| 198 | ((active.section !== "snoozed" || (input.snoozedThreadCount ?? 0) > 1) && |
| 199 | items.some((item) => item.kind === "marker" && item.marker === "snoozed-header")) |
| 200 | ) { |
| 201 | marker("snoozed-header"); |
| 202 | projected.push(...groups.snoozed); |
| 203 | } |
| 204 | marker("settled-header"); |
| 205 | section("settled"); |
| 206 | const heights = projected.map((item) => { |
| 207 | const index = indices.get(sidebarListItemId(item)); |
| 208 | const rect = index === undefined ? undefined : rects[index]; |
| 209 | const fallback = |
| 210 | item.kind === "thread" && |
| 211 | (item.section === "pinned" || item.section === "active" || item.section === "working") |
| 212 | ? cardHeight |
| 213 | : slimHeight; |
| 214 | const moved = item.kind === "thread" && item.key === active.key; |
| 215 | return item.kind === "marker" && |
| 216 | (item.marker === "pinned-header" || item.marker === "pinned-divider") |
| 217 | ? labelHeight |
| 218 | : item.kind === "marker" && item.marker.endsWith("placeholder") |
| 219 | ? slimHeight |
| 220 | : moved |
| 221 | ? fallback |
| 222 | : (rect?.height ?? fallback); |
| 223 | }); |
| 224 | const firstShelf = items.findIndex(isShelfHeader); |
| 225 | const shelfRect = rects[firstShelf]; |
| 226 | const beforeShelf = rects[firstShelf - 1]; |
| 227 | const lastRect = rects.at(-1); |
| 228 | // Consume the shelf's auto margin as drag labels and resized rows need |
| 229 | // room, keeping the combined shelves at their measured bottom. |
| 230 | let shelfSpace = |
| 231 | shelfRect && beforeShelf && lastRect && shelfRect.top > beforeShelf.bottom + 1 |
| 232 | ? Math.max( |
| 233 | 0, |
| 234 | lastRect.bottom - rects[0].top - heights.reduce((sum, height) => sum + height + 1, -1), |
| 235 | ) |
| 236 | : 0; |
| 237 | const result = items.map(() => hidden); |
| 238 | let top = rects[0].top; |
| 239 | for (const [projectedIndex, item] of projected.entries()) { |
| 240 | if (isShelfHeader(item)) { |
| 241 | top += shelfSpace; |
| 242 | shelfSpace = 0; |
| 243 | } |
| 244 | const index = indices.get(sidebarListItemId(item)); |
| 245 | const rect = index === undefined ? undefined : rects[index]; |
| 246 | if (index !== undefined && rect) result[index] = { ...stationary, y: top - rect.top }; |
| 247 | top += heights[projectedIndex]! + 1; |
| 248 | } |
| 249 | result[activeIndex] = stationary; |
| 250 | return result; |
| 251 | } |
| 252 | |
| 253 | return (args) => { |
| 254 | if ( |
| 255 | previous?.rects !== args.rects || |
| 256 | previous.activeIndex !== args.activeIndex || |
| 257 | previous.overIndex !== args.overIndex |
| 258 | ) { |
| 259 | previous = args; |
| 260 | transforms = project(args); |
| 261 | } |
| 262 | return transforms === null |
| 263 | ? verticalListSortingStrategy(args) |
| 264 | : (transforms[args.index] ?? stationary); |
| 265 | }; |
| 266 | } |