Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Sidebar.drag.ts

253 lines10.2 KB

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];
16const isShelfHeader = (item: SidebarListItem | undefined) =>
17 item?.kind === "marker" &&
18 (item.marker === "working-header" ||
19 item.marker === "snoozed-header" ||
20 item.marker === "settled-header");
21​
22export function restrictBelowSidebarLabel(
23 { transform, containerNodeRect, draggingNodeRect }: Parameters<Modifier>[0],
24 offset: number,
25) {
26 if (!containerNodeRect || !draggingNodeRect) return transform;
27 const minimumY = containerNodeRect.top + offset - draggingNodeRect.top;
28 return transform.y < minimumY ? { ...transform, y: minimumY } : transform;
30​
31export function createSidebarCollisionDetection(
32 isValidTarget: (id: string) => boolean,
33 options: {
34 items?: readonly SidebarListItem[];
35 activationY?: number | null;
36 } = {},
37): CollisionDetection {
38 const validity = new Map<string, boolean>();
39 const sections = new Map<string, SidebarSection | null>();
40 let previousPointerY = options.activationY;
41 let boundarySection: "pinned" | "active" | undefined;
42 return (args) => {
43 let collisions = closestCenter(args);
44 const pointer = args.pointerCoordinates;
45 const items = options.items;
46 const source = items?.find((item) => item.kind === "thread" && item.key === args.active.id);
47 const boundary = args.droppableContainers
48 .find((container) => container.id === sidebarMarkerId("pinned-divider"))
49 ?.node.current?.querySelector(".sidebar-drag-boundary-label")
50 ?.getBoundingClientRect();
51 if (items && boundary && source?.kind === "thread" && pointer) {
52 boundarySection ??= source.section === "pinned" ? "pinned" : "active";
53 // Use the visible divider row, including its sortable translation.
54 // Only pointer movement can change sections: opening the destination
55 // moves this row, but must not toggle a stationary gesture back.
56 const previousY = previousPointerY ?? pointer.y;
57 previousPointerY = pointer.y;
58 if (pointer.x >= boundary.left && pointer.x <= boundary.right) {
59 if (pointer.y < previousY && pointer.y <= boundary.bottom) boundarySection = "pinned";
60 else if (pointer.y > previousY && pointer.y >= boundary.top) boundarySection = "active";
61 const nextHeader = (["working-header", "snoozed-header", "settled-header"] as const)
62 .map((marker) =>
63 args.droppableContainers.find((container) => container.id === sidebarMarkerId(marker)),
64 )
65 .find((container) => container !== undefined);
66 const activeBottom = nextHeader?.node.current?.getBoundingClientRect().top;
67 if (boundarySection === "pinned" || (activeBottom != null && pointer.y < activeBottom)) {
68 const target = collisions.find((collision) => {
69 const id = String(collision.id);
70 if (!sections.has(id)) {
71 sections.set(
72 id,
73 resolveSidebarDropTarget(items, String(args.active.id), id)?.section ?? null,
74 );
75 }
76 return sections.get(id) === boundarySection;
77 });
78 if (target)
79 collisions = [target, ...collisions.filter((collision) => collision !== target)];
80 }
81 }
82 }
83 const nearest = collisions[0];
84 if (!nearest || nearest.id === args.active.id) {
85 return collisions;
86 }
87 const id = String(nearest.id);
88 const valid = validity.get(id) ?? isValidTarget(id);
89 validity.set(id, valid);
90 return valid ? collisions : collisions.filter((collision) => collision.id === args.active.id);
91 };
93​
94export function createSidebarSortingStrategy(input: {
95 items: readonly SidebarListItem[];
96 enabled?: boolean;
97 settledOrder: readonly string[];
98 activeOrder?: readonly string[];
99 settledExpanded: boolean;
100 settledVisibleCount?: number;
101 routeThreadKey?: string | null;
102 snoozedThreadCount?: number;
103 cardHeight?: number;
104 slimHeight?: number;
105 boundaryLabelHeight?: number;
106}): SortingStrategy {
107 if (input.enabled === false) return () => stationary;
108 const { items } = input;
109 const indices = new Map(items.map((item, index) => [sidebarListItemId(item), index]));
110 let previous: Pick<Layout, "rects" | "activeIndex" | "overIndex"> | undefined;
111 let transforms: ReturnType<SortingStrategy>[] | null = [];
112​
113 function project({ rects, activeIndex, overIndex }: Layout) {
114 const active = items[activeIndex];
115 const over = items[overIndex] ?? active;
116 if (active?.kind !== "thread" || !over || !rects[0]) return [];
117 const target = resolveSidebarDropTarget(items, active.key, sidebarListItemId(over));
118 if (!target) return [];
119 const groups: Record<SidebarSection, ThreadItem[]> = {
120 pinned: [],
121 active: [],
122 working: [],
123 snoozed: [],
124 settled: [],
125 };
126 let cardHeight = input.cardHeight;
127 let slimHeight = input.slimHeight;
128 let headerScale: number | undefined;
129 for (const [index, item] of items.entries()) {
130 if (item.kind === "marker") {
131 if (isShelfHeader(item)) {
132 const height = rects[index]?.height;
133 if (height) headerScale ??= height / 32;
134 }
135 continue;
136 }
137 if (item.section === "pinned" || item.section === "active" || item.section === "working")
138 cardHeight ??= rects[index]?.height;
139 else slimHeight ??= rects[index]?.height;
140 if (item.key !== active.key) groups[item.section].push(item);
141 }
142 const scale =
143 slimHeight !== undefined ? slimHeight / 36 : (headerScale ?? (cardHeight ?? 82) / 82);
144 cardHeight ??= 82 * scale;
145 slimHeight ??= 36 * scale;
146 const labelHeight = (input.boundaryLabelHeight ?? 0) * scale;
147 const group = groups[target.section];
148 const order =
149 target.section === "pinned"
150 ? target.pinnedOrder
151 : target.section === "settled"
152 ? input.settledOrder
153 : (input.activeOrder ?? target.activeOrder);
154 const ranks = new Map(order.map((key, index) => [key, index]));
155 const rank = ranks.get(active.key) ?? Number.POSITIVE_INFINITY;
156 const index = group.findIndex(
157 (item) => (ranks.get(item.key) ?? Number.POSITIVE_INFINITY) > rank,
158 );
159 group.splice(index < 0 ? group.length : index, 0, { ...active, section: target.section });
160 const settledOrder = (
161 input.settledOrder.length > 0 ? input.settledOrder : groups.settled.map((item) => item.key)
162 ).filter((key) => key !== active.key || target.section === "settled");
163 const visible = input.settledExpanded
164 ? settledOrder.slice(0, input.settledVisibleCount ?? settledOrder.length)
165 : [];
166 const routeKey = input.routeThreadKey;
167 if (routeKey && settledOrder.includes(routeKey) && !visible.includes(routeKey)) {
168 visible.push(routeKey);
169 }
170 groups.settled = visible.map((key) => ({ kind: "thread", key, section: "settled" }));
171 const projected: SidebarListItem[] = [];
172 const marker = (name: SidebarListMarker) => projected.push({ kind: "marker", marker: name });
173 const section = (name: "active" | "settled") => {
174 if (groups[name].length > 0) projected.push(...groups[name]);
175 else marker(`${name}-placeholder`);
176 };
177 marker("pinned-header");
178 projected.push(...groups.pinned);
179 marker("pinned-divider");
180 section("active");
181 if (items.some((item) => item.kind === "marker" && item.marker === "working-header")) {
182 marker("working-header");
183 projected.push(...groups.working);
184 }
185 if (
186 groups.snoozed.length > 0 ||
187 ((active.section !== "snoozed" || (input.snoozedThreadCount ?? 0) > 1) &&
188 items.some((item) => item.kind === "marker" && item.marker === "snoozed-header"))
189 ) {
190 marker("snoozed-header");
191 projected.push(...groups.snoozed);
192 }
193 marker("settled-header");
194 section("settled");
195 const heights = projected.map((item) => {
196 const index = indices.get(sidebarListItemId(item));
197 const rect = index === undefined ? undefined : rects[index];
198 const fallback =
199 item.kind === "thread" &&
200 (item.section === "pinned" || item.section === "active" || item.section === "working")
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(isShelfHeader);
214 const shelfRect = rects[firstShelf];
215 const beforeShelf = rects[firstShelf - 1];
216 const lastRect = rects.at(-1);
217 let shelfSpace =
218 shelfRect && beforeShelf && lastRect && shelfRect.top > beforeShelf.bottom + 1
219 ? Math.max(
220 0,
221 lastRect.bottom - rects[0].top - heights.reduce((sum, height) => sum + height + 1, -1),
222 )
223 : 0;
224 const result = items.map(() => hidden);
225 let top = rects[0].top;
226 for (const [projectedIndex, item] of projected.entries()) {
227 if (isShelfHeader(item)) {
228 top += shelfSpace;
229 shelfSpace = 0;
230 }
231 const index = indices.get(sidebarListItemId(item));
232 const rect = index === undefined ? undefined : rects[index];
233 if (index !== undefined && rect) result[index] = { ...stationary, y: top - rect.top };
234 top += heights[projectedIndex]! + 1;
235 }
236 result[activeIndex] = stationary;
237 return result;
238 }
239​
240 return (args) => {
241 if (
242 previous?.rects !== args.rects ||
243 previous.activeIndex !== args.activeIndex ||
244 previous.overIndex !== args.overIndex
245 ) {
246 previous = args;
247 transforms = project(args);
248 }
249 return transforms === null
250 ? verticalListSortingStrategy(args)
251 : (transforms[args.index] ?? stationary);
252 };