@mk-drag-and-drop/dom 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Matthias Kramer
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matthias Kramer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  createDropContainer,
18
18
  createDroppable,
19
19
  createSortable,
20
+ domPointerDragActiveAttribute,
20
21
  type DragUpdateEvent,
21
22
  type SortableDropPlacement,
22
23
  type SortablePreview,
@@ -252,6 +253,33 @@ and deduplicate the scheduled work to prevent loops.
252
253
 
253
254
  ## Pointer and keyboard handles
254
255
 
256
+ ### Mobile pointer ownership
257
+
258
+ Dedicated drag handles must declare touch gesture ownership before a gesture
259
+ begins. `createDragHandle` adds the stable `data-dnd-drag-handle` attribute;
260
+ apply the following CSS in every document or shadow root that renders handles:
261
+
262
+ ```css
263
+ [data-dnd-drag-handle] {
264
+ touch-action: none;
265
+ user-select: none;
266
+ -webkit-user-select: none;
267
+ }
268
+ ```
269
+
270
+ `touch-action` cannot be applied from `pointerdown`: the browser decides native
271
+ pan/zoom ownership before the handler runs. The runtime uses pointer capture
272
+ after activation and suppresses standard and WebKit text selection during both
273
+ pending and active pointer input, but neither mechanism replaces the CSS
274
+ contract.
275
+
276
+ For a draggable without a dedicated handle, apply `touch-action` to the
277
+ draggable surface only when that surface should own touch movement. `none`
278
+ prevents ordinary page scrolling from gestures that begin there. An
279
+ axis-specific value can preserve orthogonal native panning, but a vertical drag
280
+ and vertical page scroll cannot own the same gesture simultaneously. Scrolling
281
+ outside dedicated handles remains unaffected.
282
+
255
283
  `activationDelay` and `activationDistance` use OR semantics: either threshold
256
284
  activates. Quick release before activation remains an ordinary click. After an
257
285
  activated pointer drag, the browser click belonging to that interaction and
@@ -264,6 +292,32 @@ interactive-element protection prevents those keys from starting a drag. Use a
264
292
  noninteractive or separately focusable handle, or explicit commands, for
265
293
  keyboard sorting. Editable descendants remain protected.
266
294
 
295
+ ### Active pointer cursor state
296
+
297
+ When a pointer drag activates, the runtime sets the stable
298
+ `data-dnd-pointer-drag-active="true"` contract on the initiating document's
299
+ root element. Pending delay or distance activation and keyboard dragging do not
300
+ set it. The marker is removed when the actual drag ends, before lifecycle
301
+ completion and before any manual overlay release animation finishes.
302
+
303
+ The package does not choose or inject a cursor. Applications can opt into one:
304
+
305
+ ```css
306
+ :root[data-dnd-pointer-drag-active="true"],
307
+ :root[data-dnd-pointer-drag-active="true"] *,
308
+ :root[data-dnd-pointer-drag-active="true"] *::before,
309
+ :root[data-dnd-pointer-drag-active="true"] *::after {
310
+ cursor: grabbing !important;
311
+ }
312
+ ```
313
+
314
+ The descendant selectors and `!important` override explicit application
315
+ cursors such as `text`, `pointer`, or `col-resize`. Add equivalent rules inside
316
+ shadow roots when shadow content declares its own cursor. Each iframe document
317
+ also needs its own consumer stylesheet. The exported
318
+ `domPointerDragActiveAttribute` constant contains the supported attribute name
319
+ for JavaScript and CSS-in-JS integrations.
320
+
267
321
  ## Targeting and overlays
268
322
 
269
323
  Pointer-based targeting works without an overlay. `centerToCenter` and other
@@ -4,7 +4,9 @@ export type DomDraggableRuntime = {
4
4
  draggableId: string;
5
5
  group: string;
6
6
  element: HTMLElement;
7
+ pointerCaptureTarget?: Element;
7
8
  pointerId: number;
9
+ pointerType?: string;
8
10
  pointerPosition: DragPoint;
9
11
  }) => void;
10
12
  isKeyboardDragEnabled: () => boolean;
