Open History to see the last commit
1import type { ScopedThreadRef } from "@t3tools/contracts";
2import { useSyncExternalStore } from "react";
3
4/**
5 * Dragging a sidebar thread past the list edge turns the sort gesture into a context drop.
6 * The composer form marks itself as the target; the sidebar hit-tests the pointer against it
7 * and hands over the dragged thread refs through a DOM event, so neither side imports the
8 * other. Ghost position lives here rather than in Sidebar state so pointer moves only
9 * re-render the ghost.
10 */
11
12export const THREAD_CONTEXT_DROP_EVENT = "t3-thread-context-drop";
13const DROP_TARGET_ATTRIBUTE = "data-thread-context-drop";
14const DROP_OVER_ATTRIBUTE = "data-thread-context-over";
15
16export interface ThreadContextDragGhost {
17 readonly x: number;
18 readonly y: number;
19 readonly title: string;
20 readonly count: number;
21}
22
23let ghost: ThreadContextDragGhost | null = null;
24const listeners = new Set<() => void>();
25
26function setGhost(next: ThreadContextDragGhost | null) {
27 if (ghost === next) return;
28 ghost = next;
29 for (const listener of listeners) listener();
30}
31
32export function useThreadContextDragGhost(): ThreadContextDragGhost | null {
33 return useSyncExternalStore(
34 (listener) => {
35 listeners.add(listener);
36 return () => listeners.delete(listener);
37 },
38 () => ghost,
39 () => null,
40 );
41}
42
43let overTarget: HTMLElement | null = null;
44
45function findDropTarget(point: { x: number; y: number }): HTMLElement | null {
46 return (
47 document
48 .elementFromPoint(point.x, point.y)
49 ?.closest<HTMLElement>(`[${DROP_TARGET_ATTRIBUTE}]`) ?? null
50 );
51}
52
53/** Tracks the ghost and the highlighted drop target while the pointer is outside the list. */
54export function moveThreadContextDrag(
55 point: { x: number; y: number },
56 label: { title: string; count: number },
57) {
58 const target = findDropTarget(point);
59 if (target !== overTarget) {
60 overTarget?.removeAttribute(DROP_OVER_ATTRIBUTE);
61 target?.setAttribute(DROP_OVER_ATTRIBUTE, "true");
62 overTarget = target;
63 }
64 setGhost({ x: point.x, y: point.y, ...label });
65}
66
67export function endThreadContextDrag() {
68 overTarget?.removeAttribute(DROP_OVER_ATTRIBUTE);
69 overTarget = null;
70 setGhost(null);
71}
72
73/** True when a composer accepted the drop. */
74export function dropThreadContext(
75 point: { x: number; y: number },
76 threads: ReadonlyArray<ScopedThreadRef>,
77): boolean {
78 const target = findDropTarget(point);
79 if (!target || threads.length === 0) return false;
80 target.dispatchEvent(new CustomEvent(THREAD_CONTEXT_DROP_EVENT, { detail: threads }));
81 return true;
82}
83
84export function threadContextDropTargetProps() {
85 return { [DROP_TARGET_ATTRIBUTE]: "true" } as const;
86}