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 settledOrder: readonly string[];
100 settledExpanded: boolean;
101 settledVisibleCount?: number;
102 routeThreadKey?: string | null;
103 snoozedThreadCount?: number;
104 cardHeight?: number;
105 slimHeight?: number;
106 /** Space each pinned boundary opens for its label while dragging. The
107 * markers stay zero height at rest, so nothing is reserved until pickup. */
108 boundaryLabelHeight?: number;
109}): SortingStrategy {
110 const { items } = input;
111 const indices = new Map(items.map((item, index) => [sidebarListItemId(item), index]));
112 let previous: Pick<Layout, "rects" | "activeIndex" | "overIndex"> | undefined;
113 let transforms: ReturnType<SortingStrategy>[] | null = [];
114
115 function project({ rects, activeIndex, overIndex }: Layout) {
116 const active = items[activeIndex];
117 const over = items[overIndex] ?? active;
118 if (active?.kind !== "thread" || !over || !rects[0]) return [];
119 const target = resolveSidebarDropTarget(items, active.key, sidebarListItemId(over));
120 if (!target) return [];
121 const groups: Record<SidebarSection, ThreadItem[]> = {
122 pinned: [],
123 active: [],
124 snoozed: [],
125 settled: [],
126 };
127 let cardHeight = input.cardHeight;
128 let slimHeight = input.slimHeight;
129 let headerScale: number | undefined;
130 for (const [index, item] of items.entries()) {
131 if (item.kind === "marker") {
132 if (item.marker === "settled-header" || item.marker === "snoozed-header") {
133 const height = rects[index]?.height;
134 if (height) headerScale ??= height / 32;
135 }
136 continue;
137 }
138 if (item.section === "pinned" || item.section === "active")
139 cardHeight ??= rects[index]?.height;
140 else slimHeight ??= rects[index]?.height;
141 if (item.key !== active.key) groups[item.section].push(item);
142 }
143 // Cards are 4.875rem + 0.25rem padding; slim rows/placeholders are h-9.
144 const scale =
145 slimHeight !== undefined ? slimHeight / 36 : (headerScale ?? (cardHeight ?? 82) / 82);
146 cardHeight ??= 82 * scale;
147 slimHeight ??= 36 * scale;
148 const labelHeight = (input.boundaryLabelHeight ?? 0) * scale;
149 const group = groups[target.section];
150 const order =
151 target.section === "pinned"
152 ? target.pinnedOrder
153 : target.section === "settled"
154 ? input.settledOrder
155 : target.activeOrder;
156 const ranks = new Map(order.map((key, index) => [key, index]));
157 const rank = ranks.get(active.key) ?? Number.POSITIVE_INFINITY;
158 const index = group.findIndex(
159 (item) => (ranks.get(item.key) ?? Number.POSITIVE_INFINITY) > rank,
160 );
161 group.splice(index < 0 ? group.length : index, 0, { ...active, section: target.section });
162 const settledOrder = (
163 input.settledOrder.length > 0 ? input.settledOrder : groups.settled.map((item) => item.key)
164 ).filter((key) => key !== active.key || target.section === "settled");
165 const visible = input.settledExpanded
166 ? settledOrder.slice(0, input.settledVisibleCount ?? settledOrder.length)
167 : [];
168 const routeKey = input.routeThreadKey;
169 if (routeKey && settledOrder.includes(routeKey) && !visible.includes(routeKey)) {
170 visible.push(routeKey);
171 }
172 groups.settled = visible.map((key) => ({ kind: "thread", key, section: "settled" }));
173 const projected: SidebarListItem[] = [];
174 const marker = (name: SidebarListMarker) => projected.push({ kind: "marker", marker: name });
175 const section = (name: "active" | "settled") => {
176 if (groups[name].length > 0) projected.push(...groups[name]);
177 else marker(`${name}-placeholder`);
178 };
179 marker("pinned-header");
180 projected.push(...groups.pinned);
181 marker("pinned-divider");
182 section("active");
183 if (
184 groups.snoozed.length > 0 ||
185 ((active.section !== "snoozed" || (input.snoozedThreadCount ?? 0) > 1) &&
186 items.some((item) => item.kind === "marker" && item.marker === "snoozed-header"))
187 ) {
188 marker("snoozed-header");
189 projected.push(...groups.snoozed);
190 }
191 marker("settled-header");
192 section("settled");
193 const heights = projected.map((item) => {
194 const index = indices.get(sidebarListItemId(item));
195 const rect = index === undefined ? undefined : rects[index];
196 const fallback =
197 item.kind === "thread" && (item.section === "pinned" || item.section === "active")
198 ? cardHeight
199 : slimHeight;
200 const moved = item.kind === "thread" && item.key === active.key;
201 return item.kind === "marker" &&
202 (item.marker === "pinned-header" || item.marker === "pinned-divider")
203 ? labelHeight
204 : item.kind === "marker" && item.marker.endsWith("placeholder")
205 ? slimHeight
206 : moved
207 ? fallback
208 : (rect?.height ?? fallback);
209 });
210 const firstShelf = items.findIndex(
211 (item) =>
212 item.kind === "marker" &&
213 (item.marker === "snoozed-header" || item.marker === "settled-header"),
214 );
215 const shelfRect = rects[firstShelf];
216 const beforeShelf = rects[firstShelf - 1];
217 const lastRect = rects.at(-1);
218 // Consume the shelf's auto margin as drag labels and resized rows need
219 // room, keeping the combined shelves at their measured bottom.
220 let shelfSpace =
221 shelfRect && beforeShelf && lastRect && shelfRect.top > beforeShelf.bottom + 1
222 ? Math.max(
223 0,
224 lastRect.bottom - rects[0].top - heights.reduce((sum, height) => sum + height + 1, -1),
225 )
226 : 0;
227 const result = items.map(() => hidden);
228 let top = rects[0].top;
229 for (const [projectedIndex, item] of projected.entries()) {
230 if (
231 item.kind === "marker" &&
232 (item.marker === "snoozed-header" || item.marker === "settled-header")
233 ) {
234 top += shelfSpace;
235 shelfSpace = 0;
236 }
237 const index = indices.get(sidebarListItemId(item));
238 const rect = index === undefined ? undefined : rects[index];
239 if (index !== undefined && rect) result[index] = { ...stationary, y: top - rect.top };
240 top += heights[projectedIndex]! + 1;
241 }
242 result[activeIndex] = stationary;
243 return result;
244 }
245
246 return (args) => {
247 if (
248 previous?.rects !== args.rects ||
249 previous.activeIndex !== args.activeIndex ||
250 previous.overIndex !== args.overIndex
251 ) {
252 previous = args;
253 transforms = project(args);
254 }
255 return transforms === null
256 ? verticalListSortingStrategy(args)
257 : (transforms[args.index] ?? stationary);
258 };
259}