MCPcopy Create free account
hub / github.com/adobe/react-spectrum / useDrag

Function useDrag

packages/react-aria/src/dnd/useDrag.ts:108–438  ·  view source on GitHub ↗
(options: DragOptions)

Source from the content-addressed store, hash-verified

106 * based drag and drop, in addition to full parity for keyboard and screen reader users.
107 */
108export function useDrag(options: DragOptions): DragResult {
109 let {hasDragButton, isDisabled} = options;
110 let stringFormatter = useLocalizedStringFormatter(intlMessages, '@react-aria/dnd');
111 // oxlint-disable-next-line react/react-compiler
112 let state = useRef({
113 options,
114 x: 0,
115 y: 0
116 }).current;
117 state.options = options;
118 let isDraggingRef = useRef<Element | null>(null);
119 let [isDragging, setDraggingState] = useState(false);
120 let setDragging = (element: Element | null) => {
121 isDraggingRef.current = element;
122 setDraggingState(!!element);
123 };
124 let {addGlobalListener, removeAllGlobalListeners} = useGlobalListeners();
125 let modalityOnPointerDown = useRef<string>(null);
126
127 let onDragStart = (e: DragEvent) => {
128 if (e.defaultPrevented) {
129 return;
130 }
131
132 // Prevent the drag event from propagating to any parent draggables
133 e.stopPropagation();
134
135 // If this drag was initiated by a mobile screen reader (e.g. VoiceOver or TalkBack), enter virtual dragging mode.
136 if (modalityOnPointerDown.current === 'virtual') {
137 e.preventDefault();
138 startDragging(getEventTarget(e) as HTMLElement);
139 modalityOnPointerDown.current = null;
140 return;
141 }
142
143 if (typeof options.onDragStart === 'function') {
144 options.onDragStart({
145 type: 'dragstart',
146 x: e.clientX,
147 y: e.clientY
148 });
149 }
150
151 let items = options.getItems();
152 // Clear existing data (e.g. selected text on the page would be included in some browsers)
153 e.dataTransfer.clearData?.();
154 writeToDataTransfer(e.dataTransfer, items);
155
156 let allowed = DROP_OPERATION.all;
157 if (typeof options.getAllowedDropOperations === 'function') {
158 let allowedOperations = options.getAllowedDropOperations();
159 allowed = DROP_OPERATION.none;
160 for (let operation of allowedOperations) {
161 allowed |= DROP_OPERATION[operation] || DROP_OPERATION.none;
162 }
163 }
164
165 setGlobalAllowedDropOperations(allowed);

Callers 10

examples.jsFile · 0.90
useDraggableItemFunction · 0.90
DraggableFunction · 0.90
DraggableWithPreviewFunction · 0.90
DraggableFunction · 0.90
DraggableFunction · 0.90
DraggableImageFunction · 0.90
DraggableFunction · 0.90
DraggableFunction · 0.90
DraggableFunction · 0.90

Calls 8

useGlobalListenersFunction · 0.90
setGlobalDropEffectFunction · 0.90
useDragModalityFunction · 0.90
useDescriptionFunction · 0.90
setDraggingFunction · 0.70
formatMethod · 0.45

Tested by 1

DraggableFunction · 0.72