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