@@ -27,6 +29,7 @@ export type DomDraggablePointerDownEvent = {
27
29
  preventDefault: () => void;
28
30
  stopPropagation: () => void;
29
31
  pointerId: number;
32
+ pointerType?: string;
30
33
  button?: number;
31
34
  isPrimary?: boolean;
32
35
  clientX: number;
@@ -1,4 +1,4 @@
1
- import { shouldHandleKeyboardDragFromTarget, shouldStartDragFromTarget, } from "../input/drag-handle.js";
1
+ import { getPointerCaptureTarget, shouldHandleKeyboardDragFromTarget, } from "../input/drag-handle.js";
2
2
  export function createDomDraggable(input) {
3
3
  return {
4
4
  onPointerDown: (event) => {
@@ -6,10 +6,11 @@ export function createDomDraggable(input) {
6
6
  if (!element) {
7
7
  return;
8
8
  }
9
- if (!shouldStartDragFromTarget({
9
+ const pointerCaptureTarget = getPointerCaptureTarget({
10
10
  draggableElement: element,
11
11
  eventTarget: event.target,
12
- })) {
12
+ });
13
+ if (!pointerCaptureTarget) {
13
14
  return;
14
15
  }
15
16
  if (event.isPrimary === false ||
@@ -22,7 +23,9 @@ export function createDomDraggable(input) {
22
23
  draggableId: input.draggableId,
23
24
  group: input.group,
24
25
  element,
26
+ pointerCaptureTarget,
25
27
  pointerId: event.pointerId,
28
+ pointerType: event.pointerType,
26
29
  pointerPosition: {
27
30
  x: event.clientX,
28
31
  y: event.clientY,
@@ -50,7 +53,7 @@ export function createDomDraggable(input) {
50
53
  event.preventDefault();
51
54
  event.stopPropagation();
52
55
  },
53
- tabIndex: (input.keyboardDragEnabled ?? input.runtime.isKeyboardDragEnabled())
56
+ tabIndex: input.keyboardDragEnabled ?? input.runtime.isKeyboardDragEnabled()
54
57
  ? 0
55
58
  : undefined,
56
59
  };
package/dist/index.d.ts CHANGED
@@ -5,6 +5,8 @@ export { createDropContainer, type CreateDropContainerInput, } from "./droppable
5
5
  export { createSortable, type CreateSortableInput, } from "./sortable/create-sortable-binding.js";
6
6
  export type { SortableAxis, SortablePlacementBoundary, } from "./sortable/sortable-options.js";
7
7
  export { createDragHandle, type CreateDragHandleInput, } from "./input/create-drag-handle.js";
8
+ export { domDragHandleAttribute } from "./input/drag-handle.js";
9
+ export { domPointerDragActiveAttribute } from "./input/pointer-drag-state.js";
8
10
  export type { DragEndResult, DragEndEvent, DragLifecycleCallbacks, DragLifecycleHelpers, DragSource, DragStartEvent, DragUpdateEvent, DropEvent, ActiveDragResetEvent, SortablePreview, } from "./runtime/lifecycle.js";
9
11
  export type { RemeasureDropTargetsInput, SortableDropPlacement, } from "./runtime/drop-target-registry.js";
10
12
  export type { OverlayReleaseMode } from "./runtime/types.js";
package/dist/index.js CHANGED
@@ -4,6 +4,8 @@ export { createDroppable, } from "./droppable/create-droppable-binding.js";
4
4
  export { createDropContainer, } from "./droppable/create-drop-container-binding.js";
5
5
  export { createSortable, } from "./sortable/create-sortable-binding.js";
6
6
  export { createDragHandle, } from "./input/create-drag-handle.js";
7
+ export { domDragHandleAttribute } from "./input/drag-handle.js";
8
+ export { domPointerDragActiveAttribute } from "./input/pointer-drag-state.js";
7
9
  export { centerToCenter, pointerToCenter, pointerToRectDistance, } from "./targeting/algorithms.js";
8
10
  export { getDistanceToRect, maxOverlayCenterDistanceToRect, maxPointerDistanceToRect, } from "./targeting/constraints.js";
9
11
  export { lockToXAxis, lockToYAxis, restrictToContainer, } from "./modifiers/built-ins.js";
@@ -0,0 +1 @@
1
+ export declare function acquireDocumentSelectionSuppression(sourceDocument: Document): () => void;
@@ -0,0 +1,89 @@
1
+ const selectionPropertyNames = ["user-select", "-webkit-user-select"];
2
+ const documentSelectionStates = new WeakMap();
3
+ export function acquireDocumentSelectionSuppression(sourceDocument) {
4
+ const owner = {};
5
+ let state = documentSelectionStates.get(sourceDocument);
6
+ if (!state) {
7
+ const elements = [
8
+ sourceDocument.documentElement,
9
+ ...(sourceDocument.body ? [sourceDocument.body] : []),
10
+ ];
11
+ const snapshots = elements.map(createElementSelectionSnapshot);
12
+ const handleSelectStart = (event) => {
13
+ event.preventDefault();
14
+ };
15
+ state = {
16
+ owners: new Set(),
17
+ snapshots,
18
+ handleSelectStart,
19
+ };
20
+ documentSelectionStates.set(sourceDocument, state);
21
+ for (const element of elements) {
22
+ for (const propertyName of selectionPropertyNames) {
23
+ setSelectionProperty(element.style, propertyName, "none");
24
+ }
25
+ }
26
+ sourceDocument.addEventListener("selectstart", handleSelectStart, true);
27
+ }
28
+ state.owners.add(owner);
29
+ let released = false;
30
+ return () => {
31
+ if (released) {
32
+ return;
33
+ }
34
+ released = true;
35
+ if (!state?.owners.delete(owner) || state.owners.size > 0) {
36
+ return;
37
+ }
38
+ documentSelectionStates.delete(sourceDocument);
39
+ sourceDocument.removeEventListener("selectstart", state.handleSelectStart, true);
40
+ for (const snapshot of state.snapshots) {
41
+ restoreElementSelectionSnapshot(snapshot);
42
+ }
43
+ };
44
+ }
45
+ function createElementSelectionSnapshot(element) {
46
+ return {
47
+ element,
48
+ properties: selectionPropertyNames.map((name) => ({
49
+ name,
50
+ present: hasInlineProperty(element.style, name) ||
51
+ getSelectionProperty(element.style, name) !== "",
52
+ value: getSelectionProperty(element.style, name),
53
+ priority: element.style.getPropertyPriority(name),
54
+ })),
55
+ };
56
+ }
57
+ function restoreElementSelectionSnapshot(snapshot) {
58
+ for (const property of snapshot.properties) {
59
+ if (property.present) {
60
+ setSelectionProperty(snapshot.element.style, property.name, property.value, property.priority);
61
+ }
62
+ else {
63
+ snapshot.element.style.removeProperty(property.name);
64
+ if (property.name === "-webkit-user-select") {
65
+ snapshot.element.style.webkitUserSelect = "";
66
+ }
67
+ }
68
+ }
69
+ }
70
+ function getSelectionProperty(style, name) {
71
+ const cssValue = style.getPropertyValue(name);
72
+ return name === "-webkit-user-select" && cssValue === ""
73
+ ? style.webkitUserSelect ?? ""
74
+ : cssValue;
75
+ }
76
+ function setSelectionProperty(style, name, value, priority = "") {
77
+ style.setProperty(name, value, priority);
78
+ if (name === "-webkit-user-select" && style.webkitUserSelect !== value) {
79
+ style.webkitUserSelect = value;
80
+ }
81
+ }
82
+ function hasInlineProperty(style, name) {
83
+ for (let index = 0; index < style.length; index += 1) {
84
+ if (style.item(index) === name) {
85
+ return true;
86
+ }
87
+ }
88
+ return false;
89
+ }
@@ -4,6 +4,10 @@ export declare function shouldStartDragFromTarget(input: {
4
4
  draggableElement: HTMLElement;
5
5
  eventTarget: EventTarget | null;
6
6
  }): boolean;
7
+ export declare function getPointerCaptureTarget(input: {
8
+ draggableElement: HTMLElement;
9
+ eventTarget: EventTarget | null;
10
+ }): Element | null;
7
11
  export declare function shouldHandleKeyboardDragFromTarget(input: {
8
12
  draggableElement: HTMLElement;
9
13
  eventTarget: EventTarget | null;
@@ -12,20 +12,27 @@ const interactiveElementSelector = [
12
12
  "[role='textbox']",
13
13
  ].join(",");
14
14
  export function shouldStartDragFromTarget(input) {
15
+ return getPointerCaptureTarget(input) !== null;
16
+ }
17
+ export function getPointerCaptureTarget(input) {
15
18
  const eventTarget = getEventTargetElement(input.eventTarget);
16
19
  if (!eventTarget) {
17
- return false;
20
+ return null;
18
21
  }
19
22
  const hasDragHandle = input.draggableElement.querySelector(domDragHandleSelector) !== null;
20
23
  if (!hasDragHandle) {
21
- return !isInteractiveDragTarget({
24
+ return isInteractiveDragTarget({
22
25
  draggableElement: input.draggableElement,
23
26
  eventTarget,
24
- });
27
+ })
28
+ ? null
29
+ : input.draggableElement;
25
30
  }
26
31
  const closestDragHandle = eventTarget.closest(domDragHandleSelector);
27
- return (closestDragHandle !== null &&
28
- input.draggableElement.contains(closestDragHandle));
32
+ return closestDragHandle !== null &&
33
+ input.draggableElement.contains(closestDragHandle)
34
+ ? closestDragHandle
35
+ : null;
29
36
  }
30
37
  export function shouldHandleKeyboardDragFromTarget(input) {
31
38
  const eventTarget = getEventTargetElement(input.eventTarget);
@@ -24,5 +24,5 @@ export declare class KeyboardDragController {
24
24
  isEnabled(): boolean;
25
25
  handleSourceKeyDown(input: SourceKeyboardDragKeyDownInput): boolean;
26
26
  handleActiveKeyDown(key: string): boolean;
27
- bindWindowListeners(): () => void;
27
+ bindWindowListeners(targetWindow?: Window & typeof globalThis): () => void;
28
28
  }
@@ -56,7 +56,7 @@ export class KeyboardDragController {
56
56
  }
57
57
  return false;
58
58
  }
59
- bindWindowListeners() {
59
+ bindWindowListeners(targetWindow = window) {
60
60
  let isCleanedUp = false;
61
61
  const handleKeyDown = (event) => {
62
62
  if (!this.handleActiveKeyDown(event.key)) {
@@ -65,13 +65,13 @@ export class KeyboardDragController {
65
65
  event.preventDefault();
66
66
  event.stopPropagation();
67
67
  };
68
- window.addEventListener("keydown", handleKeyDown);
68
+ targetWindow.addEventListener("keydown", handleKeyDown);
69
69
  return () => {
70
70
  if (isCleanedUp) {
71
71
  return;
72
72
  }
73
73
  isCleanedUp = true;
74
- window.removeEventListener("keydown", handleKeyDown);
74
+ targetWindow.removeEventListener("keydown", handleKeyDown);
75
75
  };
76
76
  }
77
77
  }
@@ -4,20 +4,25 @@ export type PointerDragActivationRequest = {
4
4
  draggableId: string;
5
5
  group: string;
6
6
  element: HTMLElement;
7
+ pointerCaptureTarget?: Element;
7
8
  pointerId: number;
9
+ pointerType?: string;
8
10
  pointerPosition: DragPoint;
9
11
  };
10
12
  export type ActivatedPointerDrag = {
11
13
  draggableId: string;
12
14
  group: string;
13
15
  element: HTMLElement;
16
+ pointerCaptureTarget: Element;
14
17
  pointerId: number;
18
+ pointerType: string;
15
19
  initialPointerPosition: DragPoint;
16
20
  latestPointerPosition: DragPoint;
17
21
  };
18
22
  export type PointerActivationControllerOptions = {
19
23
  getConfiguration: () => NormalizedPointerConfiguration;
20
24
  isDragging: () => boolean;
25
+ acquirePendingResources?: (request: PointerDragActivationRequest) => () => void;
21
26
  startImmediately: (request: PointerDragActivationRequest) => void;
22
27
  activate: (activation: ActivatedPointerDrag) => void;
23
28
  };
@@ -11,6 +11,7 @@ export class PointerActivationController {
11
11
  return;
12
12
  }
13
13
  const { activationDelay, activationDistance } = this.options.getConfiguration();
14
+ const targetWindow = request.element.ownerDocument.defaultView ?? window;
14
15
  if (activationDelay === null && activationDistance === null) {
15
16
  this.options.startImmediately(request);
16
17
  return;
@@ -23,11 +24,15 @@ export class PointerActivationController {
23
24
  draggableId: request.draggableId,
24
25
  group: request.group,
25
26
  element: request.element,
27
+ pointerCaptureTarget: request.pointerCaptureTarget ?? request.element,
26
28
  pointerId: request.pointerId,
29
+ pointerType: request.pointerType ?? "",
27
30
  initialPointerPosition,
28
31
  latestPointerPosition: initialPointerPosition,
32
+ targetWindow,
29
33
  activationTimerId: null,
30
34
  releasePendingPointerListeners: null,
35
+ releasePendingResources: this.options.acquirePendingResources?.(request) ?? null,
31
36
  };
32
37
  const handlePointerMove = (event) => {
33
38
  if (event.pointerId !== pendingActivation.pointerId) {
@@ -55,17 +60,17 @@ export class PointerActivationController {
55
60
  }
56
61
  this.cancelPendingActivation();
57
62
  };
58
- window.addEventListener("pointermove", handlePointerMove, globalPointerListenerCapture);
59
- window.addEventListener("pointerup", handlePointerEnd, globalPointerListenerCapture);
60
- window.addEventListener("pointercancel", handlePointerEnd, globalPointerListenerCapture);
63
+ targetWindow.addEventListener("pointermove", handlePointerMove, globalPointerListenerCapture);
64
+ targetWindow.addEventListener("pointerup", handlePointerEnd, globalPointerListenerCapture);
65
+ targetWindow.addEventListener("pointercancel", handlePointerEnd, globalPointerListenerCapture);
61
66
  pendingActivation.releasePendingPointerListeners = () => {
62
- window.removeEventListener("pointermove", handlePointerMove, globalPointerListenerCapture);
63
- window.removeEventListener("pointerup", handlePointerEnd, globalPointerListenerCapture);
64
- window.removeEventListener("pointercancel", handlePointerEnd, globalPointerListenerCapture);
67
+ targetWindow.removeEventListener("pointermove", handlePointerMove, globalPointerListenerCapture);
68
+ targetWindow.removeEventListener("pointerup", handlePointerEnd, globalPointerListenerCapture);
69
+ targetWindow.removeEventListener("pointercancel", handlePointerEnd, globalPointerListenerCapture);
65
70
  };
66
71
  this.pendingActivation = pendingActivation;
67
72
  if (activationDelay !== null) {
68
- pendingActivation.activationTimerId = window.setTimeout(() => {
73
+ pendingActivation.activationTimerId = targetWindow.setTimeout(() => {
69
74
  this.activatePendingPointerDrag(pendingActivation);
70
75
  }, activationDelay);
71
76
  }
@@ -85,26 +90,38 @@ export class PointerActivationController {
85
90
  const releasePendingPointerListeners = pendingActivation.releasePendingPointerListeners;
86
91
  pendingActivation.releasePendingPointerListeners = null;
87
92
  releasePendingPointerListeners?.();
93
+ const releasePendingResources = pendingActivation.releasePendingResources;
94
+ pendingActivation.releasePendingResources = null;
95
+ releasePendingResources?.();
88
96
  }
89
97
  clearPendingActivationTimer(pendingActivation) {
90
98
  if (pendingActivation.activationTimerId === null) {
91
99
  return;
92
100
  }
93
- window.clearTimeout(pendingActivation.activationTimerId);
101
+ pendingActivation.targetWindow.clearTimeout(pendingActivation.activationTimerId);
94
102
  pendingActivation.activationTimerId = null;
95
103
  }
96
104
  activatePendingPointerDrag(pendingActivation) {
97
105
  if (this.pendingActivation !== pendingActivation) {
98
106
  return;
99
107
  }
108
+ const releasePendingResources = pendingActivation.releasePendingResources;
109
+ pendingActivation.releasePendingResources = null;
100
110
  this.clearPendingActivation(pendingActivation);
101
- this.options.activate({
102
- draggableId: pendingActivation.draggableId,
103
- group: pendingActivation.group,
104
- element: pendingActivation.element,
105
- pointerId: pendingActivation.pointerId,
106
- initialPointerPosition: pendingActivation.initialPointerPosition,
107
- latestPointerPosition: pendingActivation.latestPointerPosition,
108
- });
111
+ try {
112
+ this.options.activate({
113
+ draggableId: pendingActivation.draggableId,
114
+ group: pendingActivation.group,
115
+ element: pendingActivation.element,
116
+ pointerCaptureTarget: pendingActivation.pointerCaptureTarget,
117
+ pointerId: pendingActivation.pointerId,
118
+ pointerType: pendingActivation.pointerType,
119
+ initialPointerPosition: pendingActivation.initialPointerPosition,
120
+ latestPointerPosition: pendingActivation.latestPointerPosition,
121
+ });
122
+ }
123
+ finally {
124
+ releasePendingResources?.();
125
+ }
109
126
  }
110
127
  }
@@ -0,0 +1,2 @@
1
+ export declare const domPointerDragActiveAttribute = "data-dnd-pointer-drag-active";
2
+ export declare function acquireDocumentPointerDragState(sourceDocument: Document): () => void;
@@ -0,0 +1,32 @@
1
+ export const domPointerDragActiveAttribute = "data-dnd-pointer-drag-active";
2
+ const documentPointerDragStates = new WeakMap();
3
+ export function acquireDocumentPointerDragState(sourceDocument) {
4
+ const owner = {};
5
+ let state = documentPointerDragStates.get(sourceDocument);
6
+ if (!state) {
7
+ state = {
8
+ root: sourceDocument.documentElement,
9
+ previousValue: sourceDocument.documentElement.getAttribute(domPointerDragActiveAttribute),
10
+ owners: new Set(),
11
+ };
12
+ documentPointerDragStates.set(sourceDocument, state);
13
+ }
14
+ state.owners.add(owner);
15
+ state.root.setAttribute(domPointerDragActiveAttribute, "true");
16
+ let released = false;
17
+ return () => {
18
+ if (released) {
19
+ return;
20
+ }
21
+ released = true;
22
+ if (!state?.owners.delete(owner) || state.owners.size > 0) {
23
+ return;
24
+ }
25
+ documentPointerDragStates.delete(sourceDocument);
26
+ if (state.previousValue === null) {
27
+ state.root.removeAttribute(domPointerDragActiveAttribute);
28
+ return;
29
+ }
30
+ state.root.setAttribute(domPointerDragActiveAttribute, state.previousValue);
31
+ };
32
+ }
@@ -8,3 +8,4 @@ export { createDomSortable, type CreateDomSortableInput, type DomSortableBehavio
8
8
  export type { DomSortableRuntime } from "../sortable/sortable-registry.js";
9
9
  export type { SortableAxis, SortablePlacementBoundary, } from "../sortable/sortable-options.js";
10
10
  export { domDragHandleAttribute } from "../input/drag-handle.js";
11
+ export { domPointerDragActiveAttribute } from "../input/pointer-drag-state.js";
@@ -4,3 +4,4 @@ export { createDomDroppable, } from "../droppable/create-droppable.js";
4
4
  export { createDomDropContainer, } from "../droppable/create-drop-container.js";
5
5
  export { createDomSortable, } from "../sortable/create-sortable.js";
6
6
  export { domDragHandleAttribute } from "../input/drag-handle.js";
7
+ export { domPointerDragActiveAttribute } from "../input/pointer-drag-state.js";
@@ -17,10 +17,14 @@ export declare class DragRuntime {
17
17
  private modifiers;
18
18
  private activeDragModifiers;
19
19
  private releaseActiveInputListeners;
20
+ private ensureActivePointerCapture;
20
21
  private restoreTextSelectionSuppression;
22
+ private releasePointerDragState;
21
23
  private releasePostDragClickSuppression;
22
24
  private queuedPointerPosition;
23
25
  private pointerFrameId;
26
+ private pointerFrameWindow;
27
+ private activeDragWindow;
24
28
  private subscriptions;
25
29
  private staleDomBindingRecords;
26
30
  private lifecycleCallbacks;
@@ -3,7 +3,9 @@ import { getOverlayMeasurement, getOverlayRect, } from "../geometry/overlay.js";
3
3
  import { defaultKeyboardConfiguration, normalizeKeyboardConfiguration, normalizePointerConfiguration, } from "../input/config.js";
4
4
  import { KeyboardDragController, } from "../input/keyboard-drag.js";
5
5
  import { globalPointerListenerCapture } from "../input/global-pointer-listeners.js";
6
+ import { acquireDocumentSelectionSuppression } from "../input/document-selection-state.js";
6
7
  import { PointerActivationController } from "../input/pointer-activation.js";
8
+ import { acquireDocumentPointerDragState } from "../input/pointer-drag-state.js";
7
9
  import { applyDragModifiers, createActiveDragModifiers, } from "../modifiers/pipeline.js";
8
10
  import { getBuiltInTargetingAlgorithmKind, pointerToCenter, } from "../targeting/algorithms.js";
9
11
  import { DropTargetRegistry, } from "./drop-target-registry.js";
@@ -19,10 +21,14 @@ export class DragRuntime {
19
21
  modifiers = [];
20
22
  activeDragModifiers = [];
21
23
  releaseActiveInputListeners = null;
24
+ ensureActivePointerCapture = null;
22
25
  restoreTextSelectionSuppression = null;
26
+ releasePointerDragState = null;
23
27
  releasePostDragClickSuppression = null;
24
28
  queuedPointerPosition = null;
25
29
  pointerFrameId = null;
30
+ pointerFrameWindow = null;
31
+ activeDragWindow = null;
26
32
  subscriptions = new Set();
27
33
  staleDomBindingRecords = new Set();
28
34
  lifecycleCallbacks = {};
@@ -44,6 +50,7 @@ export class DragRuntime {
44
50
  pointerActivation = new PointerActivationController({
45
51
  getConfiguration: () => this.pointerConfiguration,
46
52
  isDragging: () => this.isDragging,
53
+ acquirePendingResources: (request) => acquireDocumentSelectionSuppression(request.element.ownerDocument),
47
54
  startImmediately: (request) => {
48
55
  if (!request.element.isConnected) {
49
56
  return;
@@ -53,6 +60,8 @@ export class DragRuntime {
53
60
  group: request.group,
54
61
  inputType: "pointer",
55
62
  pointerId: request.pointerId,
63
+ pointerCaptureTarget: request.pointerCaptureTarget ?? request.element,
64
+ pointerType: request.pointerType,
56
65
  element: request.element,
57
66
  pointerPosition: request.pointerPosition,
58
67
  sourceRect: measureDomElement(request.element),
@@ -67,6 +76,8 @@ export class DragRuntime {
67
76
  group: activation.group,
68
77
  inputType: "pointer",
69
78
  pointerId: activation.pointerId,
79
+ pointerCaptureTarget: activation.pointerCaptureTarget,
80
+ pointerType: activation.pointerType,
70
81
  element: activation.element,
71
82
  pointerPosition: activation.initialPointerPosition,
72
83
  sourceRect: measureDomElement(activation.element),
@@ -141,6 +152,7 @@ export class DragRuntime {
141
152
  draggableId: input.draggableId,
142
153
  group: input.group,
143
154
  inputType: "keyboard",
155
+ element: input.element,
144
156
  pointerPosition,
145
157
  sourceRect,
146
158
  });
@@ -177,8 +189,11 @@ export class DragRuntime {
177
189
  if (this.pointerFrameId !== null) {
178
190
  return;
179
191
  }
180
- this.pointerFrameId = window.requestAnimationFrame(() => {
192
+ const targetWindow = this.activeDragWindow ?? window;
193
+ this.pointerFrameWindow = targetWindow;
194
+ this.pointerFrameId = targetWindow.requestAnimationFrame(() => {
181
195
  this.pointerFrameId = null;
196
+ this.pointerFrameWindow = null;
182
197
  const nextPointerPosition = this.queuedPointerPosition;
183
198
  this.queuedPointerPosition = null;
184
199
  if (nextPointerPosition) {
@@ -240,6 +255,7 @@ export class DragRuntime {
240
255
  placementPosition: sortablePlacementPosition,
241
256
  movementPosition: rawPointerPosition,
242
257
  });
258
+ this.ensureActivePointerCapture?.();
243
259
  const sortablePreview = this.getSortablePreview(nextSession);
244
260
  const completedSession = {
245
261
  ...nextSession,
@@ -486,6 +502,10 @@ export class DragRuntime {
486
502
  sortablePreview: { status: "inactive" },
487
503
  };
488
504
  this.setSession(nextSession);
505
+ this.activeDragWindow = input.element.ownerDocument.defaultView ?? window;
506
+ if (input.inputType === "pointer") {
507
+ this.releasePointerDragState = acquireDocumentPointerDragState(input.element.ownerDocument);
508
+ }
489
509
  this.remeasureDropTargets({ group: input.group });
490
510
  const dragStartEvent = {
491
511
  draggableId: input.draggableId,
@@ -514,12 +534,12 @@ export class DragRuntime {
514
534
  phase: "dragging",
515
535
  },
516
536
  });
517
- this.suppressTextSelection();
537
+ this.suppressTextSelection(input.element.ownerDocument);
518
538
  if (input.inputType === "pointer") {
519
- this.bindPointerWindowListeners(input.pointerId, input.element);
539
+ this.bindPointerWindowListeners(input.pointerId, input.element, input.pointerCaptureTarget ?? input.element);
520
540
  }
521
541
  else {
522
- this.bindKeyboardWindowListeners();
542
+ this.bindKeyboardWindowListeners(this.activeDragWindow);
523
543
  }
524
544
  this.notifyDragStartLifecycle(dragStartEvent);
525
545
  }
@@ -653,9 +673,40 @@ export class DragRuntime {
653
673
  }
654
674
  this.clearOverlayHost();
655
675
  }
656
- bindPointerWindowListeners(pointerId, initiatingElement) {
676
+ bindPointerWindowListeners(pointerId, initiatingElement, pointerCaptureTarget) {
657
677
  this.releaseActiveInputListeners?.();
678
+ const targetWindow = initiatingElement.ownerDocument.defaultView ?? window;
658
679
  let listenersReleased = false;
680
+ const ensurePointerCapture = () => {
681
+ if (!pointerCaptureTarget.isConnected ||
682
+ typeof pointerCaptureTarget.setPointerCapture !== "function") {
683
+ return;
684
+ }
685
+ try {
686
+ if (typeof pointerCaptureTarget.hasPointerCapture === "function" &&
687
+ pointerCaptureTarget.hasPointerCapture(pointerId)) {
688
+ return;
689
+ }
690
+ pointerCaptureTarget.setPointerCapture(pointerId);
691
+ }
692
+ catch {
693
+ // Window listeners remain the fallback when capture is unavailable.
694
+ }
695
+ };
696
+ const releasePointerCapture = () => {
697
+ if (typeof pointerCaptureTarget.releasePointerCapture !== "function") {
698
+ return;
699
+ }
700
+ try {
701
+ if (typeof pointerCaptureTarget.hasPointerCapture !== "function" ||
702
+ pointerCaptureTarget.hasPointerCapture(pointerId)) {
703
+ pointerCaptureTarget.releasePointerCapture(pointerId);
704
+ }
705
+ }
706
+ catch {
707
+ // Pointerup/cancel may have already released capture implicitly.
708
+ }
709
+ };
659
710
  const handlePointerMove = (event) => {
660
711
  if (event.pointerId !== pointerId) {
661
712
  return;
@@ -685,29 +736,37 @@ export class DragRuntime {
685
736
  this.clearPostDragClickSuppression();
686
737
  this.cancelDrag();
687
738
  };
688
- window.addEventListener("pointermove", handlePointerMove, globalPointerListenerCapture);
689
- window.addEventListener("pointerup", handlePointerUp, globalPointerListenerCapture);
690
- window.addEventListener("pointercancel", handlePointerCancel, globalPointerListenerCapture);
739
+ targetWindow.addEventListener("pointermove", handlePointerMove, globalPointerListenerCapture);
740
+ targetWindow.addEventListener("pointerup", handlePointerUp, globalPointerListenerCapture);
741
+ targetWindow.addEventListener("pointercancel", handlePointerCancel, globalPointerListenerCapture);
742
+ this.ensureActivePointerCapture = ensurePointerCapture;
743
+ ensurePointerCapture();
691
744
  this.releaseActiveInputListeners = () => {
692
745
  if (listenersReleased) {
693
746
  return;
694
747
  }
695
748
  listenersReleased = true;
696
- window.removeEventListener("pointermove", handlePointerMove, globalPointerListenerCapture);
697
- window.removeEventListener("pointerup", handlePointerUp, globalPointerListenerCapture);
698
- window.removeEventListener("pointercancel", handlePointerCancel, globalPointerListenerCapture);
749
+ if (this.ensureActivePointerCapture === ensurePointerCapture) {
750
+ this.ensureActivePointerCapture = null;
751
+ }
752
+ releasePointerCapture();
753
+ targetWindow.removeEventListener("pointermove", handlePointerMove, globalPointerListenerCapture);
754
+ targetWindow.removeEventListener("pointerup", handlePointerUp, globalPointerListenerCapture);
755
+ targetWindow.removeEventListener("pointercancel", handlePointerCancel, globalPointerListenerCapture);
699
756
  };
700
757
  }
701
- bindKeyboardWindowListeners() {
758
+ bindKeyboardWindowListeners(targetWindow) {
702
759
  this.releaseActiveInputListeners?.();
703
- this.releaseActiveInputListeners = this.keyboardDrag.bindWindowListeners();
760
+ this.releaseActiveInputListeners =
761
+ this.keyboardDrag.bindWindowListeners(targetWindow);
704
762
  }
705
763
  suppressNextRelatedClick(initiatingElement) {
706
764
  this.clearPostDragClickSuppression();
765
+ const targetWindow = initiatingElement.ownerDocument.defaultView ?? window;
707
766
  let timeoutId = null;
708
767
  const handleClick = (event) => {
709
768
  if (event.detail === 0 ||
710
- !(event.target instanceof Node) ||
769
+ !(event.target instanceof targetWindow.Node) ||
711
770
  !initiatingElement.contains(event.target)) {
712
771
  return;
713
772
  }
@@ -716,47 +775,43 @@ export class DragRuntime {
716
775
  event.stopImmediatePropagation();
717
776
  };
718
777
  const release = () => {
719
- window.removeEventListener("click", handleClick, true);
778
+ targetWindow.removeEventListener("click", handleClick, true);
720
779
  if (timeoutId !== null) {
721
- window.clearTimeout(timeoutId);
780
+ targetWindow.clearTimeout(timeoutId);
722
781
  timeoutId = null;
723
782
  }
724
783
  if (this.releasePostDragClickSuppression === release) {
725
784
  this.releasePostDragClickSuppression = null;
726
785
  }
727
786
  };
728
- window.addEventListener("click", handleClick, true);
787
+ targetWindow.addEventListener("click", handleClick, true);
729
788
  this.releasePostDragClickSuppression = release;
730
- timeoutId = window.setTimeout(release, 0);
789
+ timeoutId = targetWindow.setTimeout(release, 0);
731
790
  }
732
791
  clearPostDragClickSuppression() {
733
792
  const release = this.releasePostDragClickSuppression;
734
793
  this.releasePostDragClickSuppression = null;
735
794
  release?.();
736
795
  }
737
- suppressTextSelection() {
796
+ suppressTextSelection(sourceDocument) {
738
797
  this.restoreTextSelectionSuppression?.();
739
- const root = document.documentElement;
740
- const body = document.body;
741
- const previousRootUserSelect = root.style.userSelect;
742
- const previousBodyUserSelect = body.style.userSelect;
743
- root.style.userSelect = "none";
744
- body.style.userSelect = "none";
745
- this.restoreTextSelectionSuppression = () => {
746
- root.style.userSelect = previousRootUserSelect;
747
- body.style.userSelect = previousBodyUserSelect;
748
- };
798
+ this.restoreTextSelectionSuppression =
799
+ acquireDocumentSelectionSuppression(sourceDocument);
749
800
  }
750
801
  resetActiveDragState() {
751
802
  this.cancelQueuedPointerUpdate();
752
803
  this.setSession({ status: "idle" });
753
804
  this.activeDragModifiers = [];
805
+ this.activeDragWindow = null;
754
806
  }
755
807
  releaseActiveInputResources() {
756
808
  const releaseActiveInputListeners = this.releaseActiveInputListeners;
757
809
  this.releaseActiveInputListeners = null;
810
+ this.ensureActivePointerCapture = null;
758
811
  const restoreTextSelectionSuppression = this.restoreTextSelectionSuppression;
759
812
  this.restoreTextSelectionSuppression = null;
813
+ const releasePointerDragState = this.releasePointerDragState;
814
+ this.releasePointerDragState = null;
760
815
  let releaseError;
761
816
  let hasReleaseError = false;
762
817
  try {
@@ -775,6 +830,15 @@ export class DragRuntime {
775
830
  hasReleaseError = true;
776
831
  }
777
832
  }
833
+ try {
834
+ releasePointerDragState?.();
835
+ }
836
+ catch (error) {
837
+ if (!hasReleaseError) {
838
+ releaseError = error;
839
+ hasReleaseError = true;
840
+ }
841
+ }
778
842
  if (hasReleaseError) {
779
843
  throw releaseError;
780
844
  }
@@ -784,8 +848,9 @@ export class DragRuntime {
784
848
  }
785
849
  flushQueuedPointerUpdate() {
786
850
  if (this.pointerFrameId !== null) {
787
- window.cancelAnimationFrame(this.pointerFrameId);
851
+ (this.pointerFrameWindow ?? window).cancelAnimationFrame(this.pointerFrameId);
788
852
  this.pointerFrameId = null;
853
+ this.pointerFrameWindow = null;
789
854
  }
790
855
  const nextPointerPosition = this.queuedPointerPosition;
791
856
  this.queuedPointerPosition = null;
@@ -795,8 +860,9 @@ export class DragRuntime {
795
860
  }
796
861
  cancelQueuedPointerUpdate() {
797
862
  if (this.pointerFrameId !== null) {
798
- window.cancelAnimationFrame(this.pointerFrameId);
863
+ (this.pointerFrameWindow ?? window).cancelAnimationFrame(this.pointerFrameId);
799
864
  this.pointerFrameId = null;
865
+ this.pointerFrameWindow = null;
800
866
  }
801
867
  this.queuedPointerPosition = null;
802
868
  }
@@ -36,13 +36,15 @@ export type RequestDragStartInput = PointerDragActivationRequest;
36
36
  type BaseStartDragInput = {
37
37
  draggableId: string;
38
38
  group: DragGroup;
39
+ element: HTMLElement;
39
40
  pointerPosition: Point;
40
41
  sourceRect: DragRect;
41
42
  };
42
43
  export type StartDragInput = (BaseStartDragInput & {
43
44
  inputType: "pointer";
44
45
  pointerId: number;
45
- element: HTMLElement;
46
+ pointerCaptureTarget?: Element;
47
+ pointerType?: string;
46
48
  }) | (BaseStartDragInput & {
47
49
  inputType: "keyboard";
48
50
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mk-drag-and-drop/dom",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Headless DOM drag-and-drop primitives for draggable, droppable, sortable, and grouped interactions.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://mkramer.dev",
@@ -42,6 +42,14 @@
42
42
  "dist"
43
43
  ],
44
44
  "sideEffects": false,
45
+ "devDependencies": {
46
+ "eslint": "^8.57.0",
47
+ "jsdom": "^24.1.3",
48
+ "typescript": "5.5.4",
49
+ "vitest": "^2.1.9",
50
+ "@repo/eslint-config": "0.0.0",
51
+ "@repo/typescript-config": "0.0.0"
52
+ },
45
53
  "scripts": {
46
54
  "clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"",
47
55
  "build": "pnpm run clean && tsc -p tsconfig.json",
@@ -49,13 +57,5 @@
49
57
  "lint": "eslint \"src/**/*.ts\"",
50
58
  "test": "vitest run",
51
59
  "test:watch": "vitest"
52
- },
53
- "devDependencies": {
54
- "@repo/eslint-config": "workspace:*",
55
- "@repo/typescript-config": "workspace:*",
56
- "eslint": "^8.57.0",
57
- "jsdom": "^24.1.3",
58
- "typescript": "5.5.4",
59
- "vitest": "^2.1.9"
60
60
  }
61
- }
61
+ }