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

Sidebar.drag.ts

251 lines10.1 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 // Only pointer movement changes sections; opening the destination moves rows under stationary gestures.
54 const previousY = previousPointerY ?? pointer.y;
55 previousPointerY = pointer.y;
56 if (pointer.x >= boundary.left && pointer.x <= boundary.right) {
57 if (pointer.y < previousY && pointer.y <= boundary.bottom) boundarySection = "pinned";
58 else if (pointer.y > previousY && pointer.y >= boundary.top) boundarySection = "active";
59 const nextHeader = (["working-header", "snoozed-header", "settled-header"] as const)
60 .map((marker) =>
61 args.droppableContainers.find((container) => container.id === sidebarMarkerId(marker)),
62 )
63 .find((container) => container !== undefined);
64 const activeBottom = nextHeader?.node.current?.getBoundingClientRect().top;
65 if (boundarySection === "pinned" || (activeBottom != null && pointer.y < activeBottom)) {
66 const target = collisions.find((collision) => {
67 const id = String(collision.id);
68 if (!sections.has(id)) {
69 sections.set(
70 id,
71 resolveSidebarDropTarget(items, String(args.active.id), id)?.section ?? null,
72 );
73 }
74 return sections.get(id) === boundarySection;
75 });
76 if (target)
77 collisions = [target, ...collisions.filter((collision) => collision !== target)];
78 }
79 }
80 }
81 const nearest = collisions[0];
82 if (!nearest || nearest.id === args.active.id) {
83 return collisions;
84 }
85 const id = String(nearest.id);
86 const valid = validity.get(id) ?? isValidTarget(id);
87 validity.set(id, valid);
88 return valid ? collisions : collisions.filter((collision) => collision.id === args.active.id);
89 };
91​
92export function createSidebarSortingStrategy(input: {
93 items: readonly SidebarListItem[];
94 enabled?: boolean;
95 settledOrder: readonly string[];
96 activeOrder?: readonly string[];
97 settledExpanded: boolean;
98 settledVisibleCount?: number;
99 routeThreadKey?: string | null;
100 snoozedThreadCount?: number;
101 cardHeight?: number;
102 slimHeight?: number;
103 boundaryLabelHeight?: number;
104}): SortingStrategy {
105 if (input.enabled === false) return () => stationary;
106 const { items } = input;
107 const indices = new Map(items.map((item, index) => [sidebarListItemId(item), index]));
108 let previous: Pick<Layout, "rects" | "activeIndex" | "overIndex"> | undefined;
109 let transforms: ReturnType<SortingStrategy>[] | null = [];
110​
111 function project({ rects, activeIndex, overIndex }: Layout) {
112 const active = items[activeIndex];
113 const over = items[overIndex] ?? active;
114 if (active?.kind !== "thread" || !over || !rects[0]) return [];
115 const target = resolveSidebarDropTarget(items, active.key, sidebarListItemId(over));
116 if (!target) return [];
117 const groups: Record<SidebarSection, ThreadItem[]> = {
118 pinned: [],
119 active: [],
120 working: [],
121 snoozed: [],
122 settled: [],
123 };
124 let cardHeight = input.cardHeight;
125 let slimHeight = input.slimHeight;
126 let headerScale: number | undefined;
127 for (const [index, item] of items.entries()) {
128 if (item.kind === "marker") {
129 if (isShelfHeader(item)) {
130 const height = rects[index]?.height;
131 if (height) headerScale ??= height / 32;
132 }
133 continue;
134 }
135 if (item.section === "pinned" || item.section === "active" || item.section === "working")
136 cardHeight ??= rects[index]?.height;
137 else slimHeight ??= rects[index]?.height;
138 if (item.key !== active.key) groups[item.section].push(item);
139 }
140 const scale =
141 slimHeight !== undefined ? slimHeight / 36 : (headerScale ?? (cardHeight ?? 82) / 82);
142 cardHeight ??= 82 * scale;
143 slimHeight ??= 36 * scale;
144 const labelHeight = (input.boundaryLabelHeight ?? 0) * scale;
145 const group = groups[target.section];
146 const order =
147 target.section === "pinned"
148 ? target.pinnedOrder
149 : target.section === "settled"
150 ? input.settledOrder
151 : (input.activeOrder ?? target.activeOrder);
152 const ranks = new Map(order.map((key, index) => [key, index]));
153 const rank = ranks.get(active.key) ?? Number.POSITIVE_INFINITY;
154 const index = group.findIndex(
155 (item) => (ranks.get(item.key) ?? Number.POSITIVE_INFINITY) > rank,
156 );
157 group.splice(index < 0 ? group.length : index, 0, { ...active, section: target.section });
158 const settledOrder = (
159 input.settledOrder.length > 0 ? input.settledOrder : groups.settled.map((item) => item.key)
160 ).filter((key) => key !== active.key || target.section === "settled");
161 const visible = input.settledExpanded
162 ? settledOrder.slice(0, input.settledVisibleCount ?? settledOrder.length)
163 : [];
164 const routeKey = input.routeThreadKey;
165 if (routeKey && settledOrder.includes(routeKey) && !visible.includes(routeKey)) {
166 visible.push(routeKey);
167 }
168 groups.settled = visible.map((key) => ({ kind: "thread", key, section: "settled" }));
169 const projected: SidebarListItem[] = [];
170 const marker = (name: SidebarListMarker) => projected.push({ kind: "marker", marker: name });
171 const section = (name: "active" | "settled") => {
172 if (groups[name].length > 0) projected.push(...groups[name]);
173 else marker(`${name}-placeholder`);
174 };
175 marker("pinned-header");
176 projected.push(...groups.pinned);
177 marker("pinned-divider");
178 section("active");
179 if (items.some((item) => item.kind === "marker" && item.marker === "working-header")) {
180 marker("working-header");
181 projected.push(...groups.working);
182 }
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" &&
198 (item.section === "pinned" || item.section === "active" || item.section === "working")
199 ? cardHeight
200 : slimHeight;
201 const moved = item.kind === "thread" && item.key === active.key;
202 return item.kind === "marker" &&
203 (item.marker === "pinned-header" || item.marker === "pinned-divider")
204 ? labelHeight
205 : item.kind === "marker" && item.marker.endsWith("placeholder")
206 ? slimHeight
207 : moved
208 ? fallback
209 : (rect?.height ?? fallback);
210 });
211 const firstShelf = items.findIndex(isShelfHeader);
212 const shelfRect = rects[firstShelf];
213 const beforeShelf = rects[firstShelf - 1];
214 const lastRect = rects.at(-1);
215 let shelfSpace =
216 shelfRect && beforeShelf && lastRect && shelfRect.top > beforeShelf.bottom + 1
217 ? Math.max(
218 0,
219 lastRect.bottom - rects[0].top - heights.reduce((sum, height) => sum + height + 1, -1),
220 )
221 : 0;
222 const result = items.map(() => hidden);
223 let top = rects[0].top;
224 for (const [projectedIndex, item] of projected.entries()) {
225 if (isShelfHeader(item)) {
226 top += shelfSpace;
227 shelfSpace = 0;
228 }
229 const index = indices.get(sidebarListItemId(item));
230 const rect = index === undefined ? undefined : rects[index];
231 if (index !== undefined && rect) result[index] = { ...stationary, y: top - rect.top };
232 top += heights[projectedIndex]! + 1;
233 }
234 result[activeIndex] = stationary;
235 return result;
236 }
237​
238 return (args) => {
239 if (
240 previous?.rects !== args.rects ||
241 previous.activeIndex !== args.activeIndex ||
242 previous.overIndex !== args.overIndex
243 ) {
244 previous = args;
245 transforms = project(args);
246 }
247 return transforms === null
248 ? verticalListSortingStrategy(args)
249 : (transforms[args.index] ?? stationary);
250 };