-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
drag-ref.ts
1562 lines (1336 loc) · 58.9 KB
/
drag-ref.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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {isFakeMousedownFromScreenReader, isFakeTouchstartFromScreenReader} from '@angular/cdk/a11y';
import {Direction} from '@angular/cdk/bidi';
import {coerceElement} from '@angular/cdk/coercion';
import {
_getEventTarget,
_getShadowRoot,
normalizePassiveListenerOptions,
} from '@angular/cdk/platform';
import {ViewportRuler} from '@angular/cdk/scrolling';
import {
ElementRef,
EmbeddedViewRef,
NgZone,
TemplateRef,
ViewContainerRef,
signal,
} from '@angular/core';
import {Observable, Subject, Subscription} from 'rxjs';
import {deepCloneNode} from './dom/clone-node';
import {adjustDomRect, getMutableClientRect} from './dom/dom-rect';
import {ParentPositionTracker} from './dom/parent-position-tracker';
import {getRootNode} from './dom/root-node';
import {
DragCSSStyleDeclaration,
combineTransforms,
getTransform,
toggleNativeDragInteractions,
toggleVisibility,
} from './dom/styling';
import {DragDropRegistry} from './drag-drop-registry';
import type {DropListRef} from './drop-list-ref';
import {DragPreviewTemplate, PreviewRef} from './preview-ref';
/** Object that can be used to configure the behavior of DragRef. */
export interface DragRefConfig {
/**
* Minimum amount of pixels that the user should
* drag, before the CDK initiates a drag sequence.
*/
dragStartThreshold: number;
/**
* Amount the pixels the user should drag before the CDK
* considers them to have changed the drag direction.
*/
pointerDirectionChangeThreshold: number;
/** `z-index` for the absolutely-positioned elements that are created by the drag item. */
zIndex?: number;
/** Ref that the current drag item is nested in. */
parentDragRef?: DragRef;
}
/** Options that can be used to bind a passive event listener. */
const passiveEventListenerOptions = normalizePassiveListenerOptions({passive: true});
/** Options that can be used to bind an active event listener. */
const activeEventListenerOptions = normalizePassiveListenerOptions({passive: false});
/** Event options that can be used to bind an active, capturing event. */
const activeCapturingEventOptions = normalizePassiveListenerOptions({
passive: false,
capture: true,
});
/**
* Time in milliseconds for which to ignore mouse events, after
* receiving a touch event. Used to avoid doing double work for
* touch devices where the browser fires fake mouse events, in
* addition to touch events.
*/
const MOUSE_EVENT_IGNORE_TIME = 800;
// TODO(crisbeto): add an API for moving a draggable up/down the
// list programmatically. Useful for keyboard controls.
/** Template that can be used to create a drag helper element (e.g. a preview or a placeholder). */
interface DragHelperTemplate<T = any> {
template: TemplateRef<T> | null;
viewContainer: ViewContainerRef;
context: T;
}
/** Point on the page or within an element. */
export interface Point {
x: number;
y: number;
}
/** Inline styles to be set as `!important` while dragging. */
const dragImportantProperties = new Set([
// Needs to be important, because some `mat-table` sets `position: sticky !important`. See #22781.
'position',
]);
/**
* Possible places into which the preview of a drag item can be inserted.
* - `global` - Preview will be inserted at the bottom of the `<body>`. The advantage is that
* you don't have to worry about `overflow: hidden` or `z-index`, but the item won't retain
* its inherited styles.
* - `parent` - Preview will be inserted into the parent of the drag item. The advantage is that
* inherited styles will be preserved, but it may be clipped by `overflow: hidden` or not be
* visible due to `z-index`. Furthermore, the preview is going to have an effect over selectors
* like `:nth-child` and some flexbox configurations.
* - `ElementRef<HTMLElement> | HTMLElement` - Preview will be inserted into a specific element.
* Same advantages and disadvantages as `parent`.
*/
export type PreviewContainer = 'global' | 'parent' | ElementRef<HTMLElement> | HTMLElement;
/**
* Reference to a draggable item. Used to manipulate or dispose of the item.
*/
export class DragRef<T = any> {
/** Element displayed next to the user's pointer while the element is dragged. */
private _preview: PreviewRef | null;
/** Container into which to insert the preview. */
private _previewContainer: PreviewContainer | undefined;
/** Reference to the view of the placeholder element. */
private _placeholderRef: EmbeddedViewRef<any> | null;
/** Element that is rendered instead of the draggable item while it is being sorted. */
private _placeholder: HTMLElement;
/** Coordinates within the element at which the user picked up the element. */
private _pickupPositionInElement: Point;
/** Coordinates on the page at which the user picked up the element. */
private _pickupPositionOnPage: Point;
/**
* Anchor node used to save the place in the DOM where the element was
* picked up so that it can be restored at the end of the drag sequence.
*/
private _anchor: Comment;
/**
* CSS `transform` applied to the element when it isn't being dragged. We need a
* passive transform in order for the dragged element to retain its new position
* after the user has stopped dragging and because we need to know the relative
* position in case they start dragging again. This corresponds to `element.style.transform`.
*/
private _passiveTransform: Point = {x: 0, y: 0};
/** CSS `transform` that is applied to the element while it's being dragged. */
private _activeTransform: Point = {x: 0, y: 0};
/** Inline `transform` value that the element had before the first dragging sequence. */
private _initialTransform?: string;
/**
* Whether the dragging sequence has been started. Doesn't
* necessarily mean that the element has been moved.
*/
private _hasStartedDragging = signal(false);
/** Whether the element has moved since the user started dragging it. */
private _hasMoved: boolean;
/** Drop container in which the DragRef resided when dragging began. */
private _initialContainer: DropListRef;
/** Index at which the item started in its initial container. */
private _initialIndex: number;
/** Cached positions of scrollable parent elements. */
private _parentPositions: ParentPositionTracker;
/** Emits when the item is being moved. */
private readonly _moveEvents = new Subject<{
source: DragRef;
pointerPosition: {x: number; y: number};
event: MouseEvent | TouchEvent;
distance: Point;
delta: {x: -1 | 0 | 1; y: -1 | 0 | 1};
}>();
/** Keeps track of the direction in which the user is dragging along each axis. */
private _pointerDirectionDelta: {x: -1 | 0 | 1; y: -1 | 0 | 1};
/** Pointer position at which the last change in the delta occurred. */
private _pointerPositionAtLastDirectionChange: Point;
/** Position of the pointer at the last pointer event. */
private _lastKnownPointerPosition: Point;
/**
* Root DOM node of the drag instance. This is the element that will
* be moved around as the user is dragging.
*/
private _rootElement: HTMLElement;
/**
* Nearest ancestor SVG, relative to which coordinates are calculated if dragging SVGElement
*/
private _ownerSVGElement: SVGSVGElement | null;
/**
* Inline style value of `-webkit-tap-highlight-color` at the time the
* dragging was started. Used to restore the value once we're done dragging.
*/
private _rootElementTapHighlight: string;
/** Subscription to pointer movement events. */
private _pointerMoveSubscription = Subscription.EMPTY;
/** Subscription to the event that is dispatched when the user lifts their pointer. */
private _pointerUpSubscription = Subscription.EMPTY;
/** Subscription to the viewport being scrolled. */
private _scrollSubscription = Subscription.EMPTY;
/** Subscription to the viewport being resized. */
private _resizeSubscription = Subscription.EMPTY;
/**
* Time at which the last touch event occurred. Used to avoid firing the same
* events multiple times on touch devices where the browser will fire a fake
* mouse event for each touch event, after a certain time.
*/
private _lastTouchEventTime: number;
/** Time at which the last dragging sequence was started. */
private _dragStartTime: number;
/** Cached reference to the boundary element. */
private _boundaryElement: HTMLElement | null = null;
/** Whether the native dragging interactions have been enabled on the root element. */
private _nativeInteractionsEnabled = true;
/** Client rect of the root element when the dragging sequence has started. */
private _initialDomRect?: DOMRect;
/** Cached dimensions of the preview element. Should be read via `_getPreviewRect`. */
private _previewRect?: DOMRect;
/** Cached dimensions of the boundary element. */
private _boundaryRect?: DOMRect;
/** Element that will be used as a template to create the draggable item's preview. */
private _previewTemplate?: DragPreviewTemplate | null;
/** Template for placeholder element rendered to show where a draggable would be dropped. */
private _placeholderTemplate?: DragHelperTemplate | null;
/** Elements that can be used to drag the draggable item. */
private _handles: HTMLElement[] = [];
/** Registered handles that are currently disabled. */
private _disabledHandles = new Set<HTMLElement>();
/** Droppable container that the draggable is a part of. */
private _dropContainer?: DropListRef;
/** Layout direction of the item. */
private _direction: Direction = 'ltr';
/** Ref that the current drag item is nested in. */
private _parentDragRef: DragRef<unknown> | null;
/**
* Cached shadow root that the element is placed in. `null` means that the element isn't in
* the shadow DOM and `undefined` means that it hasn't been resolved yet. Should be read via
* `_getShadowRoot`, not directly.
*/
private _cachedShadowRoot: ShadowRoot | null | undefined;
/** Axis along which dragging is locked. */
lockAxis: 'x' | 'y';
/**
* Amount of milliseconds to wait after the user has put their
* pointer down before starting to drag the element.
*/
dragStartDelay: number | {touch: number; mouse: number} = 0;
/** Class to be added to the preview element. */
previewClass: string | string[] | undefined;
/**
* If the parent of the dragged element has a `scale` transform, it can throw off the
* positioning when the user starts dragging. Use this input to notify the CDK of the scale.
*/
scale: number = 1;
/** Whether starting to drag this element is disabled. */
get disabled(): boolean {
return this._disabled || !!(this._dropContainer && this._dropContainer.disabled);
}
set disabled(value: boolean) {
if (value !== this._disabled) {
this._disabled = value;
this._toggleNativeDragInteractions();
this._handles.forEach(handle => toggleNativeDragInteractions(handle, value));
}
}
private _disabled = false;
/** Emits as the drag sequence is being prepared. */
readonly beforeStarted = new Subject<void>();
/** Emits when the user starts dragging the item. */
readonly started = new Subject<{source: DragRef; event: MouseEvent | TouchEvent}>();
/** Emits when the user has released a drag item, before any animations have started. */
readonly released = new Subject<{source: DragRef; event: MouseEvent | TouchEvent}>();
/** Emits when the user stops dragging an item in the container. */
readonly ended = new Subject<{
source: DragRef;
distance: Point;
dropPoint: Point;
event: MouseEvent | TouchEvent;
}>();
/** Emits when the user has moved the item into a new container. */
readonly entered = new Subject<{container: DropListRef; item: DragRef; currentIndex: number}>();
/** Emits when the user removes the item its container by dragging it into another container. */
readonly exited = new Subject<{container: DropListRef; item: DragRef}>();
/** Emits when the user drops the item inside a container. */
readonly dropped = new Subject<{
previousIndex: number;
currentIndex: number;
item: DragRef;
container: DropListRef;
previousContainer: DropListRef;
distance: Point;
dropPoint: Point;
isPointerOverContainer: boolean;
event: MouseEvent | TouchEvent;
}>();
/**
* Emits as the user is dragging the item. Use with caution,
* because this event will fire for every pixel that the user has dragged.
*/
readonly moved: Observable<{
source: DragRef;
pointerPosition: {x: number; y: number};
event: MouseEvent | TouchEvent;
distance: Point;
delta: {x: -1 | 0 | 1; y: -1 | 0 | 1};
}> = this._moveEvents;
/** Arbitrary data that can be attached to the drag item. */
data: T;
/**
* Function that can be used to customize the logic of how the position of the drag item
* is limited while it's being dragged. Gets called with a point containing the current position
* of the user's pointer on the page, a reference to the item being dragged and its dimensions.
* Should return a point describing where the item should be rendered.
*/
constrainPosition?: (
userPointerPosition: Point,
dragRef: DragRef,
dimensions: DOMRect,
pickupPositionInElement: Point,
) => Point;
constructor(
element: ElementRef<HTMLElement> | HTMLElement,
private _config: DragRefConfig,
private _document: Document,
private _ngZone: NgZone,
private _viewportRuler: ViewportRuler,
private _dragDropRegistry: DragDropRegistry,
) {
this.withRootElement(element).withParent(_config.parentDragRef || null);
this._parentPositions = new ParentPositionTracker(_document);
_dragDropRegistry.registerDragItem(this);
}
/**
* Returns the element that is being used as a placeholder
* while the current element is being dragged.
*/
getPlaceholderElement(): HTMLElement {
return this._placeholder;
}
/** Returns the root draggable element. */
getRootElement(): HTMLElement {
return this._rootElement;
}
/**
* Gets the currently-visible element that represents the drag item.
* While dragging this is the placeholder, otherwise it's the root element.
*/
getVisibleElement(): HTMLElement {
return this.isDragging() ? this.getPlaceholderElement() : this.getRootElement();
}
/** Registers the handles that can be used to drag the element. */
withHandles(handles: (HTMLElement | ElementRef<HTMLElement>)[]): this {
this._handles = handles.map(handle => coerceElement(handle));
this._handles.forEach(handle => toggleNativeDragInteractions(handle, this.disabled));
this._toggleNativeDragInteractions();
// Delete any lingering disabled handles that may have been destroyed. Note that we re-create
// the set, rather than iterate over it and filter out the destroyed handles, because while
// the ES spec allows for sets to be modified while they're being iterated over, some polyfills
// use an array internally which may throw an error.
const disabledHandles = new Set<HTMLElement>();
this._disabledHandles.forEach(handle => {
if (this._handles.indexOf(handle) > -1) {
disabledHandles.add(handle);
}
});
this._disabledHandles = disabledHandles;
return this;
}
/**
* Registers the template that should be used for the drag preview.
* @param template Template that from which to stamp out the preview.
*/
withPreviewTemplate(template: DragPreviewTemplate | null): this {
this._previewTemplate = template;
return this;
}
/**
* Registers the template that should be used for the drag placeholder.
* @param template Template that from which to stamp out the placeholder.
*/
withPlaceholderTemplate(template: DragHelperTemplate | null): this {
this._placeholderTemplate = template;
return this;
}
/**
* Sets an alternate drag root element. The root element is the element that will be moved as
* the user is dragging. Passing an alternate root element is useful when trying to enable
* dragging on an element that you might not have access to.
*/
withRootElement(rootElement: ElementRef<HTMLElement> | HTMLElement): this {
const element = coerceElement(rootElement);
if (element !== this._rootElement) {
if (this._rootElement) {
this._removeRootElementListeners(this._rootElement);
}
this._ngZone.runOutsideAngular(() => {
element.addEventListener('mousedown', this._pointerDown, activeEventListenerOptions);
element.addEventListener('touchstart', this._pointerDown, passiveEventListenerOptions);
element.addEventListener('dragstart', this._nativeDragStart, activeEventListenerOptions);
});
this._initialTransform = undefined;
this._rootElement = element;
}
if (typeof SVGElement !== 'undefined' && this._rootElement instanceof SVGElement) {
this._ownerSVGElement = this._rootElement.ownerSVGElement;
}
return this;
}
/**
* Element to which the draggable's position will be constrained.
*/
withBoundaryElement(boundaryElement: ElementRef<HTMLElement> | HTMLElement | null): this {
this._boundaryElement = boundaryElement ? coerceElement(boundaryElement) : null;
this._resizeSubscription.unsubscribe();
if (boundaryElement) {
this._resizeSubscription = this._viewportRuler
.change(10)
.subscribe(() => this._containInsideBoundaryOnResize());
}
return this;
}
/** Sets the parent ref that the ref is nested in. */
withParent(parent: DragRef<unknown> | null): this {
this._parentDragRef = parent;
return this;
}
/** Removes the dragging functionality from the DOM element. */
dispose() {
this._removeRootElementListeners(this._rootElement);
// Do this check before removing from the registry since it'll
// stop being considered as dragged once it is removed.
if (this.isDragging()) {
// Since we move out the element to the end of the body while it's being
// dragged, we have to make sure that it's removed if it gets destroyed.
this._rootElement?.remove();
}
this._anchor?.remove();
this._destroyPreview();
this._destroyPlaceholder();
this._dragDropRegistry.removeDragItem(this);
this._removeListeners();
this.beforeStarted.complete();
this.started.complete();
this.released.complete();
this.ended.complete();
this.entered.complete();
this.exited.complete();
this.dropped.complete();
this._moveEvents.complete();
this._handles = [];
this._disabledHandles.clear();
this._dropContainer = undefined;
this._resizeSubscription.unsubscribe();
this._parentPositions.clear();
this._boundaryElement =
this._rootElement =
this._ownerSVGElement =
this._placeholderTemplate =
this._previewTemplate =
this._anchor =
this._parentDragRef =
null!;
}
/** Checks whether the element is currently being dragged. */
isDragging(): boolean {
return this._hasStartedDragging() && this._dragDropRegistry.isDragging(this);
}
/** Resets a standalone drag item to its initial position. */
reset(): void {
this._rootElement.style.transform = this._initialTransform || '';
this._activeTransform = {x: 0, y: 0};
this._passiveTransform = {x: 0, y: 0};
}
/**
* Sets a handle as disabled. While a handle is disabled, it'll capture and interrupt dragging.
* @param handle Handle element that should be disabled.
*/
disableHandle(handle: HTMLElement) {
if (!this._disabledHandles.has(handle) && this._handles.indexOf(handle) > -1) {
this._disabledHandles.add(handle);
toggleNativeDragInteractions(handle, true);
}
}
/**
* Enables a handle, if it has been disabled.
* @param handle Handle element to be enabled.
*/
enableHandle(handle: HTMLElement) {
if (this._disabledHandles.has(handle)) {
this._disabledHandles.delete(handle);
toggleNativeDragInteractions(handle, this.disabled);
}
}
/** Sets the layout direction of the draggable item. */
withDirection(direction: Direction): this {
this._direction = direction;
return this;
}
/** Sets the container that the item is part of. */
_withDropContainer(container: DropListRef) {
this._dropContainer = container;
}
/**
* Gets the current position in pixels the draggable outside of a drop container.
*/
getFreeDragPosition(): Readonly<Point> {
const position = this.isDragging() ? this._activeTransform : this._passiveTransform;
return {x: position.x, y: position.y};
}
/**
* Sets the current position in pixels the draggable outside of a drop container.
* @param value New position to be set.
*/
setFreeDragPosition(value: Point): this {
this._activeTransform = {x: 0, y: 0};
this._passiveTransform.x = value.x;
this._passiveTransform.y = value.y;
if (!this._dropContainer) {
this._applyRootElementTransform(value.x, value.y);
}
return this;
}
/**
* Sets the container into which to insert the preview element.
* @param value Container into which to insert the preview.
*/
withPreviewContainer(value: PreviewContainer): this {
this._previewContainer = value;
return this;
}
/** Updates the item's sort order based on the last-known pointer position. */
_sortFromLastPointerPosition() {
const position = this._lastKnownPointerPosition;
if (position && this._dropContainer) {
this._updateActiveDropContainer(this._getConstrainedPointerPosition(position), position);
}
}
/** Unsubscribes from the global subscriptions. */
private _removeListeners() {
this._pointerMoveSubscription.unsubscribe();
this._pointerUpSubscription.unsubscribe();
this._scrollSubscription.unsubscribe();
this._getShadowRoot()?.removeEventListener(
'selectstart',
shadowDomSelectStart,
activeCapturingEventOptions,
);
}
/** Destroys the preview element and its ViewRef. */
private _destroyPreview() {
this._preview?.destroy();
this._preview = null;
}
/** Destroys the placeholder element and its ViewRef. */
private _destroyPlaceholder() {
this._placeholder?.remove();
this._placeholderRef?.destroy();
this._placeholder = this._placeholderRef = null!;
}
/** Handler for the `mousedown`/`touchstart` events. */
private _pointerDown = (event: MouseEvent | TouchEvent) => {
this.beforeStarted.next();
// Delegate the event based on whether it started from a handle or the element itself.
if (this._handles.length) {
const targetHandle = this._getTargetHandle(event);
if (targetHandle && !this._disabledHandles.has(targetHandle) && !this.disabled) {
this._initializeDragSequence(targetHandle, event);
}
} else if (!this.disabled) {
this._initializeDragSequence(this._rootElement, event);
}
};
/** Handler that is invoked when the user moves their pointer after they've initiated a drag. */
private _pointerMove = (event: MouseEvent | TouchEvent) => {
const pointerPosition = this._getPointerPositionOnPage(event);
if (!this._hasStartedDragging()) {
const distanceX = Math.abs(pointerPosition.x - this._pickupPositionOnPage.x);
const distanceY = Math.abs(pointerPosition.y - this._pickupPositionOnPage.y);
const isOverThreshold = distanceX + distanceY >= this._config.dragStartThreshold;
// Only start dragging after the user has moved more than the minimum distance in either
// direction. Note that this is preferable over doing something like `skip(minimumDistance)`
// in the `pointerMove` subscription, because we're not guaranteed to have one move event
// per pixel of movement (e.g. if the user moves their pointer quickly).
if (isOverThreshold) {
const isDelayElapsed = Date.now() >= this._dragStartTime + this._getDragStartDelay(event);
const container = this._dropContainer;
if (!isDelayElapsed) {
this._endDragSequence(event);
return;
}
// Prevent other drag sequences from starting while something in the container is still
// being dragged. This can happen while we're waiting for the drop animation to finish
// and can cause errors, because some elements might still be moving around.
if (!container || (!container.isDragging() && !container.isReceiving())) {
// Prevent the default action as soon as the dragging sequence is considered as
// "started" since waiting for the next event can allow the device to begin scrolling.
if (event.cancelable) {
event.preventDefault();
}
this._hasStartedDragging.set(true);
this._ngZone.run(() => this._startDragSequence(event));
}
}
return;
}
// We prevent the default action down here so that we know that dragging has started. This is
// important for touch devices where doing this too early can unnecessarily block scrolling,
// if there's a dragging delay.
if (event.cancelable) {
event.preventDefault();
}
const constrainedPointerPosition = this._getConstrainedPointerPosition(pointerPosition);
this._hasMoved = true;
this._lastKnownPointerPosition = pointerPosition;
this._updatePointerDirectionDelta(constrainedPointerPosition);
if (this._dropContainer) {
this._updateActiveDropContainer(constrainedPointerPosition, pointerPosition);
} else {
// If there's a position constraint function, we want the element's top/left to be at the
// specific position on the page. Use the initial position as a reference if that's the case.
const offset = this.constrainPosition ? this._initialDomRect! : this._pickupPositionOnPage;
const activeTransform = this._activeTransform;
activeTransform.x = constrainedPointerPosition.x - offset.x + this._passiveTransform.x;
activeTransform.y = constrainedPointerPosition.y - offset.y + this._passiveTransform.y;
this._applyRootElementTransform(activeTransform.x, activeTransform.y);
}
// Since this event gets fired for every pixel while dragging, we only
// want to fire it if the consumer opted into it. Also we have to
// re-enter the zone because we run all of the events on the outside.
if (this._moveEvents.observers.length) {
this._ngZone.run(() => {
this._moveEvents.next({
source: this,
pointerPosition: constrainedPointerPosition,
event,
distance: this._getDragDistance(constrainedPointerPosition),
delta: this._pointerDirectionDelta,
});
});
}
};
/** Handler that is invoked when the user lifts their pointer up, after initiating a drag. */
private _pointerUp = (event: MouseEvent | TouchEvent) => {
this._endDragSequence(event);
};
/**
* Clears subscriptions and stops the dragging sequence.
* @param event Browser event object that ended the sequence.
*/
private _endDragSequence(event: MouseEvent | TouchEvent) {
// Note that here we use `isDragging` from the service, rather than from `this`.
// The difference is that the one from the service reflects whether a dragging sequence
// has been initiated, whereas the one on `this` includes whether the user has passed
// the minimum dragging threshold.
if (!this._dragDropRegistry.isDragging(this)) {
return;
}
this._removeListeners();
this._dragDropRegistry.stopDragging(this);
this._toggleNativeDragInteractions();
if (this._handles) {
(this._rootElement.style as DragCSSStyleDeclaration).webkitTapHighlightColor =
this._rootElementTapHighlight;
}
if (!this._hasStartedDragging()) {
return;
}
this.released.next({source: this, event});
if (this._dropContainer) {
// Stop scrolling immediately, instead of waiting for the animation to finish.
this._dropContainer._stopScrolling();
this._animatePreviewToPlaceholder().then(() => {
this._cleanupDragArtifacts(event);
this._cleanupCachedDimensions();
this._dragDropRegistry.stopDragging(this);
});
} else {
// Convert the active transform into a passive one. This means that next time
// the user starts dragging the item, its position will be calculated relatively
// to the new passive transform.
this._passiveTransform.x = this._activeTransform.x;
const pointerPosition = this._getPointerPositionOnPage(event);
this._passiveTransform.y = this._activeTransform.y;
this._ngZone.run(() => {
this.ended.next({
source: this,
distance: this._getDragDistance(pointerPosition),
dropPoint: pointerPosition,
event,
});
});
this._cleanupCachedDimensions();
this._dragDropRegistry.stopDragging(this);
}
}
/** Starts the dragging sequence. */
private _startDragSequence(event: MouseEvent | TouchEvent) {
if (isTouchEvent(event)) {
this._lastTouchEventTime = Date.now();
}
this._toggleNativeDragInteractions();
// Needs to happen before the root element is moved.
const shadowRoot = this._getShadowRoot();
const dropContainer = this._dropContainer;
if (shadowRoot) {
// In some browsers the global `selectstart` that we maintain in the `DragDropRegistry`
// doesn't cross the shadow boundary so we have to prevent it at the shadow root (see #28792).
this._ngZone.runOutsideAngular(() => {
shadowRoot.addEventListener(
'selectstart',
shadowDomSelectStart,
activeCapturingEventOptions,
);
});
}
if (dropContainer) {
const element = this._rootElement;
const parent = element.parentNode as HTMLElement;
const placeholder = (this._placeholder = this._createPlaceholderElement());
const anchor = (this._anchor =
this._anchor ||
this._document.createComment(
typeof ngDevMode === 'undefined' || ngDevMode ? 'cdk-drag-anchor' : '',
));
// Insert an anchor node so that we can restore the element's position in the DOM.
parent.insertBefore(anchor, element);
// There's no risk of transforms stacking when inside a drop container so
// we can keep the initial transform up to date any time dragging starts.
this._initialTransform = element.style.transform || '';
// Create the preview after the initial transform has
// been cached, because it can be affected by the transform.
this._preview = new PreviewRef(
this._document,
this._rootElement,
this._direction,
this._initialDomRect!,
this._previewTemplate || null,
this.previewClass || null,
this._pickupPositionOnPage,
this._initialTransform,
this._config.zIndex || 1000,
);
this._preview.attach(this._getPreviewInsertionPoint(parent, shadowRoot));
// We move the element out at the end of the body and we make it hidden, because keeping it in
// place will throw off the consumer's `:last-child` selectors. We can't remove the element
// from the DOM completely, because iOS will stop firing all subsequent events in the chain.
toggleVisibility(element, false, dragImportantProperties);
this._document.body.appendChild(parent.replaceChild(placeholder, element));
this.started.next({source: this, event}); // Emit before notifying the container.
dropContainer.start();
this._initialContainer = dropContainer;
this._initialIndex = dropContainer.getItemIndex(this);
} else {
this.started.next({source: this, event});
this._initialContainer = this._initialIndex = undefined!;
}
// Important to run after we've called `start` on the parent container
// so that it has had time to resolve its scrollable parents.
this._parentPositions.cache(dropContainer ? dropContainer.getScrollableParents() : []);
}
/**
* Sets up the different variables and subscriptions
* that will be necessary for the dragging sequence.
* @param referenceElement Element that started the drag sequence.
* @param event Browser event object that started the sequence.
*/
private _initializeDragSequence(referenceElement: HTMLElement, event: MouseEvent | TouchEvent) {
// Stop propagation if the item is inside another
// draggable so we don't start multiple drag sequences.
if (this._parentDragRef) {
event.stopPropagation();
}
const isDragging = this.isDragging();
const isTouchSequence = isTouchEvent(event);
const isAuxiliaryMouseButton = !isTouchSequence && (event as MouseEvent).button !== 0;
const rootElement = this._rootElement;
const target = _getEventTarget(event);
const isSyntheticEvent =
!isTouchSequence &&
this._lastTouchEventTime &&
this._lastTouchEventTime + MOUSE_EVENT_IGNORE_TIME > Date.now();
const isFakeEvent = isTouchSequence
? isFakeTouchstartFromScreenReader(event as TouchEvent)
: isFakeMousedownFromScreenReader(event as MouseEvent);
// If the event started from an element with the native HTML drag&drop, it'll interfere
// with our own dragging (e.g. `img` tags do it by default). Prevent the default action
// to stop it from happening. Note that preventing on `dragstart` also seems to work, but
// it's flaky and it fails if the user drags it away quickly. Also note that we only want
// to do this for `mousedown` since doing the same for `touchstart` will stop any `click`
// events from firing on touch devices.
if (target && (target as HTMLElement).draggable && event.type === 'mousedown') {
event.preventDefault();
}
// Abort if the user is already dragging or is using a mouse button other than the primary one.
if (isDragging || isAuxiliaryMouseButton || isSyntheticEvent || isFakeEvent) {
return;
}
// If we've got handles, we need to disable the tap highlight on the entire root element,
// otherwise iOS will still add it, even though all the drag interactions on the handle
// are disabled.
if (this._handles.length) {
const rootStyles = rootElement.style as DragCSSStyleDeclaration;
this._rootElementTapHighlight = rootStyles.webkitTapHighlightColor || '';
rootStyles.webkitTapHighlightColor = 'transparent';
}
this._hasMoved = false;
this._hasStartedDragging.set(this._hasMoved);
// Avoid multiple subscriptions and memory leaks when multi touch
// (isDragging check above isn't enough because of possible temporal and/or dimensional delays)
this._removeListeners();
this._initialDomRect = this._rootElement.getBoundingClientRect();
this._pointerMoveSubscription = this._dragDropRegistry.pointerMove.subscribe(this._pointerMove);
this._pointerUpSubscription = this._dragDropRegistry.pointerUp.subscribe(this._pointerUp);
this._scrollSubscription = this._dragDropRegistry
.scrolled(this._getShadowRoot())
.subscribe(scrollEvent => this._updateOnScroll(scrollEvent));
if (this._boundaryElement) {
this._boundaryRect = getMutableClientRect(this._boundaryElement);
}
// If we have a custom preview we can't know ahead of time how large it'll be so we position
// it next to the cursor. The exception is when the consumer has opted into making the preview
// the same size as the root element, in which case we do know the size.
const previewTemplate = this._previewTemplate;
this._pickupPositionInElement =
previewTemplate && previewTemplate.template && !previewTemplate.matchSize
? {x: 0, y: 0}
: this._getPointerPositionInElement(this._initialDomRect, referenceElement, event);
const pointerPosition =
(this._pickupPositionOnPage =
this._lastKnownPointerPosition =
this._getPointerPositionOnPage(event));
this._pointerDirectionDelta = {x: 0, y: 0};
this._pointerPositionAtLastDirectionChange = {x: pointerPosition.x, y: pointerPosition.y};
this._dragStartTime = Date.now();
this._dragDropRegistry.startDragging(this, event);
}
/** Cleans up the DOM artifacts that were added to facilitate the element being dragged. */
private _cleanupDragArtifacts(event: MouseEvent | TouchEvent) {
// Restore the element's visibility and insert it at its old position in the DOM.
// It's important that we maintain the position, because moving the element around in the DOM
// can throw off `NgFor` which does smart diffing and re-creates elements only when necessary,
// while moving the existing elements in all other cases.
toggleVisibility(this._rootElement, true, dragImportantProperties);
this._anchor.parentNode!.replaceChild(this._rootElement, this._anchor);
this._destroyPreview();
this._destroyPlaceholder();
this._initialDomRect =
this._boundaryRect =
this._previewRect =
this._initialTransform =
undefined;
// Re-enter the NgZone since we bound `document` events on the outside.
this._ngZone.run(() => {
const container = this._dropContainer!;
const currentIndex = container.getItemIndex(this);
const pointerPosition = this._getPointerPositionOnPage(event);
const distance = this._getDragDistance(pointerPosition);
const isPointerOverContainer = container._isOverContainer(
pointerPosition.x,
pointerPosition.y,
);
this.ended.next({source: this, distance, dropPoint: pointerPosition, event});
this.dropped.next({
item: this,
currentIndex,
previousIndex: this._initialIndex,
container: container,
previousContainer: this._initialContainer,
isPointerOverContainer,
distance,
dropPoint: pointerPosition,