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