-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdrag.ts
494 lines (411 loc) · 12.3 KB
/
drag.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
import type {
LitElement,
ReactiveController,
ReactiveControllerHost,
} from 'lit';
import type { Ref } from 'lit/directives/ref.js';
import { getDefaultLayer } from '../../resize-container/default-ghost.js';
import {
findElementFromEventPath,
getRoot,
isLTR,
roundByDPR,
} from '../util.js';
type DragCallback = (parameters: DragCallbackParameters) => unknown;
type DragCancelCallback = (state: DragState) => unknown;
export type DragCallbackParameters = {
event: PointerEvent;
state: DragState;
};
type State = {
initial: DOMRect;
current: DOMRect;
position: { x: number; y: number };
offset: { x: number; y: number };
pointerState: {
initial: { initialX: number; initialY: number };
current: { currentX: number; currentY: number };
direction: Direction;
};
};
type DragState = State & {
ghost: HTMLElement | null;
element: Element | null;
};
type Direction = 'start' | 'end' | 'bottom' | 'top';
type DragControllerConfiguration = {
/** Whether the drag feature is enabled for the current host. */
enabled?: boolean;
/**
* The mode of the drag operation.
*
* Deferred will create a ghost element and keep the original element
* at its place until the operation completes successfully.
*/
mode?: 'immediate' | 'deferred';
/**
* Whether starting a drag operation should snap the dragged item's top left corner
* to the cursor position.
*/
snapToCursor?: boolean;
/**
* Guard function invoked during the `start` callback.
* Returning a truthy value will stop the current drag operation.
*/
skip?: (event: PointerEvent) => boolean;
matchTarget?: (target: Element) => boolean;
/**
*
*/
trigger?: () => HTMLElement;
/**
* Contain drag operations to the scope of the passed DOM element.
*/
container?: Ref<HTMLElement>;
/**
* The DOM element that will "host" the ghost drag element when the controller
* is set to **deferred**.
*
* @remarks
* In **immediate** mode, this property is ignored.
*/
layer?: () => HTMLElement;
ghost?: () => HTMLElement;
/** Callback invoked at the beginning of a drag operation. */
start?: DragCallback;
/** Callback invoked while dragging the target element. */
move?: DragCallback;
enter?: DragCallback;
leave?: DragCallback;
over?: DragCallback;
/** Callback invoked during a drop operation. */
end?: DragCallback;
/** Callback invoked when a drag is cancelled */
cancel?: DragCancelCallback;
};
const additionalEvents = [
'pointermove',
'lostpointercapture',
'contextmenu',
] as const;
class DragController implements ReactiveController {
private _host: ReactiveControllerHost & LitElement;
private _options: DragControllerConfiguration = {
enabled: true,
mode: 'deferred',
snapToCursor: false,
layer: getDefaultLayer,
};
private _state!: State;
private _matchedElement!: Element | null;
private _id = -1;
private _hasPointerCapture = false;
private _ghost: HTMLElement | null = null;
/** Whether `snapToCursor` is enabled for the controller. */
private get _hasSnapping(): boolean {
return Boolean(this._options.snapToCursor);
}
/** Whether the current drag mode is deferred. */
private get _isDeferred(): boolean {
return this._options.mode === 'deferred';
}
/**
* The source element which will capture pointer events and initiate drag mode.
*
* @remarks
* By default that will be the host element itself, unless `trigger` is passed in.
*/
private get _element(): HTMLElement {
return this._options.trigger?.() ?? this._host;
}
/**
* The element being dragged.
*
* @remarks
* When in **deferred** mode this returns a reference to the drag ghost element,
* otherwise it is the host element.
*/
private get _dragItem(): HTMLElement {
return this._isDeferred ? this._ghost! : this._host;
}
/**
* The DOM element that will "host" the ghost drag element when the controller
* is set to **deferred**.
*
* @remarks
* In **immediate** mode, this property is ignored.
*/
private get _layer(): HTMLElement {
if (!this._isDeferred) {
return this._host;
}
return this._options.layer?.() ?? this._host;
}
private get _stateParameters(): DragState {
this._state.pointerState.direction = this._trackPointerMovement();
return {
...this._state,
ghost: this._ghost,
element: this._matchedElement,
};
}
private _trackPointerMovement(): Direction {
const { initialX, initialY } = this._state.pointerState.initial;
const { currentX, currentY } = this._state.pointerState.current;
const deltaX = currentX - initialX;
const deltaY = currentY - initialY;
const LTR = isLTR(this._host);
const isHorizontalMove = Math.abs(deltaX) >= Math.abs(deltaY);
if (isHorizontalMove) {
return (LTR ? deltaX >= 0 : deltaX <= 0) ? 'end' : 'start';
}
return deltaY >= 0 ? 'bottom' : 'top';
}
constructor(
host: ReactiveControllerHost & LitElement,
options?: DragControllerConfiguration
) {
this._host = host;
this._host.addController(this);
this.set(options);
}
// #region Public API
/** Whether the drag controller is enabled. */
public get enabled(): boolean {
return Boolean(this._options.enabled);
}
/** Updates the drag controller configuration. */
public set(options?: DragControllerConfiguration): void {
Object.assign(this._options, options);
}
/** Stops any drag operation and cleans up state, additional event listeners and elements. */
public dispose(): void {
this._matchedElement = null;
this._removeGhost();
this._setDragState(false);
}
/** @internal */
public hostConnected(): void {
this._host.addEventListener('dragstart', this);
this._host.addEventListener('touchstart', this, { passive: false });
this._host.addEventListener('pointerdown', this);
}
/** @internal */
public hostDisconnected(): void {
this._host.removeEventListener('dragstart', this);
this._host.removeEventListener('touchstart', this);
this._host.removeEventListener('pointerdown', this);
this._setDragCancelListener(false);
this._removeGhost();
}
/** @internal */
public handleEvent(event: PointerEvent & KeyboardEvent): void {
if (!this.enabled) {
return;
}
switch (event.type) {
case 'touchstart':
case 'dragstart':
// Prevent contextmenu default behavior during drag
case 'contextmenu':
event.preventDefault();
break;
case 'keydown':
this._handleCancel(event);
break;
case 'pointerdown':
this._handlePointerDown(event);
break;
case 'pointermove':
this._handlePointerMove(event);
break;
case 'lostpointercapture':
this._handlePointerEnd(event);
break;
}
}
// #endregion
// #region Event handlers
private _handlePointerDown(event: PointerEvent): void {
if (this._shouldSkip(event)) {
return;
}
this._setInitialState(event);
this._createDragGhost();
this._updatePosition(event);
const parameters = {
event,
state: this._stateParameters,
};
if (this._options.start?.call(this._host, parameters) === false) {
this.dispose();
return;
}
this._assignPosition(this._dragItem);
this._setDragState();
}
private _handlePointerMove(event: PointerEvent): void {
if (!this._hasPointerCapture) {
return;
}
this._updatePosition(event);
this._updateMatcher(event);
this._state.pointerState.initial = {
initialX: this._state.pointerState.current.currentX,
initialY: this._state.pointerState.current.currentY,
};
this._state.pointerState.current = {
currentX: event.clientX,
currentY: event.clientY,
};
const parameters = {
event,
state: this._stateParameters,
};
this._options.move?.call(this._host, parameters);
this._assignPosition(this._dragItem);
}
private _handlePointerEnd(event: PointerEvent): void {
this._options.end?.call(this._host, {
event,
state: this._stateParameters,
});
this.dispose();
}
private _handleCancel(event: KeyboardEvent): void {
const key = event.key.toLowerCase();
if (this._hasPointerCapture && key === 'escape') {
// Reset state
this._options.cancel?.call(this._host, this._stateParameters);
}
}
// #endregion
private _setDragCancelListener(enabled = true): void {
enabled
? globalThis.addEventListener('keydown', this)
: globalThis.removeEventListener('keydown', this);
}
private _setInitialState({
pointerId,
clientX,
clientY,
}: PointerEvent): void {
const rect = this._host.getBoundingClientRect();
const position = { x: rect.x, y: rect.y };
const offset = { x: rect.x - clientX, y: rect.y - clientY };
this._id = pointerId;
this._state = {
initial: rect,
current: structuredClone(rect),
position,
offset,
pointerState: {
initial: { initialX: clientX, initialY: clientY },
current: { currentX: clientX, currentY: clientY },
direction: 'end',
},
};
}
private _setDragState(enabled = true): void {
this._hasPointerCapture = enabled;
const cssValue = enabled ? 'none' : '';
Object.assign(this._element.style, {
touchAction: cssValue,
userSelect: cssValue,
});
enabled
? this._element.setPointerCapture(this._id)
: this._element.releasePointerCapture(this._id);
this._setDragCancelListener(enabled);
// Toggle additional events
for (const type of additionalEvents) {
enabled
? this._host.addEventListener(type, this)
: this._host.removeEventListener(type, this);
}
}
private _updateMatcher(event: PointerEvent) {
if (!this._options.matchTarget) {
return;
}
const match = getRoot(this._host)
.elementsFromPoint(event.clientX, event.clientY)
.find((element) => this._options.matchTarget!.call(this._host, element));
if (match && !this._matchedElement) {
this._matchedElement = match;
this._options.enter?.call(this._host, {
event,
state: this._stateParameters,
});
return;
}
if (!match && this._matchedElement) {
this._options.leave?.call(this._host, {
event,
state: this._stateParameters,
});
this._matchedElement = null;
return;
}
if (match && match === this._matchedElement) {
this._options.over?.call(this._host, {
event,
state: this._stateParameters,
});
}
}
private _updatePosition({ clientX, clientY }: PointerEvent): void {
const { x, y } = this._state.offset;
const { x: layerX, y: layerY } = this._isDeferred
? this._layer.getBoundingClientRect()
: this._state.initial;
const posX = this._hasSnapping ? clientX - layerX : clientX - layerX + x;
const posY = this._hasSnapping ? clientY - layerY : clientY - layerY + y;
Object.assign(this._state.position, { x: posX, y: posY });
}
private _assignPosition(element: HTMLElement): void {
element.style.transform = `translate3d(${roundByDPR(this._state.position.x)}px,${roundByDPR(this._state.position.y)}px,0)`;
}
private _createDragGhost(): void {
if (!this._isDeferred) {
return;
}
this._ghost =
this._options.ghost?.call(this._host) ??
createDefaultDragGhost(this._host.getBoundingClientRect());
this._layer.append(this._ghost);
}
private _removeGhost(): void {
this._ghost?.remove();
this._ghost = null;
}
private _shouldSkip(event: PointerEvent): boolean {
return (
Boolean(event.button) ||
this._options.skip?.call(this._host, event) ||
!findElementFromEventPath((e) => e === this._element, event)
);
}
}
function createDefaultDragGhost({ x, y, width, height }: DOMRect): HTMLElement {
const element = document.createElement('div');
Object.assign(element.style, {
position: 'absolute',
left: `${x}px`,
top: `${y}px`,
width: `${width}px`,
height: `${height}px`,
zIndex: 1000,
background: 'gold',
});
return element;
}
/**
* Adds a drag and drop controller to the given host
*/
export function addDragController(
host: ReactiveControllerHost & LitElement,
options?: DragControllerConfiguration
): DragController {
return new DragController(host, options);
}