-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
drop-list-ref.ts
871 lines (752 loc) · 30.5 KB
/
drop-list-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
/**
* @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 {ElementRef, NgZone} from '@angular/core';
import {Direction} from '@angular/cdk/bidi';
import {coerceElement} from '@angular/cdk/coercion';
import {ViewportRuler} from '@angular/cdk/scrolling';
import {_getShadowRoot} from '@angular/cdk/platform';
import {Subject, Subscription, interval, animationFrameScheduler} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {DragDropRegistry} from './drag-drop-registry';
import type {DragRef, Point} from './drag-ref';
import {isPointerNearDomRect, isInsideClientRect} from './dom/dom-rect';
import {ParentPositionTracker} from './dom/parent-position-tracker';
import {DragCSSStyleDeclaration} from './dom/styling';
import {DropListSortStrategy} from './sorting/drop-list-sort-strategy';
import {SingleAxisSortStrategy} from './sorting/single-axis-sort-strategy';
import {MixedSortStrategy} from './sorting/mixed-sort-strategy';
import {DropListOrientation} from './directives/config';
/**
* Proximity, as a ratio to width/height, at which a
* dragged item will affect the drop container.
*/
const DROP_PROXIMITY_THRESHOLD = 0.05;
/**
* Proximity, as a ratio to width/height at which to start auto-scrolling the drop list or the
* viewport. The value comes from trying it out manually until it feels right.
*/
const SCROLL_PROXIMITY_THRESHOLD = 0.05;
/** Vertical direction in which we can auto-scroll. */
enum AutoScrollVerticalDirection {
NONE,
UP,
DOWN,
}
/** Horizontal direction in which we can auto-scroll. */
enum AutoScrollHorizontalDirection {
NONE,
LEFT,
RIGHT,
}
/**
* Reference to a drop list. Used to manipulate or dispose of the container.
*/
export class DropListRef<T = any> {
/** Element that the drop list is attached to. */
element: HTMLElement | ElementRef<HTMLElement>;
/** Whether starting a dragging sequence from this container is disabled. */
disabled: boolean = false;
/** Whether sorting items within the list is disabled. */
sortingDisabled: boolean = false;
/** Locks the position of the draggable elements inside the container along the specified axis. */
lockAxis: 'x' | 'y';
/**
* Whether auto-scrolling the view when the user
* moves their pointer close to the edges is disabled.
*/
autoScrollDisabled: boolean = false;
/** Number of pixels to scroll for each frame when auto-scrolling an element. */
autoScrollStep: number = 2;
/**
* Function that is used to determine whether an item
* is allowed to be moved into a drop container.
*/
enterPredicate: (drag: DragRef, drop: DropListRef) => boolean = () => true;
/** Function that is used to determine whether an item can be sorted into a particular index. */
sortPredicate: (index: number, drag: DragRef, drop: DropListRef) => boolean = () => true;
/** Emits right before dragging has started. */
readonly beforeStarted = new Subject<void>();
/**
* Emits when the user has moved a new drag item into this container.
*/
readonly entered = new Subject<{item: DragRef; container: DropListRef; currentIndex: number}>();
/**
* Emits when the user removes an item from the container
* by dragging it into another container.
*/
readonly exited = new Subject<{item: DragRef; container: DropListRef}>();
/** Emits when the user drops an item inside the container. */
readonly dropped = new Subject<{
item: DragRef;
currentIndex: number;
previousIndex: number;
container: DropListRef;
previousContainer: DropListRef;
isPointerOverContainer: boolean;
distance: Point;
dropPoint: Point;
event: MouseEvent | TouchEvent;
}>();
/** Emits as the user is swapping items while actively dragging. */
readonly sorted = new Subject<{
previousIndex: number;
currentIndex: number;
container: DropListRef;
item: DragRef;
}>();
/** Emits when a dragging sequence is started in a list connected to the current one. */
readonly receivingStarted = new Subject<{
receiver: DropListRef;
initiator: DropListRef;
items: DragRef[];
}>();
/** Emits when a dragging sequence is stopped from a list connected to the current one. */
readonly receivingStopped = new Subject<{
receiver: DropListRef;
initiator: DropListRef;
}>();
/** Arbitrary data that can be attached to the drop list. */
data: T;
/** Element that is the direct parent of the drag items. */
private _container: HTMLElement;
/** Whether an item in the list is being dragged. */
private _isDragging = false;
/** Keeps track of the positions of any parent scrollable elements. */
private _parentPositions: ParentPositionTracker;
/** Strategy being used to sort items within the list. */
private _sortStrategy: DropListSortStrategy;
/** Cached `DOMRect` of the drop list. */
private _domRect: DOMRect | undefined;
/** Draggable items in the container. */
private _draggables: readonly DragRef[] = [];
/** Drop lists that are connected to the current one. */
private _siblings: readonly DropListRef[] = [];
/** Connected siblings that currently have a dragged item. */
private _activeSiblings = new Set<DropListRef>();
/** Subscription to the window being scrolled. */
private _viewportScrollSubscription = Subscription.EMPTY;
/** Vertical direction in which the list is currently scrolling. */
private _verticalScrollDirection = AutoScrollVerticalDirection.NONE;
/** Horizontal direction in which the list is currently scrolling. */
private _horizontalScrollDirection = AutoScrollHorizontalDirection.NONE;
/** Node that is being auto-scrolled. */
private _scrollNode: HTMLElement | Window;
/** Used to signal to the current auto-scroll sequence when to stop. */
private readonly _stopScrollTimers = new Subject<void>();
/** Shadow root of the current element. Necessary for `elementFromPoint` to resolve correctly. */
private _cachedShadowRoot: DocumentOrShadowRoot | null = null;
/** Reference to the document. */
private _document: Document;
/** Elements that can be scrolled while the user is dragging. */
private _scrollableElements: HTMLElement[] = [];
/** Initial value for the element's `scroll-snap-type` style. */
private _initialScrollSnap: string;
/** Direction of the list's layout. */
private _direction: Direction = 'ltr';
constructor(
element: ElementRef<HTMLElement> | HTMLElement,
private _dragDropRegistry: DragDropRegistry,
_document: any,
private _ngZone: NgZone,
private _viewportRuler: ViewportRuler,
) {
const coercedElement = (this.element = coerceElement(element));
this._document = _document;
this.withOrientation('vertical').withElementContainer(coercedElement);
_dragDropRegistry.registerDropContainer(this);
this._parentPositions = new ParentPositionTracker(_document);
}
/** Removes the drop list functionality from the DOM element. */
dispose() {
this._stopScrolling();
this._stopScrollTimers.complete();
this._viewportScrollSubscription.unsubscribe();
this.beforeStarted.complete();
this.entered.complete();
this.exited.complete();
this.dropped.complete();
this.sorted.complete();
this.receivingStarted.complete();
this.receivingStopped.complete();
this._activeSiblings.clear();
this._scrollNode = null!;
this._parentPositions.clear();
this._dragDropRegistry.removeDropContainer(this);
}
/** Whether an item from this list is currently being dragged. */
isDragging() {
return this._isDragging;
}
/** Starts dragging an item. */
start(): void {
this._draggingStarted();
this._notifyReceivingSiblings();
}
/**
* Attempts to move an item into the container.
* @param item Item that was moved into the container.
* @param pointerX Position of the item along the X axis.
* @param pointerY Position of the item along the Y axis.
* @param index Index at which the item entered. If omitted, the container will try to figure it
* out automatically.
*/
enter(item: DragRef, pointerX: number, pointerY: number, index?: number): void {
this._draggingStarted();
// If sorting is disabled, we want the item to return to its starting
// position if the user is returning it to its initial container.
if (index == null && this.sortingDisabled) {
index = this._draggables.indexOf(item);
}
this._sortStrategy.enter(item, pointerX, pointerY, index);
// Note that this usually happens inside `_draggingStarted` as well, but the dimensions
// can change when the sort strategy moves the item around inside `enter`.
this._cacheParentPositions();
// Notify siblings at the end so that the item has been inserted into the `activeDraggables`.
this._notifyReceivingSiblings();
this.entered.next({item, container: this, currentIndex: this.getItemIndex(item)});
}
/**
* Removes an item from the container after it was dragged into another container by the user.
* @param item Item that was dragged out.
*/
exit(item: DragRef): void {
this._reset();
this.exited.next({item, container: this});
}
/**
* Drops an item into this container.
* @param item Item being dropped into the container.
* @param currentIndex Index at which the item should be inserted.
* @param previousIndex Index of the item when dragging started.
* @param previousContainer Container from which the item got dragged in.
* @param isPointerOverContainer Whether the user's pointer was over the
* container when the item was dropped.
* @param distance Distance the user has dragged since the start of the dragging sequence.
* @param event Event that triggered the dropping sequence.
*
* @breaking-change 15.0.0 `previousIndex` and `event` parameters to become required.
*/
drop(
item: DragRef,
currentIndex: number,
previousIndex: number,
previousContainer: DropListRef,
isPointerOverContainer: boolean,
distance: Point,
dropPoint: Point,
event: MouseEvent | TouchEvent = {} as any,
): void {
this._reset();
this.dropped.next({
item,
currentIndex,
previousIndex,
container: this,
previousContainer,
isPointerOverContainer,
distance,
dropPoint,
event,
});
}
/**
* Sets the draggable items that are a part of this list.
* @param items Items that are a part of this list.
*/
withItems(items: DragRef[]): this {
const previousItems = this._draggables;
this._draggables = items;
items.forEach(item => item._withDropContainer(this));
if (this.isDragging()) {
const draggedItems = previousItems.filter(item => item.isDragging());
// If all of the items being dragged were removed
// from the list, abort the current drag sequence.
if (draggedItems.every(item => items.indexOf(item) === -1)) {
this._reset();
} else {
this._sortStrategy.withItems(this._draggables);
}
}
return this;
}
/** Sets the layout direction of the drop list. */
withDirection(direction: Direction): this {
this._direction = direction;
if (this._sortStrategy instanceof SingleAxisSortStrategy) {
this._sortStrategy.direction = direction;
}
return this;
}
/**
* Sets the containers that are connected to this one. When two or more containers are
* connected, the user will be allowed to transfer items between them.
* @param connectedTo Other containers that the current containers should be connected to.
*/
connectedTo(connectedTo: DropListRef[]): this {
this._siblings = connectedTo.slice();
return this;
}
/**
* Sets the orientation of the container.
* @param orientation New orientation for the container.
*/
withOrientation(orientation: DropListOrientation): this {
if (orientation === 'mixed') {
this._sortStrategy = new MixedSortStrategy(this._document, this._dragDropRegistry);
} else {
const strategy = new SingleAxisSortStrategy(this._dragDropRegistry);
strategy.direction = this._direction;
strategy.orientation = orientation;
this._sortStrategy = strategy;
}
this._sortStrategy.withElementContainer(this._container);
this._sortStrategy.withSortPredicate((index, item) => this.sortPredicate(index, item, this));
return this;
}
/**
* Sets which parent elements are can be scrolled while the user is dragging.
* @param elements Elements that can be scrolled.
*/
withScrollableParents(elements: HTMLElement[]): this {
const element = this._container;
// We always allow the current element to be scrollable
// so we need to ensure that it's in the array.
this._scrollableElements =
elements.indexOf(element) === -1 ? [element, ...elements] : elements.slice();
return this;
}
/**
* Configures the drop list so that a different element is used as the container for the
* dragged items. This is useful for the cases when one might not have control over the
* full DOM that sets up the dragging.
* Note that the alternate container needs to be a descendant of the drop list.
* @param container New element container to be assigned.
*/
withElementContainer(container: HTMLElement): this {
if (container === this._container) {
return this;
}
const element = coerceElement(this.element);
if (
(typeof ngDevMode === 'undefined' || ngDevMode) &&
container !== element &&
!element.contains(container)
) {
throw new Error(
'Invalid DOM structure for drop list. Alternate container element must be a descendant of the drop list.',
);
}
const oldContainerIndex = this._scrollableElements.indexOf(this._container);
const newContainerIndex = this._scrollableElements.indexOf(container);
if (oldContainerIndex > -1) {
this._scrollableElements.splice(oldContainerIndex, 1);
}
if (newContainerIndex > -1) {
this._scrollableElements.splice(newContainerIndex, 1);
}
if (this._sortStrategy) {
this._sortStrategy.withElementContainer(container);
}
this._cachedShadowRoot = null;
this._scrollableElements.unshift(container);
this._container = container;
return this;
}
/** Gets the scrollable parents that are registered with this drop container. */
getScrollableParents(): readonly HTMLElement[] {
return this._scrollableElements;
}
/**
* Figures out the index of an item in the container.
* @param item Item whose index should be determined.
*/
getItemIndex(item: DragRef): number {
return this._isDragging
? this._sortStrategy.getItemIndex(item)
: this._draggables.indexOf(item);
}
/**
* Whether the list is able to receive the item that
* is currently being dragged inside a connected drop list.
*/
isReceiving(): boolean {
return this._activeSiblings.size > 0;
}
/**
* Sorts an item inside the container based on its position.
* @param item Item to be sorted.
* @param pointerX Position of the item along the X axis.
* @param pointerY Position of the item along the Y axis.
* @param pointerDelta Direction in which the pointer is moving along each axis.
*/
_sortItem(
item: DragRef,
pointerX: number,
pointerY: number,
pointerDelta: {x: number; y: number},
): void {
// Don't sort the item if sorting is disabled or it's out of range.
if (
this.sortingDisabled ||
!this._domRect ||
!isPointerNearDomRect(this._domRect, DROP_PROXIMITY_THRESHOLD, pointerX, pointerY)
) {
return;
}
const result = this._sortStrategy.sort(item, pointerX, pointerY, pointerDelta);
if (result) {
this.sorted.next({
previousIndex: result.previousIndex,
currentIndex: result.currentIndex,
container: this,
item,
});
}
}
/**
* Checks whether the user's pointer is close to the edges of either the
* viewport or the drop list and starts the auto-scroll sequence.
* @param pointerX User's pointer position along the x axis.
* @param pointerY User's pointer position along the y axis.
*/
_startScrollingIfNecessary(pointerX: number, pointerY: number) {
if (this.autoScrollDisabled) {
return;
}
let scrollNode: HTMLElement | Window | undefined;
let verticalScrollDirection = AutoScrollVerticalDirection.NONE;
let horizontalScrollDirection = AutoScrollHorizontalDirection.NONE;
// Check whether we should start scrolling any of the parent containers.
this._parentPositions.positions.forEach((position, element) => {
// We have special handling for the `document` below. Also this would be
// nicer with a for...of loop, but it requires changing a compiler flag.
if (element === this._document || !position.clientRect || scrollNode) {
return;
}
if (isPointerNearDomRect(position.clientRect, DROP_PROXIMITY_THRESHOLD, pointerX, pointerY)) {
[verticalScrollDirection, horizontalScrollDirection] = getElementScrollDirections(
element as HTMLElement,
position.clientRect,
this._direction,
pointerX,
pointerY,
);
if (verticalScrollDirection || horizontalScrollDirection) {
scrollNode = element as HTMLElement;
}
}
});
// Otherwise check if we can start scrolling the viewport.
if (!verticalScrollDirection && !horizontalScrollDirection) {
const {width, height} = this._viewportRuler.getViewportSize();
const domRect = {
width,
height,
top: 0,
right: width,
bottom: height,
left: 0,
} as DOMRect;
verticalScrollDirection = getVerticalScrollDirection(domRect, pointerY);
horizontalScrollDirection = getHorizontalScrollDirection(domRect, pointerX);
scrollNode = window;
}
if (
scrollNode &&
(verticalScrollDirection !== this._verticalScrollDirection ||
horizontalScrollDirection !== this._horizontalScrollDirection ||
scrollNode !== this._scrollNode)
) {
this._verticalScrollDirection = verticalScrollDirection;
this._horizontalScrollDirection = horizontalScrollDirection;
this._scrollNode = scrollNode;
if ((verticalScrollDirection || horizontalScrollDirection) && scrollNode) {
this._ngZone.runOutsideAngular(this._startScrollInterval);
} else {
this._stopScrolling();
}
}
}
/** Stops any currently-running auto-scroll sequences. */
_stopScrolling() {
this._stopScrollTimers.next();
}
/** Starts the dragging sequence within the list. */
private _draggingStarted() {
const styles = this._container.style as DragCSSStyleDeclaration;
this.beforeStarted.next();
this._isDragging = true;
if (
(typeof ngDevMode === 'undefined' || ngDevMode) &&
// Prevent the check from running on apps not using an alternate container. Ideally we
// would always run it, but introducing it at this stage would be a breaking change.
this._container !== coerceElement(this.element)
) {
for (const drag of this._draggables) {
if (!drag.isDragging() && drag.getVisibleElement().parentNode !== this._container) {
throw new Error(
'Invalid DOM structure for drop list. All items must be placed directly inside of the element container.',
);
}
}
}
// We need to disable scroll snapping while the user is dragging, because it breaks automatic
// scrolling. The browser seems to round the value based on the snapping points which means
// that we can't increment/decrement the scroll position.
this._initialScrollSnap = styles.msScrollSnapType || styles.scrollSnapType || '';
styles.scrollSnapType = styles.msScrollSnapType = 'none';
this._sortStrategy.start(this._draggables);
this._cacheParentPositions();
this._viewportScrollSubscription.unsubscribe();
this._listenToScrollEvents();
}
/** Caches the positions of the configured scrollable parents. */
private _cacheParentPositions() {
this._parentPositions.cache(this._scrollableElements);
// The list element is always in the `scrollableElements`
// so we can take advantage of the cached `DOMRect`.
this._domRect = this._parentPositions.positions.get(this._container)!.clientRect!;
}
/** Resets the container to its initial state. */
private _reset() {
this._isDragging = false;
const styles = this._container.style as DragCSSStyleDeclaration;
styles.scrollSnapType = styles.msScrollSnapType = this._initialScrollSnap;
this._siblings.forEach(sibling => sibling._stopReceiving(this));
this._sortStrategy.reset();
this._stopScrolling();
this._viewportScrollSubscription.unsubscribe();
this._parentPositions.clear();
}
/** Starts the interval that'll auto-scroll the element. */
private _startScrollInterval = () => {
this._stopScrolling();
interval(0, animationFrameScheduler)
.pipe(takeUntil(this._stopScrollTimers))
.subscribe(() => {
const node = this._scrollNode;
const scrollStep = this.autoScrollStep;
if (this._verticalScrollDirection === AutoScrollVerticalDirection.UP) {
node.scrollBy(0, -scrollStep);
} else if (this._verticalScrollDirection === AutoScrollVerticalDirection.DOWN) {
node.scrollBy(0, scrollStep);
}
if (this._horizontalScrollDirection === AutoScrollHorizontalDirection.LEFT) {
node.scrollBy(-scrollStep, 0);
} else if (this._horizontalScrollDirection === AutoScrollHorizontalDirection.RIGHT) {
node.scrollBy(scrollStep, 0);
}
});
};
/**
* Checks whether the user's pointer is positioned over the container.
* @param x Pointer position along the X axis.
* @param y Pointer position along the Y axis.
*/
_isOverContainer(x: number, y: number): boolean {
return this._domRect != null && isInsideClientRect(this._domRect, x, y);
}
/**
* Figures out whether an item should be moved into a sibling
* drop container, based on its current position.
* @param item Drag item that is being moved.
* @param x Position of the item along the X axis.
* @param y Position of the item along the Y axis.
*/
_getSiblingContainerFromPosition(item: DragRef, x: number, y: number): DropListRef | undefined {
return this._siblings.find(sibling => sibling._canReceive(item, x, y));
}
/**
* Checks whether the drop list can receive the passed-in item.
* @param item Item that is being dragged into the list.
* @param x Position of the item along the X axis.
* @param y Position of the item along the Y axis.
*/
_canReceive(item: DragRef, x: number, y: number): boolean {
if (
!this._domRect ||
!isInsideClientRect(this._domRect, x, y) ||
!this.enterPredicate(item, this)
) {
return false;
}
const elementFromPoint = this._getShadowRoot().elementFromPoint(x, y) as HTMLElement | null;
// If there's no element at the pointer position, then
// the client rect is probably scrolled out of the view.
if (!elementFromPoint) {
return false;
}
// The `DOMRect`, that we're using to find the container over which the user is
// hovering, doesn't give us any information on whether the element has been scrolled
// out of the view or whether it's overlapping with other containers. This means that
// we could end up transferring the item into a container that's invisible or is positioned
// below another one. We use the result from `elementFromPoint` to get the top-most element
// at the pointer position and to find whether it's one of the intersecting drop containers.
return elementFromPoint === this._container || this._container.contains(elementFromPoint);
}
/**
* Called by one of the connected drop lists when a dragging sequence has started.
* @param sibling Sibling in which dragging has started.
*/
_startReceiving(sibling: DropListRef, items: DragRef[]) {
const activeSiblings = this._activeSiblings;
if (
!activeSiblings.has(sibling) &&
items.every(item => {
// Note that we have to add an exception to the `enterPredicate` for items that started off
// in this drop list. The drag ref has logic that allows an item to return to its initial
// container, if it has left the initial container and none of the connected containers
// allow it to enter. See `DragRef._updateActiveDropContainer` for more context.
return this.enterPredicate(item, this) || this._draggables.indexOf(item) > -1;
})
) {
activeSiblings.add(sibling);
this._cacheParentPositions();
this._listenToScrollEvents();
this.receivingStarted.next({
initiator: sibling,
receiver: this,
items,
});
}
}
/**
* Called by a connected drop list when dragging has stopped.
* @param sibling Sibling whose dragging has stopped.
*/
_stopReceiving(sibling: DropListRef) {
this._activeSiblings.delete(sibling);
this._viewportScrollSubscription.unsubscribe();
this.receivingStopped.next({initiator: sibling, receiver: this});
}
/**
* Starts listening to scroll events on the viewport.
* Used for updating the internal state of the list.
*/
private _listenToScrollEvents() {
this._viewportScrollSubscription = this._dragDropRegistry
.scrolled(this._getShadowRoot())
.subscribe(event => {
if (this.isDragging()) {
const scrollDifference = this._parentPositions.handleScroll(event);
if (scrollDifference) {
this._sortStrategy.updateOnScroll(scrollDifference.top, scrollDifference.left);
}
} else if (this.isReceiving()) {
this._cacheParentPositions();
}
});
}
/**
* Lazily resolves and returns the shadow root of the element. We do this in a function, rather
* than saving it in property directly on init, because we want to resolve it as late as possible
* in order to ensure that the element has been moved into the shadow DOM. Doing it inside the
* constructor might be too early if the element is inside of something like `ngFor` or `ngIf`.
*/
private _getShadowRoot(): DocumentOrShadowRoot {
if (!this._cachedShadowRoot) {
const shadowRoot = _getShadowRoot(this._container);
this._cachedShadowRoot = shadowRoot || this._document;
}
return this._cachedShadowRoot;
}
/** Notifies any siblings that may potentially receive the item. */
private _notifyReceivingSiblings() {
const draggedItems = this._sortStrategy
.getActiveItemsSnapshot()
.filter(item => item.isDragging());
this._siblings.forEach(sibling => sibling._startReceiving(this, draggedItems));
}
}
/**
* Gets whether the vertical auto-scroll direction of a node.
* @param clientRect Dimensions of the node.
* @param pointerY Position of the user's pointer along the y axis.
*/
function getVerticalScrollDirection(clientRect: DOMRect, pointerY: number) {
const {top, bottom, height} = clientRect;
const yThreshold = height * SCROLL_PROXIMITY_THRESHOLD;
if (pointerY >= top - yThreshold && pointerY <= top + yThreshold) {
return AutoScrollVerticalDirection.UP;
} else if (pointerY >= bottom - yThreshold && pointerY <= bottom + yThreshold) {
return AutoScrollVerticalDirection.DOWN;
}
return AutoScrollVerticalDirection.NONE;
}
/**
* Gets whether the horizontal auto-scroll direction of a node.
* @param clientRect Dimensions of the node.
* @param pointerX Position of the user's pointer along the x axis.
*/
function getHorizontalScrollDirection(clientRect: DOMRect, pointerX: number) {
const {left, right, width} = clientRect;
const xThreshold = width * SCROLL_PROXIMITY_THRESHOLD;
if (pointerX >= left - xThreshold && pointerX <= left + xThreshold) {
return AutoScrollHorizontalDirection.LEFT;
} else if (pointerX >= right - xThreshold && pointerX <= right + xThreshold) {
return AutoScrollHorizontalDirection.RIGHT;
}
return AutoScrollHorizontalDirection.NONE;
}
/**
* Gets the directions in which an element node should be scrolled,
* assuming that the user's pointer is already within it scrollable region.
* @param element Element for which we should calculate the scroll direction.
* @param clientRect Bounding client rectangle of the element.
* @param direction Layout direction of the drop list.
* @param pointerX Position of the user's pointer along the x axis.
* @param pointerY Position of the user's pointer along the y axis.
*/
function getElementScrollDirections(
element: HTMLElement,
clientRect: DOMRect,
direction: Direction,
pointerX: number,
pointerY: number,
): [AutoScrollVerticalDirection, AutoScrollHorizontalDirection] {
const computedVertical = getVerticalScrollDirection(clientRect, pointerY);
const computedHorizontal = getHorizontalScrollDirection(clientRect, pointerX);
let verticalScrollDirection = AutoScrollVerticalDirection.NONE;
let horizontalScrollDirection = AutoScrollHorizontalDirection.NONE;
// Note that we here we do some extra checks for whether the element is actually scrollable in
// a certain direction and we only assign the scroll direction if it is. We do this so that we
// can allow other elements to be scrolled, if the current element can't be scrolled anymore.
// This allows us to handle cases where the scroll regions of two scrollable elements overlap.
if (computedVertical) {
const scrollTop = element.scrollTop;
if (computedVertical === AutoScrollVerticalDirection.UP) {
if (scrollTop > 0) {
verticalScrollDirection = AutoScrollVerticalDirection.UP;
}
} else if (element.scrollHeight - scrollTop > element.clientHeight) {
verticalScrollDirection = AutoScrollVerticalDirection.DOWN;
}
}
if (computedHorizontal) {
const scrollLeft = element.scrollLeft;
if (direction === 'rtl') {
if (computedHorizontal === AutoScrollHorizontalDirection.RIGHT) {
// In RTL `scrollLeft` will be negative when scrolled.
if (scrollLeft < 0) {
horizontalScrollDirection = AutoScrollHorizontalDirection.RIGHT;
}
} else if (element.scrollWidth + scrollLeft > element.clientWidth) {
horizontalScrollDirection = AutoScrollHorizontalDirection.LEFT;
}
} else {
if (computedHorizontal === AutoScrollHorizontalDirection.LEFT) {
if (scrollLeft > 0) {
horizontalScrollDirection = AutoScrollHorizontalDirection.LEFT;
}
} else if (element.scrollWidth - scrollLeft > element.clientWidth) {
horizontalScrollDirection = AutoScrollHorizontalDirection.RIGHT;
}
}
}
return [verticalScrollDirection, horizontalScrollDirection];
}