Open History to see the last commit
1import {
2 closestCenter,
3 DndContext,
4 DragOverlay,
5 type DragEndEvent,
6 KeyboardSensor,
7 PointerSensor,
8 useSensor,
9 useSensors,
10} from "@dnd-kit/core";
11import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers";
12import { SortableContext, sortableKeyboardCoordinates, useSortable } from "@dnd-kit/sortable";
13import { useGT, useMessages } from "gt-react";
14import { GripVerticalIcon } from "lucide-react";
15import { memo, useRef, useState, type ReactNode } from "react";
16import { createPortal } from "react-dom";
17
18import { updateClientSettings } from "../../hooks/useSettings";
19import { cn } from "../../lib/utils";
20import { ThreadDetailsSection } from "./ThreadDetailsSection";
21import { THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS } from "./threadDetailsPanelStyles";
22import {
23 moveThreadDetailsBlock,
24 THREAD_DETAILS_BLOCKS,
25 type ThreadDetailsBlockId,
26} from "./threadDetailsItems";
27
28type Block = (typeof THREAD_DETAILS_BLOCKS)[number];
29
30// A new items array re-renders every grip through the sortable context, and the card renders
31// often, so each list of ids is reused while it stays the same.
32const idsByKey = new Map<string, string[]>();
33function sameIdsAsBefore(ids: string[]) {
34 const key = ids.join(",");
35 const known = idsByKey.get(key);
36 if (known) return known;
37 if (idsByKey.size > 64) idsByKey.clear();
38 idsByKey.set(key, ids);
39 return ids;
40}
41
42/** Renders the card's blocks in the saved order; each one drags by the grip in its left gutter. */
43export function ThreadDetailsBlocks(props: {
44 readonly order: ReadonlyArray<ThreadDetailsBlockId>;
45 readonly blocks: Readonly<Record<ThreadDetailsBlockId, ReactNode>>;
46 readonly density: "full" | "compact" | "essential";
47}) {
48 const gt = useGT();
49 const m = useMessages();
50 const sensors = useSensors(
51 useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
52 useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
53 );
54 const listRef = useRef<HTMLDivElement>(null);
55 const [hiddenWhileDragging, setHiddenWhileDragging] = useState<ReadonlySet<string>>(new Set());
56 const [dragged, setDragged] = useState<Block | null>(null);
57 const shown = props.order
58 .filter((id) => props.blocks[id] !== null)
59 .map((id) => THREAD_DETAILS_BLOCKS.find((block) => block.id === id)!);
60 // Neighbors of one group share a section, as the card laid them out before blocks could move.
61 const runs: Block[][] = [];
62 for (const block of shown) {
63 const last = runs.at(-1);
64 if (last && block.group !== null && last[0]!.group === block.group) last.push(block);
65 else runs.push([block]);
66 }
67 // A block that renders nothing is hidden by CSS. Left in the list, its zero-size box throws
68 // its neighbors' drag offsets off the card, so a drag skips it. Content can come and go mid-drag.
69 const syncHiddenBlocks = () => {
70 const blocks = listRef.current?.querySelectorAll<HTMLElement>("[data-thread-details-block-id]");
71 const hidden = [...(blocks ?? [])]
72 .filter((block) => block.getClientRects().length === 0)
73 .map((block) => block.dataset.threadDetailsBlockId!);
74 setHiddenWhileDragging((current) =>
75 current.size === hidden.length && hidden.every((id) => current.has(id))
76 ? current
77 : new Set(hidden),
78 );
79 };
80 const handleDragEnd = (event: DragEndEvent) => {
81 setHiddenWhileDragging(new Set());
82 setDragged(null);
83 if (event.over === null || event.active.id === event.over.id) return;
84 updateClientSettings({
85 threadDetailsOrder: moveThreadDetailsBlock(
86 props.order,
87 event.active.id as ThreadDetailsBlockId,
88 event.over.id as ThreadDetailsBlockId,
89 ),
90 });
91 };
92 const groupTitles = { workspace: gt`Workspace`, versionControl: gt`Version Control` };
93 const sortableIds = sameIdsAsBefore(
94 shown.map((block) => block.id).filter((id) => !hiddenWhileDragging.has(id)),
95 );
96 const blockName = (id: string | number) => {
97 const block = THREAD_DETAILS_BLOCKS.find((candidate) => candidate.id === id);
98 return block ? m(block.label) : String(id);
99 };
100
101 return (
102 <DndContext
103 sensors={sensors}
104 accessibility={{
105 screenReaderInstructions: {
106 draggable: gt`To pick up a block, press Space or Enter. Use the arrow keys to move it, Space or Enter to drop it, and Escape to cancel.`,
107 },
108 announcements: {
109 onDragStart: ({ active }) => gt`Picked up ${{ item: blockName(active.id) }}.`,
110 // dnd-kit calls this only when the target changes, so moving within one stays quiet.
111 onDragOver: ({ active, over }) =>
112 over === null
113 ? undefined
114 : over.id === active.id
115 ? gt`${{ item: blockName(active.id) }} is back in its place.`
116 : gt`${{ item: blockName(active.id) }} is over ${{ target: blockName(over.id) }}.`,
117 onDragMove: () => undefined,
118 onDragEnd: ({ active, over }) =>
119 over === null || over.id === active.id
120 ? gt`Put ${{ item: blockName(active.id) }} back.`
121 : gt`Dropped ${{ item: blockName(active.id) }} at ${{ target: blockName(over.id) }}.`,
122 onDragCancel: ({ active }) => gt`Put ${{ item: blockName(active.id) }} back.`,
123 },
124 }}
125 collisionDetection={closestCenter}
126 modifiers={[restrictToVerticalAxis, restrictToFirstScrollableAncestor]}
127 onDragStart={(event) => {
128 syncHiddenBlocks();
129 setDragged(THREAD_DETAILS_BLOCKS.find((block) => block.id === event.active.id) ?? null);
130 }}
131 onDragMove={syncHiddenBlocks}
132 onDragEnd={handleDragEnd}
133 onDragCancel={() => {
134 setHiddenWhileDragging(new Set());
135 setDragged(null);
136 }}
137 >
138 <SortableContext
139 items={sortableIds}
140 // Blocks stay put while dragging: sections, padding and dividers regroup on drop, which
141 // shifting blocks across sections cannot show. A line marks where the block lands.
142 strategy={() => null}
143 >
144 <div ref={listRef} className="contents">
145 {runs.map((run, index) => {
146 const group = run[0]!.group;
147 const rows = run.map((block) => (
148 // Plain DOM around the block: a wrapper component would re-render with every card render,
149 // since the block's content is a new element each time. Only the grip uses the drag state.
150 <div
151 key={block.id}
152 data-thread-details-block-id={block.id}
153 className="group/block relative has-[>div:last-child:empty]:hidden has-[>button[data-dragging]]:opacity-40"
154 >
155 <BlockGrip
156 block={block}
157 inset={group === null ? "section" : "row"}
158 disabled={hiddenWhileDragging.has(block.id)}
159 />
160 <div data-thread-details-block>{props.blocks[block.id]}</div>
161 </div>
162 ));
163 return (
164 <div
165 // Stable while blocks move within a run, so the section keeps its children's state.
166 key={
167 group === null
168 ? run[0]!.id
169 : `${group}-${runs.slice(0, index).filter((other) => other[0]!.group === group).length}`
170 }
171 data-thread-details-unit
172 // A unit hides when its blocks render nothing; a divider follows only a unit that shows.
173 className={cn(
174 "not-has-[[data-thread-details-block]:not(:empty)]:hidden",
175 (group !== "versionControl" || props.density === "full") &&
176 "border-border/65 [[data-thread-details-unit]:has([data-thread-details-block]:not(:empty))~&]:border-t",
177 )}
178 >
179 {group === null ? (
180 rows
181 ) : (
182 <ThreadDetailsSection
183 headingId={`thread-details-${run[0]!.id}-group-heading`}
184 title={groupTitles[group]}
185 showHeading={false}
186 separated={false}
187 >
188 <div className="flex flex-col">{rows}</div>
189 </ThreadDetailsSection>
190 )}
191 </div>
192 );
193 })}
194 </div>
195 </SortableContext>
196 {/* The popover positions with a transform, which would offset a fixed overlay inside it. */}
197 {createPortal(
198 <DragOverlay dropAnimation={null} zIndex={100} modifiers={[restrictToVerticalAxis]}>
199 {dragged ? (
200 <div
201 className={cn(
202 THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS,
203 "flex w-fit items-center border-border/65 bg-popover shadow-md",
204 )}
205 >
206 <GripVerticalIcon className="size-3 text-muted-foreground" aria-hidden />
207 {m(dragged.label)}
208 </div>
209 ) : null}
210 </DragOverlay>,
211 document.body,
212 )}
213 </DndContext>
214 );
215}
216
217// Memoized: grips are built in a loop, where the compiler cannot cache their elements.
218const BlockGrip = memo(function BlockGrip(props: {
219 readonly block: Block;
220 readonly inset: "section" | "row";
221 readonly disabled: boolean;
222}) {
223 const gt = useGT();
224 const m = useMessages();
225 const {
226 attributes,
227 listeners,
228 setNodeRef,
229 setActivatorNodeRef,
230 isDragging,
231 isOver,
232 index,
233 activeIndex,
234 } = useSortable({
235 id: props.block.id,
236 disabled: { draggable: props.disabled, droppable: props.disabled },
237 });
238 return (
239 <>
240 {isOver && !isDragging ? (
241 <div
242 data-thread-details-drop-line
243 aria-hidden
244 // A block moved down lands after its target, and one moved up lands before it.
245 className={cn(
246 "pointer-events-none absolute inset-x-2 z-10 h-0.5 rounded-full bg-primary",
247 activeIndex < index ? "-bottom-px" : "-top-px",
248 )}
249 />
250 ) : null}
251 <button
252 type="button"
253 ref={(node) => {
254 setActivatorNodeRef(node);
255 // The block moves as a whole, so the sortable node is the block around the grip.
256 setNodeRef(node?.parentElement ?? null);
257 }}
258 data-dragging={isDragging || undefined}
259 // Inline: the grip must stay out of flow even without styles, or it skews the card's measured height.
260 style={{ position: "absolute" }}
261 {...attributes}
262 {...listeners}
263 aria-label={gt`Move ${{ name: m(props.block.label) }}`}
264 className={cn(
265 "z-10 flex h-8 w-2.5 cursor-grab touch-none items-center justify-center rounded-sm text-muted-foreground/70 opacity-0 outline-none hover:text-foreground focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring group-hover/block:opacity-100 active:cursor-grabbing pointer-coarse:hidden",
266 props.inset === "section" ? "start-0 top-2" : "-start-2 top-0",
267 isDragging && "opacity-100",
268 )}
269 >
270 <GripVerticalIcon className="size-3" aria-hidden />
271 </button>
272 </>
273 );
274});