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

Sidebar.pointer.ts

151 lines6.7 KB

1import { useLayoutEffect, type PointerEvent as ReactPointerEvent } from "react";
2import { type SensorProps } from "@dnd-kit/core";
3import { getOwnerDocument, getWindow } from "@dnd-kit/utilities";
4​
5// Search unmounts the drag context while its owning Sidebar remains mounted.
6export function SidebarDragLifecycle({ onUnmount }: { onUnmount: () => void }) {
7 useLayoutEffect(() => onUnmount, [onUnmount]);
8 return null;
9}
10​
11type Options = {
12 distance: number;
13 onAttach: (sensor: SidebarPointerSensor) => void;
14 onFinish: (started: boolean) => void;
15 /** Return true to claim the move: the sort gesture then ignores this pointer position. */
16 onMove?: (point: { x: number; y: number }) => boolean;
17 /** Return true when the release was consumed elsewhere, so the sort is cancelled. */
18 onDrop?: (point: { x: number; y: number }) => boolean;
19};
20​
21export class SidebarPointerSensor {
22 static activators = [
23 {
24 eventName: "onPointerDown" as const,
25 handler: ({ nativeEvent }: ReactPointerEvent) =>
26 nativeEvent.isPrimary && nativeEvent.button === 0,
27 },
28 ];
29 autoScrollEnabled = true;
30 private phase: "pending" | "dragging" | "finished" = "pending";
31 private readonly pointer: PointerEvent;
32 private readonly document: Document;
33 private readonly window: Window;
34​
35 constructor(private readonly props: Omit<SensorProps<Options>, "activeNode" | "context">) {
36 this.pointer = props.event as PointerEvent;
37 this.document = getOwnerDocument(this.pointer.target);
38 this.window = getWindow(this.pointer.target);
39 this.document.addEventListener("pointermove", this.move, { passive: false, capture: true });
40 this.document.addEventListener("pointerup", this.end, { capture: true });
41 this.document.addEventListener("pointercancel", this.pointerCancel, { capture: true });
42 this.document.addEventListener("keydown", this.keydown, { capture: true });
43 this.document.addEventListener("visibilitychange", this.visibilityChange);
44 this.window.addEventListener("blur", this.cancel);
45 this.window.addEventListener("pagehide", this.cancel);
46 this.window.addEventListener("resize", this.cancel);
47 this.document.addEventListener("dragstart", this.preventDefault);
48 this.document.addEventListener("contextmenu", this.preventDefault);
49 props.options.onAttach(this);
50 props.onPending(props.active, { distance: props.options.distance }, this.coordinates());
51 }
52​
53 private coordinates = () => ({ x: this.pointer.clientX, y: this.pointer.clientY });
54 private preventDefault = (event: Event) => event.preventDefault();
55 private clearClickSuppression = () => {
56 this.document.removeEventListener("click", this.suppressClick, { capture: true });
57 this.document.removeEventListener("pointerdown", this.clearClickSuppression, { capture: true });
58 };
59 private suppressClick = (event: Event) => {
60 event.stopPropagation();
61 this.clearClickSuppression();
62 };
63 private clearSelection = () => this.document.getSelection()?.removeAllRanges();
64​
65 private move = (event: PointerEvent) => {
66 if (this.phase === "finished" || event.pointerId !== this.pointer.pointerId) return;
67 const coordinates = { x: event.clientX, y: event.clientY };
68 // Desktop can report buttons=0 on the final move before pointerup. Let an
69 // active context drag drop there before cancelling the sidebar sort.
70 if ((event.buttons & 1) === 0) {
71 if (this.phase === "dragging") this.props.options.onDrop?.(coordinates);
72 return this.cancel();
73 }
74 if (this.phase === "pending") {
75 const offset = {
76 x: event.clientX - this.pointer.clientX,
77 y: event.clientY - this.pointer.clientY,
78 };
79 if (Math.hypot(offset.x, offset.y) <= this.props.options.distance) {
80 this.props.onPending(
81 this.props.active,
82 { distance: this.props.options.distance },
83 this.coordinates(),
84 offset,
85 );
86 return;
87 }
88 this.phase = "dragging";
89 this.document.addEventListener("click", this.suppressClick, { capture: true });
90 this.document.addEventListener("selectionchange", this.clearSelection);
91 this.clearSelection();
92 this.props.onStart(this.coordinates());
93 }
94 if (this.phase === "dragging") {
95 if (event.cancelable) event.preventDefault();
96 if (this.props.options.onMove?.(coordinates) === true) return;
97 this.props.onMove(coordinates);
98 }
99 };
100​
101 private end = (event: PointerEvent) => {
102 if (event.pointerId !== this.pointer.pointerId) return;
103 const dropped =
104 this.phase === "dragging" &&
105 this.props.options.onDrop?.({ x: event.clientX, y: event.clientY }) === true;
106 this.finish(dropped);
107 };
108 private pointerCancel = (event: PointerEvent) => {
109 if (event.pointerId === this.pointer.pointerId) this.cancel();
110 };
111 private keydown = (event: KeyboardEvent) => {
112 if (event.code === "Escape") this.cancel();
113 };
114 private visibilityChange = () => {
115 if (this.document.hidden) this.cancel();
116 };
117 cancel = () => this.finish(true);
118​
119 private finish(cancelled: boolean) {
120 if (this.phase === "finished") return;
121 const aborted = this.phase === "pending";
122 this.phase = "finished";
123 this.document.removeEventListener("pointermove", this.move, { capture: true });
124 this.document.removeEventListener("pointerup", this.end, { capture: true });
125 this.document.removeEventListener("pointercancel", this.pointerCancel, { capture: true });
126 this.document.removeEventListener("keydown", this.keydown, { capture: true });
127 this.document.removeEventListener("visibilitychange", this.visibilityChange);
128 this.window.removeEventListener("blur", this.cancel);
129 this.window.removeEventListener("pagehide", this.cancel);
130 this.window.removeEventListener("resize", this.cancel);
131 this.document.removeEventListener("dragstart", this.preventDefault);
132 this.document.removeEventListener("contextmenu", this.preventDefault);
133 this.document.removeEventListener("selectionchange", this.clearSelection);
134 // Cancellation can precede release by an arbitrary amount of time. Consume that release
135 // click, or let a fresh pointerdown end suppression if release happened outside the
136 // document.
137 if (!aborted || cancelled) {
138 this.document.addEventListener("click", this.suppressClick, { capture: true });
139 this.document.addEventListener("pointerdown", this.clearClickSuppression, { capture: true });
140 }
141 try {
142 // Release the sidebar preview before dnd-kit clears its transforms.
143 // Its public end/cancel event can be omitted before its first layout.
144 this.props.options.onFinish(!aborted);
145 } finally {
146 if (aborted) this.props.onAbort(this.props.active);
147 if (cancelled) this.props.onCancel();
148 else this.props.onEnd();
149 }
150 }