_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
components/src/cdk/schematics/ng-add/index.ts_0_2064
/** * @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 {Rule, SchematicContext, Tree} from '@angular-devkit/schematics'; import {NodePackageInstallTask} from '@angular-devkit/schematics/tasks'; import {addPackageToPackageJson, getPackageVersionFromPackageJson} from './package-config'; /** * Schematic factory entry-point for the `ng-add` schematic. The ng-add schematic will be * automatically executed if developers run `ng add @angular/cdk`. * * By default, the CLI already installs the package that has been specified with `ng add`. * We just store the version in the `package.json` in case the package manager didn't. Also * this ensures that there will be no error that says that the CDK does not support `ng add`. */ export default function (): Rule { return (host: Tree, context: SchematicContext) => { // The CLI inserts `@angular/cdk` into the `package.json` before this schematic runs. This // means that we do not need to insert the CDK into `package.json` files again. In some cases // though, it could happen that this schematic runs outside of the CLI `ng add` command, or // the CDK is only listed as a dev dependency. If that is the case, we insert a version based // on the current build version (substituted version placeholder). if (getPackageVersionFromPackageJson(host, '@angular/cdk') === null) { // In order to align the CDK version with other Angular dependencies that are setup by // `@schematics/angular`, we use tilde instead of caret. This is default for Angular // dependencies in new CLI projects. addPackageToPackageJson(host, '@angular/cdk', `~0.0.0-PLACEHOLDER`); // Add a task to run the package manager. This is necessary because we updated the // workspace "package.json" file and we want lock files to reflect the new version range. context.addTask(new NodePackageInstallTask()); } }; }
{ "commit_id": "ea0d1ba7b", "end_byte": 2064, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/schematics/ng-add/index.ts" }
components/src/cdk/drag-drop/drag-drop-registry.spec.ts_0_9478
import {Component} from '@angular/core'; import {fakeAsync, TestBed, ComponentFixture, inject} from '@angular/core/testing'; import { createMouseEvent, dispatchMouseEvent, createTouchEvent, dispatchTouchEvent, dispatchFakeEvent, } from '../testing/private'; import {DragDropRegistry} from './drag-drop-registry'; import {DragDropModule} from './drag-drop-module'; import {DragRef} from './drag-ref'; describe('DragDropRegistry', () => { let fixture: ComponentFixture<BlankComponent>; let registry: DragDropRegistry; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [DragDropModule, BlankComponent], }); fixture = TestBed.createComponent(BlankComponent); fixture.detectChanges(); inject([DragDropRegistry], (c: DragDropRegistry) => { registry = c; })(); })); it('should be able to start dragging an item', () => { const item = new DragItem() as unknown as DragRef; expect(registry.isDragging(item)).toBe(false); registry.startDragging(item, createMouseEvent('mousedown')); expect(registry.isDragging(item)).toBe(true); }); it('should be able to stop dragging an item', () => { const item = new DragItem() as unknown as DragRef; registry.startDragging(item, createMouseEvent('mousedown')); expect(registry.isDragging(item)).toBe(true); registry.stopDragging(item); expect(registry.isDragging(item)).toBe(false); }); it('should stop dragging an item if it is removed', () => { const item = new DragItem() as unknown as DragRef; registry.startDragging(item, createMouseEvent('mousedown')); expect(registry.isDragging(item)).toBe(true); registry.removeDragItem(item); expect(registry.isDragging(item)).toBe(false); }); it('should dispatch `mousemove` events after starting to drag via the mouse', () => { const spy = jasmine.createSpy('pointerMove spy'); const subscription = registry.pointerMove.subscribe(spy); const item = new DragItem(true) as unknown as DragRef; registry.startDragging(item, createMouseEvent('mousedown')); dispatchMouseEvent(document, 'mousemove'); expect(spy).toHaveBeenCalled(); subscription.unsubscribe(); }); it('should dispatch `touchmove` events after starting to drag via touch', () => { const spy = jasmine.createSpy('pointerMove spy'); const subscription = registry.pointerMove.subscribe(spy); const item = new DragItem(true) as unknown as DragRef; registry.startDragging(item, createTouchEvent('touchstart') as TouchEvent); dispatchTouchEvent(document, 'touchmove'); expect(spy).toHaveBeenCalled(); subscription.unsubscribe(); }); it('should dispatch pointer move events if event propagation is stopped', () => { const spy = jasmine.createSpy('pointerMove spy'); const subscription = registry.pointerMove.subscribe(spy); const item = new DragItem(true) as unknown as DragRef; fixture.nativeElement.addEventListener('mousemove', (e: MouseEvent) => e.stopPropagation()); registry.startDragging(item, createMouseEvent('mousedown')); dispatchMouseEvent(fixture.nativeElement, 'mousemove'); expect(spy).toHaveBeenCalled(); subscription.unsubscribe(); }); it('should dispatch `mouseup` events after ending the drag via the mouse', () => { const spy = jasmine.createSpy('pointerUp spy'); const subscription = registry.pointerUp.subscribe(spy); const item = new DragItem() as unknown as DragRef; registry.startDragging(item, createMouseEvent('mousedown')); dispatchMouseEvent(document, 'mouseup'); expect(spy).toHaveBeenCalled(); subscription.unsubscribe(); }); it('should dispatch `touchend` events after ending the drag via touch', () => { const spy = jasmine.createSpy('pointerUp spy'); const subscription = registry.pointerUp.subscribe(spy); const item = new DragItem() as unknown as DragRef; registry.startDragging(item, createTouchEvent('touchstart') as TouchEvent); dispatchTouchEvent(document, 'touchend'); expect(spy).toHaveBeenCalled(); subscription.unsubscribe(); }); it('should dispatch pointer up events if event propagation is stopped', () => { const spy = jasmine.createSpy('pointerUp spy'); const subscription = registry.pointerUp.subscribe(spy); const item = new DragItem() as unknown as DragRef; fixture.nativeElement.addEventListener('mouseup', (e: MouseEvent) => e.stopPropagation()); registry.startDragging(item, createMouseEvent('mousedown')); dispatchMouseEvent(fixture.nativeElement, 'mouseup'); expect(spy).toHaveBeenCalled(); subscription.unsubscribe(); }); it('should complete the pointer event streams on destroy', () => { const pointerUpSpy = jasmine.createSpy('pointerUp complete spy'); const pointerMoveSpy = jasmine.createSpy('pointerMove complete spy'); const pointerUpSubscription = registry.pointerUp.subscribe({complete: pointerUpSpy}); const pointerMoveSubscription = registry.pointerMove.subscribe({complete: pointerMoveSpy}); registry.ngOnDestroy(); expect(pointerUpSpy).toHaveBeenCalled(); expect(pointerMoveSpy).toHaveBeenCalled(); pointerUpSubscription.unsubscribe(); pointerMoveSubscription.unsubscribe(); }); it('should not emit pointer events when dragging is over (multi touch)', () => { const item = new DragItem() as unknown as DragRef; // First finger down registry.startDragging(item, createTouchEvent('touchstart') as TouchEvent); // Second finger down registry.startDragging(item, createTouchEvent('touchstart') as TouchEvent); // First finger up registry.stopDragging(item); // Ensure dragging is over - registry is empty expect(registry.isDragging(item)).toBe(false); const pointerUpSpy = jasmine.createSpy('pointerUp spy'); const pointerMoveSpy = jasmine.createSpy('pointerMove spy'); const pointerUpSubscription = registry.pointerUp.subscribe(pointerUpSpy); const pointerMoveSubscription = registry.pointerMove.subscribe(pointerMoveSpy); // Second finger keeps moving dispatchTouchEvent(document, 'touchmove'); expect(pointerMoveSpy).not.toHaveBeenCalled(); // Second finger up dispatchTouchEvent(document, 'touchend'); expect(pointerUpSpy).not.toHaveBeenCalled(); pointerUpSubscription.unsubscribe(); pointerMoveSubscription.unsubscribe(); }); it('should not prevent the default `touchmove` actions when nothing is being dragged', () => { expect(dispatchTouchEvent(document, 'touchmove').defaultPrevented).toBe(false); }); it('should prevent the default `touchmove` action when an item is being dragged', () => { const item = new DragItem(true) as unknown as DragRef; registry.startDragging(item, createTouchEvent('touchstart') as TouchEvent); expect(dispatchTouchEvent(document, 'touchmove').defaultPrevented).toBe(true); }); it( 'should prevent the default `touchmove` if the item does not consider itself as being ' + 'dragged yet', () => { const item = new DragItem(false) as unknown as DragRef & DragItem; registry.startDragging(item, createTouchEvent('touchstart') as TouchEvent); expect(dispatchTouchEvent(document, 'touchmove').defaultPrevented).toBe(false); item.shouldBeDragging = true; expect(dispatchTouchEvent(document, 'touchmove').defaultPrevented).toBe(true); }, ); it('should prevent the default `touchmove` if event propagation is stopped', () => { const item = new DragItem(true) as unknown as DragRef; registry.startDragging(item, createTouchEvent('touchstart') as TouchEvent); fixture.nativeElement.addEventListener('touchmove', (e: TouchEvent) => e.stopPropagation()); const event = dispatchTouchEvent(fixture.nativeElement, 'touchmove'); expect(event.defaultPrevented).toBe(true); }); it('should not prevent the default `selectstart` actions when nothing is being dragged', () => { expect(dispatchFakeEvent(document, 'selectstart').defaultPrevented).toBe(false); }); it('should prevent the default `selectstart` action when an item is being dragged', () => { const item = new DragItem(true) as unknown as DragRef; registry.startDragging(item, createMouseEvent('mousedown')); expect(dispatchFakeEvent(document, 'selectstart').defaultPrevented).toBe(true); }); it('should dispatch `scroll` events if the viewport is scrolled while dragging', () => { const spy = jasmine.createSpy('scroll spy'); const subscription = registry.scrolled().subscribe(spy); const item = new DragItem() as unknown as DragRef; registry.startDragging(item, createMouseEvent('mousedown')); dispatchFakeEvent(document, 'scroll'); expect(spy).toHaveBeenCalled(); subscription.unsubscribe(); }); it('should not dispatch `scroll` events when not dragging', () => { const spy = jasmine.createSpy('scroll spy'); const subscription = registry.scrolled().subscribe(spy); dispatchFakeEvent(document, 'scroll'); expect(spy).not.toHaveBeenCalled(); subscription.unsubscribe(); }); class DragItem { isDragging() { return this.shouldBeDragging; } constructor(public shouldBeDragging = false) { registry.registerDragItem(this as unknown as DragRef); } } @Component({ template: ``, standalone: true, imports: [DragDropModule], }) class BlankComponent {} });
{ "commit_id": "ea0d1ba7b", "end_byte": 9478, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-drop-registry.spec.ts" }
components/src/cdk/drag-drop/drag-utils.spec.ts_0_2864
import {moveItemInArray, transferArrayItem, copyArrayItem} from './drag-utils'; describe('dragging utilities', () => { describe('moveItemInArray', () => { let array: number[]; beforeEach(() => (array = [0, 1, 2, 3])); it('should be able to move an item inside an array', () => { moveItemInArray(array, 1, 3); expect(array).toEqual([0, 2, 3, 1]); }); it('should not do anything if the index is the same', () => { moveItemInArray(array, 2, 2); expect(array).toEqual([0, 1, 2, 3]); }); it('should handle an index greater than the length', () => { moveItemInArray(array, 0, 7); expect(array).toEqual([1, 2, 3, 0]); }); it('should handle an index less than zero', () => { moveItemInArray(array, 3, -1); expect(array).toEqual([3, 0, 1, 2]); }); }); describe('transferArrayItem', () => { it('should be able to move an item from one array to another', () => { const a = [0, 1, 2]; const b = [3, 4, 5]; transferArrayItem(a, b, 1, 2); expect(a).toEqual([0, 2]); expect(b).toEqual([3, 4, 1, 5]); }); it('should handle an index greater than the target array length', () => { const a = [0, 1, 2]; const b = [3, 4, 5]; transferArrayItem(a, b, 0, 7); expect(a).toEqual([1, 2]); expect(b).toEqual([3, 4, 5, 0]); }); it('should handle an index less than zero', () => { const a = [0, 1, 2]; const b = [3, 4, 5]; transferArrayItem(a, b, 2, -1); expect(a).toEqual([0, 1]); expect(b).toEqual([2, 3, 4, 5]); }); it('should not do anything if the source array is empty', () => { const a: number[] = []; const b = [3, 4, 5]; transferArrayItem(a, b, 0, 0); expect(a).toEqual([]); expect(b).toEqual([3, 4, 5]); }); }); describe('copyArrayItem', () => { it('should be able to copy an item from one array to another', () => { const a = [0, 1, 2]; const b = [3, 4, 5]; copyArrayItem(a, b, 1, 2); expect(a).toEqual([0, 1, 2]); expect(b).toEqual([3, 4, 1, 5]); }); it('should handle an index greater than the target array length', () => { const a = [0, 1, 2]; const b = [3, 4, 5]; copyArrayItem(a, b, 0, 7); expect(a).toEqual([0, 1, 2]); expect(b).toEqual([3, 4, 5, 0]); }); it('should handle an index less than zero', () => { const a = [0, 1, 2]; const b = [3, 4, 5]; copyArrayItem(a, b, 2, -1); expect(a).toEqual([0, 1, 2]); expect(b).toEqual([2, 3, 4, 5]); }); it('should not do anything if the source array is empty', () => { const a: number[] = []; const b = [3, 4, 5]; copyArrayItem(a, b, 0, 0); expect(a).toEqual([]); expect(b).toEqual([3, 4, 5]); }); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 2864, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-utils.spec.ts" }
components/src/cdk/drag-drop/drag-drop.spec.ts_0_1247
import {Component, ElementRef, inject} from '@angular/core'; import {TestBed, fakeAsync} from '@angular/core/testing'; import {DragDrop} from './drag-drop'; import {DragDropModule} from './drag-drop-module'; import {DragRef} from './drag-ref'; import {DropListRef} from './drop-list-ref'; describe('DragDrop', () => { let service: DragDrop; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [DragDropModule, TestComponent], }); service = TestBed.inject(DragDrop); })); it('should be able to attach a DragRef to a DOM node', () => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); const ref = service.createDrag(fixture.componentInstance.elementRef); expect(ref instanceof DragRef).toBe(true); }); it('should be able to attach a DropListRef to a DOM node', () => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); const ref = service.createDropList(fixture.componentInstance.elementRef); expect(ref instanceof DropListRef).toBe(true); }); }); @Component({ template: '<div></div>', standalone: true, }) class TestComponent { elementRef = inject<ElementRef<HTMLElement>>(ElementRef); }
{ "commit_id": "ea0d1ba7b", "end_byte": 1247, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-drop.spec.ts" }
components/src/cdk/drag-drop/drag-drop-module.ts_0_982
/** * @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 {NgModule} from '@angular/core'; import {CdkScrollableModule} from '@angular/cdk/scrolling'; import {CdkDropList} from './directives/drop-list'; import {CdkDropListGroup} from './directives/drop-list-group'; import {CdkDrag} from './directives/drag'; import {CdkDragHandle} from './directives/drag-handle'; import {CdkDragPreview} from './directives/drag-preview'; import {CdkDragPlaceholder} from './directives/drag-placeholder'; import {DragDrop} from './drag-drop'; const DRAG_DROP_DIRECTIVES = [ CdkDropList, CdkDropListGroup, CdkDrag, CdkDragHandle, CdkDragPreview, CdkDragPlaceholder, ]; @NgModule({ imports: DRAG_DROP_DIRECTIVES, exports: [CdkScrollableModule, ...DRAG_DROP_DIRECTIVES], providers: [DragDrop], }) export class DragDropModule {}
{ "commit_id": "ea0d1ba7b", "end_byte": 982, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-drop-module.ts" }
components/src/cdk/drag-drop/drag-drop-registry.ts_0_1410
/** * @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 { ChangeDetectionStrategy, Component, Injectable, NgZone, OnDestroy, ViewEncapsulation, WritableSignal, inject, signal, } from '@angular/core'; import {DOCUMENT} from '@angular/common'; import {normalizePassiveListenerOptions} from '@angular/cdk/platform'; import {_CdkPrivateStyleLoader} from '@angular/cdk/private'; import {Observable, Observer, Subject, merge} from 'rxjs'; import type {DropListRef} from './drop-list-ref'; import type {DragRef} from './drag-ref'; /** Event options that can be used to bind an active, capturing event. */ const activeCapturingEventOptions = normalizePassiveListenerOptions({ passive: false, capture: true, }); /** * Component used to load the drag&drop reset styles. * @docs-private */ @Component({ styleUrl: 'resets.css', encapsulation: ViewEncapsulation.None, template: '', changeDetection: ChangeDetectionStrategy.OnPush, host: {'cdk-drag-resets-container': ''}, }) export class _ResetsLoader {} // TODO(crisbeto): remove generics when making breaking changes. /** * Service that keeps track of all the drag item and drop container * instances, and manages global event listeners on the `document`. * @docs-private */
{ "commit_id": "ea0d1ba7b", "end_byte": 1410, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-drop-registry.ts" }
components/src/cdk/drag-drop/drag-drop-registry.ts_1411_9970
@Injectable({providedIn: 'root'}) export class DragDropRegistry<_ = unknown, __ = unknown> implements OnDestroy { private _ngZone = inject(NgZone); private _document = inject(DOCUMENT); private _styleLoader = inject(_CdkPrivateStyleLoader); /** Registered drop container instances. */ private _dropInstances = new Set<DropListRef>(); /** Registered drag item instances. */ private _dragInstances = new Set<DragRef>(); /** Drag item instances that are currently being dragged. */ private _activeDragInstances: WritableSignal<DragRef[]> = signal([]); /** Keeps track of the event listeners that we've bound to the `document`. */ private _globalListeners = new Map< string, { handler: (event: Event) => void; options?: AddEventListenerOptions | boolean; } >(); /** * Predicate function to check if an item is being dragged. Moved out into a property, * because it'll be called a lot and we don't want to create a new function every time. */ private _draggingPredicate = (item: DragRef) => item.isDragging(); /** * Emits the `touchmove` or `mousemove` events that are dispatched * while the user is dragging a drag item instance. */ readonly pointerMove: Subject<TouchEvent | MouseEvent> = new Subject<TouchEvent | MouseEvent>(); /** * Emits the `touchend` or `mouseup` events that are dispatched * while the user is dragging a drag item instance. */ readonly pointerUp: Subject<TouchEvent | MouseEvent> = new Subject<TouchEvent | MouseEvent>(); /** * Emits when the viewport has been scrolled while the user is dragging an item. * @deprecated To be turned into a private member. Use the `scrolled` method instead. * @breaking-change 13.0.0 */ readonly scroll: Subject<Event> = new Subject<Event>(); constructor(...args: unknown[]); constructor() {} /** Adds a drop container to the registry. */ registerDropContainer(drop: DropListRef) { if (!this._dropInstances.has(drop)) { this._dropInstances.add(drop); } } /** Adds a drag item instance to the registry. */ registerDragItem(drag: DragRef) { this._dragInstances.add(drag); // The `touchmove` event gets bound once, ahead of time, because WebKit // won't preventDefault on a dynamically-added `touchmove` listener. // See https://bugs.webkit.org/show_bug.cgi?id=184250. if (this._dragInstances.size === 1) { this._ngZone.runOutsideAngular(() => { // The event handler has to be explicitly active, // because newer browsers make it passive by default. this._document.addEventListener( 'touchmove', this._persistentTouchmoveListener, activeCapturingEventOptions, ); }); } } /** Removes a drop container from the registry. */ removeDropContainer(drop: DropListRef) { this._dropInstances.delete(drop); } /** Removes a drag item instance from the registry. */ removeDragItem(drag: DragRef) { this._dragInstances.delete(drag); this.stopDragging(drag); if (this._dragInstances.size === 0) { this._document.removeEventListener( 'touchmove', this._persistentTouchmoveListener, activeCapturingEventOptions, ); } } /** * Starts the dragging sequence for a drag instance. * @param drag Drag instance which is being dragged. * @param event Event that initiated the dragging. */ startDragging(drag: DragRef, event: TouchEvent | MouseEvent) { // Do not process the same drag twice to avoid memory leaks and redundant listeners if (this._activeDragInstances().indexOf(drag) > -1) { return; } this._styleLoader.load(_ResetsLoader); this._activeDragInstances.update(instances => [...instances, drag]); if (this._activeDragInstances().length === 1) { const isTouchEvent = event.type.startsWith('touch'); // We explicitly bind __active__ listeners here, because newer browsers will default to // passive ones for `mousemove` and `touchmove`. The events need to be active, because we // use `preventDefault` to prevent the page from scrolling while the user is dragging. this._globalListeners .set(isTouchEvent ? 'touchend' : 'mouseup', { handler: (e: Event) => this.pointerUp.next(e as TouchEvent | MouseEvent), options: true, }) .set('scroll', { handler: (e: Event) => this.scroll.next(e), // Use capturing so that we pick up scroll changes in any scrollable nodes that aren't // the document. See https://github.com/angular/components/issues/17144. options: true, }) // Preventing the default action on `mousemove` isn't enough to disable text selection // on Safari so we need to prevent the selection event as well. Alternatively this can // be done by setting `user-select: none` on the `body`, however it has causes a style // recalculation which can be expensive on pages with a lot of elements. .set('selectstart', { handler: this._preventDefaultWhileDragging, options: activeCapturingEventOptions, }); // We don't have to bind a move event for touch drag sequences, because // we already have a persistent global one bound from `registerDragItem`. if (!isTouchEvent) { this._globalListeners.set('mousemove', { handler: (e: Event) => this.pointerMove.next(e as MouseEvent), options: activeCapturingEventOptions, }); } this._ngZone.runOutsideAngular(() => { this._globalListeners.forEach((config, name) => { this._document.addEventListener(name, config.handler, config.options); }); }); } } /** Stops dragging a drag item instance. */ stopDragging(drag: DragRef) { this._activeDragInstances.update(instances => { const index = instances.indexOf(drag); if (index > -1) { instances.splice(index, 1); return [...instances]; } return instances; }); if (this._activeDragInstances().length === 0) { this._clearGlobalListeners(); } } /** Gets whether a drag item instance is currently being dragged. */ isDragging(drag: DragRef) { return this._activeDragInstances().indexOf(drag) > -1; } /** * Gets a stream that will emit when any element on the page is scrolled while an item is being * dragged. * @param shadowRoot Optional shadow root that the current dragging sequence started from. * Top-level listeners won't pick up events coming from the shadow DOM so this parameter can * be used to include an additional top-level listener at the shadow root level. */ scrolled(shadowRoot?: DocumentOrShadowRoot | null): Observable<Event> { const streams: Observable<Event>[] = [this.scroll]; if (shadowRoot && shadowRoot !== this._document) { // Note that this is basically the same as `fromEvent` from rxjs, but we do it ourselves, // because we want to guarantee that the event is bound outside of the `NgZone`. With // `fromEvent` it'll only happen if the subscription is outside the `NgZone`. streams.push( new Observable((observer: Observer<Event>) => { return this._ngZone.runOutsideAngular(() => { const eventOptions = true; const callback = (event: Event) => { if (this._activeDragInstances().length) { observer.next(event); } }; (shadowRoot as ShadowRoot).addEventListener('scroll', callback, eventOptions); return () => { (shadowRoot as ShadowRoot).removeEventListener('scroll', callback, eventOptions); }; }); }), ); } return merge(...streams); } ngOnDestroy() { this._dragInstances.forEach(instance => this.removeDragItem(instance)); this._dropInstances.forEach(instance => this.removeDropContainer(instance)); this._clearGlobalListeners(); this.pointerMove.complete(); this.pointerUp.complete(); } /** * Event listener that will prevent the default browser action while the user is dragging. * @param event Event whose default action should be prevented. */ private _preventDefaultWhileDragging = (event: Event) => { if (this._activeDragInstances().length > 0) { event.preventDefault(); } }; /** Event listener for `touchmove` that is bound even if no dragging is happening. */
{ "commit_id": "ea0d1ba7b", "end_byte": 9970, "start_byte": 1411, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-drop-registry.ts" }
components/src/cdk/drag-drop/drag-drop-registry.ts_9973_10817
private _persistentTouchmoveListener = (event: TouchEvent) => { if (this._activeDragInstances().length > 0) { // Note that we only want to prevent the default action after dragging has actually started. // Usually this is the same time at which the item is added to the `_activeDragInstances`, // but it could be pushed back if the user has set up a drag delay or threshold. if (this._activeDragInstances().some(this._draggingPredicate)) { event.preventDefault(); } this.pointerMove.next(event); } }; /** Clears out the global event listeners from the `document`. */ private _clearGlobalListeners() { this._globalListeners.forEach((config, name) => { this._document.removeEventListener(name, config.handler, config.options); }); this._globalListeners.clear(); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 10817, "start_byte": 9973, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-drop-registry.ts" }
components/src/cdk/drag-drop/drop-list-ref.ts_0_1846
/** * @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. */
{ "commit_id": "ea0d1ba7b", "end_byte": 1846, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drop-list-ref.ts" }
components/src/cdk/drag-drop/drop-list-ref.ts_1847_10504
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, }); }
{ "commit_id": "ea0d1ba7b", "end_byte": 10504, "start_byte": 1847, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drop-list-ref.ts" }
components/src/cdk/drag-drop/drop-list-ref.ts_10508_18942
/** * 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. */
{ "commit_id": "ea0d1ba7b", "end_byte": 18942, "start_byte": 10508, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drop-list-ref.ts" }
components/src/cdk/drag-drop/drop-list-ref.ts_18945_27411
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. */
{ "commit_id": "ea0d1ba7b", "end_byte": 27411, "start_byte": 18945, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drop-list-ref.ts" }
components/src/cdk/drag-drop/drop-list-ref.ts_27412_31250
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]; }
{ "commit_id": "ea0d1ba7b", "end_byte": 31250, "start_byte": 27412, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drop-list-ref.ts" }
components/src/cdk/drag-drop/public-api.ts_0_866
/** * @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 */ export {DragDrop} from './drag-drop'; export {DragRef, DragRefConfig, Point, PreviewContainer} from './drag-ref'; export {DropListRef} from './drop-list-ref'; export {CDK_DRAG_PARENT} from './drag-parent'; export * from './drag-events'; export * from './drag-utils'; export * from './drag-drop-module'; export {DragDropRegistry} from './drag-drop-registry'; export {CdkDropList} from './directives/drop-list'; export * from './directives/config'; export * from './directives/drop-list-group'; export * from './directives/drag'; export * from './directives/drag-handle'; export * from './directives/drag-preview'; export * from './directives/drag-placeholder';
{ "commit_id": "ea0d1ba7b", "end_byte": 866, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/public-api.ts" }
components/src/cdk/drag-drop/preview-ref.ts_0_5700
/** * @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 {EmbeddedViewRef, TemplateRef, ViewContainerRef} from '@angular/core'; import {Direction} from '@angular/cdk/bidi'; import { extendStyles, getTransform, matchElementSize, toggleNativeDragInteractions, } from './dom/styling'; import {deepCloneNode} from './dom/clone-node'; import {getRootNode} from './dom/root-node'; import {getTransformTransitionDurationInMs} from './dom/transition-duration'; /** Template that can be used to create a drag preview element. */ export interface DragPreviewTemplate<T = any> { matchSize?: boolean; template: TemplateRef<T> | null; viewContainer: ViewContainerRef; context: T; } /** Inline styles to be set as `!important` while dragging. */ const importantProperties = new Set([ // Needs to be important, because some `mat-table` sets `position: sticky !important`. See #22781. 'position', ]); export class PreviewRef { /** Reference to the view of the preview element. */ private _previewEmbeddedView: EmbeddedViewRef<any> | null; /** Reference to the preview element. */ private _preview: HTMLElement; get element(): HTMLElement { return this._preview; } constructor( private _document: Document, private _rootElement: HTMLElement, private _direction: Direction, private _initialDomRect: DOMRect, private _previewTemplate: DragPreviewTemplate | null, private _previewClass: string | string[] | null, private _pickupPositionOnPage: { x: number; y: number; }, private _initialTransform: string | null, private _zIndex: number, ) {} attach(parent: HTMLElement): void { this._preview = this._createPreview(); parent.appendChild(this._preview); // The null check is necessary for browsers that don't support the popover API. // Note that we use a string access for compatibility with Closure. if (supportsPopover(this._preview)) { this._preview['showPopover'](); } } destroy(): void { this._preview.remove(); this._previewEmbeddedView?.destroy(); this._preview = this._previewEmbeddedView = null!; } setTransform(value: string): void { this._preview.style.transform = value; } getBoundingClientRect(): DOMRect { return this._preview.getBoundingClientRect(); } addClass(className: string): void { this._preview.classList.add(className); } getTransitionDuration(): number { return getTransformTransitionDurationInMs(this._preview); } addEventListener(name: string, handler: EventListenerOrEventListenerObject) { this._preview.addEventListener(name, handler); } removeEventListener(name: string, handler: EventListenerOrEventListenerObject) { this._preview.removeEventListener(name, handler); } private _createPreview(): HTMLElement { const previewConfig = this._previewTemplate; const previewClass = this._previewClass; const previewTemplate = previewConfig ? previewConfig.template : null; let preview: HTMLElement; if (previewTemplate && previewConfig) { // Measure the element before we've inserted the preview // since the insertion could throw off the measurement. const rootRect = previewConfig.matchSize ? this._initialDomRect : null; const viewRef = previewConfig.viewContainer.createEmbeddedView( previewTemplate, previewConfig.context, ); viewRef.detectChanges(); preview = getRootNode(viewRef, this._document); this._previewEmbeddedView = viewRef; if (previewConfig.matchSize) { matchElementSize(preview, rootRect!); } else { preview.style.transform = getTransform( this._pickupPositionOnPage.x, this._pickupPositionOnPage.y, ); } } else { preview = deepCloneNode(this._rootElement); matchElementSize(preview, this._initialDomRect!); if (this._initialTransform) { preview.style.transform = this._initialTransform; } } extendStyles( preview.style, { // It's important that we disable the pointer events on the preview, because // it can throw off the `document.elementFromPoint` calls in the `CdkDropList`. 'pointer-events': 'none', // If the preview has a margin, it can throw off our positioning so we reset it. The reset // value for `margin-right` needs to be `auto` when opened as a popover, because our // positioning is always top/left based, but native popover seems to position itself // to the top/right if `<html>` or `<body>` have `dir="rtl"` (see #29604). Setting it // to `auto` pushed it to the top/left corner in RTL and is a noop in LTR. 'margin': supportsPopover(preview) ? '0 auto 0 0' : '0', 'position': 'fixed', 'top': '0', 'left': '0', 'z-index': this._zIndex + '', }, importantProperties, ); toggleNativeDragInteractions(preview, false); preview.classList.add('cdk-drag-preview'); preview.setAttribute('popover', 'manual'); preview.setAttribute('dir', this._direction); if (previewClass) { if (Array.isArray(previewClass)) { previewClass.forEach(className => preview.classList.add(className)); } else { preview.classList.add(previewClass); } } return preview; } } /** Checks whether a specific element supports the popover API. */ function supportsPopover(element: HTMLElement): boolean { return 'showPopover' in element; }
{ "commit_id": "ea0d1ba7b", "end_byte": 5700, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/preview-ref.ts" }
components/src/cdk/drag-drop/drag-ref.ts_0_4300
/** * @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. */
{ "commit_id": "ea0d1ba7b", "end_byte": 4300, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-ref.ts" }
components/src/cdk/drag-drop/drag-ref.ts_4301_12751
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. */
{ "commit_id": "ea0d1ba7b", "end_byte": 12751, "start_byte": 4301, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-ref.ts" }
components/src/cdk/drag-drop/drag-ref.ts_12754_21527
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. */
{ "commit_id": "ea0d1ba7b", "end_byte": 21527, "start_byte": 12754, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-ref.ts" }
components/src/cdk/drag-drop/drag-ref.ts_21530_29382
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. */
{ "commit_id": "ea0d1ba7b", "end_byte": 29382, "start_byte": 21530, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-ref.ts" }
components/src/cdk/drag-drop/drag-ref.ts_29385_36762
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. */
{ "commit_id": "ea0d1ba7b", "end_byte": 36762, "start_byte": 29385, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-ref.ts" }
components/src/cdk/drag-drop/drag-ref.ts_36765_45057
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, event, }); container.drop( this, currentIndex, this._initialIndex, this._initialContainer, isPointerOverContainer, distance, pointerPosition, event, ); this._dropContainer = this._initialContainer; }); } /** * Updates the item's position in its drop container, or moves it * into a new one, depending on its current drag position. */ private _updateActiveDropContainer({x, y}: Point, {x: rawX, y: rawY}: Point) { // Drop container that draggable has been moved into. let newContainer = this._initialContainer._getSiblingContainerFromPosition(this, x, y); // If we couldn't find a new container to move the item into, and the item has left its // initial container, check whether the it's over the initial container. This handles the // case where two containers are connected one way and the user tries to undo dragging an // item into a new container. if ( !newContainer && this._dropContainer !== this._initialContainer && this._initialContainer._isOverContainer(x, y) ) { newContainer = this._initialContainer; } if (newContainer && newContainer !== this._dropContainer) { this._ngZone.run(() => { // Notify the old container that the item has left. this.exited.next({item: this, container: this._dropContainer!}); this._dropContainer!.exit(this); // Notify the new container that the item has entered. this._dropContainer = newContainer!; this._dropContainer.enter( this, x, y, newContainer === this._initialContainer && // If we're re-entering the initial container and sorting is disabled, // put item the into its starting index to begin with. newContainer.sortingDisabled ? this._initialIndex : undefined, ); this.entered.next({ item: this, container: newContainer!, currentIndex: newContainer!.getItemIndex(this), }); }); } // Dragging may have been interrupted as a result of the events above. if (this.isDragging()) { this._dropContainer!._startScrollingIfNecessary(rawX, rawY); this._dropContainer!._sortItem(this, x, y, this._pointerDirectionDelta); if (this.constrainPosition) { this._applyPreviewTransform(x, y); } else { this._applyPreviewTransform( x - this._pickupPositionInElement.x, y - this._pickupPositionInElement.y, ); } } } /** * Animates the preview element from its current position to the location of the drop placeholder. * @returns Promise that resolves when the animation completes. */ private _animatePreviewToPlaceholder(): Promise<void> { // If the user hasn't moved yet, the transitionend event won't fire. if (!this._hasMoved) { return Promise.resolve(); } const placeholderRect = this._placeholder.getBoundingClientRect(); // Apply the class that adds a transition to the preview. this._preview!.addClass('cdk-drag-animating'); // Move the preview to the placeholder position. this._applyPreviewTransform(placeholderRect.left, placeholderRect.top); // If the element doesn't have a `transition`, the `transitionend` event won't fire. Since // we need to trigger a style recalculation in order for the `cdk-drag-animating` class to // apply its style, we take advantage of the available info to figure out whether we need to // bind the event in the first place. const duration = this._preview!.getTransitionDuration(); if (duration === 0) { return Promise.resolve(); } return this._ngZone.runOutsideAngular(() => { return new Promise(resolve => { const handler = ((event: TransitionEvent) => { if ( !event || (this._preview && _getEventTarget(event) === this._preview.element && event.propertyName === 'transform') ) { this._preview?.removeEventListener('transitionend', handler); resolve(); clearTimeout(timeout); } }) as EventListenerOrEventListenerObject; // If a transition is short enough, the browser might not fire the `transitionend` event. // Since we know how long it's supposed to take, add a timeout with a 50% buffer that'll // fire if the transition hasn't completed when it was supposed to. const timeout = setTimeout(handler as Function, duration * 1.5); this._preview!.addEventListener('transitionend', handler); }); }); } /** Creates an element that will be shown instead of the current element while dragging. */ private _createPlaceholderElement(): HTMLElement { const placeholderConfig = this._placeholderTemplate; const placeholderTemplate = placeholderConfig ? placeholderConfig.template : null; let placeholder: HTMLElement; if (placeholderTemplate) { this._placeholderRef = placeholderConfig!.viewContainer.createEmbeddedView( placeholderTemplate, placeholderConfig!.context, ); this._placeholderRef.detectChanges(); placeholder = getRootNode(this._placeholderRef, this._document); } else { placeholder = deepCloneNode(this._rootElement); } // Stop pointer events on the preview so the user can't // interact with it while the preview is animating. placeholder.style.pointerEvents = 'none'; placeholder.classList.add('cdk-drag-placeholder'); return placeholder; } /** * Figures out the coordinates at which an element was picked up. * @param referenceElement Element that initiated the dragging. * @param event Event that initiated the dragging. */ private _getPointerPositionInElement( elementRect: DOMRect, referenceElement: HTMLElement, event: MouseEvent | TouchEvent, ): Point { const handleElement = referenceElement === this._rootElement ? null : referenceElement; const referenceRect = handleElement ? handleElement.getBoundingClientRect() : elementRect; const point = isTouchEvent(event) ? event.targetTouches[0] : event; const scrollPosition = this._getViewportScrollPosition(); const x = point.pageX - referenceRect.left - scrollPosition.left; const y = point.pageY - referenceRect.top - scrollPosition.top; return { x: referenceRect.left - elementRect.left + x, y: referenceRect.top - elementRect.top + y, }; } /** Determines the point of the page that was touched by the user. */
{ "commit_id": "ea0d1ba7b", "end_byte": 45057, "start_byte": 36765, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-ref.ts" }
components/src/cdk/drag-drop/drag-ref.ts_45060_52939
private _getPointerPositionOnPage(event: MouseEvent | TouchEvent): Point { const scrollPosition = this._getViewportScrollPosition(); const point = isTouchEvent(event) ? // `touches` will be empty for start/end events so we have to fall back to `changedTouches`. // Also note that on real devices we're guaranteed for either `touches` or `changedTouches` // to have a value, but Firefox in device emulation mode has a bug where both can be empty // for `touchstart` and `touchend` so we fall back to a dummy object in order to avoid // throwing an error. The value returned here will be incorrect, but since this only // breaks inside a developer tool and the value is only used for secondary information, // we can get away with it. See https://bugzilla.mozilla.org/show_bug.cgi?id=1615824. event.touches[0] || event.changedTouches[0] || {pageX: 0, pageY: 0} : event; const x = point.pageX - scrollPosition.left; const y = point.pageY - scrollPosition.top; // if dragging SVG element, try to convert from the screen coordinate system to the SVG // coordinate system if (this._ownerSVGElement) { const svgMatrix = this._ownerSVGElement.getScreenCTM(); if (svgMatrix) { const svgPoint = this._ownerSVGElement.createSVGPoint(); svgPoint.x = x; svgPoint.y = y; return svgPoint.matrixTransform(svgMatrix.inverse()); } } return {x, y}; } /** Gets the pointer position on the page, accounting for any position constraints. */ private _getConstrainedPointerPosition(point: Point): Point { const dropContainerLock = this._dropContainer ? this._dropContainer.lockAxis : null; let {x, y} = this.constrainPosition ? this.constrainPosition(point, this, this._initialDomRect!, this._pickupPositionInElement) : point; if (this.lockAxis === 'x' || dropContainerLock === 'x') { y = this._pickupPositionOnPage.y - (this.constrainPosition ? this._pickupPositionInElement.y : 0); } else if (this.lockAxis === 'y' || dropContainerLock === 'y') { x = this._pickupPositionOnPage.x - (this.constrainPosition ? this._pickupPositionInElement.x : 0); } if (this._boundaryRect) { // If not using a custom constrain we need to account for the pickup position in the element // otherwise we do not need to do this, as it has already been accounted for const {x: pickupX, y: pickupY} = !this.constrainPosition ? this._pickupPositionInElement : {x: 0, y: 0}; const boundaryRect = this._boundaryRect; const {width: previewWidth, height: previewHeight} = this._getPreviewRect(); const minY = boundaryRect.top + pickupY; const maxY = boundaryRect.bottom - (previewHeight - pickupY); const minX = boundaryRect.left + pickupX; const maxX = boundaryRect.right - (previewWidth - pickupX); x = clamp(x, minX, maxX); y = clamp(y, minY, maxY); } return {x, y}; } /** Updates the current drag delta, based on the user's current pointer position on the page. */ private _updatePointerDirectionDelta(pointerPositionOnPage: Point) { const {x, y} = pointerPositionOnPage; const delta = this._pointerDirectionDelta; const positionSinceLastChange = this._pointerPositionAtLastDirectionChange; // Amount of pixels the user has dragged since the last time the direction changed. const changeX = Math.abs(x - positionSinceLastChange.x); const changeY = Math.abs(y - positionSinceLastChange.y); // Because we handle pointer events on a per-pixel basis, we don't want the delta // to change for every pixel, otherwise anything that depends on it can look erratic. // To make the delta more consistent, we track how much the user has moved since the last // delta change and we only update it after it has reached a certain threshold. if (changeX > this._config.pointerDirectionChangeThreshold) { delta.x = x > positionSinceLastChange.x ? 1 : -1; positionSinceLastChange.x = x; } if (changeY > this._config.pointerDirectionChangeThreshold) { delta.y = y > positionSinceLastChange.y ? 1 : -1; positionSinceLastChange.y = y; } return delta; } /** Toggles the native drag interactions, based on how many handles are registered. */ private _toggleNativeDragInteractions() { if (!this._rootElement || !this._handles) { return; } const shouldEnable = this._handles.length > 0 || !this.isDragging(); if (shouldEnable !== this._nativeInteractionsEnabled) { this._nativeInteractionsEnabled = shouldEnable; toggleNativeDragInteractions(this._rootElement, shouldEnable); } } /** Removes the manually-added event listeners from the root element. */ private _removeRootElementListeners(element: HTMLElement) { element.removeEventListener('mousedown', this._pointerDown, activeEventListenerOptions); element.removeEventListener('touchstart', this._pointerDown, passiveEventListenerOptions); element.removeEventListener('dragstart', this._nativeDragStart, activeEventListenerOptions); } /** * Applies a `transform` to the root element, taking into account any existing transforms on it. * @param x New transform value along the X axis. * @param y New transform value along the Y axis. */ private _applyRootElementTransform(x: number, y: number) { const scale = 1 / this.scale; const transform = getTransform(x * scale, y * scale); const styles = this._rootElement.style; // Cache the previous transform amount only after the first drag sequence, because // we don't want our own transforms to stack on top of each other. // Should be excluded none because none + translate3d(x, y, x) is invalid css if (this._initialTransform == null) { this._initialTransform = styles.transform && styles.transform != 'none' ? styles.transform : ''; } // Preserve the previous `transform` value, if there was one. Note that we apply our own // transform before the user's, because things like rotation can affect which direction // the element will be translated towards. styles.transform = combineTransforms(transform, this._initialTransform); } /** * Applies a `transform` to the preview, taking into account any existing transforms on it. * @param x New transform value along the X axis. * @param y New transform value along the Y axis. */ private _applyPreviewTransform(x: number, y: number) { // Only apply the initial transform if the preview is a clone of the original element, otherwise // it could be completely different and the transform might not make sense anymore. const initialTransform = this._previewTemplate?.template ? undefined : this._initialTransform; const transform = getTransform(x, y); this._preview!.setTransform(combineTransforms(transform, initialTransform)); } /** * Gets the distance that the user has dragged during the current drag sequence. * @param currentPosition Current position of the user's pointer. */ private _getDragDistance(currentPosition: Point): Point { const pickupPosition = this._pickupPositionOnPage; if (pickupPosition) { return {x: currentPosition.x - pickupPosition.x, y: currentPosition.y - pickupPosition.y}; } return {x: 0, y: 0}; } /** Cleans up any cached element dimensions that we don't need after dragging has stopped. */ private _cleanupCachedDimensions() { this._boundaryRect = this._previewRect = undefined; this._parentPositions.clear(); } /** * Checks whether the element is still inside its boundary after the viewport has been resized. * If not, the position is adjusted so that the element fits again. */
{ "commit_id": "ea0d1ba7b", "end_byte": 52939, "start_byte": 45060, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-ref.ts" }
components/src/cdk/drag-drop/drag-ref.ts_52942_60305
private _containInsideBoundaryOnResize() { let {x, y} = this._passiveTransform; if ((x === 0 && y === 0) || this.isDragging() || !this._boundaryElement) { return; } // Note: don't use `_clientRectAtStart` here, because we want the latest position. const elementRect = this._rootElement.getBoundingClientRect(); const boundaryRect = this._boundaryElement.getBoundingClientRect(); // It's possible that the element got hidden away after dragging (e.g. by switching to a // different tab). Don't do anything in this case so we don't clear the user's position. if ( (boundaryRect.width === 0 && boundaryRect.height === 0) || (elementRect.width === 0 && elementRect.height === 0) ) { return; } const leftOverflow = boundaryRect.left - elementRect.left; const rightOverflow = elementRect.right - boundaryRect.right; const topOverflow = boundaryRect.top - elementRect.top; const bottomOverflow = elementRect.bottom - boundaryRect.bottom; // If the element has become wider than the boundary, we can't // do much to make it fit so we just anchor it to the left. if (boundaryRect.width > elementRect.width) { if (leftOverflow > 0) { x += leftOverflow; } if (rightOverflow > 0) { x -= rightOverflow; } } else { x = 0; } // If the element has become taller than the boundary, we can't // do much to make it fit so we just anchor it to the top. if (boundaryRect.height > elementRect.height) { if (topOverflow > 0) { y += topOverflow; } if (bottomOverflow > 0) { y -= bottomOverflow; } } else { y = 0; } if (x !== this._passiveTransform.x || y !== this._passiveTransform.y) { this.setFreeDragPosition({y, x}); } } /** Gets the drag start delay, based on the event type. */ private _getDragStartDelay(event: MouseEvent | TouchEvent): number { const value = this.dragStartDelay; if (typeof value === 'number') { return value; } else if (isTouchEvent(event)) { return value.touch; } return value ? value.mouse : 0; } /** Updates the internal state of the draggable element when scrolling has occurred. */ private _updateOnScroll(event: Event) { const scrollDifference = this._parentPositions.handleScroll(event); if (scrollDifference) { const target = _getEventTarget<HTMLElement | Document>(event)!; // DOMRect dimensions are based on the scroll position of the page and its parent // node so we have to update the cached boundary DOMRect if the user has scrolled. if ( this._boundaryRect && target !== this._boundaryElement && target.contains(this._boundaryElement) ) { adjustDomRect(this._boundaryRect, scrollDifference.top, scrollDifference.left); } this._pickupPositionOnPage.x += scrollDifference.left; this._pickupPositionOnPage.y += scrollDifference.top; // If we're in free drag mode, we have to update the active transform, because // it isn't relative to the viewport like the preview inside a drop list. if (!this._dropContainer) { this._activeTransform.x -= scrollDifference.left; this._activeTransform.y -= scrollDifference.top; this._applyRootElementTransform(this._activeTransform.x, this._activeTransform.y); } } } /** Gets the scroll position of the viewport. */ private _getViewportScrollPosition() { return ( this._parentPositions.positions.get(this._document)?.scrollPosition || this._parentPositions.getViewportScrollPosition() ); } /** * 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(): ShadowRoot | null { if (this._cachedShadowRoot === undefined) { this._cachedShadowRoot = _getShadowRoot(this._rootElement); } return this._cachedShadowRoot; } /** Gets the element into which the drag preview should be inserted. */ private _getPreviewInsertionPoint( initialParent: HTMLElement, shadowRoot: ShadowRoot | null, ): HTMLElement { const previewContainer = this._previewContainer || 'global'; if (previewContainer === 'parent') { return initialParent; } if (previewContainer === 'global') { const documentRef = this._document; // We can't use the body if the user is in fullscreen mode, // because the preview will render under the fullscreen element. // TODO(crisbeto): dedupe this with the `FullscreenOverlayContainer` eventually. return ( shadowRoot || documentRef.fullscreenElement || (documentRef as any).webkitFullscreenElement || (documentRef as any).mozFullScreenElement || (documentRef as any).msFullscreenElement || documentRef.body ); } return coerceElement(previewContainer); } /** Lazily resolves and returns the dimensions of the preview. */ private _getPreviewRect(): DOMRect { // Cache the preview element rect if we haven't cached it already or if // we cached it too early before the element dimensions were computed. if (!this._previewRect || (!this._previewRect.width && !this._previewRect.height)) { this._previewRect = this._preview ? this._preview!.getBoundingClientRect() : this._initialDomRect!; } return this._previewRect; } /** Handles a native `dragstart` event. */ private _nativeDragStart = (event: DragEvent) => { if (this._handles.length) { const targetHandle = this._getTargetHandle(event); if (targetHandle && !this._disabledHandles.has(targetHandle) && !this.disabled) { event.preventDefault(); } } else if (!this.disabled) { // Usually this isn't necessary since the we prevent the default action in `pointerDown`, // but some cases like dragging of links can slip through (see #24403). event.preventDefault(); } }; /** Gets a handle that is the target of an event. */ private _getTargetHandle(event: Event): HTMLElement | undefined { return this._handles.find(handle => { return event.target && (event.target === handle || handle.contains(event.target as Node)); }); } } /** Clamps a value between a minimum and a maximum. */ function clamp(value: number, min: number, max: number) { return Math.max(min, Math.min(max, value)); } /** Determines whether an event is a touch event. */ function isTouchEvent(event: MouseEvent | TouchEvent): event is TouchEvent { // This function is called for every pixel that the user has dragged so we need it to be // as fast as possible. Since we only bind mouse events and touch events, we can assume // that if the event's name starts with `t`, it's a touch event. return event.type[0] === 't'; } /** Callback invoked for `selectstart` events inside the shadow DOM. */ function shadowDomSelectStart(event: Event) { event.preventDefault(); }
{ "commit_id": "ea0d1ba7b", "end_byte": 60305, "start_byte": 52942, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-ref.ts" }
components/src/cdk/drag-drop/drag-parent.ts_0_612
/** * @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 {InjectionToken} from '@angular/core'; import type {CdkDrag} from './directives/drag'; /** * Injection token that can be used for a `CdkDrag` to provide itself as a parent to the * drag-specific child directive (`CdkDragHandle`, `CdkDragPreview` etc.). Used primarily * to avoid circular imports. * @docs-private */ export const CDK_DRAG_PARENT = new InjectionToken<CdkDrag>('CDK_DRAG_PARENT');
{ "commit_id": "ea0d1ba7b", "end_byte": 612, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-parent.ts" }
components/src/cdk/drag-drop/drag-utils.ts_0_2260
/** * @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 */ /** * Moves an item one index in an array to another. * @param array Array in which to move the item. * @param fromIndex Starting index of the item. * @param toIndex Index to which the item should be moved. */ export function moveItemInArray<T = any>(array: T[], fromIndex: number, toIndex: number): void { const from = clamp(fromIndex, array.length - 1); const to = clamp(toIndex, array.length - 1); if (from === to) { return; } const target = array[from]; const delta = to < from ? -1 : 1; for (let i = from; i !== to; i += delta) { array[i] = array[i + delta]; } array[to] = target; } /** * Moves an item from one array to another. * @param currentArray Array from which to transfer the item. * @param targetArray Array into which to put the item. * @param currentIndex Index of the item in its current array. * @param targetIndex Index at which to insert the item. */ export function transferArrayItem<T = any>( currentArray: T[], targetArray: T[], currentIndex: number, targetIndex: number, ): void { const from = clamp(currentIndex, currentArray.length - 1); const to = clamp(targetIndex, targetArray.length); if (currentArray.length) { targetArray.splice(to, 0, currentArray.splice(from, 1)[0]); } } /** * Copies an item from one array to another, leaving it in its * original position in current array. * @param currentArray Array from which to copy the item. * @param targetArray Array into which is copy the item. * @param currentIndex Index of the item in its current array. * @param targetIndex Index at which to insert the item. * */ export function copyArrayItem<T = any>( currentArray: T[], targetArray: T[], currentIndex: number, targetIndex: number, ): void { const to = clamp(targetIndex, targetArray.length); if (currentArray.length) { targetArray.splice(to, 0, currentArray[currentIndex]); } } /** Clamps a number between zero and a maximum. */ function clamp(value: number, max: number): number { return Math.max(0, Math.min(max, value)); }
{ "commit_id": "ea0d1ba7b", "end_byte": 2260, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-utils.ts" }
components/src/cdk/drag-drop/drag-drop.md_0_6900
The `@angular/cdk/drag-drop` module provides you with a way to easily and declaratively create drag-and-drop interfaces, with support for free dragging, sorting within a list, transferring items between lists, animations, touch devices, custom drag handles, previews, and placeholders, in addition to horizontal lists and locking along an axis. ### Getting started Start by importing `DragDropModule` into the `NgModule` where you want to use drag-and-drop features. You can now add the `cdkDrag` directive to elements to make them draggable. When outside of a `cdkDropList` element, draggable elements can be freely moved around the page. You can add `cdkDropList` elements to constrain where elements may be dropped. <!-- example(cdk-drag-drop-overview) --> ### Reordering lists Adding `cdkDropList` around a set of `cdkDrag` elements groups the draggables into a reorderable collection. Items will automatically rearrange as an element moves. Note that this will *not* update your data model; you can listen to the `cdkDropListDropped` event to update the data model once the user finishes dragging. <!-- example(cdk-drag-drop-sorting) --> ### Transferring items between lists The `cdkDropList` directive supports transferring dragged items between connected drop zones. You can connect one or more `cdkDropList` instances together by setting the `cdkDropListConnectedTo` property or by wrapping the elements in an element with the `cdkDropListGroup` attribute. <!-- example(cdk-drag-drop-connected-sorting) --> Note that `cdkDropListConnectedTo` works both with a direct reference to another `cdkDropList`, or by referencing the `id` of another drop container: ```html <!-- This is valid --> <div cdkDropList #listOne="cdkDropList" [cdkDropListConnectedTo]="[listTwo]"></div> <div cdkDropList #listTwo="cdkDropList" [cdkDropListConnectedTo]="[listOne]"></div> <!-- This is valid as well --> <div cdkDropList id="list-one" [cdkDropListConnectedTo]="['list-two']"></div> <div cdkDropList id="list-two" [cdkDropListConnectedTo]="['list-one']"></div> ``` If you have an unknown number of connected drop lists, you can use the `cdkDropListGroup` directive to set up the connection automatically. Note that any new `cdkDropList` that is added under a group will be connected to all other lists automatically. ```html <div cdkDropListGroup> <!-- All lists in here will be connected. --> @for (list of lists; track list) { <div cdkDropList></div> } </div> ``` <!-- example(cdk-drag-drop-connected-sorting-group) --> ### Attaching data You can associate some arbitrary data with both `cdkDrag` and `cdkDropList` by setting `cdkDragData` or `cdkDropListData`, respectively. Events fired from both directives include this data, allowing you to easily identify the origin of the drag or drop interaction. ```html @for (list of lists; track list) { <div cdkDropList [cdkDropListData]="list" (cdkDropListDropped)="drop($event)"> @for (item of list; track item) { <div cdkDrag [cdkDragData]="item"></div> } </div> } ``` ### Styling The `cdkDrag` and `cdkDropList` directive include only those styles strictly necessary for functionality. The application can then customize the elements by styling CSS classes added by the directives: | Selector | Description | |---------------------|--------------------------------------------------------------------------| | `.cdk-drop-list` | Corresponds to the `cdkDropList` container. | | `.cdk-drag` | Corresponds to a `cdkDrag` instance. | | `.cdk-drag-disabled`| Class that is added to a disabled `cdkDrag`. | | `.cdk-drag-handle` | Class that is added to the host element of the cdkDragHandle directive. | | `.cdk-drag-preview` | This is the element that will be rendered next to the user's cursor as they're dragging an item in a sortable list. By default the element looks exactly like the element that is being dragged. | | `.cdk-drag-placeholder` | This is element that will be shown instead of the real element as it's being dragged inside a `cdkDropList`. By default this will look exactly like the element that is being sorted. | | `.cdk-drop-list-dragging` | A class that is added to `cdkDropList` while the user is dragging an item. | | `.cdk-drop-list-disabled` | A class that is added to `cdkDropList` when it is disabled. | | `.cdk-drop-list-receiving`| A class that is added to `cdkDropList` when it can receive an item that is being dragged inside a connected drop list. | ### Animations The drag-and-drop module supports animations both while sorting an element inside a list, as well as animating it from the position that the user dropped it to its final place in the list. To set up your animations, you have to define a `transition` that targets the `transform` property. The following classes can be used for animations: * `.cdk-drag` - If you add a `transition` to this class, it'll animate as the user is sorting through a list. * `.cdk-drag-animating` - This class is added to a `cdkDrag` when the user has stopped dragging. If you add a `transition` to it, the CDK will animate the element from its drop position to the final position inside the `cdkDropList` container. Example animations: ```css /* Animate items as they're being sorted. */ .cdk-drop-list-dragging .cdk-drag { transition: transform 250ms cubic-bezier(0, 0, 0.2, 1); } /* Animate an item that has been dropped. */ .cdk-drag-animating { transition: transform 300ms cubic-bezier(0, 0, 0.2, 1); } ``` ### Customizing the drag area using a handle By default, the user can drag the entire `cdkDrag` element to move it around. If you want to restrict the user to only be able to do so using a handle element, you can do it by adding the `cdkDragHandle` directive to an element inside of `cdkDrag`. Note that you can have as many `cdkDragHandle` elements as you want: <!-- example(cdk-drag-drop-handle) --> ### Customizing the drag preview When a `cdkDrag` element is picked up, it will create a preview element visible while dragging. By default, this will be a clone of the original element positioned next to the user's cursor. This preview can be customized, though, by providing a custom template via `*cdkDragPreview`. Using the default configuration the custom preview won't match the size of the original dragged element, because the CDK doesn't make assumptions about the element's content. If you want the size to be matched, you can pass `true` to the `matchSize` input. Note that the cloned element will remove its `id` attribute in order to avoid having multiple elements with the same `id` on the page. This will cause any CSS that targets that `id` not to be applied. <!-- example(cdk-drag-drop-custom-preview) -->
{ "commit_id": "ea0d1ba7b", "end_byte": 6900, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-drop.md" }
components/src/cdk/drag-drop/drag-drop.md_6900_14238
### Drag preview insertion point By default, the preview of a `cdkDrag` will be inserted into the `<body>` of the page in order to avoid issues with `z-index` and `overflow: hidden`. This may not be desireable in some cases, because the preview won't retain its inherited styles. You can control where the preview is inserted using the `cdkDragPreviewContainer` input on `cdkDrag`. The possible values are: | Value | Description | Advantages | Disadvantages | |-------------------|-------------------------|------------------------|---------------------------| | `global` | Default value. Preview is inserted into the `<body>` or the closest shadow root. | Preview won't be affected by `z-index` or `overflow: hidden`. It also won't affect `:nth-child` selectors and flex layouts. | Doesn't retain inherited styles. | `parent` | Preview is inserted inside the parent of the item that is being dragged. | Preview inherits the same styles as the dragged item. | Preview may be clipped by `overflow: hidden` or be placed under other elements due to `z-index`. Furthermore, it can affect `:nth-child` selectors and some flex layouts. | `ElementRef` or `HTMLElement` | Preview will be inserted into the specified element. | Preview inherits styles from the specified container element. | Preview may be clipped by `overflow: hidden` or be placed under other elements due to `z-index`. Furthermore, it can affect `:nth-child` selectors and some flex layouts. ### Customizing the drag placeholder While a `cdkDrag` element is being dragged, the CDK will create a placeholder element that will show where it will be placed when it's dropped. By default the placeholder is a clone of the element that is being dragged, however you can replace it with a custom one using the `*cdkDragPlaceholder` directive: <!-- example(cdk-drag-drop-custom-placeholder) --> ### List orientation The `cdkDropList` directive assumes that lists are vertical by default. This can be changed by setting the `cdkDropListOrientation` property to `horizontal`. <!-- example(cdk-drag-drop-horizontal-sorting) --> ### List wrapping By default the `cdkDropList` sorts the items by moving them around using a CSS `transform`. This allows for the sorting to be animated which provides a better user experience, but comes with the drawback that it works only one direction: vertically or horizontally. If you have a sortable list that needs to wrap, you can set `cdkDropListOrientation="mixed"` which will use a different strategy of sorting the elements that works by moving them in the DOM. It has the advantage of allowing the items to wrap to the next line, but it **cannot** animate the sorting action. <!-- example(cdk-drag-drop-mixed-sorting) --> ### Restricting movement within an element If you want to stop the user from being able to drag a `cdkDrag` element outside of another element, you can pass a CSS selector to the `cdkDragBoundary` attribute. The attribute works by accepting a selector and looking up the DOM until it finds an element that matches it. If a match is found, it'll be used as the boundary outside of which the element can't be dragged. `cdkDragBoundary` can also be used when `cdkDrag` is placed inside a `cdkDropList`. <!-- example(cdk-drag-drop-boundary) --> ### Restricting movement along an axis By default, `cdkDrag` allows free movement in all directions. To restrict dragging to a specific axis, you can set `cdkDragLockAxis` on `cdkDrag` or `cdkDropListLockAxis` on `cdkDropList` to either `"x"` or `"y"`. <!-- example(cdk-drag-drop-axis-lock) --> ### Alternate drag root element If there's an element that you want to make draggable, but you don't have direct access to it, you can use the `cdkDragRootElement` attribute. The attribute works by accepting a selector and looking up the DOM until it finds an element that matches the selector. If an element is found, it'll become the element that is moved as the user is dragging. This is useful for cases like making a dialog draggable. <!-- example(cdk-drag-drop-root-element) --> ### Controlling which items can be moved into a container By default, all `cdkDrag` items from one container can be moved into another connected container. If you want more fine-grained control over which items can be dropped, you can use the `cdkDropListEnterPredicate` which will be called whenever an item is about to enter a new container. Depending on whether the predicate returns `true` or `false`, the item may or may not be allowed into the new container. <!-- example(cdk-drag-drop-enter-predicate) --> ### Disabled dragging If you want to disable dragging for a particular drag item, you can do so by setting the `cdkDragDisabled` input on a `cdkDrag` item. Furthermore, you can disable an entire list using the `cdkDropListDisabled` input on a `cdkDropList` or a particular handle via `cdkDragHandleDisabled` on `cdkDragHandle`. <!-- example(cdk-drag-drop-disabled) --> ### Disabled sorting There are cases where draggable items can be dragged out of one list into another, however the user shouldn't be able to sort them within the source list. For these cases you can set the `cdkDropListSortingDisabled` input which will prevent the items in a `cdkDropList` from sorting, in addition to preserving the dragged item's initial position in the source list, if the user decides to return the item. <!-- example(cdk-drag-drop-disabled-sorting) --> ### Delayed dragging By default as soon as the user puts their pointer down on a `cdkDrag`, the dragging sequence will be started. This might not be desirable in cases like fullscreen draggable elements on touch devices where the user might accidentally trigger a drag as they're scrolling the page. For cases like these you can delay the dragging sequence using the `cdkDragStartDelay` input which will wait for the user to hold down their pointer for the specified number of milliseconds before moving the element. <!-- example(cdk-drag-drop-delay) --> ### Changing the standalone drag position By default, standalone `cdkDrag` elements move from their normal DOM position only when manually moved by a user. The element's position can be explicitly set, however, via the `cdkDragFreeDragPosition` input. Applications commonly use this, for example, to restore a draggable's position after a user has navigated away and then returned. <!-- example(cdk-drag-drop-free-drag-position) --> ### Controlling whether an item can be sorted into a particular index `cdkDrag` items can be sorted into any position inside of a `cdkDropList` by default. You can change this behavior by setting a `cdkDropListSortPredicate`. The predicate function will be called whenever an item is about to be moved into a new index. If the predicate returns `true`, the item will be moved into the new index, otherwise it will keep its current position. <!-- example(cdk-drag-drop-sort-predicate) --> ### Integrations with Angular Material The CDK's drag&drop functionality can be integrated with different parts of Angular Material. #### Sortable table This example shows how you can set up a table which supports re-ordering of tabs. <!-- example(cdk-drag-drop-table) --> #### Sortable tabs Example of how to add sorting support to a `mat-tab-group`. <!-- example(cdk-drag-drop-tabs) -->
{ "commit_id": "ea0d1ba7b", "end_byte": 14238, "start_byte": 6900, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-drop.md" }
components/src/cdk/drag-drop/drag-events.ts_0_4256
/** * @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 type {CdkDrag} from './directives/drag'; import type {CdkDropList} from './directives/drop-list'; /** Event emitted when the user starts dragging a draggable. */ export interface CdkDragStart<T = any> { /** Draggable that emitted the event. */ source: CdkDrag<T>; /** Native event that started the drag sequence. */ event: MouseEvent | TouchEvent; } /** Event emitted when the user releases an item, before any animations have started. */ export interface CdkDragRelease<T = any> { /** Draggable that emitted the event. */ source: CdkDrag<T>; /** Native event that caused the release event. */ event: MouseEvent | TouchEvent; } /** Event emitted when the user stops dragging a draggable. */ export interface CdkDragEnd<T = any> { /** Draggable that emitted the event. */ source: CdkDrag<T>; /** Distance in pixels that the user has dragged since the drag sequence started. */ distance: {x: number; y: number}; /** Position where the pointer was when the item was dropped */ dropPoint: {x: number; y: number}; /** Native event that caused the dragging to stop. */ event: MouseEvent | TouchEvent; } /** Event emitted when the user moves an item into a new drop container. */ export interface CdkDragEnter<T = any, I = T> { /** Container into which the user has moved the item. */ container: CdkDropList<T>; /** Item that was moved into the container. */ item: CdkDrag<I>; /** Index at which the item has entered the container. */ currentIndex: number; } /** * Event emitted when the user removes an item from a * drop container by moving it into another one. */ export interface CdkDragExit<T = any, I = T> { /** Container from which the user has a removed an item. */ container: CdkDropList<T>; /** Item that was removed from the container. */ item: CdkDrag<I>; } /** Event emitted when the user drops a draggable item inside a drop container. */ export interface CdkDragDrop<T, O = T, I = any> { /** Index of the item when it was picked up. */ previousIndex: number; /** Current index of the item. */ currentIndex: number; /** Item that is being dropped. */ item: CdkDrag<I>; /** Container in which the item was dropped. */ container: CdkDropList<T>; /** Container from which the item was picked up. Can be the same as the `container`. */ previousContainer: CdkDropList<O>; /** Whether the user's pointer was over the container when the item was dropped. */ isPointerOverContainer: boolean; /** Distance in pixels that the user has dragged since the drag sequence started. */ distance: {x: number; y: number}; /** Position where the pointer was when the item was dropped */ dropPoint: {x: number; y: number}; /** Native event that caused the drop event. */ event: MouseEvent | TouchEvent; } /** Event emitted as the user is dragging a draggable item. */ export interface CdkDragMove<T = any> { /** Item that is being dragged. */ source: CdkDrag<T>; /** Position of the user's pointer on the page. */ pointerPosition: {x: number; y: number}; /** Native event that is causing the dragging. */ event: MouseEvent | TouchEvent; /** Distance in pixels that the user has dragged since the drag sequence started. */ distance: {x: number; y: number}; /** * Indicates the direction in which the user is dragging the element along each axis. * `1` means that the position is increasing (e.g. the user is moving to the right or downwards), * whereas `-1` means that it's decreasing (they're moving to the left or upwards). `0` means * that the position hasn't changed. */ delta: {x: -1 | 0 | 1; y: -1 | 0 | 1}; } /** Event emitted when the user swaps the position of two drag items. */ export interface CdkDragSortEvent<T = any, I = T> { /** Index from which the item was sorted previously. */ previousIndex: number; /** Index that the item is currently in. */ currentIndex: number; /** Container that the item belongs to. */ container: CdkDropList<T>; /** Item that is being sorted. */ item: CdkDrag<I>; }
{ "commit_id": "ea0d1ba7b", "end_byte": 4256, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-events.ts" }
components/src/cdk/drag-drop/resets.scss_0_553
@layer cdk-resets { .cdk-drag-preview { background: none; border: none; padding: 0; color: inherit; // Chrome sets a user agent style of `inset: 0` which combined // with `align-self` can break the positioning (see #29809). inset: auto; } } // These elements get `pointer-events: none` when they're created, but any descendants might // override it back to `auto`. Reset them here since they can affect the pointer position detection. .cdk-drag-placeholder *, .cdk-drag-preview * { pointer-events: none !important; }
{ "commit_id": "ea0d1ba7b", "end_byte": 553, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/resets.scss" }
components/src/cdk/drag-drop/BUILD.bazel_0_1331
load( "//tools:defaults.bzl", "markdown_to_html", "ng_module", "ng_test_library", "ng_web_test_suite", "sass_binary", ) package(default_visibility = ["//visibility:public"]) ng_module( name = "drag-drop", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), assets = [ ":resets_scss", ], deps = [ "//src:dev_mode_types", "//src/cdk/a11y", "//src/cdk/bidi", "//src/cdk/coercion", "//src/cdk/platform", "//src/cdk/private", "//src/cdk/scrolling", "@npm//@angular/common", "@npm//@angular/core", "@npm//rxjs", ], ) ng_test_library( name = "unit_test_sources", srcs = glob( ["**/*.spec.ts"], exclude = ["**/*.e2e.spec.ts"], ), deps = [ ":drag-drop", "//src/cdk/bidi", "//src/cdk/platform", "//src/cdk/scrolling", "//src/cdk/testing/private", "@npm//@angular/common", "@npm//rxjs", ], ) sass_binary( name = "resets_scss", src = "resets.scss", ) ng_web_test_suite( name = "unit_tests", deps = [":unit_test_sources"], ) markdown_to_html( name = "overview", srcs = [":drag-drop.md"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "commit_id": "ea0d1ba7b", "end_byte": 1331, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/BUILD.bazel" }
components/src/cdk/drag-drop/index.ts_0_234
/** * @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 */ export * from './public-api';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/index.ts" }
components/src/cdk/drag-drop/drag-drop.ts_0_1953
/** * @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 {Injectable, NgZone, ElementRef, inject} from '@angular/core'; import {DOCUMENT} from '@angular/common'; import {ViewportRuler} from '@angular/cdk/scrolling'; import {DragRef, DragRefConfig} from './drag-ref'; import {DropListRef} from './drop-list-ref'; import {DragDropRegistry} from './drag-drop-registry'; /** Default configuration to be used when creating a `DragRef`. */ const DEFAULT_CONFIG = { dragStartThreshold: 5, pointerDirectionChangeThreshold: 5, }; /** * Service that allows for drag-and-drop functionality to be attached to DOM elements. */ @Injectable({providedIn: 'root'}) export class DragDrop { private _document = inject(DOCUMENT); private _ngZone = inject(NgZone); private _viewportRuler = inject(ViewportRuler); private _dragDropRegistry = inject(DragDropRegistry); constructor(...args: unknown[]); constructor() {} /** * Turns an element into a draggable item. * @param element Element to which to attach the dragging functionality. * @param config Object used to configure the dragging behavior. */ createDrag<T = any>( element: ElementRef<HTMLElement> | HTMLElement, config: DragRefConfig = DEFAULT_CONFIG, ): DragRef<T> { return new DragRef<T>( element, config, this._document, this._ngZone, this._viewportRuler, this._dragDropRegistry, ); } /** * Turns an element into a drop list. * @param element Element to which to attach the drop list functionality. */ createDropList<T = any>(element: ElementRef<HTMLElement> | HTMLElement): DropListRef<T> { return new DropListRef<T>( element, this._dragDropRegistry, this._document, this._ngZone, this._viewportRuler, ); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 1953, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/drag-drop.ts" }
components/src/cdk/drag-drop/directives/mixed-drop-list.spec.ts_0_4427
import {Component, QueryList, ViewChild, ViewChildren} from '@angular/core'; import {fakeAsync, flush} from '@angular/core/testing'; import {CdkDropList} from './drop-list'; import {CdkDrag} from './drag'; import {moveItemInArray} from '../drag-utils'; import {CdkDragDrop} from '../drag-events'; import { ITEM_HEIGHT, ITEM_WIDTH, assertStartToEndSorting, assertEndToStartSorting, defineCommonDropListTests, } from './drop-list-shared.spec'; import {createComponent, dragElementViaMouse} from './test-utils.spec'; describe('mixed drop list', () => { defineCommonDropListTests({ verticalListOrientation: 'mixed', horizontalListOrientation: 'mixed', getSortedSiblings, }); it('should dispatch the `dropped` event in a wrapping drop zone', fakeAsync(() => { const fixture = createComponent(DraggableInHorizontalWrappingDropZone); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', ]); const firstItem = dragItems.first; const seventhItemRect = dragItems.toArray()[6].element.nativeElement.getBoundingClientRect(); dragElementViaMouse( fixture, firstItem.element.nativeElement, seventhItemRect.left + 1, seventhItemRect.top + 1, ); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; // Assert the event like this, rather than `toHaveBeenCalledWith`, because Jasmine will // go into an infinite loop trying to stringify the event, if the test fails. expect(event).toEqual({ previousIndex: 0, currentIndex: 6, item: firstItem, container: fixture.componentInstance.dropInstance, previousContainer: fixture.componentInstance.dropInstance, isPointerOverContainer: true, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Zero', 'Seven', ]); })); it('should move the placeholder as an item is being sorted to the right in a wrapping drop zone', fakeAsync(() => { const fixture = createComponent(DraggableInHorizontalWrappingDropZone); fixture.detectChanges(); assertStartToEndSorting( 'horizontal', fixture, getSortedSiblings, fixture.componentInstance.dragItems.map(item => item.element.nativeElement), ); })); it('should move the placeholder as an item is being sorted to the left in a wrapping drop zone', fakeAsync(() => { const fixture = createComponent(DraggableInHorizontalWrappingDropZone); fixture.detectChanges(); assertEndToStartSorting( 'horizontal', fixture, getSortedSiblings, fixture.componentInstance.dragItems.map(item => item.element.nativeElement), ); })); }); function getSortedSiblings(item: Element) { return Array.from(item.parentElement?.children || []); } @Component({ styles: ` .cdk-drop-list { display: block; width: ${ITEM_WIDTH * 3}px; background: pink; font-size: 0; } .cdk-drag { height: ${ITEM_HEIGHT * 2}px; width: ${ITEM_WIDTH}px; background: red; display: inline-block; } `, template: ` <div cdkDropList cdkDropListOrientation="mixed" [cdkDropListData]="items" (cdkDropListDropped)="droppedSpy($event)"> @for (item of items; track item) { <div cdkDrag>{{item}}</div> } </div> `, standalone: true, imports: [CdkDropList, CdkDrag], }) class DraggableInHorizontalWrappingDropZone { @ViewChildren(CdkDrag) dragItems: QueryList<CdkDrag>; @ViewChild(CdkDropList) dropInstance: CdkDropList; items = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven']; droppedSpy = jasmine.createSpy('dropped spy').and.callFake((event: CdkDragDrop<string[]>) => { moveItemInArray(this.items, event.previousIndex, event.currentIndex); }); }
{ "commit_id": "ea0d1ba7b", "end_byte": 4427, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/mixed-drop-list.spec.ts" }
components/src/cdk/drag-drop/directives/standalone-drag.spec.ts_0_8899
import { ChangeDetectionStrategy, Component, ElementRef, ErrorHandler, QueryList, ViewChild, ViewChildren, ViewEncapsulation, signal, } from '@angular/core'; import {fakeAsync, flush, tick} from '@angular/core/testing'; import { dispatchEvent, createMouseEvent, createTouchEvent, dispatchFakeEvent, dispatchMouseEvent, dispatchTouchEvent, } from '@angular/cdk/testing/private'; import {_supportsShadowDom} from '@angular/cdk/platform'; import {CdkDragHandle} from './drag-handle'; import {CdkDrag} from './drag'; import {CDK_DRAG_CONFIG, DragAxis, DragDropConfig} from './config'; import {DragRef, Point} from '../drag-ref'; import { createComponent, continueDraggingViaTouch, dragElementViaMouse, dragElementViaTouch, makeScrollable, startDraggingViaMouse, startDraggingViaTouch, } from './test-utils.spec'; describe('Standalone CdkDrag', () => { describe('mouse dragging', () => { it('should drag an element freely to a particular position', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); })); it('should drag an element freely to a particular position when the page is scrolled', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const cleanup = makeScrollable(); const dragElement = fixture.componentInstance.dragElement.nativeElement; scrollTo(0, 500); expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); cleanup(); })); it('should continue dragging the element from where it was left off', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); dragElementViaMouse(fixture, dragElement, 100, 200); expect(dragElement.style.transform).toBe('translate3d(150px, 300px, 0px)'); })); it('should continue dragging from where it was left off when the page is scrolled', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const cleanup = makeScrollable(); scrollTo(0, 500); expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); dragElementViaMouse(fixture, dragElement, 100, 200); expect(dragElement.style.transform).toBe('translate3d(150px, 300px, 0px)'); cleanup(); })); it('should not drag an element with the right mouse button', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const event = createMouseEvent('mousedown', 50, 100, 2); expect(dragElement.style.transform).toBeFalsy(); dispatchEvent(dragElement, event); fixture.detectChanges(); dispatchMouseEvent(document, 'mousemove', 50, 100); fixture.detectChanges(); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); expect(dragElement.style.transform).toBeFalsy(); })); it('should not drag the element if it was not moved more than the minimum distance', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable, {dragDistance: 5}); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 2, 2); expect(dragElement.style.transform).toBeFalsy(); })); it('should be able to stop dragging after a double click', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable, {dragDistance: 5}); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dispatchMouseEvent(dragElement, 'mousedown'); fixture.detectChanges(); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); dispatchMouseEvent(dragElement, 'mousedown'); fixture.detectChanges(); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); dragElementViaMouse(fixture, dragElement, 50, 50); dispatchMouseEvent(document, 'mousemove', 100, 100); fixture.detectChanges(); expect(dragElement.style.transform).toBeFalsy(); })); it('should preserve the previous `transform` value', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; dragElement.style.transform = 'translateX(-50%)'; dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px) translateX(-50%)'); })); it('should not generate multiple own `translate3d` values', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; dragElement.style.transform = 'translateY(-50%)'; dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px) translateY(-50%)'); dragElementViaMouse(fixture, dragElement, 100, 200); expect(dragElement.style.transform).toBe('translate3d(150px, 300px, 0px) translateY(-50%)'); })); it('should prevent the `mousedown` action for native draggable elements', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; dragElement.draggable = true; const mousedownEvent = createMouseEvent('mousedown', 50, 50); Object.defineProperty(mousedownEvent, 'target', {get: () => dragElement}); spyOn(mousedownEvent, 'preventDefault').and.callThrough(); dispatchEvent(dragElement, mousedownEvent); fixture.detectChanges(); dispatchMouseEvent(document, 'mousemove', 50, 50); fixture.detectChanges(); expect(mousedownEvent.preventDefault).toHaveBeenCalled(); })); it('should not start dragging an element with a fake mousedown event', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const event = createMouseEvent('mousedown', 0, 0); Object.defineProperties(event, { buttons: {get: () => 0}, detail: {get: () => 0}, }); expect(dragElement.style.transform).toBeFalsy(); dispatchEvent(dragElement, event); fixture.detectChanges(); dispatchMouseEvent(document, 'mousemove', 20, 100); fixture.detectChanges(); dispatchMouseEvent(document, 'mousemove', 50, 100); fixture.detectChanges(); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); expect(dragElement.style.transform).toBeFalsy(); })); it('should prevent the default dragstart action', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const event = dispatchFakeEvent( fixture.componentInstance.dragElement.nativeElement, 'dragstart', ); fixture.detectChanges(); expect(event.defaultPrevented).toBe(true); })); it('should not prevent the default dragstart action when dragging is disabled', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.dragDisabled.set(true); fixture.detectChanges(); const event = dispatchFakeEvent( fixture.componentInstance.dragElement.nativeElement, 'dragstart', ); fixture.detectChanges(); expect(event.defaultPrevented).toBe(false); })); });
{ "commit_id": "ea0d1ba7b", "end_byte": 8899, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/standalone-drag.spec.ts" }
components/src/cdk/drag-drop/directives/standalone-drag.spec.ts_8903_18043
describe('touch dragging', () => { it('should drag an element freely to a particular position', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaTouch(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); })); it('should drag an element freely to a particular position when the page is scrolled', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const cleanup = makeScrollable(); scrollTo(0, 500); expect(dragElement.style.transform).toBeFalsy(); dragElementViaTouch(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); cleanup(); })); it('should continue dragging the element from where it was left off', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaTouch(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); dragElementViaTouch(fixture, dragElement, 100, 200); expect(dragElement.style.transform).toBe('translate3d(150px, 300px, 0px)'); })); it('should continue dragging from where it was left off when the page is scrolled', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const cleanup = makeScrollable(); scrollTo(0, 500); expect(dragElement.style.transform).toBeFalsy(); dragElementViaTouch(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); dragElementViaTouch(fixture, dragElement, 100, 200); expect(dragElement.style.transform).toBe('translate3d(150px, 300px, 0px)'); cleanup(); })); it('should prevent the default `touchmove` action on the page while dragging', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); dispatchTouchEvent(fixture.componentInstance.dragElement.nativeElement, 'touchstart'); fixture.detectChanges(); expect(dispatchTouchEvent(document, 'touchmove').defaultPrevented) .withContext('Expected initial touchmove to be prevented.') .toBe(true); expect(dispatchTouchEvent(document, 'touchmove').defaultPrevented) .withContext('Expected subsequent touchmose to be prevented.') .toBe(true); dispatchTouchEvent(document, 'touchend'); fixture.detectChanges(); })); it('should not prevent `touchstart` action for native draggable elements', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; dragElement.draggable = true; const touchstartEvent = createTouchEvent('touchstart', 50, 50); Object.defineProperty(touchstartEvent, 'target', {get: () => dragElement}); spyOn(touchstartEvent, 'preventDefault').and.callThrough(); dispatchEvent(dragElement, touchstartEvent); fixture.detectChanges(); dispatchTouchEvent(document, 'touchmove'); fixture.detectChanges(); expect(touchstartEvent.preventDefault).not.toHaveBeenCalled(); })); it('should not start dragging an element with a fake touchstart event', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const event = createTouchEvent('touchstart', 50, 50) as TouchEvent; Object.defineProperties(event.touches[0], { identifier: {get: () => -1}, radiusX: {get: () => null}, radiusY: {get: () => null}, }); expect(dragElement.style.transform).toBeFalsy(); dispatchEvent(dragElement, event); fixture.detectChanges(); dispatchTouchEvent(document, 'touchmove', 20, 100); fixture.detectChanges(); dispatchTouchEvent(document, 'touchmove', 50, 100); fixture.detectChanges(); dispatchTouchEvent(document, 'touchend'); fixture.detectChanges(); expect(dragElement.style.transform).toBeFalsy(); })); }); describe('mouse dragging when initial transform is none', () => { it('should drag an element freely to a particular position', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; dragElement.style.transform = 'none'; dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); })); }); it('should dispatch an event when the user has started dragging', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); startDraggingViaMouse(fixture, fixture.componentInstance.dragElement.nativeElement); expect(fixture.componentInstance.startedSpy).toHaveBeenCalled(); const event = fixture.componentInstance.startedSpy.calls.mostRecent().args[0]; // Assert the event like this, rather than `toHaveBeenCalledWith`, because Jasmine will // go into an infinite loop trying to stringify the event, if the test fails. expect(event).toEqual({ source: fixture.componentInstance.dragInstance, event: jasmine.anything(), }); })); it('should dispatch an event when the user has stopped dragging', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); dragElementViaMouse(fixture, fixture.componentInstance.dragElement.nativeElement, 5, 10); expect(fixture.componentInstance.endedSpy).toHaveBeenCalled(); const event = fixture.componentInstance.endedSpy.calls.mostRecent().args[0]; // Assert the event like this, rather than `toHaveBeenCalledWith`, because Jasmine will // go into an infinite loop trying to stringify the event, if the test fails. expect(event).toEqual({ source: fixture.componentInstance.dragInstance, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); })); it('should include the drag distance in the ended event', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); dragElementViaMouse(fixture, fixture.componentInstance.dragElement.nativeElement, 25, 30); let event = fixture.componentInstance.endedSpy.calls.mostRecent().args[0]; expect(event).toEqual({ source: jasmine.anything(), distance: {x: 25, y: 30}, dropPoint: {x: 25, y: 30}, event: jasmine.anything(), }); dragElementViaMouse(fixture, fixture.componentInstance.dragElement.nativeElement, 40, 50); event = fixture.componentInstance.endedSpy.calls.mostRecent().args[0]; expect(event).toEqual({ source: jasmine.anything(), distance: {x: 40, y: 50}, dropPoint: {x: 40, y: 50}, event: jasmine.anything(), }); })); it('should emit when the user is moving the drag element', () => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const spy = jasmine.createSpy('move spy'); const subscription = fixture.componentInstance.dragInstance.moved.subscribe(spy); dragElementViaMouse(fixture, fixture.componentInstance.dragElement.nativeElement, 5, 10); expect(spy).toHaveBeenCalledTimes(1); dragElementViaMouse(fixture, fixture.componentInstance.dragElement.nativeElement, 10, 20); expect(spy).toHaveBeenCalledTimes(2); subscription.unsubscribe(); }); it('should not emit events if it was not moved more than the minimum distance', () => { const fixture = createComponent(StandaloneDraggable, {dragDistance: 5}); fixture.detectChanges(); const moveSpy = jasmine.createSpy('move spy'); const subscription = fixture.componentInstance.dragInstance.moved.subscribe(moveSpy); dragElementViaMouse(fixture, fixture.componentInstance.dragElement.nativeElement, 2, 2); expect(fixture.componentInstance.startedSpy).not.toHaveBeenCalled(); expect(fixture.componentInstance.releasedSpy).not.toHaveBeenCalled(); expect(fixture.componentInstance.endedSpy).not.toHaveBeenCalled(); expect(moveSpy).not.toHaveBeenCalled(); subscription.unsubscribe(); });
{ "commit_id": "ea0d1ba7b", "end_byte": 18043, "start_byte": 8903, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/standalone-drag.spec.ts" }
components/src/cdk/drag-drop/directives/standalone-drag.spec.ts_18047_26284
it('should complete the `moved` stream on destroy', () => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const spy = jasmine.createSpy('move spy'); const subscription = fixture.componentInstance.dragInstance.moved.subscribe({complete: spy}); fixture.destroy(); expect(spy).toHaveBeenCalled(); subscription.unsubscribe(); }); it('should be able to lock dragging along the x axis', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.dragLockAxis.set('x'); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 0px, 0px)'); dragElementViaMouse(fixture, dragElement, 100, 200); expect(dragElement.style.transform).toBe('translate3d(150px, 0px, 0px)'); })); it('should be able to lock dragging along the x axis while using constrainPosition', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.dragLockAxis.set('x'); fixture.componentInstance.constrainPosition = ( {x, y}: Point, _dragRef: DragRef, _dimensions: DOMRect, pickup: Point, ) => { x -= pickup.x; y -= pickup.y; return {x, y}; }; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 0px, 0px)'); dragElementViaMouse(fixture, dragElement, 100, 200); expect(dragElement.style.transform).toBe('translate3d(150px, 0px, 0px)'); })); it('should be able to lock dragging along the y axis', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.dragLockAxis.set('y'); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(0px, 100px, 0px)'); dragElementViaMouse(fixture, dragElement, 100, 200); expect(dragElement.style.transform).toBe('translate3d(0px, 300px, 0px)'); })); it('should be able to lock dragging along the y axis while using constrainPosition', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.dragLockAxis.set('y'); fixture.componentInstance.constrainPosition = ( {x, y}: Point, _dragRef: DragRef, _dimensions: DOMRect, pickup: Point, ) => { x -= pickup.x; y -= pickup.y; return {x, y}; }; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(0px, 100px, 0px)'); dragElementViaMouse(fixture, dragElement, 100, 200); expect(dragElement.style.transform).toBe('translate3d(0px, 300px, 0px)'); })); it('should add a class while an element is being dragged', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const element = fixture.componentInstance.dragElement.nativeElement; expect(element.classList).not.toContain('cdk-drag-dragging'); startDraggingViaMouse(fixture, element); expect(element.classList).toContain('cdk-drag-dragging'); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); expect(element.classList).not.toContain('cdk-drag-dragging'); })); it('should add a class while an element is being dragged with OnPush change detection', fakeAsync(() => { const fixture = createComponent(StandaloneDraggableWithOnPush); fixture.detectChanges(); const element = fixture.componentInstance.dragElement.nativeElement; expect(element.classList).not.toContain('cdk-drag-dragging'); startDraggingViaMouse(fixture, element); expect(element.classList).toContain('cdk-drag-dragging'); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); expect(element.classList).not.toContain('cdk-drag-dragging'); })); it('should not add a class if item was not dragged more than the threshold', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable, {dragDistance: 5}); fixture.detectChanges(); const element = fixture.componentInstance.dragElement.nativeElement; expect(element.classList).not.toContain('cdk-drag-dragging'); startDraggingViaMouse(fixture, element); expect(element.classList).not.toContain('cdk-drag-dragging'); })); it('should be able to set an alternate drag root element', fakeAsync(() => { const fixture = createComponent(DraggableWithAlternateRoot); fixture.componentInstance.rootElementSelector = '.alternate-root'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const dragRoot = fixture.componentInstance.dragRoot.nativeElement; const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragRoot.style.transform).toBeFalsy(); expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragRoot, 50, 100); expect(dragRoot.style.transform).toBe('translate3d(50px, 100px, 0px)'); expect(dragElement.style.transform).toBeFalsy(); })); it('should be able to set the cdkDrag element as handle if it has a different root element', fakeAsync(() => { const fixture = createComponent(DraggableWithAlternateRootAndSelfHandle); fixture.detectChanges(); const dragRoot = fixture.componentInstance.dragRoot.nativeElement; const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragRoot.style.transform).toBeFalsy(); expect(dragElement.style.transform).toBeFalsy(); // Try dragging the root. This should be possible since the drag element is the handle. dragElementViaMouse(fixture, dragRoot, 50, 100); expect(dragRoot.style.transform).toBeFalsy(); expect(dragElement.style.transform).toBeFalsy(); // Drag via the drag element which acts as the handle. dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragRoot.style.transform).toBe('translate3d(50px, 100px, 0px)'); expect(dragElement.style.transform).toBeFalsy(); })); it('should be able to set an alternate drag root element for ng-container', fakeAsync(() => { const fixture = createComponent(DraggableNgContainerWithAlternateRoot); fixture.detectChanges(); const dragRoot = fixture.componentInstance.dragRoot.nativeElement; expect(dragRoot.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragRoot, 50, 100); expect(dragRoot.style.transform).toBe('translate3d(50px, 100px, 0px)'); })); it('should preserve the initial transform if the root element changes', fakeAsync(() => { const fixture = createComponent(DraggableWithAlternateRoot); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const alternateRoot = fixture.componentInstance.dragRoot.nativeElement; dragElement.style.transform = 'translateX(-50%)'; dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toContain('translateX(-50%)'); alternateRoot.style.transform = 'scale(2)'; fixture.componentInstance.rootElementSelector = '.alternate-root'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); dragElementViaMouse(fixture, alternateRoot, 50, 100); expect(alternateRoot.style.transform).not.toContain('translateX(-50%)'); expect(alternateRoot.style.transform).toContain('scale(2)'); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 26284, "start_byte": 18047, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/standalone-drag.spec.ts" }
components/src/cdk/drag-drop/directives/standalone-drag.spec.ts_26288_35949
it('should handle the root element selector changing after init', fakeAsync(() => { const fixture = createComponent(DraggableWithAlternateRoot); fixture.detectChanges(); tick(); fixture.componentInstance.rootElementSelector = '.alternate-root'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const dragRoot = fixture.componentInstance.dragRoot.nativeElement; const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragRoot.style.transform).toBeFalsy(); expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragRoot, 50, 100); expect(dragRoot.style.transform).toBe('translate3d(50px, 100px, 0px)'); expect(dragElement.style.transform).toBeFalsy(); })); it('should not be able to drag the element if dragging is disabled', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.classList).not.toContain('cdk-drag-disabled'); fixture.componentInstance.dragDisabled.set(true); fixture.detectChanges(); expect(dragElement.classList).toContain('cdk-drag-disabled'); expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBeFalsy(); })); it('should enable native drag interactions if dragging is disabled', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const styles = dragElement.style; expect(styles.touchAction || (styles as any).webkitUserDrag).toBeFalsy(); fixture.componentInstance.dragDisabled.set(true); fixture.detectChanges(); expect(styles.touchAction || (styles as any).webkitUserDrag).toBeFalsy(); })); it('should enable native drag interactions if not dragging', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const styles = dragElement.style; expect(styles.touchAction || (styles as any).webkitUserDrag).toBeFalsy(); })); it('should disable native drag interactions if dragging', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const styles = dragElement.style; expect(styles.touchAction || (styles as any).webkitUserDrag).toBeFalsy(); startDraggingViaMouse(fixture, dragElement); dispatchMouseEvent(document, 'mousemove', 50, 100); fixture.detectChanges(); expect(styles.touchAction || (styles as any).webkitUserDrag).toBe('none'); })); it('should re-enable drag interactions once dragging is over', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const styles = dragElement.style; startDraggingViaMouse(fixture, dragElement); dispatchMouseEvent(document, 'mousemove', 50, 100); fixture.detectChanges(); expect(styles.touchAction || (styles as any).webkitUserDrag).toBe('none'); dispatchMouseEvent(document, 'mouseup', 50, 100); fixture.detectChanges(); expect(styles.touchAction || (styles as any).webkitUserDrag).toBeFalsy(); })); it('should not stop propagation for the drag sequence start event by default', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const event = createMouseEvent('mousedown'); spyOn(event, 'stopPropagation').and.callThrough(); dispatchEvent(dragElement, event); fixture.detectChanges(); expect(event.stopPropagation).not.toHaveBeenCalled(); })); it('should not throw if destroyed before the first change detection run', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); expect(() => { fixture.destroy(); }).not.toThrow(); })); it('should enable native drag interactions on the drag item when there is a handle', () => { const fixture = createComponent(StandaloneDraggableWithHandle); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.touchAction).not.toBe('none'); }); it('should disable native drag interactions on the drag handle', () => { const fixture = createComponent(StandaloneDraggableWithHandle); fixture.detectChanges(); const styles = fixture.componentInstance.handleElement.nativeElement.style; expect(styles.touchAction || (styles as any).webkitUserDrag).toBe('none'); }); it('should enable native drag interactions on the drag handle if dragging is disabled', () => { const fixture = createComponent(StandaloneDraggableWithHandle); fixture.detectChanges(); fixture.componentInstance.draggingDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const styles = fixture.componentInstance.handleElement.nativeElement.style; expect(styles.touchAction || (styles as any).webkitUserDrag).toBeFalsy(); }); it( 'should enable native drag interactions on the drag handle if dragging is disabled ' + 'on init', () => { const fixture = createComponent(StandaloneDraggableWithHandle); fixture.componentInstance.draggingDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const styles = fixture.componentInstance.handleElement.nativeElement.style; expect(styles.touchAction || (styles as any).webkitUserDrag).toBeFalsy(); }, ); it('should toggle native drag interactions based on whether the handle is disabled', () => { const fixture = createComponent(StandaloneDraggableWithHandle); fixture.detectChanges(); fixture.componentInstance.handleInstance.disabled = true; fixture.detectChanges(); const styles = fixture.componentInstance.handleElement.nativeElement.style; expect(styles.touchAction || (styles as any).webkitUserDrag).toBeFalsy(); fixture.componentInstance.handleInstance.disabled = false; fixture.detectChanges(); expect(styles.touchAction || (styles as any).webkitUserDrag).toBe('none'); }); it('should be able to reset a freely-dragged item to its initial position', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); fixture.componentInstance.dragInstance.reset(); expect(dragElement.style.transform).toBeFalsy(); })); it('should preserve initial transform after resetting', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; dragElement.style.transform = 'scale(2)'; dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px) scale(2)'); fixture.componentInstance.dragInstance.reset(); expect(dragElement.style.transform).toBe('scale(2)'); })); it('should start dragging an item from its initial position after a reset', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); fixture.componentInstance.dragInstance.reset(); dragElementViaMouse(fixture, dragElement, 25, 50); expect(dragElement.style.transform).toBe('translate3d(25px, 50px, 0px)'); })); it('should not dispatch multiple events for a mouse event right after a touch event', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; // Dispatch a touch sequence. dispatchTouchEvent(dragElement, 'touchstart'); fixture.detectChanges(); dispatchTouchEvent(dragElement, 'touchend'); fixture.detectChanges(); tick(); // Immediately dispatch a mouse sequence to simulate a fake event. startDraggingViaMouse(fixture, dragElement); fixture.detectChanges(); dispatchMouseEvent(dragElement, 'mouseup'); fixture.detectChanges(); tick(); expect(fixture.componentInstance.startedSpy).toHaveBeenCalledTimes(1); expect(fixture.componentInstance.endedSpy).toHaveBeenCalledTimes(1); })); it('should round the transform value', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 13.37, 37); expect(dragElement.style.transform).toBe('translate3d(13px, 37px, 0px)'); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 35949, "start_byte": 26288, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/standalone-drag.spec.ts" }
components/src/cdk/drag-drop/directives/standalone-drag.spec.ts_35953_44679
it('should allow for dragging to be constrained to an element', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.boundary = '.wrapper'; fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 300, 300); expect(dragElement.style.transform).toBe('translate3d(100px, 100px, 0px)'); })); it('should allow for dragging to be constrained to an element while using constrainPosition', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.boundary = '.wrapper'; fixture.detectChanges(); fixture.componentInstance.dragInstance.constrainPosition = ( {x, y}: Point, _dragRef: DragRef, _dimensions: DOMRect, pickup: Point, ) => { x -= pickup.x; y -= pickup.y; return {x, y}; }; const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 300, 300); expect(dragElement.style.transform).toBe('translate3d(100px, 100px, 0px)'); })); it('should be able to pass in a DOM node as the boundary', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.boundary = fixture.nativeElement.querySelector('.wrapper'); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 300, 300); expect(dragElement.style.transform).toBe('translate3d(100px, 100px, 0px)'); })); it('should adjust the x offset if the boundary becomes narrower after a viewport resize', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); const boundary: HTMLElement = fixture.nativeElement.querySelector('.wrapper'); fixture.componentInstance.boundary = boundary; fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; dragElementViaMouse(fixture, dragElement, 300, 300); expect(dragElement.style.transform).toBe('translate3d(100px, 100px, 0px)'); boundary.style.width = '150px'; dispatchFakeEvent(window, 'resize'); tick(20); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); })); it('should keep the old position if the boundary is invisible after a resize', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); const boundary: HTMLElement = fixture.nativeElement.querySelector('.wrapper'); fixture.componentInstance.boundary = boundary; fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; dragElementViaMouse(fixture, dragElement, 300, 300); expect(dragElement.style.transform).toBe('translate3d(100px, 100px, 0px)'); boundary.style.display = 'none'; dispatchFakeEvent(window, 'resize'); tick(20); expect(dragElement.style.transform).toBe('translate3d(100px, 100px, 0px)'); })); it('should handle the element and boundary dimensions changing between drag sequences', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); const boundary: HTMLElement = fixture.nativeElement.querySelector('.wrapper'); fixture.componentInstance.boundary = boundary; fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; dragElementViaMouse(fixture, dragElement, 300, 300); expect(dragElement.style.transform).toBe('translate3d(100px, 100px, 0px)'); // Bump the width and height of both the boundary and the drag element. boundary.style.width = boundary.style.height = '300px'; dragElement.style.width = dragElement.style.height = '150px'; dragElementViaMouse(fixture, dragElement, 300, 300); expect(dragElement.style.transform).toBe('translate3d(150px, 150px, 0px)'); })); it('should adjust the y offset if the boundary becomes shorter after a viewport resize', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); const boundary: HTMLElement = fixture.nativeElement.querySelector('.wrapper'); fixture.componentInstance.boundary = boundary; fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; dragElementViaMouse(fixture, dragElement, 300, 300); expect(dragElement.style.transform).toBe('translate3d(100px, 100px, 0px)'); boundary.style.height = '150px'; dispatchFakeEvent(window, 'resize'); tick(20); expect(dragElement.style.transform).toBe('translate3d(100px, 50px, 0px)'); })); it( 'should reset the x offset if the boundary becomes narrower than the element ' + 'after a resize', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); const boundary: HTMLElement = fixture.nativeElement.querySelector('.wrapper'); fixture.componentInstance.boundary = boundary; fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; dragElementViaMouse(fixture, dragElement, 300, 300); expect(dragElement.style.transform).toBe('translate3d(100px, 100px, 0px)'); boundary.style.width = '50px'; dispatchFakeEvent(window, 'resize'); tick(20); expect(dragElement.style.transform).toBe('translate3d(0px, 100px, 0px)'); }), ); it('should reset the y offset if the boundary becomes shorter than the element after a resize', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); const boundary: HTMLElement = fixture.nativeElement.querySelector('.wrapper'); fixture.componentInstance.boundary = boundary; fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; dragElementViaMouse(fixture, dragElement, 300, 300); expect(dragElement.style.transform).toBe('translate3d(100px, 100px, 0px)'); boundary.style.height = '50px'; dispatchFakeEvent(window, 'resize'); tick(20); expect(dragElement.style.transform).toBe('translate3d(100px, 0px, 0px)'); })); it('should allow for the position constrain logic to be customized', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); const spy = jasmine.createSpy('constrain position spy').and.returnValue({ x: 50, y: 50, } as Point); fixture.componentInstance.constrainPosition = spy; fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 300, 300); expect(spy).toHaveBeenCalledWith( jasmine.objectContaining({x: 300, y: 300}), jasmine.any(DragRef), jasmine.anything(), jasmine.objectContaining({x: jasmine.any(Number), y: jasmine.any(Number)}), ); const elementRect = dragElement.getBoundingClientRect(); expect(Math.floor(elementRect.top)).toBe(50); expect(Math.floor(elementRect.left)).toBe(50); })); it('should throw if drag item is attached to an ng-container', () => { const errorHandler = jasmine.createSpyObj(['handleError']); createComponent(DraggableOnNgContainer, { providers: [ { provide: ErrorHandler, useValue: errorHandler, }, ], }).detectChanges(); expect(errorHandler.handleError.calls.mostRecent().args[0].message).toMatch( /^cdkDrag must be attached to an element node/, ); }); it('should cancel drag if the mouse moves before the delay is elapsed', fakeAsync(() => { // We can't use Jasmine's `clock` because Zone.js interferes with it. spyOn(Date, 'now').and.callFake(() => currentTime); let currentTime = 0; const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.dragStartDelay = 1000; fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform) .withContext('Expected element not to be moved by default.') .toBeFalsy(); startDraggingViaMouse(fixture, dragElement); currentTime += 750; dispatchMouseEvent(document, 'mousemove', 50, 100); currentTime += 500; fixture.detectChanges(); expect(dragElement.style.transform) .withContext('Expected element not to be moved if the mouse moved before the delay.') .toBeFalsy(); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 44679, "start_byte": 35953, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/standalone-drag.spec.ts" }
components/src/cdk/drag-drop/directives/standalone-drag.spec.ts_44683_53353
it('should enable native drag interactions if mouse moves before the delay', fakeAsync(() => { // We can't use Jasmine's `clock` because Zone.js interferes with it. spyOn(Date, 'now').and.callFake(() => currentTime); let currentTime = 0; const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.dragStartDelay = 1000; fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const styles = dragElement.style; expect(dragElement.style.transform) .withContext('Expected element not to be moved by default.') .toBeFalsy(); startDraggingViaMouse(fixture, dragElement); currentTime += 750; dispatchMouseEvent(document, 'mousemove', 50, 100); currentTime += 500; fixture.detectChanges(); expect(styles.touchAction || (styles as any).webkitUserDrag).toBeFalsy(); })); it('should allow dragging after the drag start delay is elapsed', fakeAsync(() => { // We can't use Jasmine's `clock` because Zone.js interferes with it. spyOn(Date, 'now').and.callFake(() => currentTime); let currentTime = 0; const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.dragStartDelay = 500; fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform) .withContext('Expected element not to be moved by default.') .toBeFalsy(); dispatchMouseEvent(dragElement, 'mousedown'); fixture.detectChanges(); currentTime += 750; // The first `mousemove` here starts the sequence and the second one moves the element. dispatchMouseEvent(document, 'mousemove', 50, 100); dispatchMouseEvent(document, 'mousemove', 50, 100); fixture.detectChanges(); expect(dragElement.style.transform) .withContext('Expected element to be dragged after all the time has passed.') .toBe('translate3d(50px, 100px, 0px)'); })); it('should not prevent the default touch action before the delay has elapsed', fakeAsync(() => { spyOn(Date, 'now').and.callFake(() => currentTime); let currentTime = 0; const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.dragStartDelay = 500; fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform) .withContext('Expected element not to be moved by default.') .toBeFalsy(); dispatchTouchEvent(dragElement, 'touchstart'); fixture.detectChanges(); currentTime += 250; expect(dispatchTouchEvent(document, 'touchmove', 50, 100).defaultPrevented).toBe(false); })); it('should handle the drag delay as a string', fakeAsync(() => { // We can't use Jasmine's `clock` because Zone.js interferes with it. spyOn(Date, 'now').and.callFake(() => currentTime); let currentTime = 0; const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.dragStartDelay = '500'; fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform) .withContext('Expected element not to be moved by default.') .toBeFalsy(); dispatchMouseEvent(dragElement, 'mousedown'); fixture.detectChanges(); currentTime += 750; // The first `mousemove` here starts the sequence and the second one moves the element. dispatchMouseEvent(document, 'mousemove', 50, 100); dispatchMouseEvent(document, 'mousemove', 50, 100); fixture.detectChanges(); expect(dragElement.style.transform) .withContext('Expected element to be dragged after all the time has passed.') .toBe('translate3d(50px, 100px, 0px)'); })); it('should be able to configure the drag start delay based on the event type', fakeAsync(() => { // We can't use Jasmine's `clock` because Zone.js interferes with it. spyOn(Date, 'now').and.callFake(() => currentTime); let currentTime = 0; const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.dragStartDelay = {touch: 500, mouse: 0}; fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform) .withContext('Expected element not to be moved by default.') .toBeFalsy(); dragElementViaTouch(fixture, dragElement, 50, 100); expect(dragElement.style.transform) .withContext('Expected element not to be moved via touch because it has a delay.') .toBeFalsy(); dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform) .withContext('Expected element to be moved via mouse because it has no delay.') .toBe('translate3d(50px, 100px, 0px)'); })); it('should be able to get the current position', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const dragInstance = fixture.componentInstance.dragInstance; expect(dragInstance.getFreeDragPosition()).toEqual({x: 0, y: 0}); dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragInstance.getFreeDragPosition()).toEqual({x: 50, y: 100}); dragElementViaMouse(fixture, dragElement, 100, 200); expect(dragInstance.getFreeDragPosition()).toEqual({x: 150, y: 300}); })); it('should be able to set the current position programmatically', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const dragInstance = fixture.componentInstance.dragInstance; dragInstance.setFreeDragPosition({x: 50, y: 100}); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); expect(dragInstance.getFreeDragPosition()).toEqual({x: 50, y: 100}); })); it('should be able to set the current position', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.freeDragPosition = {x: 50, y: 100}; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const dragInstance = fixture.componentInstance.dragInstance; expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); expect(dragInstance.getFreeDragPosition()).toEqual({x: 50, y: 100}); })); it('should be able to get the up-to-date position as the user is dragging', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const dragInstance = fixture.componentInstance.dragInstance; expect(dragInstance.getFreeDragPosition()).toEqual({x: 0, y: 0}); startDraggingViaMouse(fixture, dragElement); dispatchMouseEvent(document, 'mousemove', 50, 100); fixture.detectChanges(); expect(dragInstance.getFreeDragPosition()).toEqual({x: 50, y: 100}); dispatchMouseEvent(document, 'mousemove', 100, 200); fixture.detectChanges(); expect(dragInstance.getFreeDragPosition()).toEqual({x: 100, y: 200}); })); it('should react to changes in the free drag position', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.freeDragPosition = {x: 50, y: 100}; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); fixture.componentInstance.freeDragPosition = {x: 100, y: 200}; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(dragElement.style.transform).toBe('translate3d(100px, 200px, 0px)'); })); it('should be able to continue dragging after the current position was set', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.freeDragPosition = {x: 50, y: 100}; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); dragElementViaMouse(fixture, dragElement, 100, 200); expect(dragElement.style.transform).toBe('translate3d(150px, 300px, 0px)'); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 53353, "start_byte": 44683, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/standalone-drag.spec.ts" }
components/src/cdk/drag-drop/directives/standalone-drag.spec.ts_53357_58714
it('should account for the scale when setting the free drag position', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.scale = 0.5; fixture.componentInstance.freeDragPosition = {x: 50, y: 100}; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const dragInstance = fixture.componentInstance.dragInstance; expect(dragElement.style.transform).toBe('translate3d(100px, 200px, 0px)'); expect(dragInstance.getFreeDragPosition()).toEqual({x: 50, y: 100}); })); it('should include the dragged distance as the user is dragging', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const spy = jasmine.createSpy('moved spy'); const subscription = fixture.componentInstance.dragInstance.moved.subscribe(spy); startDraggingViaMouse(fixture, dragElement); dispatchMouseEvent(document, 'mousemove', 50, 100); fixture.detectChanges(); let event = spy.calls.mostRecent().args[0]; expect(event.distance).toEqual({x: 50, y: 100}); dispatchMouseEvent(document, 'mousemove', 75, 50); fixture.detectChanges(); event = spy.calls.mostRecent().args[0]; expect(event.distance).toEqual({x: 75, y: 50}); subscription.unsubscribe(); })); it('should be able to configure the drag input defaults through a provider', fakeAsync(() => { const config: DragDropConfig = { draggingDisabled: true, dragStartDelay: 1337, lockAxis: 'y', constrainPosition: () => ({x: 1337, y: 42}), previewClass: 'custom-preview-class', boundaryElement: '.boundary', rootElementSelector: '.root', previewContainer: 'parent', }; const fixture = createComponent(PlainStandaloneDraggable, { providers: [ { provide: CDK_DRAG_CONFIG, useValue: config, }, ], }); fixture.detectChanges(); const drag = fixture.componentInstance.dragInstance; expect(drag.disabled).toBe(true); expect(drag.dragStartDelay).toBe(1337); expect(drag.lockAxis).toBe('y'); expect(drag.constrainPosition).toBe(config.constrainPosition); expect(drag.previewClass).toBe('custom-preview-class'); expect(drag.boundaryElement).toBe('.boundary'); expect(drag.rootElementSelector).toBe('.root'); expect(drag.previewContainer).toBe('parent'); })); it('should not throw if touches and changedTouches are empty', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; startDraggingViaTouch(fixture, dragElement); continueDraggingViaTouch(fixture, 50, 100); const event = createTouchEvent('touchend', 50, 100); Object.defineProperties(event, { touches: {get: () => []}, changedTouches: {get: () => []}, }); expect(() => { dispatchEvent(document, event); fixture.detectChanges(); tick(); }).not.toThrow(); })); it('should update the free drag position if the page is scrolled', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const cleanup = makeScrollable(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); startDraggingViaMouse(fixture, dragElement, 0, 0); dispatchMouseEvent(document, 'mousemove', 50, 100); fixture.detectChanges(); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); scrollTo(0, 500); dispatchFakeEvent(document, 'scroll'); fixture.detectChanges(); expect(dragElement.style.transform).toBe('translate3d(50px, 600px, 0px)'); cleanup(); })); it('should update the free drag position if the user moves their pointer after the page is scrolled', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.detectChanges(); const cleanup = makeScrollable(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); startDraggingViaMouse(fixture, dragElement, 0, 0); dispatchMouseEvent(document, 'mousemove', 50, 100); fixture.detectChanges(); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); scrollTo(0, 500); dispatchFakeEvent(document, 'scroll'); fixture.detectChanges(); dispatchMouseEvent(document, 'mousemove', 50, 200); fixture.detectChanges(); expect(dragElement.style.transform).toBe('translate3d(50px, 700px, 0px)'); cleanup(); })); it('should account for scale when moving the element', fakeAsync(() => { const fixture = createComponent(StandaloneDraggable); fixture.componentInstance.scale = 0.5; fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBe('translate3d(100px, 200px, 0px)'); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 58714, "start_byte": 53357, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/standalone-drag.spec.ts" }
components/src/cdk/drag-drop/directives/standalone-drag.spec.ts_58718_67407
describe('with a handle', () => { it('should not be able to drag the entire element if it has a handle', fakeAsync(() => { const fixture = createComponent(StandaloneDraggableWithHandle); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform).toBeFalsy(); })); it('should be able to drag an element using its handle', fakeAsync(() => { const fixture = createComponent(StandaloneDraggableWithHandle); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const handle = fixture.componentInstance.handleElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, handle, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); })); it('should not be able to drag the element if the handle is disabled', fakeAsync(() => { const fixture = createComponent(StandaloneDraggableWithHandle); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const handle = fixture.componentInstance.handleElement.nativeElement; fixture.componentInstance.handleInstance.disabled = true; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, handle, 50, 100); expect(dragElement.style.transform).toBeFalsy(); })); it('should not be able to drag the element if the handle is disabled before init', fakeAsync(() => { const fixture = createComponent(StandaloneDraggableWithPreDisabledHandle); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const handle = fixture.componentInstance.handleElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, handle, 50, 100); expect(dragElement.style.transform).toBeFalsy(); })); it('should not be able to drag using the handle if the element is disabled', fakeAsync(() => { const fixture = createComponent(StandaloneDraggableWithHandle); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const handle = fixture.componentInstance.handleElement.nativeElement; fixture.componentInstance.draggingDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, handle, 50, 100); expect(dragElement.style.transform).toBeFalsy(); })); it('should be able to use a handle that was added after init', fakeAsync(() => { const fixture = createComponent(StandaloneDraggableWithDelayedHandle); fixture.detectChanges(); fixture.componentInstance.showHandle = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const handle = fixture.componentInstance.handleElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, handle, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); })); it('should be able to use more than one handle to drag the element', fakeAsync(async () => { const fixture = createComponent(StandaloneDraggableWithMultipleHandles); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const handles = fixture.componentInstance.handles.map(handle => handle.element.nativeElement); expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, handles[1], 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); dragElementViaMouse(fixture, handles[0], 100, 200); expect(dragElement.style.transform).toBe('translate3d(150px, 300px, 0px)'); })); it('should be able to drag with a handle that is not a direct descendant', fakeAsync(() => { const fixture = createComponent(StandaloneDraggableWithIndirectHandle); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const handle = fixture.componentInstance.handleElement.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, dragElement, 50, 100); expect(dragElement.style.transform) .withContext('Expected not to be able to drag the element by itself.') .toBeFalsy(); dragElementViaMouse(fixture, handle, 50, 100); expect(dragElement.style.transform) .withContext('Expected to drag the element by its handle.') .toBe('translate3d(50px, 100px, 0px)'); })); it('should disable the tap highlight while dragging via the handle', fakeAsync(() => { // This test is irrelevant if the browser doesn't support styling the tap highlight color. if (!('webkitTapHighlightColor' in document.body.style)) { return; } const fixture = createComponent(StandaloneDraggableWithHandle); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const handle = fixture.componentInstance.handleElement.nativeElement; expect((dragElement.style as any).webkitTapHighlightColor).toBeFalsy(); startDraggingViaMouse(fixture, handle); expect((dragElement.style as any).webkitTapHighlightColor).toBe('transparent'); dispatchMouseEvent(document, 'mousemove', 50, 100); fixture.detectChanges(); dispatchMouseEvent(document, 'mouseup', 50, 100); fixture.detectChanges(); expect((dragElement.style as any).webkitTapHighlightColor).toBeFalsy(); })); it('should preserve any existing `webkitTapHighlightColor`', fakeAsync(() => { // This test is irrelevant if the browser doesn't support styling the tap highlight color. if (!('webkitTapHighlightColor' in document.body.style)) { return; } const fixture = createComponent(StandaloneDraggableWithHandle); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const handle = fixture.componentInstance.handleElement.nativeElement; (dragElement.style as any).webkitTapHighlightColor = 'purple'; startDraggingViaMouse(fixture, handle); expect((dragElement.style as any).webkitTapHighlightColor).toBe('transparent'); dispatchMouseEvent(document, 'mousemove', 50, 100); fixture.detectChanges(); dispatchMouseEvent(document, 'mouseup', 50, 100); fixture.detectChanges(); expect((dragElement.style as any).webkitTapHighlightColor).toBe('purple'); })); it('should throw if drag handle is attached to an ng-container', fakeAsync(() => { expect(() => { createComponent(DragHandleOnNgContainer).detectChanges(); flush(); }).toThrowError(/^cdkDragHandle must be attached to an element node/); })); it('should be able to drag an element using a handle with a shadow DOM child', fakeAsync(() => { if (!_supportsShadowDom()) { return; } const fixture = createComponent(StandaloneDraggableWithShadowInsideHandle); fixture.detectChanges(); const dragElement = fixture.componentInstance.dragElement.nativeElement; const handleChild = fixture.componentInstance.handleChild.nativeElement; expect(dragElement.style.transform).toBeFalsy(); dragElementViaMouse(fixture, handleChild, 50, 100); expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)'); })); it('should prevent default dragStart on handle, not on entire draggable', fakeAsync(() => { const fixture = createComponent(StandaloneDraggableWithHandle); fixture.detectChanges(); const draggableEvent = dispatchFakeEvent( fixture.componentInstance.dragElement.nativeElement, 'dragstart', ); fixture.detectChanges(); const handleEvent = dispatchFakeEvent( fixture.componentInstance.handleElement.nativeElement, 'dragstart', true, ); fixture.detectChanges(); expect(draggableEvent.defaultPrevented).toBe(false); expect(handleEvent.defaultPrevented).toBe(true); })); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 67407, "start_byte": 58718, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/standalone-drag.spec.ts" }
components/src/cdk/drag-drop/directives/standalone-drag.spec.ts_67409_74403
@Component({ template: ` <div class="wrapper" style="width: 200px; height: 200px; background: green;"> <div cdkDrag [cdkDragBoundary]="boundary" [cdkDragStartDelay]="dragStartDelay" [cdkDragConstrainPosition]="constrainPosition" [cdkDragFreeDragPosition]="freeDragPosition" [cdkDragDisabled]="dragDisabled()" [cdkDragLockAxis]="dragLockAxis()" [cdkDragScale]="scale" (cdkDragStarted)="startedSpy($event)" (cdkDragReleased)="releasedSpy($event)" (cdkDragEnded)="endedSpy($event)" #dragElement style="width: 100px; height: 100px; background: red;"></div> </div> `, standalone: true, imports: [CdkDrag], }) class StandaloneDraggable { @ViewChild('dragElement') dragElement: ElementRef<HTMLElement>; @ViewChild(CdkDrag) dragInstance: CdkDrag; startedSpy = jasmine.createSpy('started spy'); endedSpy = jasmine.createSpy('ended spy'); releasedSpy = jasmine.createSpy('released spy'); boundary: string | HTMLElement; dragStartDelay: number | string | {touch: number; mouse: number}; constrainPosition: ( userPointerPosition: Point, dragRef: DragRef, dimensions: DOMRect, pickupPositionInElement: Point, ) => Point; freeDragPosition?: {x: number; y: number}; dragDisabled = signal(false); dragLockAxis = signal<DragAxis | undefined>(undefined); scale = 1; } @Component({ changeDetection: ChangeDetectionStrategy.OnPush, template: ` <div cdkDrag #dragElement style="width: 100px; height: 100px; background: red;"></div> `, standalone: true, imports: [CdkDrag], }) class StandaloneDraggableWithOnPush { @ViewChild('dragElement') dragElement: ElementRef<HTMLElement>; @ViewChild(CdkDrag) dragInstance: CdkDrag; } @Component({ template: ` <div #dragElement cdkDrag [cdkDragDisabled]="draggingDisabled" style="width: 100px; height: 100px; background: red; position: relative"> <div #handleElement cdkDragHandle style="width: 10px; height: 10px; background: green;"></div> </div> `, standalone: true, imports: [CdkDrag, CdkDragHandle], }) class StandaloneDraggableWithHandle { @ViewChild('dragElement') dragElement: ElementRef<HTMLElement>; @ViewChild('handleElement') handleElement: ElementRef<HTMLElement>; @ViewChild(CdkDrag) dragInstance: CdkDrag; @ViewChild(CdkDragHandle) handleInstance: CdkDragHandle; draggingDisabled = false; } @Component({ template: ` <div #dragElement cdkDrag style="width: 100px; height: 100px; background: red; position: relative"> <div #handleElement cdkDragHandle [cdkDragHandleDisabled]="disableHandle" style="width: 10px; height: 10px; background: green;"></div> </div> `, standalone: true, imports: [CdkDrag, CdkDragHandle], }) class StandaloneDraggableWithPreDisabledHandle { @ViewChild('dragElement') dragElement: ElementRef<HTMLElement>; @ViewChild('handleElement') handleElement: ElementRef<HTMLElement>; @ViewChild(CdkDrag) dragInstance: CdkDrag; disableHandle = true; } @Component({ template: ` <div #dragElement cdkDrag style="width: 100px; height: 100px; background: red; position: relative"> @if (showHandle) { <div #handleElement cdkDragHandle style="width: 10px; height: 10px; background: green;"></div> } </div> `, standalone: true, imports: [CdkDrag, CdkDragHandle], }) class StandaloneDraggableWithDelayedHandle { @ViewChild('dragElement') dragElement: ElementRef<HTMLElement>; @ViewChild('handleElement') handleElement: ElementRef<HTMLElement>; showHandle = false; } /** * Component that passes through whatever content is projected into it. * Used to test having drag elements being projected into a component. */ @Component({ selector: 'passthrough-component', template: '<ng-content></ng-content>', standalone: true, }) class PassthroughComponent {} @Component({ template: ` <div #dragElement cdkDrag style="width: 100px; height: 100px; background: red; position: relative"> <passthrough-component> <div #handleElement cdkDragHandle style="width: 10px; height: 10px; background: green;"></div> </passthrough-component> </div> `, standalone: true, imports: [CdkDrag, CdkDragHandle, PassthroughComponent], }) class StandaloneDraggableWithIndirectHandle { @ViewChild('dragElement') dragElement: ElementRef<HTMLElement>; @ViewChild('handleElement') handleElement: ElementRef<HTMLElement>; } @Component({ selector: 'shadow-wrapper', template: '<ng-content></ng-content>', encapsulation: ViewEncapsulation.ShadowDom, standalone: true, }) class ShadowWrapper {} @Component({ template: ` <div #dragElement cdkDrag style="width: 100px; height: 100px; background: red;"> <div cdkDragHandle style="width: 10px; height: 10px;"> <shadow-wrapper> <div #handleChild style="width: 10px; height: 10px; background: green;"></div> </shadow-wrapper> </div> </div> `, standalone: true, imports: [CdkDrag, CdkDragHandle, ShadowWrapper], }) class StandaloneDraggableWithShadowInsideHandle { @ViewChild('dragElement') dragElement: ElementRef<HTMLElement>; @ViewChild('handleChild') handleChild: ElementRef<HTMLElement>; } @Component({ encapsulation: ViewEncapsulation.None, styles: ` .cdk-drag-handle { position: absolute; top: 0; background: green; width: 10px; height: 10px; } `, template: ` <div #dragElement cdkDrag style="width: 100px; height: 100px; background: red; position: relative"> <div cdkDragHandle style="left: 0;"></div> <div cdkDragHandle style="right: 0;"></div> </div> `, standalone: true, imports: [CdkDrag, CdkDragHandle], }) class StandaloneDraggableWithMultipleHandles { @ViewChild('dragElement') dragElement: ElementRef<HTMLElement>; @ViewChildren(CdkDragHandle) handles: QueryList<CdkDragHandle>; } @Component({ template: ` <div #dragRoot class="alternate-root" style="width: 200px; height: 200px; background: hotpink"> <div cdkDrag [cdkDragRootElement]="rootElementSelector" #dragElement style="width: 100px; height: 100px; background: red;"></div> </div> `, standalone: true, imports: [CdkDrag], }) class DraggableWithAlternateRoot { @ViewChild('dragElement') dragElement: ElementRef<HTMLElement>; @ViewChild('dragRoot') dragRoot: ElementRef<HTMLElement>; @ViewChild(CdkDrag) dragInstance: CdkDrag; rootElementSelector: string; } @Component({ template: ` <ng-container cdkDrag></ng-container> `, standalone: true, imports: [CdkDrag], }) class DraggableOnNgContainer {} @Component({ template: ` <div cdkDrag> <ng-container cdkDragHandle></ng-container> </div> `, standalone: true, imports: [CdkDrag, CdkDragHandle], }) class DragHandleOnNgContainer {}
{ "commit_id": "ea0d1ba7b", "end_byte": 74403, "start_byte": 67409, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/standalone-drag.spec.ts" }
components/src/cdk/drag-drop/directives/standalone-drag.spec.ts_74405_75690
@Component({ template: ` <div #dragRoot class="alternate-root" style="width: 200px; height: 200px; background: hotpink"> <div cdkDrag cdkDragRootElement=".alternate-root" cdkDragHandle #dragElement style="width: 100px; height: 100px; background: red;"></div> </div> `, standalone: true, imports: [CdkDrag, CdkDragHandle], }) class DraggableWithAlternateRootAndSelfHandle { @ViewChild('dragElement') dragElement: ElementRef<HTMLElement>; @ViewChild('dragRoot') dragRoot: ElementRef<HTMLElement>; @ViewChild(CdkDrag) dragInstance: CdkDrag; } @Component({ template: ` <div #dragRoot class="alternate-root" style="width: 200px; height: 200px; background: hotpink"> <ng-container cdkDrag cdkDragRootElement=".alternate-root"> <div style="width: 100px; height: 100px; background: red;"></div> </ng-container> </div> `, standalone: true, imports: [CdkDrag], }) class DraggableNgContainerWithAlternateRoot { @ViewChild('dragRoot') dragRoot: ElementRef<HTMLElement>; @ViewChild(CdkDrag) dragInstance: CdkDrag; } @Component({ template: `<div cdkDrag></div>`, standalone: true, imports: [CdkDrag], }) class PlainStandaloneDraggable { @ViewChild(CdkDrag) dragInstance: CdkDrag; }
{ "commit_id": "ea0d1ba7b", "end_byte": 75690, "start_byte": 74405, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/standalone-drag.spec.ts" }
components/src/cdk/drag-drop/directives/single-axis-drop-list.spec.ts_0_8651
import {fakeAsync, flush} from '@angular/core/testing'; import {dispatchMouseEvent} from '@angular/cdk/testing/private'; import {_supportsShadowDom} from '@angular/cdk/platform'; import {createComponent, startDraggingViaMouse} from './test-utils.spec'; import { ConnectedDropZones, DraggableInDropZone, DraggableInScrollableVerticalDropZone, ITEM_HEIGHT, ITEM_WIDTH, defineCommonDropListTests, getHorizontalFixtures, } from './drop-list-shared.spec'; describe('Single-axis drop list', () => { const {DraggableInHorizontalDropZone} = getHorizontalFixtures('horizontal'); defineCommonDropListTests({ verticalListOrientation: 'vertical', horizontalListOrientation: 'horizontal', getSortedSiblings: (element, direction) => { return element.parentElement ? Array.from(element.parentElement.children).sort((a, b) => { return a.getBoundingClientRect()[direction] - b.getBoundingClientRect()[direction]; }) : []; }, }); it('should lay out the elements correctly, when swapping down with a taller element', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const items = fixture.componentInstance.dragItems.map(i => i.element.nativeElement); const {top, left} = items[0].getBoundingClientRect(); fixture.componentInstance.items[0].height = ITEM_HEIGHT * 2; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); startDraggingViaMouse(fixture, items[0], left, top); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; const target = items[1]; const targetRect = target.getBoundingClientRect(); // Add a few pixels to the top offset so we get some overlap. dispatchMouseEvent(document, 'mousemove', targetRect.left, targetRect.top + 5); fixture.detectChanges(); expect(placeholder.style.transform).toBe(`translate3d(0px, ${ITEM_HEIGHT}px, 0px)`); expect(target.style.transform).toBe(`translate3d(0px, ${-ITEM_HEIGHT * 2}px, 0px)`); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); })); it('should lay out the elements correctly, when swapping up with a taller element', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const items = fixture.componentInstance.dragItems.map(i => i.element.nativeElement); const {top, left} = items[1].getBoundingClientRect(); fixture.componentInstance.items[1].height = ITEM_HEIGHT * 2; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); startDraggingViaMouse(fixture, items[1], left, top); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; const target = items[0]; const targetRect = target.getBoundingClientRect(); // Add a few pixels to the top offset so we get some overlap. dispatchMouseEvent(document, 'mousemove', targetRect.left, targetRect.bottom - 5); fixture.detectChanges(); expect(placeholder.style.transform).toBe(`translate3d(0px, ${-ITEM_HEIGHT}px, 0px)`); expect(target.style.transform).toBe(`translate3d(0px, ${ITEM_HEIGHT * 2}px, 0px)`); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); })); it('should lay out elements correctly, when swapping an item with margin', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const items = fixture.componentInstance.dragItems.map(i => i.element.nativeElement); const {top, left} = items[0].getBoundingClientRect(); fixture.componentInstance.items[0].margin = 12; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); startDraggingViaMouse(fixture, items[0], left, top); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; const target = items[1]; const targetRect = target.getBoundingClientRect(); // Add a few pixels to the top offset so we get some overlap. dispatchMouseEvent(document, 'mousemove', targetRect.left, targetRect.top + 5); fixture.detectChanges(); expect(placeholder.style.transform).toBe(`translate3d(0px, ${ITEM_HEIGHT + 12}px, 0px)`); expect(target.style.transform).toBe(`translate3d(0px, ${-ITEM_HEIGHT - 12}px, 0px)`); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); })); it('should lay out the elements correctly, when swapping to the right with a wider element', fakeAsync(() => { const fixture = createComponent(DraggableInHorizontalDropZone); fixture.detectChanges(); const items = fixture.componentInstance.dragItems.map(i => i.element.nativeElement); fixture.componentInstance.items[0].width = ITEM_WIDTH * 2; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const {top, left} = items[0].getBoundingClientRect(); startDraggingViaMouse(fixture, items[0], left, top); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; const target = items[1]; const targetRect = target.getBoundingClientRect(); dispatchMouseEvent(document, 'mousemove', targetRect.right - 5, targetRect.top); fixture.detectChanges(); expect(placeholder.style.transform).toBe(`translate3d(${ITEM_WIDTH}px, 0px, 0px)`); expect(target.style.transform).toBe(`translate3d(${-ITEM_WIDTH * 2}px, 0px, 0px)`); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); })); it('should lay out the elements correctly, when swapping left with a wider element', fakeAsync(() => { const fixture = createComponent(DraggableInHorizontalDropZone); fixture.detectChanges(); const items = fixture.componentInstance.dragItems.map(i => i.element.nativeElement); const {top, left} = items[1].getBoundingClientRect(); fixture.componentInstance.items[1].width = ITEM_WIDTH * 2; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); startDraggingViaMouse(fixture, items[1], left, top); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; const target = items[0]; const targetRect = target.getBoundingClientRect(); dispatchMouseEvent(document, 'mousemove', targetRect.right - 5, targetRect.top); fixture.detectChanges(); expect(placeholder.style.transform).toBe(`translate3d(${-ITEM_WIDTH}px, 0px, 0px)`); expect(target.style.transform).toBe(`translate3d(${ITEM_WIDTH * 2}px, 0px, 0px)`); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); })); it('should clear the `transform` value from siblings when item is dropped', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; const firstItem = dragItems.first; const thirdItem = dragItems.toArray()[2].element.nativeElement; const thirdItemRect = thirdItem.getBoundingClientRect(); startDraggingViaMouse(fixture, firstItem.element.nativeElement); dispatchMouseEvent(document, 'mousemove', thirdItemRect.left + 1, thirdItemRect.top + 1); fixture.detectChanges(); expect(thirdItem.style.transform).toBeTruthy(); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(thirdItem.style.transform).toBeFalsy(); })); it('should lay out elements correctly, when horizontally swapping an item with margin', fakeAsync(() => { const fixture = createComponent(DraggableInHorizontalDropZone); fixture.detectChanges(); const items = fixture.componentInstance.dragItems.map(i => i.element.nativeElement); const {top, left} = items[0].getBoundingClientRect(); fixture.componentInstance.items[0].margin = 12; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); startDraggingViaMouse(fixture, items[0], left, top); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; const target = items[1]; const targetRect = target.getBoundingClientRect(); dispatchMouseEvent(document, 'mousemove', targetRect.right - 5, targetRect.top); fixture.detectChanges(); expect(placeholder.style.transform).toBe(`translate3d(${ITEM_WIDTH + 12}px, 0px, 0px)`); expect(target.style.transform).toBe(`translate3d(${-ITEM_WIDTH - 12}px, 0px, 0px)`); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 8651, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/single-axis-drop-list.spec.ts" }
components/src/cdk/drag-drop/directives/single-axis-drop-list.spec.ts_8655_13411
it('should preserve the original `transform` of items in the list', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableVerticalDropZone); fixture.detectChanges(); const items = fixture.componentInstance.dragItems.map(item => item.element.nativeElement); items.forEach(element => (element.style.transform = 'rotate(180deg)')); const thirdItemRect = items[2].getBoundingClientRect(); const hasInitialTransform = (element: HTMLElement) => element.style.transform.indexOf('rotate(180deg)') > -1; startDraggingViaMouse(fixture, items[0]); fixture.detectChanges(); const preview = document.querySelector('.cdk-drag-preview') as HTMLElement; const placeholder = fixture.nativeElement.querySelector('.cdk-drag-placeholder'); expect(items.every(hasInitialTransform)) .withContext('Expected items to preserve transform when dragging starts.') .toBe(true); expect(hasInitialTransform(preview)) .withContext('Expected preview to preserve transform when dragging starts.') .toBe(true); expect(hasInitialTransform(placeholder)) .withContext('Expected placeholder to preserve transform when dragging starts.') .toBe(true); dispatchMouseEvent(document, 'mousemove', thirdItemRect.left + 1, thirdItemRect.top + 1); fixture.detectChanges(); expect(items.every(hasInitialTransform)) .withContext('Expected items to preserve transform while dragging.') .toBe(true); expect(hasInitialTransform(preview)) .withContext('Expected preview to preserve transform while dragging.') .toBe(true); expect(hasInitialTransform(placeholder)) .withContext('Expected placeholder to preserve transform while dragging.') .toBe(true); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(items.every(hasInitialTransform)) .withContext('Expected items to preserve transform when dragging stops.') .toBe(true); expect(hasInitialTransform(preview)) .withContext('Expected preview to preserve transform when dragging stops.') .toBe(true); expect(hasInitialTransform(placeholder)) .withContext('Expected placeholder to preserve transform when dragging stops.') .toBe(true); })); it('should enter as last child if entering from top in reversed container', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); // Make sure there's only one item in the first list. fixture.componentInstance.todo = ['things']; fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const dropZones = fixture.componentInstance.dropInstances.map(d => d.element.nativeElement); const item = groups[0][0]; // Add some initial padding as the target drop zone const targetDropZoneStyle = dropZones[1].style; targetDropZoneStyle.paddingTop = '10px'; targetDropZoneStyle.display = 'flex'; targetDropZoneStyle.flexDirection = 'column-reverse'; const targetRect = dropZones[1].getBoundingClientRect(); startDraggingViaMouse(fixture, item.element.nativeElement); const placeholder = dropZones[0].querySelector('.cdk-drag-placeholder')!; expect(placeholder).toBeTruthy(); expect(dropZones[0].contains(placeholder)) .withContext('Expected placeholder to be inside the first container.') .toBe(true); dispatchMouseEvent(document, 'mousemove', targetRect.left, targetRect.top); fixture.detectChanges(); expect(dropZones[1].lastChild === placeholder) .withContext('Expected placeholder to be last child inside second container.') .toBe(true); dispatchMouseEvent(document, 'mouseup'); })); it('should lay out the elements correctly when scaled', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.componentInstance.scale = 0.5; fixture.detectChanges(); const items = fixture.componentInstance.dragItems.map(i => i.element.nativeElement); const {top, left} = items[0].getBoundingClientRect(); startDraggingViaMouse(fixture, items[0], left, top); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; const target = items[1]; const targetRect = target.getBoundingClientRect(); dispatchMouseEvent(document, 'mousemove', targetRect.left, targetRect.top + 5); fixture.detectChanges(); expect(placeholder.style.transform).toBe(`translate3d(0px, ${ITEM_HEIGHT * 2}px, 0px)`); expect(target.style.transform).toBe(`translate3d(0px, ${-ITEM_HEIGHT * 2}px, 0px)`); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); })); });
{ "commit_id": "ea0d1ba7b", "end_byte": 13411, "start_byte": 8655, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/single-axis-drop-list.spec.ts" }
components/src/cdk/drag-drop/directives/drag-preview.ts_0_1560
/** * @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 { Directive, InjectionToken, Input, OnDestroy, TemplateRef, booleanAttribute, inject, } from '@angular/core'; import {CDK_DRAG_PARENT} from '../drag-parent'; /** * Injection token that can be used to reference instances of `CdkDragPreview`. It serves as * alternative token to the actual `CdkDragPreview` class which could cause unnecessary * retention of the class and its directive metadata. */ export const CDK_DRAG_PREVIEW = new InjectionToken<CdkDragPreview>('CdkDragPreview'); /** * Element that will be used as a template for the preview * of a CdkDrag when it is being dragged. */ @Directive({ selector: 'ng-template[cdkDragPreview]', providers: [{provide: CDK_DRAG_PREVIEW, useExisting: CdkDragPreview}], }) export class CdkDragPreview<T = any> implements OnDestroy { templateRef = inject<TemplateRef<T>>(TemplateRef); private _drag = inject(CDK_DRAG_PARENT, {optional: true}); /** Context data to be added to the preview template instance. */ @Input() data: T; /** Whether the preview should preserve the same size as the item that is being dragged. */ @Input({transform: booleanAttribute}) matchSize: boolean = false; constructor(...args: unknown[]); constructor() { this._drag?._setPreviewTemplate(this); } ngOnDestroy(): void { this._drag?._resetPreviewTemplate(this); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 1560, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drag-preview.ts" }
components/src/cdk/drag-drop/directives/standalone-drag.zone.spec.ts_0_2206
import { Component, ElementRef, NgZone, Type, ViewChild, provideZoneChangeDetection, } from '@angular/core'; import {Point} from '../drag-ref'; import {CdkDrag} from './drag'; import {createComponent as _createComponent, dragElementViaMouse} from './test-utils.spec'; import {ComponentFixture} from '@angular/core/testing'; describe('Standalone CdkDrag Zone.js integration', () => { function createComponent<T>(type: Type<T>): ComponentFixture<T> { return _createComponent(type, { providers: [provideZoneChangeDetection()], }); } it('should emit to `moved` inside the NgZone', () => { const fixture = createComponent(StandaloneDraggable); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const spy = jasmine.createSpy('move spy'); const subscription = fixture.componentInstance.dragInstance.moved.subscribe(() => spy(NgZone.isInAngularZone()), ); dragElementViaMouse(fixture, fixture.componentInstance.dragElement.nativeElement, 10, 20); expect(spy).toHaveBeenCalledWith(true); subscription.unsubscribe(); }); }); @Component({ template: ` <div class="wrapper" style="width: 200px; height: 200px; background: green;"> <div cdkDrag [cdkDragBoundary]="boundary" [cdkDragStartDelay]="dragStartDelay" [cdkDragConstrainPosition]="constrainPosition" [cdkDragFreeDragPosition]="freeDragPosition" (cdkDragStarted)="startedSpy($event)" (cdkDragReleased)="releasedSpy($event)" (cdkDragEnded)="endedSpy($event)" #dragElement style="width: 100px; height: 100px; background: red;"></div> </div> `, standalone: true, imports: [CdkDrag], }) class StandaloneDraggable { @ViewChild('dragElement') dragElement: ElementRef<HTMLElement>; @ViewChild(CdkDrag) dragInstance: CdkDrag; startedSpy = jasmine.createSpy('started spy'); endedSpy = jasmine.createSpy('ended spy'); releasedSpy = jasmine.createSpy('released spy'); boundary: string | HTMLElement; dragStartDelay: number | string | {touch: number; mouse: number}; constrainPosition: (point: Point) => Point; freeDragPosition?: {x: number; y: number}; }
{ "commit_id": "ea0d1ba7b", "end_byte": 2206, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/standalone-drag.zone.spec.ts" }
components/src/cdk/drag-drop/directives/drag.ts_0_1845
/** * @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 {Directionality} from '@angular/cdk/bidi'; import { Directive, ElementRef, EventEmitter, Input, NgZone, OnDestroy, Output, ViewContainerRef, OnChanges, SimpleChanges, ChangeDetectorRef, InjectionToken, booleanAttribute, afterNextRender, AfterViewInit, inject, Injector, numberAttribute, } from '@angular/core'; import {coerceElement, coerceNumberProperty} from '@angular/cdk/coercion'; import {BehaviorSubject, Observable, Observer, Subject, merge} from 'rxjs'; import {startWith, take, map, takeUntil, switchMap, tap} from 'rxjs/operators'; import type { CdkDragDrop, CdkDragEnd, CdkDragEnter, CdkDragExit, CdkDragMove, CdkDragStart, CdkDragRelease, } from '../drag-events'; import {CDK_DRAG_HANDLE, CdkDragHandle} from './drag-handle'; import {CdkDragPlaceholder} from './drag-placeholder'; import {CdkDragPreview} from './drag-preview'; import {CDK_DRAG_PARENT} from '../drag-parent'; import {DragRef, Point, PreviewContainer} from '../drag-ref'; import type {CdkDropList} from './drop-list'; import {DragDrop} from '../drag-drop'; import {CDK_DRAG_CONFIG, DragDropConfig, DragStartDelay, DragAxis} from './config'; import {assertElementNode} from './assertions'; const DRAG_HOST_CLASS = 'cdk-drag'; /** * Injection token that can be used to reference instances of `CdkDropList`. It serves as * alternative token to the actual `CdkDropList` class which could cause unnecessary * retention of the class and its directive metadata. */ export const CDK_DROP_LIST = new InjectionToken<CdkDropList>('CdkDropList'); /** Element that can be moved inside a CdkDropList container. */
{ "commit_id": "ea0d1ba7b", "end_byte": 1845, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drag.ts" }
components/src/cdk/drag-drop/directives/drag.ts_1846_8728
@Directive({ selector: '[cdkDrag]', exportAs: 'cdkDrag', host: { 'class': DRAG_HOST_CLASS, '[class.cdk-drag-disabled]': 'disabled', '[class.cdk-drag-dragging]': '_dragRef.isDragging()', }, providers: [{provide: CDK_DRAG_PARENT, useExisting: CdkDrag}], }) export class CdkDrag<T = any> implements AfterViewInit, OnChanges, OnDestroy { element = inject<ElementRef<HTMLElement>>(ElementRef); dropContainer = inject<CdkDropList>(CDK_DROP_LIST, {optional: true, skipSelf: true})!; private _ngZone = inject(NgZone); private _viewContainerRef = inject(ViewContainerRef); private _dir = inject(Directionality, {optional: true}); private _changeDetectorRef = inject(ChangeDetectorRef); private _selfHandle = inject<CdkDragHandle>(CDK_DRAG_HANDLE, {optional: true, self: true}); private _parentDrag = inject<CdkDrag>(CDK_DRAG_PARENT, {optional: true, skipSelf: true}); private readonly _destroyed = new Subject<void>(); private static _dragInstances: CdkDrag[] = []; private _handles = new BehaviorSubject<CdkDragHandle[]>([]); private _previewTemplate: CdkDragPreview | null; private _placeholderTemplate: CdkDragPlaceholder | null; /** Reference to the underlying drag instance. */ _dragRef: DragRef<CdkDrag<T>>; /** Arbitrary data to attach to this drag instance. */ @Input('cdkDragData') data: T; /** Locks the position of the dragged element along the specified axis. */ @Input('cdkDragLockAxis') lockAxis: DragAxis; /** * Selector that will be used to determine the root draggable element, starting from * the `cdkDrag` element and going up the DOM. Passing an alternate root element is useful * when trying to enable dragging on an element that you might not have access to. */ @Input('cdkDragRootElement') rootElementSelector: string; /** * Node or selector that will be used to determine the element to which the draggable's * position will be constrained. If a string is passed in, it'll be used as a selector that * will be matched starting from the element's parent and going up the DOM until a match * has been found. */ @Input('cdkDragBoundary') boundaryElement: string | ElementRef<HTMLElement> | HTMLElement; /** * Amount of milliseconds to wait after the user has put their * pointer down before starting to drag the element. */ @Input('cdkDragStartDelay') dragStartDelay: DragStartDelay; /** * Sets the position of a `CdkDrag` that is outside of a drop container. * Can be used to restore the element's position for a returning user. */ @Input('cdkDragFreeDragPosition') freeDragPosition: Point; /** Whether starting to drag this element is disabled. */ @Input({alias: 'cdkDragDisabled', transform: booleanAttribute}) get disabled(): boolean { return this._disabled || !!(this.dropContainer && this.dropContainer.disabled); } set disabled(value: boolean) { this._disabled = value; this._dragRef.disabled = this._disabled; } private _disabled: boolean; /** * 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. */ @Input('cdkDragConstrainPosition') constrainPosition?: ( userPointerPosition: Point, dragRef: DragRef, dimensions: DOMRect, pickupPositionInElement: Point, ) => Point; /** Class to be added to the preview element. */ @Input('cdkDragPreviewClass') previewClass: string | string[]; /** * Configures the place into which the preview of the item will be inserted. Can be configured * globally through `CDK_DROP_LIST`. Possible values: * - `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`. */ @Input('cdkDragPreviewContainer') previewContainer: PreviewContainer; /** * 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. */ @Input({alias: 'cdkDragScale', transform: numberAttribute}) scale: number = 1; /** Emits when the user starts dragging the item. */ @Output('cdkDragStarted') readonly started: EventEmitter<CdkDragStart> = new EventEmitter<CdkDragStart>(); /** Emits when the user has released a drag item, before any animations have started. */ @Output('cdkDragReleased') readonly released: EventEmitter<CdkDragRelease> = new EventEmitter<CdkDragRelease>(); /** Emits when the user stops dragging an item in the container. */ @Output('cdkDragEnded') readonly ended: EventEmitter<CdkDragEnd> = new EventEmitter<CdkDragEnd>(); /** Emits when the user has moved the item into a new container. */ @Output('cdkDragEntered') readonly entered: EventEmitter<CdkDragEnter<any>> = new EventEmitter< CdkDragEnter<any> >(); /** Emits when the user removes the item its container by dragging it into another container. */ @Output('cdkDragExited') readonly exited: EventEmitter<CdkDragExit<any>> = new EventEmitter< CdkDragExit<any> >(); /** Emits when the user drops the item inside a container. */ @Output('cdkDragDropped') readonly dropped: EventEmitter<CdkDragDrop<any>> = new EventEmitter< CdkDragDrop<any> >(); /** * Emits as the user is dragging the item. Use with caution, * because this event will fire for every pixel that the user has dragged. */ @Output('cdkDragMoved') readonly moved: Observable<CdkDragMove<T>> = new Observable( (observer: Observer<CdkDragMove<T>>) => { const subscription = this._dragRef.moved .pipe( map(movedEvent => ({ source: this, pointerPosition: movedEvent.pointerPosition, event: movedEvent.event, delta: movedEvent.delta, distance: movedEvent.distance, })), ) .subscribe(observer); return () => { subscription.unsubscribe(); }; }, ); private _injector = inject(Injector); constructor(...args: unknown[]);
{ "commit_id": "ea0d1ba7b", "end_byte": 8728, "start_byte": 1846, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drag.ts" }
components/src/cdk/drag-drop/directives/drag.ts_8732_15608
constructor() { const dropContainer = this.dropContainer; const config = inject<DragDropConfig>(CDK_DRAG_CONFIG, {optional: true}); const dragDrop = inject(DragDrop); this._dragRef = dragDrop.createDrag(this.element, { dragStartThreshold: config && config.dragStartThreshold != null ? config.dragStartThreshold : 5, pointerDirectionChangeThreshold: config && config.pointerDirectionChangeThreshold != null ? config.pointerDirectionChangeThreshold : 5, zIndex: config?.zIndex, }); this._dragRef.data = this; // We have to keep track of the drag instances in order to be able to match an element to // a drag instance. We can't go through the global registry of `DragRef`, because the root // element could be different. CdkDrag._dragInstances.push(this); if (config) { this._assignDefaults(config); } // Note that usually the container is assigned when the drop list is picks up the item, but in // some cases (mainly transplanted views with OnPush, see #18341) we may end up in a situation // where there are no items on the first change detection pass, but the items get picked up as // soon as the user triggers another pass by dragging. This is a problem, because the item would // have to switch from standalone mode to drag mode in the middle of the dragging sequence which // is too late since the two modes save different kinds of information. We work around it by // assigning the drop container both from here and the list. if (dropContainer) { this._dragRef._withDropContainer(dropContainer._dropListRef); dropContainer.addItem(this); // The drop container reads this so we need to sync it here. dropContainer._dropListRef.beforeStarted.pipe(takeUntil(this._destroyed)).subscribe(() => { this._dragRef.scale = this.scale; }); } this._syncInputs(this._dragRef); this._handleEvents(this._dragRef); } /** * Returns the element that is being used as a placeholder * while the current element is being dragged. */ getPlaceholderElement(): HTMLElement { return this._dragRef.getPlaceholderElement(); } /** Returns the root draggable element. */ getRootElement(): HTMLElement { return this._dragRef.getRootElement(); } /** Resets a standalone drag item to its initial position. */ reset(): void { this._dragRef.reset(); } /** * Gets the pixel coordinates of the draggable outside of a drop container. */ getFreeDragPosition(): Readonly<Point> { return this._dragRef.getFreeDragPosition(); } /** * Sets the current position in pixels the draggable outside of a drop container. * @param value New position to be set. */ setFreeDragPosition(value: Point): void { this._dragRef.setFreeDragPosition(value); } ngAfterViewInit() { // We need to wait until after render, in order for the reference // element to be in the proper place in the DOM. This is mostly relevant // for draggable elements inside portals since they get stamped out in // their original DOM position, and then they get transferred to the portal. afterNextRender( () => { this._updateRootElement(); this._setupHandlesListener(); this._dragRef.scale = this.scale; if (this.freeDragPosition) { this._dragRef.setFreeDragPosition(this.freeDragPosition); } }, {injector: this._injector}, ); } ngOnChanges(changes: SimpleChanges) { const rootSelectorChange = changes['rootElementSelector']; const positionChange = changes['freeDragPosition']; // We don't have to react to the first change since it's being // handled in the `afterNextRender` queued up in the constructor. if (rootSelectorChange && !rootSelectorChange.firstChange) { this._updateRootElement(); } // Scale affects the free drag position so we need to sync it up here. this._dragRef.scale = this.scale; // Skip the first change since it's being handled in the `afterNextRender` queued up in the // constructor. if (positionChange && !positionChange.firstChange && this.freeDragPosition) { this._dragRef.setFreeDragPosition(this.freeDragPosition); } } ngOnDestroy() { if (this.dropContainer) { this.dropContainer.removeItem(this); } const index = CdkDrag._dragInstances.indexOf(this); if (index > -1) { CdkDrag._dragInstances.splice(index, 1); } // Unnecessary in most cases, but used to avoid extra change detections with `zone-paths-rxjs`. this._ngZone.runOutsideAngular(() => { this._handles.complete(); this._destroyed.next(); this._destroyed.complete(); this._dragRef.dispose(); }); } _addHandle(handle: CdkDragHandle) { const handles = this._handles.getValue(); handles.push(handle); this._handles.next(handles); } _removeHandle(handle: CdkDragHandle) { const handles = this._handles.getValue(); const index = handles.indexOf(handle); if (index > -1) { handles.splice(index, 1); this._handles.next(handles); } } _setPreviewTemplate(preview: CdkDragPreview) { this._previewTemplate = preview; } _resetPreviewTemplate(preview: CdkDragPreview) { if (preview === this._previewTemplate) { this._previewTemplate = null; } } _setPlaceholderTemplate(placeholder: CdkDragPlaceholder) { this._placeholderTemplate = placeholder; } _resetPlaceholderTemplate(placeholder: CdkDragPlaceholder) { if (placeholder === this._placeholderTemplate) { this._placeholderTemplate = null; } } /** Syncs the root element with the `DragRef`. */ private _updateRootElement() { const element = this.element.nativeElement as HTMLElement; let rootElement = element; if (this.rootElementSelector) { rootElement = element.closest !== undefined ? (element.closest(this.rootElementSelector) as HTMLElement) : // Comment tag doesn't have closest method, so use parent's one. (element.parentElement?.closest(this.rootElementSelector) as HTMLElement); } if (rootElement && (typeof ngDevMode === 'undefined' || ngDevMode)) { assertElementNode(rootElement, 'cdkDrag'); } this._dragRef.withRootElement(rootElement || element); } /** Gets the boundary element, based on the `boundaryElement` value. */ private _getBoundaryElement() { const boundary = this.boundaryElement; if (!boundary) { return null; } if (typeof boundary === 'string') { return this.element.nativeElement.closest<HTMLElement>(boundary); } return coerceElement(boundary); } /** Syncs the inputs of the CdkDrag with the options of the underlying DragRef. */
{ "commit_id": "ea0d1ba7b", "end_byte": 15608, "start_byte": 8732, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drag.ts" }
components/src/cdk/drag-drop/directives/drag.ts_15611_22013
private _syncInputs(ref: DragRef<CdkDrag<T>>) { ref.beforeStarted.subscribe(() => { if (!ref.isDragging()) { const dir = this._dir; const dragStartDelay = this.dragStartDelay; const placeholder = this._placeholderTemplate ? { template: this._placeholderTemplate.templateRef, context: this._placeholderTemplate.data, viewContainer: this._viewContainerRef, } : null; const preview = this._previewTemplate ? { template: this._previewTemplate.templateRef, context: this._previewTemplate.data, matchSize: this._previewTemplate.matchSize, viewContainer: this._viewContainerRef, } : null; ref.disabled = this.disabled; ref.lockAxis = this.lockAxis; ref.scale = this.scale; ref.dragStartDelay = typeof dragStartDelay === 'object' && dragStartDelay ? dragStartDelay : coerceNumberProperty(dragStartDelay); ref.constrainPosition = this.constrainPosition; ref.previewClass = this.previewClass; ref .withBoundaryElement(this._getBoundaryElement()) .withPlaceholderTemplate(placeholder) .withPreviewTemplate(preview) .withPreviewContainer(this.previewContainer || 'global'); if (dir) { ref.withDirection(dir.value); } } }); // This only needs to be resolved once. ref.beforeStarted.pipe(take(1)).subscribe(() => { // If we managed to resolve a parent through DI, use it. if (this._parentDrag) { ref.withParent(this._parentDrag._dragRef); return; } // Otherwise fall back to resolving the parent by looking up the DOM. This can happen if // the item was projected into another item by something like `ngTemplateOutlet`. let parent = this.element.nativeElement.parentElement; while (parent) { if (parent.classList.contains(DRAG_HOST_CLASS)) { ref.withParent( CdkDrag._dragInstances.find(drag => { return drag.element.nativeElement === parent; })?._dragRef || null, ); break; } parent = parent.parentElement; } }); } /** Handles the events from the underlying `DragRef`. */ private _handleEvents(ref: DragRef<CdkDrag<T>>) { ref.started.subscribe(startEvent => { this.started.emit({source: this, event: startEvent.event}); // Since all of these events run outside of change detection, // we need to ensure that everything is marked correctly. this._changeDetectorRef.markForCheck(); }); ref.released.subscribe(releaseEvent => { this.released.emit({source: this, event: releaseEvent.event}); }); ref.ended.subscribe(endEvent => { this.ended.emit({ source: this, distance: endEvent.distance, dropPoint: endEvent.dropPoint, event: endEvent.event, }); // Since all of these events run outside of change detection, // we need to ensure that everything is marked correctly. this._changeDetectorRef.markForCheck(); }); ref.entered.subscribe(enterEvent => { this.entered.emit({ container: enterEvent.container.data, item: this, currentIndex: enterEvent.currentIndex, }); }); ref.exited.subscribe(exitEvent => { this.exited.emit({ container: exitEvent.container.data, item: this, }); }); ref.dropped.subscribe(dropEvent => { this.dropped.emit({ previousIndex: dropEvent.previousIndex, currentIndex: dropEvent.currentIndex, previousContainer: dropEvent.previousContainer.data, container: dropEvent.container.data, isPointerOverContainer: dropEvent.isPointerOverContainer, item: this, distance: dropEvent.distance, dropPoint: dropEvent.dropPoint, event: dropEvent.event, }); }); } /** Assigns the default input values based on a provided config object. */ private _assignDefaults(config: DragDropConfig) { const { lockAxis, dragStartDelay, constrainPosition, previewClass, boundaryElement, draggingDisabled, rootElementSelector, previewContainer, } = config; this.disabled = draggingDisabled == null ? false : draggingDisabled; this.dragStartDelay = dragStartDelay || 0; if (lockAxis) { this.lockAxis = lockAxis; } if (constrainPosition) { this.constrainPosition = constrainPosition; } if (previewClass) { this.previewClass = previewClass; } if (boundaryElement) { this.boundaryElement = boundaryElement; } if (rootElementSelector) { this.rootElementSelector = rootElementSelector; } if (previewContainer) { this.previewContainer = previewContainer; } } /** Sets up the listener that syncs the handles with the drag ref. */ private _setupHandlesListener() { // Listen for any newly-added handles. this._handles .pipe( // Sync the new handles with the DragRef. tap(handles => { const handleElements = handles.map(handle => handle.element); // Usually handles are only allowed to be a descendant of the drag element, but if // the consumer defined a different drag root, we should allow the drag element // itself to be a handle too. if (this._selfHandle && this.rootElementSelector) { handleElements.push(this.element); } this._dragRef.withHandles(handleElements); }), // Listen if the state of any of the handles changes. switchMap((handles: CdkDragHandle[]) => { return merge( ...handles.map(item => item._stateChanges.pipe(startWith(item))), ) as Observable<CdkDragHandle>; }), takeUntil(this._destroyed), ) .subscribe(handleInstance => { // Enabled/disable the handle that changed in the DragRef. const dragRef = this._dragRef; const handle = handleInstance.element.nativeElement; handleInstance.disabled ? dragRef.disableHandle(handle) : dragRef.enableHandle(handle); }); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 22013, "start_byte": 15611, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drag.ts" }
components/src/cdk/drag-drop/directives/assertions.ts_0_599
/** * @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 */ /** * Asserts that a particular node is an element. * @param node Node to be checked. * @param name Name to attach to the error message. */ export function assertElementNode(node: Node, name: string): asserts node is HTMLElement { if (node.nodeType !== 1) { throw Error( `${name} must be attached to an element node. ` + `Currently attached to "${node.nodeName}".`, ); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 599, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/assertions.ts" }
components/src/cdk/drag-drop/directives/drag-placeholder.ts_0_1482
/** * @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 {Directive, TemplateRef, Input, InjectionToken, inject, OnDestroy} from '@angular/core'; import {CDK_DRAG_PARENT} from '../drag-parent'; /** * Injection token that can be used to reference instances of `CdkDragPlaceholder`. It serves as * alternative token to the actual `CdkDragPlaceholder` class which could cause unnecessary * retention of the class and its directive metadata. */ export const CDK_DRAG_PLACEHOLDER = new InjectionToken<CdkDragPlaceholder>('CdkDragPlaceholder'); /** * Element that will be used as a template for the placeholder of a CdkDrag when * it is being dragged. The placeholder is displayed in place of the element being dragged. */ @Directive({ selector: 'ng-template[cdkDragPlaceholder]', providers: [{provide: CDK_DRAG_PLACEHOLDER, useExisting: CdkDragPlaceholder}], }) export class CdkDragPlaceholder<T = any> implements OnDestroy { templateRef = inject<TemplateRef<T>>(TemplateRef); private _drag = inject(CDK_DRAG_PARENT, {optional: true}); /** Context data to be added to the placeholder template instance. */ @Input() data: T; constructor(...args: unknown[]); constructor() { this._drag?._setPlaceholderTemplate(this); } ngOnDestroy(): void { this._drag?._resetPlaceholderTemplate(this); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 1482, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drag-placeholder.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_0_2316
import {Directionality} from '@angular/cdk/bidi'; import {Platform, _supportsShadowDom} from '@angular/cdk/platform'; import {CdkScrollable, ViewportRuler} from '@angular/cdk/scrolling'; import { createMouseEvent, createTouchEvent, dispatchEvent, dispatchFakeEvent, dispatchMouseEvent, dispatchTouchEvent, } from '@angular/cdk/testing/private'; import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, Input, QueryList, Type, ViewChild, ViewChildren, ViewEncapsulation, inject, signal, } from '@angular/core'; import {ComponentFixture, TestBed, fakeAsync, flush, tick} from '@angular/core/testing'; import {of as observableOf} from 'rxjs'; import {extendStyles} from '../dom/styling'; import {CdkDragDrop, CdkDragEnter, CdkDragStart} from '../drag-events'; import {DragRef, Point, PreviewContainer} from '../drag-ref'; import {moveItemInArray} from '../drag-utils'; import {CDK_DRAG_CONFIG, DragAxis, DragDropConfig, DropListOrientation} from './config'; import {CdkDrag} from './drag'; import {CdkDropList} from './drop-list'; import {CdkDropListGroup} from './drop-list-group'; import { createComponent as _createComponent, DragDropTestConfig, continueDraggingViaTouch, dragElementViaMouse, makeScrollable, startDraggingViaMouse, startDraggingViaTouch, stopDraggingViaTouch, tickAnimationFrames, } from './test-utils.spec'; import {NgClass, NgFor, NgIf, NgTemplateOutlet} from '@angular/common'; import {CdkDragPreview} from './drag-preview'; import {CdkDragPlaceholder} from './drag-placeholder'; export const ITEM_HEIGHT = 25; export const ITEM_WIDTH = 75; /** Function that can be used to get the sorted siblings of an element. */ type SortedSiblingsFunction = (element: Element, direction: 'top' | 'left') => Element[]; export function defineCommonDropListTests(config: { /** Orientation value that will be passed to tests checking vertical orientation. */ verticalListOrientation: Exclude<DropListOrientation, 'horizontal'>; /** Orientation value that will be passed to tests checking horizontal orientation. */ horizontalListOrientation: Exclude<DropListOrientation, 'vertical'>; /** Gets the siblings of an element, sorted by their visible position. */ getSortedSiblings: SortedSiblingsFunction; })
{ "commit_id": "ea0d1ba7b", "end_byte": 2316, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_2317_12030
{ const { DraggableInHorizontalDropZone, DraggableInScrollableHorizontalDropZone, DraggableInHorizontalFlexDropZoneWithMatchSizePreview, } = getHorizontalFixtures(config.horizontalListOrientation); function createComponent<T>( type: Type<T>, testConfig: DragDropTestConfig = {}, ): ComponentFixture<T> { return _createComponent(type, {...testConfig, listOrientation: config.verticalListOrientation}); } describe('in a drop container', () => { it('should be able to attach data to the drop container', () => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); expect(fixture.componentInstance.dropInstance.data).toBe(fixture.componentInstance.items); }); it('should register an item with the drop container', () => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const list = fixture.componentInstance.dropInstance; spyOn(list, 'addItem').and.callThrough(); fixture.componentInstance.items.push({value: 'Extra', margin: 0, height: ITEM_HEIGHT}); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(list.addItem).toHaveBeenCalledTimes(1); }); it('should remove an item from the drop container', () => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const list = fixture.componentInstance.dropInstance; spyOn(list, 'removeItem').and.callThrough(); fixture.componentInstance.items.pop(); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(list.removeItem).toHaveBeenCalledTimes(1); }); it('should return the items sorted by their position in the DOM', () => { const fixture = createComponent(DraggableInDropZone); const items = fixture.componentInstance.items; fixture.detectChanges(); // Insert a couple of items in the start and the middle so the list gets shifted around. items.unshift({value: 'Extra 0', margin: 0, height: ITEM_HEIGHT}); items.splice(3, 0, {value: 'Extra 1', margin: 0, height: ITEM_HEIGHT}); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect( fixture.componentInstance.dropInstance.getSortedItems().map(item => { return item.element.nativeElement.textContent!.trim(); }), ).toEqual(['Extra 0', 'Zero', 'One', 'Extra 1', 'Two', 'Three']); }); it('should sync the drop list inputs with the drop list ref', () => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const dropInstance = fixture.componentInstance.dropInstance; const dropListRef = dropInstance._dropListRef; expect(dropListRef.lockAxis).toBeFalsy(); expect(dropListRef.disabled).toBe(false); fixture.componentInstance.dropLockAxis.set('x'); fixture.componentInstance.dropDisabled.set(true); fixture.detectChanges(); dropListRef.beforeStarted.next(); expect(dropListRef.lockAxis).toBe('x'); expect(dropListRef.disabled).toBe(true); }); it('should be able to attach data to a drag item', () => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); expect(fixture.componentInstance.dragItems.first.data).toBe( fixture.componentInstance.items[0], ); }); it('should be able to overwrite the drop zone id', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.componentInstance.dropZoneId = 'custom-id'; fixture.detectChanges(); const drop = fixture.componentInstance.dropInstance; expect(drop.id).toBe('custom-id'); expect(drop.element.nativeElement.getAttribute('id')).toBe('custom-id'); })); it('should toggle a class when the user starts dragging an item', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const dropZone = fixture.componentInstance.dropInstance; expect(dropZone.element.nativeElement.classList).not.toContain('cdk-drop-list-dragging'); startDraggingViaMouse(fixture, item); expect(dropZone.element.nativeElement.classList).toContain('cdk-drop-list-dragging'); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(dropZone.element.nativeElement.classList).not.toContain('cdk-drop-dragging'); })); it('should toggle the drop dragging classes if there is nothing to trigger change detection', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithoutEvents); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const dropZone = fixture.componentInstance.dropInstance; expect(dropZone.element.nativeElement.classList).not.toContain('cdk-drop-list-dragging'); expect(item.classList).not.toContain('cdk-drag-dragging'); startDraggingViaMouse(fixture, item); expect(dropZone.element.nativeElement.classList).toContain('cdk-drop-list-dragging'); expect(item.classList).toContain('cdk-drag-dragging'); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(dropZone.element.nativeElement.classList).not.toContain('cdk-drop-dragging'); expect(item.classList).not.toContain('cdk-drag-dragging'); })); it('should toggle a class when the user starts dragging an item with OnPush change detection', fakeAsync(() => { const fixture = createComponent(DraggableInOnPushDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const dropZone = fixture.componentInstance.dropInstance; expect(dropZone.element.nativeElement.classList).not.toContain('cdk-drop-list-dragging'); startDraggingViaMouse(fixture, item); expect(dropZone.element.nativeElement.classList).toContain('cdk-drop-list-dragging'); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(dropZone.element.nativeElement.classList).not.toContain('cdk-drop-dragging'); })); it('should not toggle dragging class if the element was not dragged more than the threshold', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone, {dragDistance: 5}); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const dropZone = fixture.componentInstance.dropInstance; expect(dropZone.element.nativeElement.classList).not.toContain('cdk-drop-dragging'); startDraggingViaMouse(fixture, item); expect(dropZone.element.nativeElement.classList).not.toContain('cdk-drop-dragging'); })); it('should dispatch the `dropped` event when an item has been dropped', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); const firstItem = dragItems.first; const thirdItemRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect(); dragElementViaMouse( fixture, firstItem.element.nativeElement, thirdItemRect.left + 1, thirdItemRect.top + 1, ); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; // Assert the event like this, rather than `toHaveBeenCalledWith`, because Jasmine will // go into an infinite loop trying to stringify the event, if the test fails. expect(event).toEqual({ previousIndex: 0, currentIndex: 2, item: firstItem, container: fixture.componentInstance.dropInstance, previousContainer: fixture.componentInstance.dropInstance, isPointerOverContainer: true, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'One', 'Two', 'Zero', 'Three', ]); })); it('should expose whether an item was dropped over a container', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; const firstItem = dragItems.first; const thirdItemRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect(); dragElementViaMouse( fixture, firstItem.element.nativeElement, thirdItemRect.left + 1, thirdItemRect.top + 1, ); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event: CdkDragDrop<any> = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event.isPointerOverContainer).toBe(true); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 12030, "start_byte": 2317, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_12036_20224
it('should expose the drag distance when an item is dropped', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; const firstItem = dragItems.first; dragElementViaMouse(fixture, firstItem.element.nativeElement, 50, 60); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event: CdkDragDrop<any> = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event.distance).toEqual({x: 50, y: 60}); expect(event.dropPoint).toEqual({x: 50, y: 60}); })); it('should expose whether an item was dropped outside of a container', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; const firstItem = dragItems.first; const containerRect = fixture.componentInstance.dropInstance.element.nativeElement.getBoundingClientRect(); dragElementViaMouse( fixture, firstItem.element.nativeElement, containerRect.right + 10, containerRect.bottom + 10, ); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event: CdkDragDrop<any> = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event.isPointerOverContainer).toBe(false); })); it('should dispatch the `sorted` event as an item is being sorted', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const items = fixture.componentInstance.dragItems.map(item => item.element.nativeElement); const draggedItem = items[0]; const {top, left} = draggedItem.getBoundingClientRect(); startDraggingViaMouse(fixture, draggedItem, left, top); // Drag over each item one-by-one going downwards. for (let i = 1; i < items.length; i++) { const elementRect = items[i].getBoundingClientRect(); dispatchMouseEvent(document, 'mousemove', elementRect.left, elementRect.top + 5); fixture.detectChanges(); expect(fixture.componentInstance.sortedSpy.calls.mostRecent().args[0]).toEqual({ previousIndex: i - 1, currentIndex: i, item: fixture.componentInstance.dragItems.first, container: fixture.componentInstance.dropInstance, }); } dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); })); it('should not dispatch the `sorted` event when an item is dragged inside a single-item list', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.componentInstance.items = [fixture.componentInstance.items[0]]; fixture.detectChanges(); const draggedItem = fixture.componentInstance.dragItems.first.element.nativeElement; const {top, left} = draggedItem.getBoundingClientRect(); startDraggingViaMouse(fixture, draggedItem, left, top); for (let i = 0; i < 5; i++) { dispatchMouseEvent(document, 'mousemove', left, top + 1); fixture.detectChanges(); expect(fixture.componentInstance.sortedSpy).not.toHaveBeenCalled(); } dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); })); it('should not move items in a vertical list if the pointer is too far away', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); const firstItem = dragItems.first; const thirdItemRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect(); // Move the cursor all the way to the right so it doesn't intersect along the x axis. dragElementViaMouse( fixture, firstItem.element.nativeElement, thirdItemRect.right + 1000, thirdItemRect.top + 1, ); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; // Assert the event like this, rather than `toHaveBeenCalledWith`, because Jasmine will // go into an infinite loop trying to stringify the event, if the test fails. expect(event).toEqual({ previousIndex: 0, currentIndex: 0, item: firstItem, container: fixture.componentInstance.dropInstance, previousContainer: fixture.componentInstance.dropInstance, isPointerOverContainer: false, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); })); it('should not move the original element from its initial DOM position', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const root = fixture.nativeElement as HTMLElement; let dragElements = Array.from(root.querySelectorAll('.cdk-drag')); expect(dragElements.map(el => el.textContent)).toEqual(['Zero', 'One', 'Two', 'Three']); // Stub out the original call so the list doesn't get re-rendered. // We're testing the DOM order explicitly. fixture.componentInstance.droppedSpy.and.callFake(() => {}); const thirdItemRect = dragElements[2].getBoundingClientRect(); dragElementViaMouse( fixture, fixture.componentInstance.dragItems.first.element.nativeElement, thirdItemRect.left + 1, thirdItemRect.top + 1, ); flush(); fixture.detectChanges(); dragElements = Array.from(root.querySelectorAll('.cdk-drag')); expect(dragElements.map(el => el.textContent)).toEqual(['Zero', 'One', 'Two', 'Three']); })); it('should dispatch the `dropped` event in a horizontal drop zone', fakeAsync(() => { const fixture = createComponent(DraggableInHorizontalDropZone); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); const firstItem = dragItems.first; const thirdItemRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect(); dragElementViaMouse( fixture, firstItem.element.nativeElement, thirdItemRect.left + 1, thirdItemRect.top + 1, ); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; // Assert the event like this, rather than `toHaveBeenCalledWith`, because Jasmine will // go into an infinite loop trying to stringify the event, if the test fails. expect(event).toEqual({ previousIndex: 0, currentIndex: 2, item: firstItem, container: fixture.componentInstance.dropInstance, previousContainer: fixture.componentInstance.dropInstance, isPointerOverContainer: true, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'One', 'Two', 'Zero', 'Three', ]); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 20224, "start_byte": 12036, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_20230_29757
it('should dispatch the correct `dropped` event in RTL horizontal drop zone', fakeAsync(() => { const fixture = createComponent(DraggableInHorizontalDropZone, { providers: [ { provide: Directionality, useValue: {value: 'rtl', change: observableOf()}, }, ], }); fixture.nativeElement.setAttribute('dir', 'rtl'); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); const firstItem = dragItems.first; const thirdItemRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect(); dragElementViaMouse( fixture, firstItem.element.nativeElement, thirdItemRect.right - 1, thirdItemRect.top + 1, ); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; // Assert the event like this, rather than `toHaveBeenCalledWith`, because Jasmine will // go into an infinite loop trying to stringify the event, if the test fails. expect(event).toEqual({ previousIndex: 0, currentIndex: 2, item: firstItem, container: fixture.componentInstance.dropInstance, previousContainer: fixture.componentInstance.dropInstance, isPointerOverContainer: true, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'One', 'Two', 'Zero', 'Three', ]); })); it('should not move items in a horizontal list if pointer is too far away', fakeAsync(() => { const fixture = createComponent(DraggableInHorizontalDropZone); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); const firstItem = dragItems.first; const thirdItemRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect(); // Move the cursor all the way to the bottom so it doesn't intersect along the y axis. dragElementViaMouse( fixture, firstItem.element.nativeElement, thirdItemRect.left + 1, thirdItemRect.bottom + 1000, ); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; // Assert the event like this, rather than `toHaveBeenCalledWith`, because Jasmine will // go into an infinite loop trying to stringify the event, if the test fails. expect(event).toEqual({ previousIndex: 0, currentIndex: 0, item: firstItem, container: fixture.componentInstance.dropInstance, previousContainer: fixture.componentInstance.dropInstance, isPointerOverContainer: false, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); })); it('should calculate the index if the list is scrolled while dragging', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableVerticalDropZone); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; const firstItem = dragItems.first; const thirdItemRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect(); const list = fixture.componentInstance.dropInstance.element.nativeElement; startDraggingViaMouse(fixture, firstItem.element.nativeElement); fixture.detectChanges(); dispatchMouseEvent(document, 'mousemove', thirdItemRect.left + 1, thirdItemRect.top + 1); fixture.detectChanges(); list.scrollTop = ITEM_HEIGHT * 10; dispatchFakeEvent(list, 'scroll'); fixture.detectChanges(); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; // Assert the event like this, rather than `toHaveBeenCalledWith`, because Jasmine will // go into an infinite loop trying to stringify the event, if the test fails. expect(event).toEqual({ previousIndex: 0, currentIndex: 12, item: firstItem, container: fixture.componentInstance.dropInstance, previousContainer: fixture.componentInstance.dropInstance, isPointerOverContainer: jasmine.any(Boolean), distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); })); it('should calculate the index if the list is scrolled while dragging inside the shadow DOM', fakeAsync(() => { // This test is only relevant for Shadow DOM-supporting browsers. if (!_supportsShadowDom()) { return; } const fixture = createComponent(DraggableInScrollableVerticalDropZone, { encapsulation: ViewEncapsulation.ShadowDom, }); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; const firstItem = dragItems.first; const thirdItemRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect(); const list = fixture.componentInstance.dropInstance.element.nativeElement; startDraggingViaMouse(fixture, firstItem.element.nativeElement); fixture.detectChanges(); dispatchMouseEvent(document, 'mousemove', thirdItemRect.left + 1, thirdItemRect.top + 1); fixture.detectChanges(); list.scrollTop = ITEM_HEIGHT * 10; dispatchFakeEvent(list, 'scroll'); fixture.detectChanges(); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; // Assert the event like this, rather than `toHaveBeenCalledWith`, because Jasmine will // go into an infinite loop trying to stringify the event, if the test fails. expect(event).toEqual({ previousIndex: 0, currentIndex: 12, item: firstItem, container: fixture.componentInstance.dropInstance, previousContainer: fixture.componentInstance.dropInstance, isPointerOverContainer: jasmine.any(Boolean), distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); })); it('should calculate the index if the viewport is scrolled while dragging', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); for (let i = 0; i < 200; i++) { fixture.componentInstance.items.push({ value: `Extra item ${i}`, height: ITEM_HEIGHT, margin: 0, }); } fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; const firstItem = dragItems.first; const thirdItemRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect(); startDraggingViaMouse(fixture, firstItem.element.nativeElement); fixture.detectChanges(); dispatchMouseEvent(document, 'mousemove', thirdItemRect.left + 1, thirdItemRect.top + 1); fixture.detectChanges(); scrollTo(0, ITEM_HEIGHT * 10); dispatchFakeEvent(document, 'scroll'); fixture.detectChanges(); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; // Assert the event like this, rather than `toHaveBeenCalledWith`, because Jasmine will // go into an infinite loop trying to stringify the event, if the test fails. expect(event).toEqual({ previousIndex: 0, currentIndex: 12, item: firstItem, container: fixture.componentInstance.dropInstance, previousContainer: fixture.componentInstance.dropInstance, isPointerOverContainer: jasmine.any(Boolean), distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); scrollTo(0, 0); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 29757, "start_byte": 20230, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_29763_39061
it('should remove the anchor node once dragging stops', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const list = fixture.componentInstance.dropInstance.element.nativeElement; startDraggingViaMouse(fixture, item); const anchor = Array.from(list.childNodes).find( node => node.textContent === 'cdk-drag-anchor', ); expect(anchor).toBeTruthy(); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); expect(anchor!.parentNode).toBeFalsy(); })); it('should create a preview element while the item is dragged', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const itemRect = item.getBoundingClientRect(); const initialParent = item.parentNode; startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview') as HTMLElement; const previewRect = preview.getBoundingClientRect(); expect(item.parentNode) .withContext('Expected element to be moved out into the body') .toBe(document.body); expect(item.style.position) .withContext('Expected element to be removed from layout') .toBe('fixed'); expect(item.style.getPropertyPriority('position')) .withContext('Expect element position to be !important') .toBe('important'); // Use a regex here since some browsers normalize 0 to 0px, but others don't. expect(item.style.top) .withContext('Expected element to be removed from layout') .toMatch(/^0(px)?$/); expect(item.style.left) .withContext('Expected element to be removed from layout') .toBe('-999em'); expect(item.style.opacity).withContext('Expected element to be invisible').toBe('0'); expect(preview).withContext('Expected preview to be in the DOM').toBeTruthy(); expect(preview.getAttribute('popover')) .withContext('Expected preview to be a popover') .toBe('manual'); expect(preview.style.margin) .withContext('Expected preview to reset the margin') .toMatch(/^(0(px)? auto 0(px)? 0(px)?)|(0(px)?)$/); expect(preview.textContent!.trim()) .withContext('Expected preview content to match element') .toContain('One'); expect(preview.getAttribute('dir')) .withContext('Expected preview element to inherit the directionality.') .toBe('ltr'); expect(previewRect.width) .withContext('Expected preview width to match element') .toBe(itemRect.width); expect(previewRect.height) .withContext('Expected preview height to match element') .toBe(itemRect.height); expect(preview.style.pointerEvents) .withContext('Expected pointer events to be disabled on the preview') .toBe('none'); expect(preview.style.zIndex) .withContext('Expected preview to have a high default zIndex.') .toBe('1000'); // Use a regex here since some browsers normalize 0 to 0px, but others don't. expect(preview.style.margin) .withContext('Expected the preview margin to be reset.') .toMatch(/^(0(px)? auto 0(px)? 0(px)?)|(0(px)?)$/); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); expect(item.parentNode) .withContext('Expected element to be moved back into its old parent') .toBe(initialParent); expect(item.style.position) .withContext('Expected element to be within the layout') .toBeFalsy(); expect(item.style.top).withContext('Expected element to be within the layout').toBeFalsy(); expect(item.style.left).withContext('Expected element to be within the layout').toBeFalsy(); expect(item.style.opacity).withContext('Expected element to be visible').toBeFalsy(); expect(preview.parentNode) .withContext('Expected preview to be removed from the DOM') .toBeFalsy(); })); it('should be able to configure the preview z-index', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone, { providers: [ { provide: CDK_DRAG_CONFIG, useValue: { dragStartThreshold: 0, zIndex: 3000, }, }, ], }); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; expect(preview.style.zIndex).toBe('3000'); })); it('should be able to constrain the preview position', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.componentInstance.boundarySelector = '.cdk-drop-list'; fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const listRect = fixture.componentInstance.dropInstance.element.nativeElement.getBoundingClientRect(); startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; startDraggingViaMouse(fixture, item, listRect.right + 50, listRect.bottom + 50); flush(); dispatchMouseEvent(document, 'mousemove', listRect.right + 50, listRect.bottom + 50); fixture.detectChanges(); const previewRect = preview.getBoundingClientRect(); expect(Math.floor(previewRect.bottom)).toBe(Math.floor(listRect.bottom)); expect(Math.floor(previewRect.right)).toBe(Math.floor(listRect.right)); })); it('should update the boundary if the page is scrolled while dragging', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.componentInstance.boundarySelector = '.cdk-drop-list'; fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const list = fixture.componentInstance.dropInstance.element.nativeElement; const cleanup = makeScrollable(); scrollTo(0, 10); let listRect = list.getBoundingClientRect(); // Note that we need to measure after scrolling. startDraggingViaMouse(fixture, item); startDraggingViaMouse(fixture, item, listRect.right, listRect.bottom); flush(); dispatchMouseEvent(document, 'mousemove', listRect.right, listRect.bottom); fixture.detectChanges(); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; let previewRect = preview.getBoundingClientRect(); expect(Math.floor(previewRect.bottom)).toBe(Math.floor(listRect.bottom)); scrollTo(0, 0); dispatchFakeEvent(document, 'scroll'); fixture.detectChanges(); listRect = list.getBoundingClientRect(); // We need to update these since we've scrolled. dispatchMouseEvent(document, 'mousemove', listRect.right, listRect.bottom); fixture.detectChanges(); previewRect = preview.getBoundingClientRect(); expect(Math.floor(previewRect.bottom)).toBe(Math.floor(listRect.bottom)); cleanup(); })); it('should update the boundary if a parent is scrolled while dragging', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableParentContainer); fixture.componentInstance.boundarySelector = '.cdk-drop-list'; fixture.detectChanges(); const container: HTMLElement = fixture.nativeElement.querySelector('.scroll-container'); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const list = fixture.componentInstance.dropInstance.element.nativeElement; const cleanup = makeScrollable('vertical', container); container.scrollTop = 10; let listRect = list.getBoundingClientRect(); // Note that we need to measure after scrolling. startDraggingViaMouse(fixture, item); startDraggingViaMouse(fixture, item, listRect.right, listRect.bottom); flush(); dispatchMouseEvent(document, 'mousemove', listRect.right, listRect.bottom); fixture.detectChanges(); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; let previewRect = preview.getBoundingClientRect(); // Different browsers round the scroll position differently so // assert that the offsets are within a pixel of each other. expect(Math.abs(previewRect.bottom - listRect.bottom)).toBeLessThan(2); container.scrollTop = 0; dispatchFakeEvent(container, 'scroll'); fixture.detectChanges(); listRect = list.getBoundingClientRect(); // We need to update these since we've scrolled. dispatchMouseEvent(document, 'mousemove', listRect.right, listRect.bottom); fixture.detectChanges(); previewRect = preview.getBoundingClientRect(); expect(Math.abs(previewRect.bottom - listRect.bottom)).toBeLessThan(2); cleanup(); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 39061, "start_byte": 29763, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_39067_48695
it('should update the boundary if a parent is scrolled while dragging inside the shadow DOM', fakeAsync(() => { // This test is only relevant for Shadow DOM-supporting browsers. if (!_supportsShadowDom()) { return; } const fixture = createComponent(DraggableInScrollableParentContainer, { encapsulation: ViewEncapsulation.ShadowDom, }); fixture.componentInstance.boundarySelector = '.cdk-drop-list'; fixture.detectChanges(); const container: HTMLElement = fixture.nativeElement.shadowRoot.querySelector('.scroll-container'); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const list = fixture.componentInstance.dropInstance.element.nativeElement; const cleanup = makeScrollable('vertical', container); container.scrollTop = 10; // Note that we need to measure after scrolling. let listRect = list.getBoundingClientRect(); startDraggingViaMouse(fixture, item); startDraggingViaMouse(fixture, item, listRect.right, listRect.bottom); flush(); dispatchMouseEvent(document, 'mousemove', listRect.right, listRect.bottom); fixture.detectChanges(); const preview = fixture.nativeElement.shadowRoot.querySelector( '.cdk-drag-preview', )! as HTMLElement; let previewRect = preview.getBoundingClientRect(); // Different browsers round the scroll position differently so // assert that the offsets are within a pixel of each other. expect(Math.abs(previewRect.bottom - listRect.bottom)).toBeLessThan(2); container.scrollTop = 0; dispatchFakeEvent(container, 'scroll'); fixture.detectChanges(); listRect = list.getBoundingClientRect(); // We need to update these since we've scrolled. dispatchMouseEvent(document, 'mousemove', listRect.right, listRect.bottom); fixture.detectChanges(); previewRect = preview.getBoundingClientRect(); expect(Math.abs(previewRect.bottom - listRect.bottom)).toBeLessThan(2); cleanup(); })); it('should clear the id from the preview', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; item.id = 'custom-id'; startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; expect(preview.getAttribute('id')).toBeFalsy(); })); it('should clone the content of descendant canvas elements', fakeAsync(() => { const fixture = createComponent(DraggableWithCanvasInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const sourceCanvas = item.querySelector('canvas') as HTMLCanvasElement; // via https://stackoverflow.com/a/17386803/2204158 // via https://stackoverflow.com/a/17386803/2204158 expect( sourceCanvas .getContext('2d')! .getImageData(0, 0, sourceCanvas.width, sourceCanvas.height) .data.some(channel => channel !== 0), ) .withContext('Expected source canvas to have data.') .toBe(true); startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; const previewCanvas = preview.querySelector('canvas')!; expect(previewCanvas.toDataURL()) .withContext('Expected cloned canvas to have the same content as the source.') .toBe(sourceCanvas.toDataURL()); })); it('should not throw when cloning an invalid canvas', fakeAsync(() => { const fixture = createComponent(DraggableWithInvalidCanvasInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; expect(() => { startDraggingViaMouse(fixture, item); tick(); }).not.toThrow(); expect(document.querySelector('.cdk-drag-preview canvas')).toBeTruthy(); })); it('should clone the content of descendant input elements', fakeAsync(() => { const fixture = createComponent(DraggableWithInputsInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const sourceInput = item.querySelector('input')!; const sourceTextarea = item.querySelector('textarea')!; const sourceSelect = item.querySelector('select')!; const value = fixture.componentInstance.inputValue; expect(sourceInput.value).toBe(value); expect(sourceTextarea.value).toBe(value); expect(sourceSelect.value).toBe(value); startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview')!; const previewInput = preview.querySelector('input')!; const previewTextarea = preview.querySelector('textarea')!; const previewSelect = preview.querySelector('select')!; expect(previewInput.value).toBe(value); expect(previewTextarea.value).toBe(value); expect(previewSelect.value).toBe(value); })); it('should preserve checked state for radio inputs in the content', fakeAsync(() => { const fixture = createComponent(DraggableWithRadioInputsInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[2].element.nativeElement; const sourceRadioInput = item.querySelector<HTMLInputElement>('input[type="radio"]')!; expect(sourceRadioInput.checked).toBeTruthy(); startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview')!; const previewRadioInput = preview.querySelector<HTMLInputElement>('input[type="radio"]')!; expect(previewRadioInput.checked).toBeTruthy( 'Expected cloned radio input in preview has the same state as original radio input', ); const placeholder = document.querySelector('.cdk-drag-placeholder')!; const placeholderRadioInput = placeholder.querySelector<HTMLInputElement>('input[type="radio"]')!; expect(placeholderRadioInput.checked).toBeTruthy( 'Expected cloned radio input in placeholder has the same state as original radio input', ); dispatchMouseEvent(document, 'mouseup'); // Important to tick with 0 since we don't want to flush any pending timeouts. // It also makes sure that all clones have been removed from the DOM. tick(0); expect(sourceRadioInput.checked) .withContext('Expected original radio input has preserved its original checked state') .toBeTruthy(); })); it('should clear the ids from descendants of the preview', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const extraChild = document.createElement('div'); extraChild.id = 'child-id'; extraChild.classList.add('preview-child'); item.appendChild(extraChild); startDraggingViaMouse(fixture, item); expect(document.querySelectorAll('.preview-child').length).toBeGreaterThan(1); expect(document.querySelectorAll('[id="child-id"]').length).toBe(1); })); it('should not create a preview if the element was not dragged far enough', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone, {dragDistance: 5}); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item); expect(document.querySelector('.cdk-drag-preview')).toBeFalsy(); })); it('should pass the proper direction to the preview in rtl', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone, { providers: [ { provide: Directionality, useValue: {value: 'rtl', change: observableOf()}, }, ], }); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item); expect(document.querySelector('.cdk-drag-preview')!.getAttribute('dir')) .withContext('Expected preview to inherit the directionality.') .toBe('rtl'); })); it('should remove the preview if its `transitionend` event timed out', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview') as HTMLElement; // Add a duration since the tests won't include one. preview.style.transitionDuration = '500ms'; // Move somewhere so the draggable doesn't exit immediately. dispatchMouseEvent(document, 'mousemove', 50, 50); fixture.detectChanges(); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); tick(250); expect(preview.parentNode) .withContext('Expected preview to be in the DOM mid-way through the transition') .toBeTruthy(); tick(500); expect(preview.parentNode) .withContext('Expected preview to be removed from the DOM if the transition timed out') .toBeFalsy(); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 48695, "start_byte": 39067, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_48701_58735
it('should be able to set a single class on a preview', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.componentInstance.previewClass = 'custom-class'; fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; expect(preview.classList).toContain('custom-class'); })); it('should be able to set multiple classes on a preview', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.componentInstance.previewClass = ['custom-class-1', 'custom-class-2']; fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; expect(preview.classList).toContain('custom-class-1'); expect(preview.classList).toContain('custom-class-2'); })); it('should emit the released event as soon as the item is released', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1]; const endedSpy = jasmine.createSpy('ended spy'); const releasedSpy = jasmine.createSpy('released spy'); const endedSubscription = item.ended.subscribe(endedSpy); const releasedSubscription = item.released.subscribe(releasedSpy); startDraggingViaMouse(fixture, item.element.nativeElement); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; // Add a duration since the tests won't include one. preview.style.transitionDuration = '500ms'; // Move somewhere so the draggable doesn't exit immediately. dispatchMouseEvent(document, 'mousemove', 50, 50); fixture.detectChanges(); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); // Expected the released event to fire immediately upon release. expect(releasedSpy).toHaveBeenCalled(); tick(1000); // Expected the ended event to fire once the entire sequence is done. expect(endedSpy).toHaveBeenCalled(); endedSubscription.unsubscribe(); releasedSubscription.unsubscribe(); })); it('should reset immediately when failed drag happens after a successful one', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const itemInstance = fixture.componentInstance.dragItems.toArray()[1]; const item = itemInstance.element.nativeElement; const spy = jasmine.createSpy('dropped spy'); const subscription = itemInstance.dropped.subscribe(spy); // Do an initial drag and drop sequence. dragElementViaMouse(fixture, item, 50, 50); tick(0); // Important to tick with 0 since we don't want to flush any pending timeouts. expect(spy).toHaveBeenCalledTimes(1); // Start another drag. startDraggingViaMouse(fixture, item); // Add a duration since the tests won't include one. const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; preview.style.transitionDuration = '500ms'; // Dispatch the mouseup immediately to simulate the user not moving the element. dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); tick(0); // Important to tick with 0 since we don't want to flush any pending timeouts. expect(spy).toHaveBeenCalledTimes(2); subscription.unsubscribe(); })); it('should not wait for transition that are not on the `transform` property', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; preview.style.transition = 'opacity 500ms ease'; dispatchMouseEvent(document, 'mousemove', 50, 50); fixture.detectChanges(); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); tick(0); expect(preview.parentNode) .withContext('Expected preview to be removed from the DOM immediately') .toBeFalsy(); })); it('should pick out the `transform` duration if multiple properties are being transitioned', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; preview.style.transition = 'opacity 500ms ease, transform 1000ms ease'; dispatchMouseEvent(document, 'mousemove', 50, 50); fixture.detectChanges(); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); tick(500); expect(preview.parentNode) .withContext('Expected preview to be in the DOM at the end of the opacity transition') .toBeTruthy(); tick(1000); expect(preview.parentNode) .withContext( 'Expected preview to be removed from the DOM at the end of the transform transition', ) .toBeFalsy(); })); it('should create a placeholder element while the item is dragged', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const initialParent = item.parentNode; startDraggingViaMouse(fixture, item); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; expect(placeholder).withContext('Expected placeholder to be in the DOM').toBeTruthy(); expect(placeholder.parentNode) .withContext('Expected placeholder to be inserted into the same parent') .toBe(initialParent); expect(placeholder.textContent!.trim()) .withContext('Expected placeholder content to match element') .toContain('One'); expect(placeholder.style.pointerEvents) .withContext('Expected pointer events to be disabled on placeholder') .toBe('none'); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); expect(placeholder.parentNode) .withContext('Expected placeholder to be removed from the DOM') .toBeFalsy(); })); it('should insert the preview into the `body` if previewContainer is set to `global`', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.componentInstance.previewContainer = 'global'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview') as HTMLElement; expect(preview.parentNode).toBe(document.body); })); it('should insert the preview into the parent node if previewContainer is set to `parent`', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.componentInstance.previewContainer = 'parent'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const list = fixture.nativeElement.querySelector('.drop-list'); startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview') as HTMLElement; expect(list).toBeTruthy(); expect(preview.parentNode).toBe(list); })); it('should insert the preview into a particular element, if specified', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const previewContainer = fixture.componentInstance.alternatePreviewContainer; expect(previewContainer).toBeTruthy(); fixture.componentInstance.previewContainer = previewContainer; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview') as HTMLElement; expect(preview.parentNode).toBe(previewContainer.nativeElement); })); it('should remove the id from the placeholder', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; item.id = 'custom-id'; startDraggingViaMouse(fixture, item); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; expect(placeholder.getAttribute('id')).toBeFalsy(); })); it('should clear the ids from descendants of the placeholder', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const extraChild = document.createElement('div'); extraChild.id = 'child-id'; extraChild.classList.add('placeholder-child'); item.appendChild(extraChild); startDraggingViaMouse(fixture, item); expect(document.querySelectorAll('.placeholder-child').length).toBeGreaterThan(1); expect(document.querySelectorAll('[id="child-id"]').length).toBe(1); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 58735, "start_byte": 48701, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_58741_67448
it('should not create placeholder if the element was not dragged far enough', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone, {dragDistance: 5}); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item); expect(document.querySelector('.cdk-drag-placeholder')).toBeFalsy(); })); it('should move the placeholder as an item is being sorted down', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); assertStartToEndSorting( 'vertical', fixture, config.getSortedSiblings, fixture.componentInstance.dragItems.map(item => item.element.nativeElement), ); })); it('should move the placeholder as an item is being sorted down on a scrolled page', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const cleanup = makeScrollable(); scrollTo(0, 5000); assertStartToEndSorting( 'vertical', fixture, config.getSortedSiblings, fixture.componentInstance.dragItems.map(item => item.element.nativeElement), ); cleanup(); })); it('should move the placeholder as an item is being sorted up', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); assertEndToStartSorting( 'vertical', fixture, config.getSortedSiblings, fixture.componentInstance.dragItems.map(item => item.element.nativeElement), ); })); it('should move the placeholder as an item is being sorted up on a scrolled page', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const cleanup = makeScrollable(); scrollTo(0, 5000); assertEndToStartSorting( 'vertical', fixture, config.getSortedSiblings, fixture.componentInstance.dragItems.map(item => item.element.nativeElement), ); cleanup(); })); it('should move the placeholder as an item is being sorted to the right', fakeAsync(() => { const fixture = createComponent(DraggableInHorizontalDropZone); fixture.detectChanges(); assertStartToEndSorting( 'horizontal', fixture, config.getSortedSiblings, fixture.componentInstance.dragItems.map(item => item.element.nativeElement), ); })); it('should move the placeholder as an item is being sorted to the left', fakeAsync(() => { const fixture = createComponent(DraggableInHorizontalDropZone); fixture.detectChanges(); assertEndToStartSorting( 'horizontal', fixture, config.getSortedSiblings, fixture.componentInstance.dragItems.map(item => item.element.nativeElement), ); })); it('should lay out the elements correctly, if an element skips multiple positions when sorting vertically', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const items = fixture.componentInstance.dragItems.map(i => i.element.nativeElement); const draggedItem = items[0]; const {top, left} = draggedItem.getBoundingClientRect(); startDraggingViaMouse(fixture, draggedItem, left, top); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; const targetRect = items[items.length - 1].getBoundingClientRect(); // Add a few pixels to the top offset so we get some overlap. dispatchMouseEvent(document, 'mousemove', targetRect.left, targetRect.top + 5); fixture.detectChanges(); expect(config.getSortedSiblings(placeholder, 'top').map(e => e.textContent!.trim())).toEqual([ 'One', 'Two', 'Three', 'Zero', ]); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); })); it('should lay out the elements correctly, if an element skips multiple positions when sorting horizontally', fakeAsync(() => { const fixture = createComponent(DraggableInHorizontalDropZone); fixture.detectChanges(); const items = fixture.componentInstance.dragItems.map(i => i.element.nativeElement); const draggedItem = items[0]; const {top, left} = draggedItem.getBoundingClientRect(); startDraggingViaMouse(fixture, draggedItem, left, top); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; const targetRect = items[items.length - 1].getBoundingClientRect(); // Add a few pixels to the left offset so we get some overlap. dispatchMouseEvent(document, 'mousemove', targetRect.right - 5, targetRect.top); fixture.detectChanges(); expect(config.getSortedSiblings(placeholder, 'left').map(e => e.textContent!.trim())).toEqual( ['One', 'Two', 'Three', 'Zero'], ); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); })); it('should not swap position for tiny pointer movements', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const items = fixture.componentInstance.dragItems.map(i => i.element.nativeElement); const draggedItem = items[0]; const target = items[1]; const {top, left} = draggedItem.getBoundingClientRect(); // Bump the height so the pointer doesn't leave after swapping. target.style.height = `${ITEM_HEIGHT * 3}px`; startDraggingViaMouse(fixture, draggedItem, left, top); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; expect(config.getSortedSiblings(placeholder, 'top').map(e => e.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); const targetRect = target.getBoundingClientRect(); const pointerTop = targetRect.top + 20; // Move over the target so there's a 20px overlap. dispatchMouseEvent(document, 'mousemove', targetRect.left, pointerTop); fixture.detectChanges(); expect(config.getSortedSiblings(placeholder, 'top').map(e => e.textContent!.trim())) .withContext('Expected position to swap.') .toEqual(['One', 'Zero', 'Two', 'Three']); // Move down a further 1px. dispatchMouseEvent(document, 'mousemove', targetRect.left, pointerTop + 1); fixture.detectChanges(); expect(config.getSortedSiblings(placeholder, 'top').map(e => e.textContent!.trim())) .withContext('Expected positions not to swap.') .toEqual(['One', 'Zero', 'Two', 'Three']); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); })); it('should swap position for pointer movements in the opposite direction', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const items = fixture.componentInstance.dragItems.map(i => i.element.nativeElement); const draggedItem = items[0]; const target = items[1]; const {top, left} = draggedItem.getBoundingClientRect(); // Bump the height so the pointer doesn't leave after swapping. target.style.height = `${ITEM_HEIGHT * 3}px`; startDraggingViaMouse(fixture, draggedItem, left, top); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; expect(config.getSortedSiblings(placeholder, 'top').map(e => e.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); const targetRect = target.getBoundingClientRect(); const pointerTop = targetRect.top + 20; // Move over the target so there's a 20px overlap. dispatchMouseEvent(document, 'mousemove', targetRect.left, pointerTop); fixture.detectChanges(); expect(config.getSortedSiblings(placeholder, 'top').map(e => e.textContent!.trim())) .withContext('Expected position to swap.') .toEqual(['One', 'Zero', 'Two', 'Three']); // Move up 10px. dispatchMouseEvent(document, 'mousemove', targetRect.left, pointerTop - 10); fixture.detectChanges(); expect(config.getSortedSiblings(placeholder, 'top').map(e => e.textContent!.trim())) .withContext('Expected positions to swap again.') .toEqual(['Zero', 'One', 'Two', 'Three']); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 67448, "start_byte": 58741, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_67454_76698
it('it should allow item swaps in the same drag direction, if the pointer did not overlap with the sibling item after the previous swap', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const items = fixture.componentInstance.dragItems.map(i => i.element.nativeElement); const draggedItem = items[0]; const target = items[items.length - 1]; const itemRect = draggedItem.getBoundingClientRect(); startDraggingViaMouse(fixture, draggedItem, itemRect.left, itemRect.top); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; expect(config.getSortedSiblings(placeholder, 'top').map(e => e.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); let targetRect = target.getBoundingClientRect(); // Trigger a mouse move coming from the bottom so that the list thinks that we're // sorting upwards. This usually how a user would behave with a mouse pointer. dispatchMouseEvent(document, 'mousemove', targetRect.left, targetRect.bottom + 50); fixture.detectChanges(); dispatchMouseEvent(document, 'mousemove', targetRect.left, targetRect.bottom - 1); fixture.detectChanges(); expect(config.getSortedSiblings(placeholder, 'top').map(e => e.textContent!.trim())).toEqual([ 'One', 'Two', 'Three', 'Zero', ]); // Refresh the rect since the element position has changed. targetRect = target.getBoundingClientRect(); dispatchMouseEvent(document, 'mousemove', targetRect.left, targetRect.bottom - 1); fixture.detectChanges(); expect(config.getSortedSiblings(placeholder, 'top').map(e => e.textContent!.trim())).toEqual([ 'One', 'Two', 'Zero', 'Three', ]); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); })); it('should clean up the preview element if the item is destroyed mid-drag', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview') as HTMLElement; expect(preview.parentNode).withContext('Expected preview to be in the DOM').toBeTruthy(); expect(item.parentNode).withContext('Expected drag item to be in the DOM').toBeTruthy(); fixture.destroy(); expect(preview.parentNode) .withContext('Expected preview to be removed from the DOM') .toBeFalsy(); expect(item.parentNode) .withContext('Expected drag item to be removed from the DOM') .toBeFalsy(); })); it('should be able to customize the preview element', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomPreview); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; expect(preview).toBeTruthy(); expect(preview.classList).toContain('custom-preview'); expect(preview.textContent!.trim()).toContain('Custom preview'); })); it('should handle the custom preview being removed', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomPreview); fixture.detectChanges(); flush(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; fixture.componentInstance.renderCustomPreview = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; expect(preview).toBeTruthy(); expect(preview.classList).not.toContain('custom-preview'); expect(preview.textContent!.trim()).not.toContain('Custom preview'); })); it('should be able to constrain the position of a custom preview', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomPreview); fixture.componentInstance.boundarySelector = '.cdk-drop-list'; fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const listRect = fixture.componentInstance.dropInstance.element.nativeElement.getBoundingClientRect(); startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; startDraggingViaMouse(fixture, item, listRect.right + 50, listRect.bottom + 50); flush(); dispatchMouseEvent(document, 'mousemove', listRect.right + 50, listRect.bottom + 50); fixture.detectChanges(); const previewRect = preview.getBoundingClientRect(); expect(Math.floor(previewRect.bottom)).toBe(Math.floor(listRect.bottom)); expect(Math.floor(previewRect.right)).toBe(Math.floor(listRect.right)); })); it('should be able to constrain the preview position with a custom function', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomPreview); const spy = jasmine.createSpy('constrain position spy').and.returnValue({ x: 50, y: 50, } as Point); fixture.componentInstance.constrainPosition = spy; fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; startDraggingViaMouse(fixture, item, 200, 200); flush(); dispatchMouseEvent(document, 'mousemove', 200, 200); fixture.detectChanges(); const previewRect = preview.getBoundingClientRect(); expect(spy).toHaveBeenCalledWith( jasmine.objectContaining({x: 200, y: 200}), jasmine.any(DragRef), jasmine.anything(), jasmine.objectContaining({x: jasmine.any(Number), y: jasmine.any(Number)}), ); expect(Math.floor(previewRect.top)).toBe(50); expect(Math.floor(previewRect.left)).toBe(50); })); it('should revert the element back to its parent after dragging with a custom preview has stopped', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomPreview); fixture.detectChanges(); const dragContainer = fixture.componentInstance.dropInstance.element.nativeElement; const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; expect(dragContainer.contains(item)) .withContext('Expected item to be in container.') .toBe(true); // The coordinates don't matter. dragElementViaMouse(fixture, item, 10, 10); flush(); fixture.detectChanges(); expect(dragContainer.contains(item)) .withContext('Expected item to be returned to container.') .toBe(true); })); it('should position custom previews next to the pointer', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomPreview); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item, 50, 50); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; expect(preview.style.transform).toBe('translate3d(50px, 50px, 0px)'); })); it('should keep the preview next to the trigger if the page was scrolled', fakeAsync(() => { const extractTransform = (element: HTMLElement) => { const match = element.style.transform.match(/translate3d\(\d+px, (\d+)px, \d+px\)/); return match ? parseInt(match[1]) : 0; }; const fixture = createComponent(DraggableInDropZoneWithCustomPreview); fixture.detectChanges(); const platform = TestBed.inject(Platform); // The programmatic scrolling inside the Karma iframe doesn't seem to work on iOS in the CI. // Skip the test since the logic is the same for all other browsers which are covered. if (platform.IOS) { return; } const cleanup = makeScrollable(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item, 50, 50); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; expect(extractTransform(preview)).toBe(50); scrollTo(0, 5000); fixture.detectChanges(); // Move the pointer a bit so the preview has to reposition. dispatchMouseEvent(document, 'mousemove', 55, 55); fixture.detectChanges(); // Note that here we just check that the value is greater, because on the // CI the values end up being inconsistent between browsers. expect(extractTransform(preview)).toBeGreaterThan(1000); cleanup(); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 76698, "start_byte": 67454, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_76704_86313
it('should lock position inside a drop container along the x axis', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomPreview); fixture.detectChanges(); const element = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; fixture.componentInstance.items[1].lockAxis = 'x'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); startDraggingViaMouse(fixture, element, 50, 50); dispatchMouseEvent(element, 'mousemove', 100, 100); fixture.detectChanges(); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; expect(preview.style.transform).toBe('translate3d(100px, 50px, 0px)'); })); it('should lock position inside a drop container along the y axis', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomPreview); fixture.detectChanges(); const element = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; fixture.componentInstance.items[1].lockAxis = 'y'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); startDraggingViaMouse(fixture, element, 50, 50); dispatchMouseEvent(element, 'mousemove', 100, 100); fixture.detectChanges(); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; expect(preview.style.transform).toBe('translate3d(50px, 100px, 0px)'); })); it('should inherit the position locking from the drop container', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomPreview); fixture.detectChanges(); const element = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; fixture.componentInstance.dropLockAxis.set('x'); fixture.detectChanges(); startDraggingViaMouse(fixture, element, 50, 50); dispatchMouseEvent(element, 'mousemove', 100, 100); fixture.detectChanges(); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; expect(preview.style.transform).toBe('translate3d(100px, 50px, 0px)'); })); it('should be able to set a class on a custom preview', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomPreview); fixture.componentInstance.previewClass = 'custom-class'; fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; expect(preview.classList).toContain('custom-preview'); expect(preview.classList).toContain('custom-class'); })); it('should be able to apply the size of the dragged element to a custom preview', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomPreview); fixture.componentInstance.matchPreviewSize = true; fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const itemRect = item.getBoundingClientRect(); startDraggingViaMouse(fixture, item); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; expect(preview).toBeTruthy(); expect(preview.style.width).toBe(`${itemRect.width}px`); expect(preview.style.height).toBe(`${itemRect.height}px`); })); it('should preserve the pickup position if the custom preview inherits the size of the dragged element', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomPreview); fixture.componentInstance.matchPreviewSize = true; fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item, 50, 50); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; expect(preview.style.transform).toBe('translate3d(8px, 33px, 0px)'); })); it('should not have the size of the inserted preview affect the size applied via matchSize', fakeAsync(() => { const fixture = createComponent(DraggableInHorizontalFlexDropZoneWithMatchSizePreview); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const itemRect = item.getBoundingClientRect(); startDraggingViaMouse(fixture, item); fixture.detectChanges(); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; const previewRect = preview.getBoundingClientRect(); expect(Math.floor(previewRect.width)).toBe(Math.floor(itemRect.width)); expect(Math.floor(previewRect.height)).toBe(Math.floor(itemRect.height)); })); it('should not throw when custom preview only has text', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomTextOnlyPreview); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; expect(() => { startDraggingViaMouse(fixture, item); }).not.toThrow(); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; expect(preview).toBeTruthy(); expect(preview.textContent!.trim()).toContain('Hello One'); })); it('should handle custom preview with multiple root nodes', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomMultiNodePreview); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; expect(() => { startDraggingViaMouse(fixture, item); }).not.toThrow(); const preview = document.querySelector('.cdk-drag-preview')! as HTMLElement; expect(preview).toBeTruthy(); expect(preview.textContent!.trim()).toContain('HelloOne'); })); it('should be able to customize the placeholder', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomPlaceholder); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; startDraggingViaMouse(fixture, item); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; expect(placeholder).toBeTruthy(); expect(placeholder.classList).toContain('custom-placeholder'); expect(placeholder.textContent!.trim()).toContain('Custom placeholder'); })); it('should handle the custom placeholder being removed', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomPlaceholder); fixture.detectChanges(); flush(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; fixture.componentInstance.renderPlaceholder = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); startDraggingViaMouse(fixture, item); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; expect(placeholder).toBeTruthy(); expect(placeholder.classList).not.toContain('custom-placeholder'); expect(placeholder.textContent!.trim()).not.toContain('Custom placeholder'); })); it('should measure the custom placeholder after the first change detection', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomPlaceholder); fixture.componentInstance.extraPlaceholderClass = 'tall-placeholder'; fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; const item = dragItems.toArray()[0].element.nativeElement; startDraggingViaMouse(fixture, item); const thirdItem = dragItems.toArray()[2].element.nativeElement; const thirdItemRect = thirdItem.getBoundingClientRect(); dispatchMouseEvent(document, 'mousemove', thirdItemRect.left + 1, thirdItemRect.top + 1); fixture.detectChanges(); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); fixture.detectChanges(); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event.currentIndex).toBe(2); })); it('should not throw when custom placeholder only has text', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomTextOnlyPlaceholder); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; expect(() => { startDraggingViaMouse(fixture, item); }).not.toThrow(); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; expect(placeholder).toBeTruthy(); expect(placeholder.textContent!.trim()).toContain('Hello One'); })); it('should handle custom placeholder with multiple root nodes', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithCustomMultiNodePlaceholder); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; expect(() => { startDraggingViaMouse(fixture, item); }).not.toThrow(); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; expect(placeholder).toBeTruthy(); expect(placeholder.textContent!.trim()).toContain('HelloOne'); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 86313, "start_byte": 76704, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_86319_95870
it('should not move the item if the list is disabled', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; const dropElement = fixture.componentInstance.dropInstance.element.nativeElement; expect(dropElement.classList).not.toContain('cdk-drop-list-disabled'); fixture.componentInstance.dropDisabled.set(true); fixture.detectChanges(); expect(dropElement.classList).toContain('cdk-drop-list-disabled'); expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); const firstItem = dragItems.first; const thirdItemRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect(); dragElementViaMouse( fixture, firstItem.element.nativeElement, thirdItemRect.right + 1, thirdItemRect.top + 1, ); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).not.toHaveBeenCalled(); expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); })); it('should not throw if the `touches` array is empty', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; dispatchTouchEvent(item, 'touchstart'); fixture.detectChanges(); dispatchTouchEvent(document, 'touchmove'); fixture.detectChanges(); dispatchTouchEvent(document, 'touchmove', 50, 50); fixture.detectChanges(); expect(() => { const endEvent = createTouchEvent('touchend', 50, 50); Object.defineProperty(endEvent, 'touches', {get: () => []}); dispatchEvent(document, endEvent); fixture.detectChanges(); }).not.toThrow(); })); it('should not move the item if the group is disabled', fakeAsync(() => { const fixture = createComponent(ConnectedDropZonesViaGroupDirective); fixture.detectChanges(); const dragItems = fixture.componentInstance.groupedDragItems[0]; fixture.componentInstance.groupDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); const firstItem = dragItems[0]; const thirdItemRect = dragItems[2].element.nativeElement.getBoundingClientRect(); dragElementViaMouse( fixture, firstItem.element.nativeElement, thirdItemRect.right + 1, thirdItemRect.top + 1, ); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).not.toHaveBeenCalled(); expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); })); it('should not sort an item if sorting the list is disabled', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const dropInstance = fixture.componentInstance.dropInstance; const dragItems = fixture.componentInstance.dragItems; dropInstance.sortingDisabled = true; expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); const firstItem = dragItems.first; const thirdItemRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect(); const targetX = thirdItemRect.left + 1; const targetY = thirdItemRect.top + 1; startDraggingViaMouse(fixture, firstItem.element.nativeElement); const placeholder = document.querySelector('.cdk-drag-placeholder') as HTMLElement; dispatchMouseEvent(document, 'mousemove', targetX, targetY); fixture.detectChanges(); expect(config.getSortedSiblings(placeholder, 'top').indexOf(placeholder)) .withContext('Expected placeholder to stay in place.') .toBe(0); dispatchMouseEvent(document, 'mouseup', targetX, targetY); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; // Assert the event like this, rather than `toHaveBeenCalledWith`, because Jasmine will // go into an infinite loop trying to stringify the event, if the test fails. expect(event).toEqual({ previousIndex: 0, currentIndex: 0, item: firstItem, container: dropInstance, previousContainer: dropInstance, isPointerOverContainer: true, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); })); it('should not throw if an item is removed after dragging has started', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; const firstElement = dragItems.first.element.nativeElement; const lastItemRect = dragItems.last.element.nativeElement.getBoundingClientRect(); // Start dragging. startDraggingViaMouse(fixture, firstElement); // Remove the last item. fixture.componentInstance.items.pop(); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(() => { // Move the dragged item over where the remove item would've been. dispatchMouseEvent(document, 'mousemove', lastItemRect.left + 1, lastItemRect.top + 1); fixture.detectChanges(); flush(); }).not.toThrow(); })); it('should not be able to start a drag sequence while another one is still active', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const [item, otherItem] = fixture.componentInstance.dragItems.toArray(); startDraggingViaMouse(fixture, item.element.nativeElement); expect(document.querySelectorAll('.cdk-drag-dragging').length) .withContext('Expected one item to be dragged initially.') .toBe(1); startDraggingViaMouse(fixture, otherItem.element.nativeElement); expect(document.querySelectorAll('.cdk-drag-dragging').length) .withContext('Expected only one item to continue to be dragged.') .toBe(1); })); it('should should be able to disable auto-scrolling', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableVerticalDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.first.element.nativeElement; const list = fixture.componentInstance.dropInstance.element.nativeElement; const listRect = list.getBoundingClientRect(); fixture.componentInstance.dropInstance.autoScrollDisabled = true; fixture.detectChanges(); expect(list.scrollTop).toBe(0); startDraggingViaMouse(fixture, item); dispatchMouseEvent( document, 'mousemove', listRect.left + listRect.width / 2, listRect.top + listRect.height, ); fixture.detectChanges(); tickAnimationFrames(20); expect(list.scrollTop).toBe(0); })); it('should auto-scroll down if the user holds their pointer at bottom edge', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableVerticalDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.first.element.nativeElement; const list = fixture.componentInstance.dropInstance.element.nativeElement; const listRect = list.getBoundingClientRect(); expect(list.scrollTop).toBe(0); startDraggingViaMouse(fixture, item); dispatchMouseEvent( document, 'mousemove', listRect.left + listRect.width / 2, listRect.top + listRect.height, ); fixture.detectChanges(); tickAnimationFrames(20); expect(list.scrollTop).toBeGreaterThan(0); })); it('should auto-scroll up if the user holds their pointer at top edge', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableVerticalDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.first.element.nativeElement; const list = fixture.componentInstance.dropInstance.element.nativeElement; const listRect = list.getBoundingClientRect(); const initialScrollDistance = (list.scrollTop = list.scrollHeight); startDraggingViaMouse(fixture, item); dispatchMouseEvent(document, 'mousemove', listRect.left + listRect.width / 2, listRect.top); fixture.detectChanges(); tickAnimationFrames(20); expect(list.scrollTop).toBeLessThan(initialScrollDistance); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 95870, "start_byte": 86319, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_95876_105117
it('should auto-scroll right if the user holds their pointer at right edge in ltr', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableHorizontalDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.first.element.nativeElement; const list = fixture.componentInstance.dropInstance.element.nativeElement; const listRect = list.getBoundingClientRect(); expect(list.scrollLeft).toBe(0); startDraggingViaMouse(fixture, item); dispatchMouseEvent( document, 'mousemove', listRect.left + listRect.width, listRect.top + listRect.height / 2, ); fixture.detectChanges(); tickAnimationFrames(20); expect(list.scrollLeft).toBeGreaterThan(0); })); it('should auto-scroll left if the user holds their pointer at left edge in ltr', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableHorizontalDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.first.element.nativeElement; const list = fixture.componentInstance.dropInstance.element.nativeElement; const listRect = list.getBoundingClientRect(); const initialScrollDistance = (list.scrollLeft = list.scrollWidth); startDraggingViaMouse(fixture, item); dispatchMouseEvent(document, 'mousemove', listRect.left, listRect.top + listRect.height / 2); fixture.detectChanges(); tickAnimationFrames(20); expect(list.scrollLeft).toBeLessThan(initialScrollDistance); })); it('should auto-scroll right if the user holds their pointer at right edge in rtl', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableHorizontalDropZone, { providers: [ { provide: Directionality, useValue: {value: 'rtl', change: observableOf()}, }, ], }); fixture.nativeElement.setAttribute('dir', 'rtl'); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.first.element.nativeElement; const list = fixture.componentInstance.dropInstance.element.nativeElement; const listRect = list.getBoundingClientRect(); const initialScrollDistance = (list.scrollLeft = -list.scrollWidth); startDraggingViaMouse(fixture, item); dispatchMouseEvent( document, 'mousemove', listRect.left + listRect.width, listRect.top + listRect.height / 2, ); fixture.detectChanges(); tickAnimationFrames(20); expect(list.scrollLeft).toBeGreaterThan(initialScrollDistance); })); it('should auto-scroll left if the user holds their pointer at left edge in rtl', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableHorizontalDropZone, { providers: [ { provide: Directionality, useValue: {value: 'rtl', change: observableOf()}, }, ], }); fixture.nativeElement.setAttribute('dir', 'rtl'); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.first.element.nativeElement; const list = fixture.componentInstance.dropInstance.element.nativeElement; const listRect = list.getBoundingClientRect(); expect(list.scrollLeft).toBe(0); startDraggingViaMouse(fixture, item); dispatchMouseEvent(document, 'mousemove', listRect.left, listRect.top + listRect.height / 2); fixture.detectChanges(); tickAnimationFrames(20); expect(list.scrollLeft).toBeLessThan(0); })); it('should be able to start auto scrolling with a drag boundary', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableHorizontalDropZone); fixture.componentInstance.boundarySelector = '.drop-list'; fixture.detectChanges(); const item = fixture.componentInstance.dragItems.first.element.nativeElement; const list = fixture.componentInstance.dropInstance.element.nativeElement; const listRect = list.getBoundingClientRect(); expect(list.scrollLeft).toBe(0); startDraggingViaMouse(fixture, item); dispatchMouseEvent( document, 'mousemove', listRect.left + listRect.width, listRect.top + listRect.height / 2, ); fixture.detectChanges(); tickAnimationFrames(20); expect(list.scrollLeft).toBeGreaterThan(0); })); it('should stop scrolling if the user moves their pointer away', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableVerticalDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.first.element.nativeElement; const list = fixture.componentInstance.dropInstance.element.nativeElement; const listRect = list.getBoundingClientRect(); expect(list.scrollTop).toBe(0); startDraggingViaMouse(fixture, item); dispatchMouseEvent( document, 'mousemove', listRect.left + listRect.width / 2, listRect.top + listRect.height, ); fixture.detectChanges(); tickAnimationFrames(20); const previousScrollTop = list.scrollTop; expect(previousScrollTop).toBeGreaterThan(0); // Move the pointer away from the edge of the element. dispatchMouseEvent( document, 'mousemove', listRect.left + listRect.width / 2, listRect.bottom + listRect.height / 2, ); fixture.detectChanges(); tickAnimationFrames(20); expect(list.scrollTop).toBe(previousScrollTop); })); it('should stop scrolling if the user stops dragging', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableVerticalDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.first.element.nativeElement; const list = fixture.componentInstance.dropInstance.element.nativeElement; const listRect = list.getBoundingClientRect(); expect(list.scrollTop).toBe(0); startDraggingViaMouse(fixture, item); dispatchMouseEvent( document, 'mousemove', listRect.left + listRect.width / 2, listRect.top + listRect.height, ); fixture.detectChanges(); tickAnimationFrames(20); const previousScrollTop = list.scrollTop; expect(previousScrollTop).toBeGreaterThan(0); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); tickAnimationFrames(20); flush(); fixture.detectChanges(); expect(list.scrollTop).toBe(previousScrollTop); })); it('should auto-scroll viewport down if the pointer is close to bottom edge', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const cleanup = makeScrollable(); const item = fixture.componentInstance.dragItems.first.element.nativeElement; const viewportRuler = TestBed.inject(ViewportRuler); const viewportSize = viewportRuler.getViewportSize(); expect(viewportRuler.getViewportScrollPosition().top).toBe(0); startDraggingViaMouse(fixture, item); dispatchMouseEvent(document, 'mousemove', viewportSize.width / 2, viewportSize.height); fixture.detectChanges(); tickAnimationFrames(20); expect(viewportRuler.getViewportScrollPosition().top).toBeGreaterThan(0); cleanup(); })); it('should auto-scroll viewport up if the pointer is close to top edge', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const cleanup = makeScrollable(); const item = fixture.componentInstance.dragItems.first.element.nativeElement; const viewportRuler = TestBed.inject(ViewportRuler); const viewportSize = viewportRuler.getViewportSize(); scrollTo(0, viewportSize.height * 5); const initialScrollDistance = viewportRuler.getViewportScrollPosition().top; expect(initialScrollDistance).toBeGreaterThan(0); startDraggingViaMouse(fixture, item); dispatchMouseEvent(document, 'mousemove', viewportSize.width / 2, 0); fixture.detectChanges(); tickAnimationFrames(20); expect(viewportRuler.getViewportScrollPosition().top).toBeLessThan(initialScrollDistance); cleanup(); })); it('should auto-scroll viewport right if the pointer is near right edge', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const cleanup = makeScrollable('horizontal'); const item = fixture.componentInstance.dragItems.first.element.nativeElement; const viewportRuler = TestBed.inject(ViewportRuler); const viewportSize = viewportRuler.getViewportSize(); expect(viewportRuler.getViewportScrollPosition().left).toBe(0); startDraggingViaMouse(fixture, item); dispatchMouseEvent(document, 'mousemove', viewportSize.width, viewportSize.height / 2); fixture.detectChanges(); tickAnimationFrames(20); expect(viewportRuler.getViewportScrollPosition().left).toBeGreaterThan(0); cleanup(); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 105117, "start_byte": 95876, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_105123_114686
it('should auto-scroll viewport left if the pointer is close to left edge', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const cleanup = makeScrollable('horizontal'); const item = fixture.componentInstance.dragItems.first.element.nativeElement; const viewportRuler = TestBed.inject(ViewportRuler); const viewportSize = viewportRuler.getViewportSize(); scrollTo(viewportSize.width * 5, 0); const initialScrollDistance = viewportRuler.getViewportScrollPosition().left; expect(initialScrollDistance).toBeGreaterThan(0); startDraggingViaMouse(fixture, item); dispatchMouseEvent(document, 'mousemove', 0, viewportSize.height / 2); fixture.detectChanges(); tickAnimationFrames(20); expect(viewportRuler.getViewportScrollPosition().left).toBeLessThan(initialScrollDistance); cleanup(); })); it('should auto-scroll the list, not the viewport, when the pointer is over the edge of both the list and the viewport', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableVerticalDropZone); fixture.detectChanges(); const list = fixture.componentInstance.dropInstance.element.nativeElement; const viewportRuler = TestBed.inject(ViewportRuler); const item = fixture.componentInstance.dragItems.first.element.nativeElement; // Position the list so that its top aligns with the viewport top. That way the pointer // will both over its top edge and the viewport's. We use top instead of bottom, because // bottom behaves weirdly when we run tests on mobile devices. list.style.position = 'fixed'; list.style.left = '50%'; list.style.top = '0'; list.style.margin = '0'; const listRect = list.getBoundingClientRect(); const cleanup = makeScrollable(); scrollTo(0, viewportRuler.getViewportSize().height * 5); list.scrollTop = 50; const initialScrollDistance = viewportRuler.getViewportScrollPosition().top; expect(initialScrollDistance).toBeGreaterThan(0); expect(list.scrollTop).toBe(50); startDraggingViaMouse(fixture, item); dispatchMouseEvent(document, 'mousemove', listRect.left + listRect.width / 2, 0); fixture.detectChanges(); tickAnimationFrames(20); expect(viewportRuler.getViewportScrollPosition().top).toBe(initialScrollDistance); expect(list.scrollTop).toBeLessThan(50); cleanup(); })); it('should auto-scroll the viewport, when the pointer is over the edge of both the list and the viewport, if the list cannot be scrolled in that direction', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableVerticalDropZone); fixture.detectChanges(); const list = fixture.componentInstance.dropInstance.element.nativeElement; const viewportRuler = TestBed.inject(ViewportRuler); const item = fixture.componentInstance.dragItems.first.element.nativeElement; // Position the list so that its top aligns with the viewport top. That way the pointer // will both over its top edge and the viewport's. We use top instead of bottom, because // bottom behaves weirdly when we run tests on mobile devices. list.style.position = 'fixed'; list.style.left = '50%'; list.style.top = '0'; list.style.margin = '0'; const listRect = list.getBoundingClientRect(); const cleanup = makeScrollable(); scrollTo(0, viewportRuler.getViewportSize().height * 5); list.scrollTop = 0; const initialScrollDistance = viewportRuler.getViewportScrollPosition().top; expect(initialScrollDistance).toBeGreaterThan(0); expect(list.scrollTop).toBe(0); startDraggingViaMouse(fixture, item); dispatchMouseEvent(document, 'mousemove', listRect.left + listRect.width / 2, 0); fixture.detectChanges(); tickAnimationFrames(20); expect(viewportRuler.getViewportScrollPosition().top).toBeLessThan(initialScrollDistance); expect(list.scrollTop).toBe(0); cleanup(); })); it('should be able to auto-scroll a parent container', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableParentContainer); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.first.element.nativeElement; const container = fixture.nativeElement.querySelector('.scroll-container'); const containerRect = container.getBoundingClientRect(); expect(container.scrollTop).toBe(0); startDraggingViaMouse(fixture, item); dispatchMouseEvent( document, 'mousemove', containerRect.left + containerRect.width / 2, containerRect.top + containerRect.height, ); fixture.detectChanges(); tickAnimationFrames(20); expect(container.scrollTop).toBeGreaterThan(0); })); it('should be able to configure the auto-scroll speed', fakeAsync(() => { const fixture = createComponent(DraggableInScrollableVerticalDropZone); fixture.detectChanges(); fixture.componentInstance.dropInstance.autoScrollStep = 20; const item = fixture.componentInstance.dragItems.first.element.nativeElement; const list = fixture.componentInstance.dropInstance.element.nativeElement; const listRect = list.getBoundingClientRect(); expect(list.scrollTop).toBe(0); startDraggingViaMouse(fixture, item); dispatchMouseEvent( document, 'mousemove', listRect.left + listRect.width / 2, listRect.top + listRect.height, ); fixture.detectChanges(); tickAnimationFrames(10); expect(list.scrollTop).toBeGreaterThan(100); })); it('should pick up descendants inside of containers', fakeAsync(() => { const fixture = createComponent(DraggableInDropZoneWithContainer); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; const firstItem = dragItems.first; const thirdItemRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect(); dragElementViaMouse( fixture, firstItem.element.nativeElement, thirdItemRect.left + 1, thirdItemRect.top + 1, ); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; // Assert the event like this, rather than `toHaveBeenCalledWith`, because Jasmine will // go into an infinite loop trying to stringify the event, if the test fails. expect(event).toEqual({ previousIndex: 0, currentIndex: 2, item: firstItem, container: fixture.componentInstance.dropInstance, previousContainer: fixture.componentInstance.dropInstance, isPointerOverContainer: true, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); })); it('should not pick up items from descendant drop lists', fakeAsync(() => { const fixture = createComponent(NestedDropZones); fixture.detectChanges(); const {dragItems, innerList, outerList} = fixture.componentInstance; const innerClasses = innerList.nativeElement.classList; const outerClasses = outerList.nativeElement.classList; const draggingClass = 'cdk-drop-list-dragging'; expect(innerClasses).not.toContain( draggingClass, 'Expected inner list to start off as not dragging.', ); expect(outerClasses).not.toContain( draggingClass, 'Expected outer list to start off as not dragging.', ); startDraggingViaMouse(fixture, dragItems.first.element.nativeElement); fixture.detectChanges(); expect(innerClasses) .withContext('Expected inner list to be dragging.') .toContain(draggingClass); expect(outerClasses).not.toContain(draggingClass, 'Expected outer list to not be dragging.'); })); it('should be able to re-enable a disabled drop list', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; const tryDrag = () => { const firstItem = dragItems.first; const thirdItemRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect(); dragElementViaMouse( fixture, firstItem.element.nativeElement, thirdItemRect.left + 1, thirdItemRect.top + 1, ); flush(); fixture.detectChanges(); }; expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); fixture.componentInstance.dropDisabled.set(true); fixture.detectChanges(); tryDrag(); expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); fixture.componentInstance.dropDisabled.set(false); fixture.detectChanges(); tryDrag(); expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'One', 'Two', 'Zero', 'Three', ]); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 114686, "start_byte": 105123, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_114692_123030
it('should be able to configure the drop input defaults through a provider', fakeAsync(() => { const config: DragDropConfig = { draggingDisabled: true, sortingDisabled: true, listAutoScrollDisabled: true, listOrientation: 'horizontal', lockAxis: 'y', }; const fixture = createComponent(PlainStandaloneDropList, { providers: [ { provide: CDK_DRAG_CONFIG, useValue: config, }, ], }); fixture.detectChanges(); const list = fixture.componentInstance.dropList; expect(list.disabled).toBe(true); expect(list.sortingDisabled).toBe(true); expect(list.autoScrollDisabled).toBe(true); expect(list.orientation).toBe('horizontal'); expect(list.lockAxis).toBe('y'); })); it('should disable scroll snapping while the user is dragging', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const styles: any = fixture.componentInstance.dropInstance.element.nativeElement.style; // This test only applies to browsers that support scroll snapping. if (!('scrollSnapType' in styles) && !('msScrollSnapType' in styles)) { return; } expect(styles.scrollSnapType || styles.msScrollSnapType).toBeFalsy(); startDraggingViaMouse(fixture, item); expect(styles.scrollSnapType || styles.msScrollSnapType).toBe('none'); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(styles.scrollSnapType || styles.msScrollSnapType).toBeFalsy(); })); it('should restore the previous inline scroll snap value', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; const styles: any = fixture.componentInstance.dropInstance.element.nativeElement.style; // This test only applies to browsers that support scroll snapping. if (!('scrollSnapType' in styles) && !('msScrollSnapType' in styles)) { return; } styles.scrollSnapType = styles.msScrollSnapType = 'block'; expect(styles.scrollSnapType || styles.msScrollSnapType).toBe('block'); startDraggingViaMouse(fixture, item); expect(styles.scrollSnapType || styles.msScrollSnapType).toBe('none'); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(styles.scrollSnapType || styles.msScrollSnapType).toBe('block'); })); it('should be able to start dragging again if the dragged item is destroyed', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); let item = fixture.componentInstance.dragItems.first; startDraggingViaMouse(fixture, item.element.nativeElement); expect(document.querySelector('.cdk-drop-list-dragging')) .withContext('Expected to drag initially.') .toBeTruthy(); fixture.componentInstance.items = [ {value: 'Five', height: ITEM_HEIGHT, margin: 0}, {value: 'Six', height: ITEM_HEIGHT, margin: 0}, ]; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).not.toHaveBeenCalled(); expect(document.querySelector('.cdk-drop-list-dragging')) .withContext('Expected not to be dragging after item is destroyed.') .toBeFalsy(); item = fixture.componentInstance.dragItems.first; startDraggingViaMouse(fixture, item.element.nativeElement); expect(document.querySelector('.cdk-drop-list-dragging')) .withContext('Expected to be able to start a new drag sequence.') .toBeTruthy(); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); })); it('should make the placeholder available in the start event', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement; let placeholder: HTMLElement | undefined; fixture.componentInstance.startedSpy.and.callFake((event: CdkDragStart) => { placeholder = event.source.getPlaceholderElement(); }); startDraggingViaMouse(fixture, item); expect(placeholder).toBeTruthy(); })); it('should not move item into position not allowed by the sort predicate', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const dragItems = fixture.componentInstance.dragItems; const spy = jasmine.createSpy('sort predicate spy').and.returnValue(false); fixture.componentInstance.dropInstance.sortPredicate = spy; expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); const firstItem = dragItems.first; const thirdItemRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect(); startDraggingViaMouse(fixture, firstItem.element.nativeElement); dispatchMouseEvent(document, 'mousemove', thirdItemRect.left + 1, thirdItemRect.top + 1); fixture.detectChanges(); expect(spy).toHaveBeenCalledWith(2, firstItem, fixture.componentInstance.dropInstance); expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim())).toEqual([ 'Zero', 'One', 'Two', 'Three', ]); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; // Assert the event like this, rather than `toHaveBeenCalledWith`, because Jasmine will // go into an infinite loop trying to stringify the event, if the test fails. expect(event).toEqual({ previousIndex: 0, currentIndex: 0, item: firstItem, container: fixture.componentInstance.dropInstance, previousContainer: fixture.componentInstance.dropInstance, isPointerOverContainer: jasmine.any(Boolean), distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); })); it('should not call the sort predicate for the same index', fakeAsync(() => { const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); const spy = jasmine.createSpy('sort predicate spy').and.returnValue(true); fixture.componentInstance.dropInstance.sortPredicate = spy; const item = fixture.componentInstance.dragItems.first.element.nativeElement; const itemRect = item.getBoundingClientRect(); startDraggingViaMouse(fixture, item); dispatchMouseEvent(document, 'mousemove', itemRect.left + 10, itemRect.top + 10); fixture.detectChanges(); expect(spy).not.toHaveBeenCalled(); })); it('should throw if drop list is attached to an ng-container', fakeAsync(() => { expect(() => { createComponent(DropListOnNgContainer).detectChanges(); flush(); }).toThrowError(/^cdkDropList must be attached to an element node/); })); it('should sort correctly if the <html> node has been offset', fakeAsync(() => { const documentElement = document.documentElement!; const fixture = createComponent(DraggableInDropZone); fixture.detectChanges(); documentElement.style.position = 'absolute'; documentElement.style.top = '100px'; assertStartToEndSorting( 'vertical', fixture, config.getSortedSiblings, fixture.componentInstance.dragItems.map(item => item.element.nativeElement), ); documentElement.style.position = ''; documentElement.style.top = ''; })); });
{ "commit_id": "ea0d1ba7b", "end_byte": 123030, "start_byte": 114692, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_123034_132559
describe('in a connected drop container', () => { it('should dispatch the `dropped` event when an item has been dropped into a new container', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const item = groups[0][1]; const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); dragElementViaMouse( fixture, item.element.nativeElement, targetRect.left + 1, targetRect.top + 1, ); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event).toEqual({ previousIndex: 1, currentIndex: 3, item, container: fixture.componentInstance.dropInstances.toArray()[1], previousContainer: fixture.componentInstance.dropInstances.first, isPointerOverContainer: true, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); })); it('should be able to move the element over a new container and return it', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const dropZones = fixture.componentInstance.dropInstances.map(d => d.element.nativeElement); const item = groups[0][1]; const initialRect = item.element.nativeElement.getBoundingClientRect(); const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); startDraggingViaMouse(fixture, item.element.nativeElement); const placeholder = dropZones[0].querySelector('.cdk-drag-placeholder')!; expect(placeholder).toBeTruthy(); expect(dropZones[0].contains(placeholder)) .withContext('Expected placeholder to be inside the first container.') .toBe(true); dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1); fixture.detectChanges(); expect(dropZones[1].contains(placeholder)) .withContext('Expected placeholder to be inside second container.') .toBe(true); dispatchMouseEvent(document, 'mousemove', initialRect.left + 1, initialRect.top + 1); fixture.detectChanges(); expect(dropZones[0].contains(placeholder)) .withContext('Expected placeholder to be back inside first container.') .toBe(true); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).not.toHaveBeenCalled(); })); it('should be able to move the element over a new container and return it to the initial one, even if it no longer matches the enterPredicate', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const dropZones = fixture.componentInstance.dropInstances.map(d => d.element.nativeElement); const item = groups[0][1]; const initialRect = item.element.nativeElement.getBoundingClientRect(); const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); fixture.componentInstance.dropInstances.first.enterPredicate = () => false; fixture.detectChanges(); startDraggingViaMouse(fixture, item.element.nativeElement); const placeholder = dropZones[0].querySelector('.cdk-drag-placeholder')!; expect(placeholder).toBeTruthy(); expect(dropZones[0].contains(placeholder)) .withContext('Expected placeholder to be inside the first container.') .toBe(true); dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1); fixture.detectChanges(); expect(dropZones[1].contains(placeholder)) .withContext('Expected placeholder to be inside second container.') .toBe(true); dispatchMouseEvent(document, 'mousemove', initialRect.left + 1, initialRect.top + 1); fixture.detectChanges(); expect(dropZones[0].contains(placeholder)) .withContext('Expected placeholder to be back inside first container.') .toBe(true); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).not.toHaveBeenCalled(); })); it('should transfer the DOM element from one drop zone to another', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems.slice(); const element = groups[0][1].element.nativeElement; const dropInstances = fixture.componentInstance.dropInstances.toArray(); const targetRect = groups[1][1].element.nativeElement.getBoundingClientRect(); // Use coordinates of [1] item corresponding to [2] item // after dragged item is removed from first container dragElementViaMouse(fixture, element, targetRect.left + 1, targetRect.top); flush(); fixture.detectChanges(); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event).toBeTruthy(); expect(event).toEqual({ previousIndex: 1, currentIndex: 2, // dragged item should replace the [2] item (see comment above) item: groups[0][1], container: dropInstances[1], previousContainer: dropInstances[0], isPointerOverContainer: true, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); })); it('should not be able to transfer an item into a container that is not in `connectedTo`', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.componentInstance.todoConnectedTo.set([]); fixture.componentInstance.doneConnectedTo.set([]); fixture.componentInstance.extraConnectedTo.set([]); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems.slice(); const element = groups[0][1].element.nativeElement; const dropInstances = fixture.componentInstance.dropInstances.toArray(); const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); dragElementViaMouse(fixture, element, targetRect.left + 1, targetRect.top + 1); flush(); fixture.detectChanges(); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event).toBeTruthy(); expect(event).toEqual({ previousIndex: 1, currentIndex: 1, item: groups[0][1], container: dropInstances[0], previousContainer: dropInstances[0], isPointerOverContainer: false, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); })); it('should not be able to transfer an item that does not match the `enterPredicate`', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); fixture.componentInstance.dropInstances.forEach(d => (d.enterPredicate = () => false)); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems.slice(); const element = groups[0][1].element.nativeElement; const dropInstances = fixture.componentInstance.dropInstances.toArray(); const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); dragElementViaMouse(fixture, element, targetRect.left + 1, targetRect.top + 1); flush(); fixture.detectChanges(); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event).toBeTruthy(); expect(event).toEqual({ previousIndex: 1, currentIndex: 1, item: groups[0][1], container: dropInstances[0], previousContainer: dropInstances[0], isPointerOverContainer: false, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); })); it('should call the `enterPredicate` with the item and the container it is entering', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const dropInstances = fixture.componentInstance.dropInstances.toArray(); const spy = jasmine.createSpy('enterPredicate spy').and.returnValue(true); const groups = fixture.componentInstance.groupedDragItems.slice(); const dragItem = groups[0][1]; const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); dropInstances[1].enterPredicate = spy; fixture.detectChanges(); dragElementViaMouse( fixture, dragItem.element.nativeElement, targetRect.left + 1, targetRect.top + 1, ); flush(); fixture.detectChanges(); expect(spy).toHaveBeenCalledWith(dragItem, dropInstances[1]); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 132559, "start_byte": 123034, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_132565_141513
it('should be able to start dragging after an item has been transferred', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const element = groups[0][1].element.nativeElement; const dropZone = fixture.componentInstance.dropInstances.toArray()[1].element.nativeElement; const targetRect = dropZone.getBoundingClientRect(); // Drag the element into the drop zone and move it to the top. [1, -1].forEach(offset => { dragElementViaMouse(fixture, element, targetRect.left + offset, targetRect.top + offset); flush(); fixture.detectChanges(); }); assertStartToEndSorting( 'vertical', fixture, config.getSortedSiblings, Array.from(dropZone.querySelectorAll('.cdk-drag')), ); })); it('should be able to return the last item inside its initial container', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); // Make sure there's only one item in the first list. fixture.componentInstance.todo = ['things']; fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const dropZones = fixture.componentInstance.dropInstances.map(d => d.element.nativeElement); const item = groups[0][0]; const initialRect = item.element.nativeElement.getBoundingClientRect(); const targetRect = groups[1][0].element.nativeElement.getBoundingClientRect(); startDraggingViaMouse(fixture, item.element.nativeElement); const placeholder = dropZones[0].querySelector('.cdk-drag-placeholder')!; expect(placeholder).toBeTruthy(); expect(dropZones[0].contains(placeholder)) .withContext('Expected placeholder to be inside the first container.') .toBe(true); dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1); fixture.detectChanges(); expect(dropZones[1].contains(placeholder)) .withContext('Expected placeholder to be inside second container.') .toBe(true); dispatchMouseEvent(document, 'mousemove', initialRect.left + 1, initialRect.top + 1); fixture.detectChanges(); expect(dropZones[0].contains(placeholder)) .withContext('Expected placeholder to be back inside first container.') .toBe(true); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).not.toHaveBeenCalled(); })); it('should update drop zone after element has entered', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); // Make sure there's only one item in the first list. fixture.componentInstance.todo = ['things']; fixture.detectChanges(); const dropInstances = fixture.componentInstance.dropInstances.toArray(); const groups = fixture.componentInstance.groupedDragItems; const dropZones = dropInstances.map(d => d.element.nativeElement); const item = groups[0][0]; const initialTargetZoneRect = dropZones[1].getBoundingClientRect(); const targetElement = groups[1][groups[1].length - 1].element.nativeElement; let targetRect = targetElement.getBoundingClientRect(); startDraggingViaMouse(fixture, item.element.nativeElement); const placeholder = dropZones[0].querySelector('.cdk-drag-placeholder')!; expect(placeholder).toBeTruthy(); dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1); fixture.detectChanges(); expect(targetElement.previousSibling === placeholder) .withContext('Expected placeholder to be inside second container before last item.') .toBe(true); // Update target rect targetRect = targetElement.getBoundingClientRect(); expect(initialTargetZoneRect.bottom <= targetRect.top) .withContext('Expected target rect to be outside of initial target zone rect') .toBe(true); // Swap with target dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.bottom - 1); fixture.detectChanges(); // Drop and verify item drop positon and coontainer dispatchMouseEvent(document, 'mouseup', targetRect.left + 1, targetRect.bottom - 1); flush(); fixture.detectChanges(); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event).toBeTruthy(); expect(event).toEqual({ previousIndex: 0, currentIndex: 3, item: item, container: dropInstances[1], previousContainer: dropInstances[0], isPointerOverContainer: true, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); })); it('should enter as first child if entering from top', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); // Make sure there's only one item in the first list. fixture.componentInstance.todo = ['things']; fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const dropZones = fixture.componentInstance.dropInstances.map(d => d.element.nativeElement); const item = groups[0][0]; // Add some initial padding as the target drop zone dropZones[1].style.paddingTop = '10px'; const targetRect = dropZones[1].getBoundingClientRect(); startDraggingViaMouse(fixture, item.element.nativeElement); const placeholder = dropZones[0].querySelector('.cdk-drag-placeholder')!; expect(placeholder).toBeTruthy(); expect(dropZones[0].contains(placeholder)) .withContext('Expected placeholder to be inside the first container.') .toBe(true); dispatchMouseEvent(document, 'mousemove', targetRect.left, targetRect.top); fixture.detectChanges(); expect(dropZones[1].firstElementChild === placeholder) .withContext('Expected placeholder to be first child inside second container.') .toBe(true); dispatchMouseEvent(document, 'mouseup'); })); it('should not throw when entering from the top with an intermediate sibling present', fakeAsync(() => { const fixture = createComponent(ConnectedDropZonesWithIntermediateSibling); // Make sure there's only one item in the first list. fixture.componentInstance.todo = ['things']; fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const dropZones = fixture.componentInstance.dropInstances.map(d => d.element.nativeElement); const item = groups[0][0]; // Add some initial padding as the target drop zone dropZones[1].style.paddingTop = '10px'; const targetRect = dropZones[1].getBoundingClientRect(); expect(() => { dragElementViaMouse(fixture, item.element.nativeElement, targetRect.left, targetRect.top); flush(); fixture.detectChanges(); }).not.toThrow(); })); it('should assign a default id on each drop zone', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); expect( fixture.componentInstance.dropInstances.toArray().every(dropZone => { return !!dropZone.id && !!dropZone.element.nativeElement.getAttribute('id'); }), ).toBe(true); })); it('should be able to connect two drop zones by id', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const [todoDropInstance, doneDropInstance] = fixture.componentInstance.dropInstances.toArray(); fixture.componentInstance.todoConnectedTo.set([doneDropInstance.id]); fixture.componentInstance.doneConnectedTo.set([todoDropInstance.id]); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const element = groups[0][1].element.nativeElement; const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); dragElementViaMouse(fixture, element, targetRect.left + 1, targetRect.top + 1); flush(); fixture.detectChanges(); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event).toBeTruthy(); expect(event).toEqual({ previousIndex: 1, currentIndex: 3, item: groups[0][1], container: doneDropInstance, previousContainer: todoDropInstance, isPointerOverContainer: true, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 141513, "start_byte": 132565, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_141519_151113
it('should be able to connect two drop zones using the drop list group', fakeAsync(() => { const fixture = createComponent(ConnectedDropZonesViaGroupDirective); fixture.detectChanges(); const dropInstances = fixture.componentInstance.dropInstances.toArray(); const groups = fixture.componentInstance.groupedDragItems; const element = groups[0][1].element.nativeElement; const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); dragElementViaMouse(fixture, element, targetRect.left + 1, targetRect.top + 1); flush(); fixture.detectChanges(); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event).toBeTruthy(); expect(event).toEqual({ previousIndex: 1, currentIndex: 3, item: groups[0][1], container: dropInstances[1], previousContainer: dropInstances[0], isPointerOverContainer: true, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); })); it('should be able to pass a single id to `connectedTo`', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const [todoDropInstance, doneDropInstance] = fixture.componentInstance.dropInstances.toArray(); fixture.componentInstance.todoConnectedTo.set([doneDropInstance.id]); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const element = groups[0][1].element.nativeElement; const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); dragElementViaMouse(fixture, element, targetRect.left + 1, targetRect.top + 1); flush(); fixture.detectChanges(); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event).toBeTruthy(); expect(event).toEqual({ previousIndex: 1, currentIndex: 3, item: groups[0][1], container: doneDropInstance, previousContainer: todoDropInstance, isPointerOverContainer: true, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); })); it('should return DOM element to its initial container after it is dropped, in a container with one draggable item', fakeAsync(() => { const fixture = createComponent(ConnectedDropZonesWithSingleItems); fixture.detectChanges(); const items = fixture.componentInstance.dragItems.toArray(); const item = items[0]; const targetRect = items[1].element.nativeElement.getBoundingClientRect(); const dropContainers = fixture.componentInstance.dropInstances.map( drop => drop.element.nativeElement, ); expect(dropContainers[0].contains(item.element.nativeElement)) .withContext('Expected DOM element to be in first container') .toBe(true); expect(item.dropContainer) .withContext('Expected CdkDrag to be in first container in memory') .toBe(fixture.componentInstance.dropInstances.first); dragElementViaMouse( fixture, item.element.nativeElement, targetRect.left + 1, targetRect.top + 1, ); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event).toEqual({ previousIndex: 0, currentIndex: 0, item, container: fixture.componentInstance.dropInstances.toArray()[1], previousContainer: fixture.componentInstance.dropInstances.first, isPointerOverContainer: true, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); expect(dropContainers[0].contains(item.element.nativeElement)) .withContext('Expected DOM element to be returned to first container') .toBe(true); expect(item.dropContainer) .withContext('Expected CdkDrag to be returned to first container in memory') .toBe(fixture.componentInstance.dropInstances.first); })); it('should be able to return an element to its initial container in the same sequence, even if it is not connected to the current container', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const [todoDropInstance, doneDropInstance] = fixture.componentInstance.dropInstances.toArray(); const todoZone = todoDropInstance.element.nativeElement; const doneZone = doneDropInstance.element.nativeElement; const item = groups[0][1]; const initialRect = item.element.nativeElement.getBoundingClientRect(); const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); // Change the `connectedTo` so the containers are only connected one-way. fixture.componentInstance.todoConnectedTo.set([doneDropInstance]); fixture.componentInstance.doneConnectedTo.set([]); fixture.detectChanges(); startDraggingViaMouse(fixture, item.element.nativeElement); fixture.detectChanges(); const placeholder = todoZone.querySelector('.cdk-drag-placeholder')!; expect(placeholder).toBeTruthy(); expect(todoZone.contains(placeholder)) .withContext('Expected placeholder to be inside the first container.') .toBe(true); dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1); fixture.detectChanges(); expect(doneZone.contains(placeholder)) .withContext('Expected placeholder to be inside second container.') .toBe(true); dispatchMouseEvent(document, 'mousemove', initialRect.left + 1, initialRect.top + 1); fixture.detectChanges(); expect(todoZone.contains(placeholder)) .withContext('Expected placeholder to be back inside first container.') .toBe(true); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).not.toHaveBeenCalled(); })); it('should not add child drop lists to the same group as their parents', fakeAsync(() => { const fixture = createComponent(NestedDropListGroups); const component = fixture.componentInstance; fixture.detectChanges(); expect(Array.from(component.group._items)).toEqual([component.listOne, component.listTwo]); })); it('should not be able to drop an element into a container that is under another element', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems.slice(); const element = groups[0][1].element.nativeElement; const dropInstances = fixture.componentInstance.dropInstances.toArray(); const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); const coverElement = document.createElement('div'); const targetGroupRect = dropInstances[1].element.nativeElement.getBoundingClientRect(); // Add an extra element that covers the target container. fixture.nativeElement.appendChild(coverElement); extendStyles(coverElement.style, { position: 'fixed', top: targetGroupRect.top + 'px', left: targetGroupRect.left + 'px', bottom: targetGroupRect.bottom + 'px', right: targetGroupRect.right + 'px', background: 'orange', }); dragElementViaMouse(fixture, element, targetRect.left + 1, targetRect.top + 1); flush(); fixture.detectChanges(); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event).toBeTruthy(); expect(event).toEqual({ previousIndex: 1, currentIndex: 1, item: groups[0][1], container: dropInstances[0], previousContainer: dropInstances[0], isPointerOverContainer: false, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); })); it('should set a class when a container can receive an item', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const dropZones = fixture.componentInstance.dropInstances.map(d => d.element.nativeElement); const item = fixture.componentInstance.groupedDragItems[0][1]; expect(dropZones.every(c => !c.classList.contains('cdk-drop-list-receiving'))) .withContext('Expected neither of the containers to have the class.') .toBe(true); startDraggingViaMouse(fixture, item.element.nativeElement); fixture.detectChanges(); expect(dropZones[0].classList).not.toContain( 'cdk-drop-list-receiving', 'Expected source container not to have the receiving class.', ); expect(dropZones[1].classList) .withContext('Expected target container to have the receiving class.') .toContain('cdk-drop-list-receiving'); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 151113, "start_byte": 141519, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_151119_158895
it('should toggle the `receiving` class when the item enters a new list', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const dropZones = fixture.componentInstance.dropInstances.map(d => d.element.nativeElement); const item = groups[0][1]; const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); expect(dropZones.every(c => !c.classList.contains('cdk-drop-list-receiving'))) .withContext('Expected neither of the containers to have the class.') .toBe(true); startDraggingViaMouse(fixture, item.element.nativeElement); expect(dropZones[0].classList).not.toContain( 'cdk-drop-list-receiving', 'Expected source container not to have the receiving class.', ); expect(dropZones[1].classList) .withContext('Expected target container to have the receiving class.') .toContain('cdk-drop-list-receiving'); dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1); fixture.detectChanges(); expect(dropZones[0].classList) .withContext('Expected old container to have the receiving class after exiting.') .toContain('cdk-drop-list-receiving'); expect(dropZones[1].classList) .not.withContext('Expected new container not to have the receiving class after exiting.') .toContain('cdk-drop-list-receiving'); })); it('should not set the receiving class if the item does not match the enter predicate', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); fixture.componentInstance.dropInstances.toArray()[1].enterPredicate = () => false; const dropZones = fixture.componentInstance.dropInstances.map(d => d.element.nativeElement); const item = fixture.componentInstance.groupedDragItems[0][1]; expect(dropZones.every(c => !c.classList.contains('cdk-drop-list-receiving'))) .withContext('Expected neither of the containers to have the class.') .toBe(true); startDraggingViaMouse(fixture, item.element.nativeElement); fixture.detectChanges(); expect(dropZones.every(c => !c.classList.contains('cdk-drop-list-receiving'))) .withContext('Expected neither of the containers to have the class.') .toBe(true); })); it('should set the receiving class on the source container, even if the enter predicate does not match', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); fixture.componentInstance.dropInstances.toArray()[0].enterPredicate = () => false; const groups = fixture.componentInstance.groupedDragItems; const dropZones = fixture.componentInstance.dropInstances.map(d => d.element.nativeElement); const item = groups[0][1]; const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); expect(dropZones.every(c => !c.classList.contains('cdk-drop-list-receiving'))) .withContext('Expected neither of the containers to have the class.') .toBe(true); startDraggingViaMouse(fixture, item.element.nativeElement); expect(dropZones[0].classList) .not.withContext('Expected source container not to have the receiving class.') .toContain('cdk-drop-list-receiving'); expect(dropZones[1].classList) .withContext('Expected target container to have the receiving class.') .toContain('cdk-drop-list-receiving'); dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1); fixture.detectChanges(); expect(dropZones[0].classList) .withContext('Expected old container to have the receiving class after exiting.') .toContain('cdk-drop-list-receiving'); expect(dropZones[1].classList).not.toContain( 'cdk-drop-list-receiving', 'Expected new container not to have the receiving class after exiting.', ); })); it('should set the receiving class when the list is wrapped in an OnPush component', fakeAsync(() => { const fixture = createComponent(ConnectedDropListsInOnPush); fixture.detectChanges(); const dropZones = Array.from<HTMLElement>( fixture.nativeElement.querySelectorAll('.cdk-drop-list'), ); const item = dropZones[0].querySelector('.cdk-drag')!; expect(dropZones.every(c => !c.classList.contains('cdk-drop-list-receiving'))) .withContext('Expected neither of the containers to have the class.') .toBe(true); startDraggingViaMouse(fixture, item); fixture.detectChanges(); expect(dropZones[0].classList) .withContext('Expected source container not to have the receiving class.') .not.toContain('cdk-drop-list-receiving'); expect(dropZones[1].classList) .withContext('Expected target container to have the receiving class.') .toContain('cdk-drop-list-receiving'); })); it('should be able to move the item over an intermediate container before dropping it into the final one', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const [todoDropInstance, doneDropInstance, extraDropInstance] = fixture.componentInstance.dropInstances.toArray(); fixture.componentInstance.todoConnectedTo.set([doneDropInstance, extraDropInstance]); fixture.componentInstance.doneConnectedTo.set([]); fixture.componentInstance.extraConnectedTo.set([]); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const todoZone = todoDropInstance.element.nativeElement; const doneZone = doneDropInstance.element.nativeElement; const extraZone = extraDropInstance.element.nativeElement; const item = groups[0][1]; const intermediateRect = doneZone.getBoundingClientRect(); const finalRect = extraZone.getBoundingClientRect(); startDraggingViaMouse(fixture, item.element.nativeElement); const placeholder = todoZone.querySelector('.cdk-drag-placeholder')!; expect(placeholder).toBeTruthy(); expect(todoZone.contains(placeholder)) .withContext('Expected placeholder to be inside the first container.') .toBe(true); dispatchMouseEvent( document, 'mousemove', intermediateRect.left + 1, intermediateRect.top + 1, ); fixture.detectChanges(); expect(doneZone.contains(placeholder)) .withContext('Expected placeholder to be inside second container.') .toBe(true); dispatchMouseEvent(document, 'mousemove', finalRect.left + 1, finalRect.top + 1); fixture.detectChanges(); expect(extraZone.contains(placeholder)) .withContext('Expected placeholder to be inside third container.') .toBe(true); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); fixture.detectChanges(); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event).toBeTruthy(); expect(event).toEqual( jasmine.objectContaining({ previousIndex: 1, currentIndex: 0, item: groups[0][1], container: extraDropInstance, previousContainer: todoDropInstance, isPointerOverContainer: false, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }), ); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 158895, "start_byte": 151119, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_158901_168476
it('should not be able to move an item into a drop container that the initial container is not connected to by passing it over an intermediate one that is', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const [todoDropInstance, doneDropInstance, extraDropInstance] = fixture.componentInstance.dropInstances.toArray(); fixture.componentInstance.todoConnectedTo.set([doneDropInstance]); fixture.componentInstance.doneConnectedTo.set([todoDropInstance, extraDropInstance]); fixture.componentInstance.extraConnectedTo.set([doneDropInstance]); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const todoZone = todoDropInstance.element.nativeElement; const doneZone = doneDropInstance.element.nativeElement; const extraZone = extraDropInstance.element.nativeElement; const item = groups[0][1]; const intermediateRect = doneZone.getBoundingClientRect(); const finalRect = extraZone.getBoundingClientRect(); startDraggingViaMouse(fixture, item.element.nativeElement); const placeholder = todoZone.querySelector('.cdk-drag-placeholder')!; expect(placeholder).toBeTruthy(); expect(todoZone.contains(placeholder)) .withContext('Expected placeholder to be inside the first container.') .toBe(true); dispatchMouseEvent( document, 'mousemove', intermediateRect.left + 1, intermediateRect.top + 1, ); fixture.detectChanges(); expect(doneZone.contains(placeholder)) .withContext('Expected placeholder to be inside second container.') .toBe(true); dispatchMouseEvent(document, 'mousemove', finalRect.left + 1, finalRect.top + 1); fixture.detectChanges(); expect(doneZone.contains(placeholder)) .withContext('Expected placeholder to remain in the second container.') .toBe(true); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); fixture.detectChanges(); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event).toBeTruthy(); expect(event).toEqual( jasmine.objectContaining({ previousIndex: 1, currentIndex: 1, item: groups[0][1], container: doneDropInstance, previousContainer: todoDropInstance, isPointerOverContainer: false, }), ); })); it('should return the item to its initial position, if sorting in the source container was disabled', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const dropZones = fixture.componentInstance.dropInstances.map(d => d.element.nativeElement); const item = groups[0][1]; const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); fixture.componentInstance.dropInstances.first.sortingDisabled = true; startDraggingViaMouse(fixture, item.element.nativeElement); const placeholder = dropZones[0].querySelector('.cdk-drag-placeholder')!; expect(placeholder).toBeTruthy(); expect(dropZones[0].contains(placeholder)) .withContext('Expected placeholder to be inside the first container.') .toBe(true); expect(config.getSortedSiblings(placeholder, 'top').indexOf(placeholder)) .withContext('Expected placeholder to be at item index.') .toBe(1); dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1); fixture.detectChanges(); expect(dropZones[1].contains(placeholder)) .withContext('Expected placeholder to be inside second container.') .toBe(true); expect(config.getSortedSiblings(placeholder, 'top').indexOf(placeholder)) .withContext('Expected placeholder to be at the target index.') .toBe(3); const firstInitialSiblingRect = groups[0][0].element.nativeElement.getBoundingClientRect(); // Return the item to an index that is different from the initial one. dispatchMouseEvent( document, 'mousemove', firstInitialSiblingRect.left + 1, firstInitialSiblingRect.top + 1, ); fixture.detectChanges(); expect(dropZones[0].contains(placeholder)) .withContext('Expected placeholder to be back inside first container.') .toBe(true); expect(config.getSortedSiblings(placeholder, 'top').indexOf(placeholder)) .withContext('Expected placeholder to be back at the initial index.') .toBe(1); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).not.toHaveBeenCalled(); })); it('should enter an item into the correct index when returning to the initial container, if sorting is enabled', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const dropZones = fixture.componentInstance.dropInstances.map(d => d.element.nativeElement); const item = groups[0][1]; const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); // Explicitly enable just in case. fixture.componentInstance.dropInstances.first.sortingDisabled = false; startDraggingViaMouse(fixture, item.element.nativeElement); const placeholder = dropZones[0].querySelector('.cdk-drag-placeholder')!; expect(placeholder).toBeTruthy(); expect(dropZones[0].contains(placeholder)) .withContext('Expected placeholder to be inside the first container.') .toBe(true); expect(config.getSortedSiblings(placeholder, 'top').indexOf(placeholder)) .withContext('Expected placeholder to be at item index.') .toBe(1); dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1); fixture.detectChanges(); expect(dropZones[1].contains(placeholder)) .withContext('Expected placeholder to be inside second container.') .toBe(true); expect(config.getSortedSiblings(placeholder, 'top').indexOf(placeholder)) .withContext('Expected placeholder to be at the target index.') .toBe(3); const nextTargetRect = groups[0][3].element.nativeElement.getBoundingClientRect(); // Return the item to an index that is different from the initial one. dispatchMouseEvent(document, 'mousemove', nextTargetRect.left + 1, nextTargetRect.top + 1); fixture.detectChanges(); expect(dropZones[0].contains(placeholder)) .withContext('Expected placeholder to be back inside first container.') .toBe(true); expect(config.getSortedSiblings(placeholder, 'top').indexOf(placeholder)) .withContext('Expected placeholder to be at the index at which it entered.') .toBe(2); })); it('should return the last item to initial position when dragging back into a container with disabled sorting', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const dropZones = fixture.componentInstance.dropInstances.map(d => d.element.nativeElement); const lastIndex = groups[0].length - 1; const lastItem = groups[0][lastIndex]; const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); fixture.componentInstance.dropInstances.first.sortingDisabled = true; startDraggingViaMouse(fixture, lastItem.element.nativeElement); const placeholder = dropZones[0].querySelector('.cdk-drag-placeholder')!; expect(placeholder).toBeTruthy(); expect(dropZones[0].contains(placeholder)) .withContext('Expected placeholder to be inside the first container.') .toBe(true); expect(config.getSortedSiblings(placeholder, 'top').indexOf(placeholder)) .withContext('Expected placeholder to be at item index.') .toBe(lastIndex); dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1); fixture.detectChanges(); expect(dropZones[1].contains(placeholder)) .withContext('Expected placeholder to be inside second container.') .toBe(true); expect(config.getSortedSiblings(placeholder, 'top').indexOf(placeholder)) .withContext('Expected placeholder to be at the target index.') .toBe(3); const firstInitialSiblingRect = groups[0][0].element.nativeElement.getBoundingClientRect(); // Return the item to an index that is different from the initial one. dispatchMouseEvent( document, 'mousemove', firstInitialSiblingRect.left, firstInitialSiblingRect.top, ); fixture.detectChanges(); expect(dropZones[0].contains(placeholder)) .withContext('Expected placeholder to be back inside first container.') .toBe(true); expect(config.getSortedSiblings(placeholder, 'top').indexOf(placeholder)) .withContext('Expected placeholder to be back at the initial index.') .toBe(lastIndex); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).not.toHaveBeenCalled(); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 168476, "start_byte": 158901, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_168482_177505
it('should toggle a class when dragging an item inside a wrapper component component with OnPush change detection', fakeAsync(() => { const fixture = createComponent(ConnectedWrappedDropZones); fixture.detectChanges(); const [startZone, targetZone] = fixture.nativeElement.querySelectorAll('.cdk-drop-list'); const item = startZone.querySelector('.cdk-drag'); const targetRect = targetZone.getBoundingClientRect(); expect(startZone.classList).not.toContain( 'cdk-drop-list-dragging', 'Expected start not to have dragging class on init.', ); expect(targetZone.classList).not.toContain( 'cdk-drop-list-dragging', 'Expected target not to have dragging class on init.', ); startDraggingViaMouse(fixture, item); expect(startZone.classList) .withContext('Expected start to have dragging class after dragging has started.') .toContain('cdk-drop-list-dragging'); expect(targetZone.classList) .not.withContext('Expected target not to have dragging class after dragging has started.') .toContain('cdk-drop-list-dragging'); dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1); fixture.detectChanges(); expect(startZone.classList) .not.withContext('Expected start not to have dragging class once item has been moved over.') .toContain('cdk-drop-list-dragging'); expect(targetZone.classList) .withContext('Expected target to have dragging class once item has been moved over.') .toContain('cdk-drop-list-dragging'); })); it('should dispatch an event when an item enters a new container', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const item = groups[0][1]; const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); startDraggingViaMouse(fixture, item.element.nativeElement); dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1); fixture.detectChanges(); const containerEnterEvent = fixture.componentInstance.enteredSpy.calls.mostRecent().args[0]; const itemEnterEvent = fixture.componentInstance.itemEnteredSpy.calls.mostRecent().args[0]; const expectedEvent: CdkDragEnter = { container: fixture.componentInstance.dropInstances.toArray()[1], item: item, currentIndex: 2, }; expect(containerEnterEvent).toEqual(expectedEvent); expect(itemEnterEvent).toEqual(expectedEvent); })); it('should not throw if dragging was interrupted as a result of the entered event', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const item = groups[0][1]; const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); fixture.componentInstance.enteredSpy.and.callFake(() => { fixture.componentInstance.todo = []; fixture.detectChanges(); }); expect(() => { dragElementViaMouse( fixture, item.element.nativeElement, targetRect.left + 1, targetRect.top + 1, ); flush(); fixture.detectChanges(); }).not.toThrow(); })); it('should be able to drop into a new container after scrolling into view', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); // Make the page scrollable and scroll the items out of view. const cleanup = makeScrollable(); scrollTo(0, 0); dispatchFakeEvent(document, 'scroll'); fixture.detectChanges(); flush(); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const item = groups[0][1]; // Start dragging and then scroll the elements back into view. startDraggingViaMouse(fixture, item.element.nativeElement); scrollTo(0, 5000); dispatchFakeEvent(document, 'scroll'); const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1); dispatchMouseEvent(document, 'mouseup', targetRect.left + 1, targetRect.top + 1); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event).toEqual({ previousIndex: 1, currentIndex: 3, item, container: fixture.componentInstance.dropInstances.toArray()[1], previousContainer: fixture.componentInstance.dropInstances.first, isPointerOverContainer: true, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); cleanup(); })); it('should be able to drop into a new container inside the Shadow DOM', fakeAsync(() => { // This test is only relevant for Shadow DOM-supporting browsers. if (!_supportsShadowDom()) { return; } const fixture = createComponent(ConnectedDropZones, { encapsulation: ViewEncapsulation.ShadowDom, }); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const item = groups[0][1]; const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); dragElementViaMouse( fixture, item.element.nativeElement, targetRect.left + 1, targetRect.top + 1, ); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event).toEqual({ previousIndex: 1, currentIndex: 3, item, container: fixture.componentInstance.dropInstances.toArray()[1], previousContainer: fixture.componentInstance.dropInstances.first, isPointerOverContainer: true, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); })); it('should be able to drop into a new container inside the Shadow DOM and ngIf', fakeAsync(() => { // This test is only relevant for Shadow DOM-supporting browsers. if (!_supportsShadowDom()) { return; } const fixture = createComponent(ConnectedDropZonesInsideShadowRootWithNgIf); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const item = groups[0][1]; const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect(); dragElementViaMouse( fixture, item.element.nativeElement, targetRect.left + 1, targetRect.top + 1, ); flush(); fixture.detectChanges(); expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1); const event = fixture.componentInstance.droppedSpy.calls.mostRecent().args[0]; expect(event).toEqual({ previousIndex: 1, currentIndex: 3, item, container: fixture.componentInstance.dropInstances.toArray()[1], previousContainer: fixture.componentInstance.dropInstances.first, isPointerOverContainer: true, distance: {x: jasmine.any(Number), y: jasmine.any(Number)}, dropPoint: {x: jasmine.any(Number), y: jasmine.any(Number)}, event: jasmine.anything(), }); })); it('should prevent selection at the shadow root level', fakeAsync(() => { // This test is only relevant for Shadow DOM-supporting browsers. if (!_supportsShadowDom()) { return; } const fixture = createComponent(ConnectedDropZones, { encapsulation: ViewEncapsulation.ShadowDom, }); fixture.detectChanges(); const shadowRoot = fixture.nativeElement.shadowRoot; const item = fixture.componentInstance.groupedDragItems[0][1]; startDraggingViaMouse(fixture, item.element.nativeElement); fixture.detectChanges(); const initialSelectStart = dispatchFakeEvent(shadowRoot, 'selectstart'); fixture.detectChanges(); expect(initialSelectStart.defaultPrevented).toBe(true); dispatchMouseEvent(document, 'mouseup'); fixture.detectChanges(); flush(); const afterDropSelectStart = dispatchFakeEvent(shadowRoot, 'selectstart'); fixture.detectChanges(); expect(afterDropSelectStart.defaultPrevented).toBe(false); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 177505, "start_byte": 168482, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_177511_186518
it('should not throw if its next sibling is removed while dragging', fakeAsync(() => { const fixture = createComponent(ConnectedDropZonesWithSingleItems); fixture.detectChanges(); const items = fixture.componentInstance.dragItems.toArray(); const item = items[0]; const nextSibling = items[1].element.nativeElement; const extraSibling = document.createElement('div'); const targetRect = nextSibling.getBoundingClientRect(); // Manually insert an element after the node to simulate an external package. nextSibling.parentNode!.insertBefore(extraSibling, nextSibling); dragElementViaMouse( fixture, item.element.nativeElement, targetRect.left + 1, targetRect.top + 1, ); // Remove the extra node after the element was dropped, but before the animation is over. extraSibling.remove(); expect(() => { flush(); fixture.detectChanges(); }).not.toThrow(); })); it('should warn when the connected container ID does not exist', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); fixture.componentInstance.todoConnectedTo.set(['does-not-exist']); fixture.detectChanges(); const groups = fixture.componentInstance.groupedDragItems; const element = groups[0][1].element.nativeElement; spyOn(console, 'warn'); dragElementViaMouse(fixture, element, 0, 0); flush(); fixture.detectChanges(); expect(console.warn).toHaveBeenCalledWith( `CdkDropList could not find connected drop ` + `list with id "does-not-exist"`, ); })); it('should not be able to start a drag sequence while a connected container is active', fakeAsync(() => { const fixture = createComponent(ConnectedDropZones); fixture.detectChanges(); const item = fixture.componentInstance.groupedDragItems[0][0]; const itemInOtherList = fixture.componentInstance.groupedDragItems[1][0]; startDraggingViaMouse(fixture, item.element.nativeElement); expect(document.querySelectorAll('.cdk-drag-dragging').length) .withContext('Expected one item to be dragged initially.') .toBe(1); startDraggingViaMouse(fixture, itemInOtherList.element.nativeElement); expect(document.querySelectorAll('.cdk-drag-dragging').length) .withContext('Expected only one item to continue to be dragged.') .toBe(1); })); it('should insert the preview inside the shadow root by default', fakeAsync(() => { // This test is only relevant for Shadow DOM-supporting browsers. if (!_supportsShadowDom()) { return; } const fixture = createComponent(ConnectedDropZones, { encapsulation: ViewEncapsulation.ShadowDom, }); fixture.detectChanges(); const item = fixture.componentInstance.groupedDragItems[0][1]; startDraggingViaMouse(fixture, item.element.nativeElement); fixture.detectChanges(); // `querySelector` doesn't descend into the shadow DOM so we can assert that the preview // isn't at its default location by searching for it at the `document` level. expect(document.querySelector('.cdk-drag-preview')).toBeFalsy(); })); }); describe('with nested drags', () => { it('should not move draggable container when dragging child (multitouch)', fakeAsync(() => { const fixture = createComponent(NestedDragsComponent, {dragDistance: 10}); fixture.detectChanges(); // First finger drags container (less then threshold) startDraggingViaTouch(fixture, fixture.componentInstance.container.nativeElement); continueDraggingViaTouch(fixture, 2, 0); // Second finger drags container startDraggingViaTouch(fixture, fixture.componentInstance.container.nativeElement); continueDraggingViaTouch(fixture, 0, 10); continueDraggingViaTouch(fixture, 0, 20); // First finger releases stopDraggingViaTouch(fixture, 0, 20); // Second finger releases stopDraggingViaTouch(fixture, 0, 10); // Container spies worked const containerDragStartedCount = fixture.componentInstance.containerDragStartedSpy.calls.count(); const containerDragMovedCount = fixture.componentInstance.containerDragMovedSpy.calls.count(); const containerDragReleasedCount = fixture.componentInstance.containerDragReleasedSpy.calls.count(); expect(containerDragStartedCount).toBeGreaterThan(0); expect(containerDragMovedCount).toBeGreaterThan(0); expect(containerDragReleasedCount).toBeGreaterThan(0); // Drag item startDraggingViaTouch(fixture, fixture.componentInstance.item.nativeElement); continueDraggingViaTouch(fixture, 20, 20); continueDraggingViaTouch(fixture, 40, 40); stopDraggingViaTouch(fixture, 60, 60); // Spies on item worked expect(fixture.componentInstance.itemDragStartedSpy).toHaveBeenCalledTimes(1); expect(fixture.componentInstance.itemDragMovedSpy).toHaveBeenCalledTimes(1); expect(fixture.componentInstance.itemDragReleasedSpy).toHaveBeenCalledTimes(1); // Spies on container stay intact expect(fixture.componentInstance.containerDragStartedSpy).toHaveBeenCalledTimes( containerDragStartedCount, ); expect(fixture.componentInstance.containerDragMovedSpy).toHaveBeenCalledTimes( containerDragMovedCount, ); expect(fixture.componentInstance.containerDragReleasedSpy).toHaveBeenCalledTimes( containerDragReleasedCount, ); })); it('should stop event propagation when dragging a nested item', fakeAsync(() => { const fixture = createComponent(NestedDragsComponent); fixture.detectChanges(); const dragElement = fixture.componentInstance.item.nativeElement; const event = createMouseEvent('mousedown'); spyOn(event, 'stopPropagation').and.callThrough(); dispatchEvent(dragElement, event); fixture.detectChanges(); expect(event.stopPropagation).toHaveBeenCalled(); })); it('should stop event propagation when dragging item nested via ng-template', fakeAsync(() => { const fixture = createComponent(NestedDragsThroughTemplate); fixture.detectChanges(); const dragElement = fixture.componentInstance.item.nativeElement; const event = createMouseEvent('mousedown'); spyOn(event, 'stopPropagation').and.callThrough(); dispatchEvent(dragElement, event); fixture.detectChanges(); expect(event.stopPropagation).toHaveBeenCalled(); })); }); describe('with an alternate element container', () => { it('should move the placeholder into the alternate container of an empty list', fakeAsync(() => { const fixture = createComponent(ConnectedDropZonesWithAlternateContainer); fixture.detectChanges(); const dropZones = fixture.componentInstance.dropInstances.map(d => d.element.nativeElement); const item = fixture.componentInstance.groupedDragItems[0][1]; const sourceContainer = dropZones[0].querySelector('.inner-container')!; const targetContainer = dropZones[1].querySelector('.inner-container')!; const targetRect = targetContainer.getBoundingClientRect(); startDraggingViaMouse(fixture, item.element.nativeElement); const placeholder = dropZones[0].querySelector('.cdk-drag-placeholder')!; expect(placeholder).toBeTruthy(); expect(placeholder.parentNode) .withContext('Expected placeholder to be inside the first container.') .toBe(sourceContainer); dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1); fixture.detectChanges(); expect(placeholder.parentNode) .withContext('Expected placeholder to be inside second container.') .toBe(targetContainer); })); it('should throw if the items are not inside of the alternate container', fakeAsync(() => { const fixture = createComponent(DraggableWithInvalidAlternateContainer); fixture.detectChanges(); expect(() => { const item = fixture.componentInstance.dragItems.first.element.nativeElement; startDraggingViaMouse(fixture, item); tick(); }).toThrowError( /Invalid DOM structure for drop list\. All items must be placed directly inside of the element container/, ); })); it('should throw if the alternate container cannot be found', fakeAsync(() => { const fixture = createComponent(DraggableWithMissingAlternateContainer); fixture.detectChanges(); expect(() => { const item = fixture.componentInstance.dragItems.first.element.nativeElement; startDraggingViaMouse(fixture, item); tick(); }).toThrowError( /CdkDropList could not find an element container matching the selector "does-not-exist"/, ); })); }); }
{ "commit_id": "ea0d1ba7b", "end_byte": 186518, "start_byte": 177511, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_186520_194328
export function assertStartToEndSorting( listOrientation: 'vertical' | 'horizontal', fixture: ComponentFixture<any>, getSortedSiblings: SortedSiblingsFunction, items: Element[], ) { const draggedItem = items[0]; const {top, left} = draggedItem.getBoundingClientRect(); startDraggingViaMouse(fixture, draggedItem, left, top); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; // Drag over each item one-by-one going downwards. for (let i = 0; i < items.length; i++) { const elementRect = items[i].getBoundingClientRect(); // Add a few pixels to the top offset so we get some overlap. if (listOrientation === 'vertical') { dispatchMouseEvent(document, 'mousemove', elementRect.left, elementRect.top + 5); } else { dispatchMouseEvent(document, 'mousemove', elementRect.left + 5, elementRect.top); } fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const sortedSiblings = getSortedSiblings( placeholder, listOrientation === 'vertical' ? 'top' : 'left', ); expect(sortedSiblings.indexOf(placeholder)).toBe(i); } dispatchMouseEvent(document, 'mouseup'); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); flush(); } export function assertEndToStartSorting( listOrientation: 'vertical' | 'horizontal', fixture: ComponentFixture<any>, getSortedSiblings: SortedSiblingsFunction, items: Element[], ) { const draggedItem = items[items.length - 1]; const {top, left} = draggedItem.getBoundingClientRect(); startDraggingViaMouse(fixture, draggedItem, left, top); const placeholder = document.querySelector('.cdk-drag-placeholder')! as HTMLElement; // Drag over each item one-by-one going upwards. for (let i = items.length - 1; i > -1; i--) { const elementRect = items[i].getBoundingClientRect(); // Remove a few pixels from the bottom offset so we get some overlap. if (listOrientation === 'vertical') { dispatchMouseEvent(document, 'mousemove', elementRect.left, elementRect.bottom - 5); } else { dispatchMouseEvent(document, 'mousemove', elementRect.right - 5, elementRect.top); } fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect( getSortedSiblings(placeholder, listOrientation === 'vertical' ? 'top' : 'left').indexOf( placeholder, ), ).toBe(i); } dispatchMouseEvent(document, 'mouseup'); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); flush(); } /** * Dynamically creates the horizontal list fixtures. They need to be * generated so that the list orientation can be changed between tests. * @param listOrientation Orientation value to be assigned to the list. * Does not affect the actual styles. */ export function getHorizontalFixtures(listOrientation: Exclude<DropListOrientation, 'vertical'>) { // Use inline blocks here to avoid flexbox issues and not to have to flip floats in rtl. const HORIZONTAL_FIXTURE_STYLES = ` .cdk-drop-list { display: block; width: 500px; background: pink; font-size: 0; } .cdk-drag { height: ${ITEM_HEIGHT * 2}px; background: red; display: inline-block; } `; const HORIZONTAL_FIXTURE_TEMPLATE = ` <div class="drop-list scroll-container" cdkDropList cdkDropListOrientation="${listOrientation}" [cdkDropListData]="items" (cdkDropListDropped)="droppedSpy($event)"> @for (item of items; track item) { <div [style.width.px]="item.width" [style.margin-right.px]="item.margin" [cdkDragBoundary]="boundarySelector" cdkDrag>{{item.value}}</div> } </div> `; @Component({ encapsulation: ViewEncapsulation.None, styles: HORIZONTAL_FIXTURE_STYLES, template: HORIZONTAL_FIXTURE_TEMPLATE, standalone: true, imports: [CdkDropList, CdkDrag], }) class DraggableInHorizontalDropZone implements AfterViewInit { readonly _elementRef = inject(ElementRef); @ViewChildren(CdkDrag) dragItems: QueryList<CdkDrag>; @ViewChild(CdkDropList) dropInstance: CdkDropList; items = [ {value: 'Zero', width: ITEM_WIDTH, margin: 0}, {value: 'One', width: ITEM_WIDTH, margin: 0}, {value: 'Two', width: ITEM_WIDTH, margin: 0}, {value: 'Three', width: ITEM_WIDTH, margin: 0}, ]; boundarySelector: string; droppedSpy = jasmine.createSpy('dropped spy').and.callFake((event: CdkDragDrop<string[]>) => { moveItemInArray(this.items, event.previousIndex, event.currentIndex); }); constructor(...args: unknown[]); constructor() {} ngAfterViewInit() { // Firefox preserves the `scrollLeft` value from previous similar containers. This // could throw off test assertions and result in flaky results. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=959812. this._elementRef.nativeElement.querySelector('.scroll-container').scrollLeft = 0; } } @Component({ standalone: true, imports: [CdkDropList, CdkDrag], template: HORIZONTAL_FIXTURE_TEMPLATE, // Note that it needs a margin to ensure that it's not flush against the viewport // edge which will cause the viewport to scroll, rather than the list. styles: [ HORIZONTAL_FIXTURE_STYLES, ` .drop-list { max-width: 300px; margin: 10vw 0 0 10vw; overflow: auto; white-space: nowrap; } `, ], }) class DraggableInScrollableHorizontalDropZone extends DraggableInHorizontalDropZone { constructor() { super(); for (let i = 0; i < 60; i++) { this.items.push({value: `Extra item ${i}`, width: ITEM_WIDTH, margin: 0}); } } } @Component({ styles: ` .list { display: flex; width: 100px; flex-direction: row; } .item { display: flex; flex-grow: 1; flex-basis: 0; min-height: 50px; } `, template: ` <div class="list" cdkDropList cdkDropListOrientation="${listOrientation}"> @for (item of items; track item) { <div class="item" cdkDrag> {{item}} <ng-template cdkDragPreview [matchSize]="true"> <div class="item">{{item}}</div> </ng-template> </div> } </div> `, standalone: true, imports: [CdkDropList, CdkDrag, CdkDragPreview], }) class DraggableInHorizontalFlexDropZoneWithMatchSizePreview { @ViewChildren(CdkDrag) dragItems: QueryList<CdkDrag>; items = ['Zero', 'One', 'Two']; } return { DraggableInHorizontalDropZone, DraggableInScrollableHorizontalDropZone, DraggableInHorizontalFlexDropZoneWithMatchSizePreview, }; } // TODO(crisbeto): figure out why switch `*ngFor` with `@for` here causes a test failure. const DROP_ZONE_FIXTURE_TEMPLATE = ` <div cdkDropList class="drop-list scroll-container" style="width: 100px; background: pink;" [id]="dropZoneId" [cdkDropListData]="items" [cdkDropListDisabled]="dropDisabled()" [cdkDropListLockAxis]="dropLockAxis()" (cdkDropListSorted)="sortedSpy($event)" (cdkDropListDropped)="droppedSpy($event)"> <div *ngFor="let item of items" cdkDrag [cdkDragData]="item" [cdkDragBoundary]="boundarySelector" [cdkDragPreviewClass]="previewClass" [cdkDragPreviewContainer]="previewContainer" [cdkDragScale]="scale" [style.height.px]="item.height" [style.margin-bottom.px]="item.margin" (cdkDragStarted)="startedSpy($event)" style="width: 100%; background: red;">{{item.value}}</div> </div> <div #alternatePreviewContainer></div> `;
{ "commit_id": "ea0d1ba7b", "end_byte": 194328, "start_byte": 186520, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_194330_201499
@Component({ template: DROP_ZONE_FIXTURE_TEMPLATE, standalone: true, imports: [CdkDropList, CdkDrag, NgFor], }) export class DraggableInDropZone implements AfterViewInit { protected _elementRef = inject(ElementRef); @ViewChildren(CdkDrag) dragItems: QueryList<CdkDrag>; @ViewChild(CdkDropList) dropInstance: CdkDropList; @ViewChild('alternatePreviewContainer') alternatePreviewContainer: ElementRef<HTMLElement>; items = [ {value: 'Zero', height: ITEM_HEIGHT, margin: 0}, {value: 'One', height: ITEM_HEIGHT, margin: 0}, {value: 'Two', height: ITEM_HEIGHT, margin: 0}, {value: 'Three', height: ITEM_HEIGHT, margin: 0}, ]; dropZoneId = 'items'; boundarySelector: string; previewClass: string | string[]; sortedSpy = jasmine.createSpy('sorted spy'); droppedSpy = jasmine.createSpy('dropped spy').and.callFake((event: CdkDragDrop<string[]>) => { moveItemInArray(this.items, event.previousIndex, event.currentIndex); }); startedSpy = jasmine.createSpy('started spy'); previewContainer: PreviewContainer = 'global'; dropDisabled = signal(false); dropLockAxis = signal<DragAxis | undefined>(undefined); scale = 1; ngAfterViewInit() { // Firefox preserves the `scrollTop` value from previous similar containers. This // could throw off test assertions and result in flaky results. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=959812. this.dropInstance.element.nativeElement.scrollTop = 0; } } @Component({ selector: 'draggable-in-on-push-zone', template: DROP_ZONE_FIXTURE_TEMPLATE, changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, imports: [CdkDropList, CdkDrag, NgFor], }) class DraggableInOnPushDropZone extends DraggableInDropZone {} @Component({ template: ` <div cdkDropListGroup> <draggable-in-on-push-zone></draggable-in-on-push-zone> <draggable-in-on-push-zone></draggable-in-on-push-zone> </div> `, standalone: true, imports: [CdkDropListGroup, DraggableInOnPushDropZone], }) class ConnectedDropListsInOnPush {} @Component({ template: DROP_ZONE_FIXTURE_TEMPLATE, // Note that it needs a margin to ensure that it's not flush against the viewport // edge which will cause the viewport to scroll, rather than the list. styles: ` .drop-list { max-height: 200px; overflow: auto; margin: 10vw 0 0 10vw; } `, standalone: true, imports: [CdkDropList, CdkDrag, NgFor], }) export class DraggableInScrollableVerticalDropZone extends DraggableInDropZone { constructor() { super(); for (let i = 0; i < 60; i++) { this.items.push({value: `Extra item ${i}`, height: ITEM_HEIGHT, margin: 0}); } } } @Component({ template: ` <div #scrollContainer class="scroll-container" cdkScrollable>${DROP_ZONE_FIXTURE_TEMPLATE}</div>`, // Note that it needs a margin to ensure that it's not flush against the viewport // edge which will cause the viewport to scroll, rather than the list. styles: ` .scroll-container { max-height: 200px; overflow: auto; margin: 10vw 0 0 10vw; } `, standalone: true, imports: [CdkDropList, CdkDrag, NgFor, CdkScrollable], }) class DraggableInScrollableParentContainer extends DraggableInDropZone implements AfterViewInit { @ViewChild('scrollContainer') scrollContainer: ElementRef<HTMLElement>; constructor() { super(); for (let i = 0; i < 60; i++) { this.items.push({value: `Extra item ${i}`, height: ITEM_HEIGHT, margin: 0}); } } override ngAfterViewInit() { super.ngAfterViewInit(); // Firefox preserves the `scrollTop` value from previous similar containers. This // could throw off test assertions and result in flaky results. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=959812. this.scrollContainer.nativeElement.scrollTop = 0; } } @Component({ // Note that we need the blank `@if` below to hit the code path that we're testing. template: ` <div cdkDropList class="drop-list scroll-container" style="width: 100px; background: pink;" [id]="dropZoneId" [cdkDropListData]="items" (cdkDropListSorted)="sortedSpy($event)" (cdkDropListDropped)="droppedSpy($event)"> @if (true) { @for (item of items; track item) { <div cdkDrag [cdkDragData]="item" [cdkDragBoundary]="boundarySelector" [style.height.px]="item.height" [style.margin-bottom.px]="item.margin" style="width: 100%; background: red;">{{item.value}}</div> } } </div> `, standalone: true, imports: [CdkDropList, CdkDrag], }) class DraggableInDropZoneWithContainer extends DraggableInDropZone {} // TODO(crisbeto): `*ngIf` here can be removed after updating to a version of Angular that includes // https://github.com/angular/angular/pull/52515 @Component({ template: ` <div cdkDropList style="width: 100px; background: pink;" [cdkDropListLockAxis]="dropLockAxis()"> @for (item of items; track item) { <div cdkDrag [cdkDragConstrainPosition]="constrainPosition" [cdkDragBoundary]="boundarySelector" [cdkDragPreviewClass]="previewClass" [cdkDragLockAxis]="item.lockAxis" style="width: 100%; height: ${ITEM_HEIGHT}px; background: red;"> {{item.label}} <ng-container *ngIf="renderCustomPreview"> <ng-template cdkDragPreview [matchSize]="matchPreviewSize"> <div class="custom-preview" style="width: 50px; height: 50px; background: purple;">Custom preview</div> </ng-template> </ng-container> </div> } </div> `, standalone: true, imports: [CdkDropList, CdkDrag, CdkDragPreview, NgIf], }) class DraggableInDropZoneWithCustomPreview { @ViewChild(CdkDropList) dropInstance: CdkDropList; @ViewChildren(CdkDrag) dragItems: QueryList<CdkDrag>; items: {label: string; lockAxis?: DragAxis}[] = [ {label: 'Zero'}, {label: 'One'}, {label: 'Two'}, {label: 'Three'}, ]; boundarySelector: string; renderCustomPreview = true; matchPreviewSize = false; previewClass: string | string[]; constrainPosition: (point: Point) => Point; dropLockAxis = signal<DragAxis | undefined>(undefined); } @Component({ template: ` <div cdkDropList style="width: 100px; background: pink;"> @for (item of items; track item) { <div cdkDrag [cdkDragConstrainPosition]="constrainPosition" [cdkDragBoundary]="boundarySelector" style="width: 100%; height: ${ITEM_HEIGHT}px; background: red;"> {{item}} <ng-template cdkDragPreview>Hello {{item}}</ng-template> </div> } </div> `, standalone: true, imports: [CdkDropList, CdkDrag, CdkDragPreview], }) class DraggableInDropZoneWithCustomTextOnlyPreview { @ViewChild(CdkDropList) dropInstance: CdkDropList; @ViewChildren(CdkDrag) dragItems: QueryList<CdkDrag>; items = ['Zero', 'One', 'Two', 'Three']; }
{ "commit_id": "ea0d1ba7b", "end_byte": 201499, "start_byte": 194330, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_201501_208510
@Component({ template: ` <div cdkDropList style="width: 100px; background: pink;"> @for (item of items; track item) { <div cdkDrag style="width: 100%; height: ${ITEM_HEIGHT}px; background: red;"> {{item}} <ng-template cdkDragPreview> <span>Hello</span> <span>{{item}}</span> </ng-template> </div> } </div> `, standalone: true, imports: [CdkDropList, CdkDrag, CdkDragPreview], }) class DraggableInDropZoneWithCustomMultiNodePreview { @ViewChild(CdkDropList) dropInstance: CdkDropList; @ViewChildren(CdkDrag) dragItems: QueryList<CdkDrag>; items = ['Zero', 'One', 'Two', 'Three']; } @Component({ template: ` <div cdkDropList (cdkDropListDropped)="droppedSpy($event)" style="width: 100px; background: pink;"> @for (item of items; track item) { <div cdkDrag style="width: 100%; height: ${ITEM_HEIGHT}px; background: red;"> {{item}} @if (renderPlaceholder) { <div class="custom-placeholder" [ngClass]="extraPlaceholderClass" *cdkDragPlaceholder>Custom placeholder</div> } </div> } </div> `, styles: ` .tall-placeholder { height: ${ITEM_HEIGHT * 3}px; } `, standalone: true, imports: [CdkDropList, CdkDrag, CdkDragPlaceholder, NgClass], }) class DraggableInDropZoneWithCustomPlaceholder { @ViewChildren(CdkDrag) dragItems: QueryList<CdkDrag>; items = ['Zero', 'One', 'Two', 'Three']; renderPlaceholder = true; extraPlaceholderClass = ''; droppedSpy = jasmine.createSpy('dropped spy'); } @Component({ template: ` <div cdkDropList style="width: 100px; background: pink;"> @for (item of items; track item) { <div cdkDrag style="width: 100%; height: ${ITEM_HEIGHT}px; background: red;"> {{item}} <ng-template cdkDragPlaceholder>Hello {{item}}</ng-template> </div> } </div> `, standalone: true, imports: [CdkDropList, CdkDrag, CdkDragPlaceholder], }) class DraggableInDropZoneWithCustomTextOnlyPlaceholder { @ViewChildren(CdkDrag) dragItems: QueryList<CdkDrag>; items = ['Zero', 'One', 'Two', 'Three']; } @Component({ template: ` <div cdkDropList style="width: 100px; background: pink;"> @for (item of items; track item) { <div cdkDrag style="width: 100%; height: ${ITEM_HEIGHT}px; background: red;"> {{item}} <ng-template cdkDragPlaceholder> <span>Hello</span> <span>{{item}}</span> </ng-template> </div> } </div> `, standalone: true, imports: [CdkDropList, CdkDrag, CdkDragPlaceholder], }) class DraggableInDropZoneWithCustomMultiNodePlaceholder { @ViewChildren(CdkDrag) dragItems: QueryList<CdkDrag>; items = ['Zero', 'One', 'Two', 'Three']; } const CONNECTED_DROP_ZONES_STYLES = [ ` .cdk-drop-list { display: block; width: 100px; min-height: ${ITEM_HEIGHT}px; background: hotpink; } .cdk-drag { display: block; height: ${ITEM_HEIGHT}px; background: red; } `, ]; const CONNECTED_DROP_ZONES_TEMPLATE = ` <div cdkDropList #todoZone="cdkDropList" [cdkDropListData]="todo" [cdkDropListConnectedTo]="todoConnectedTo() || [doneZone]" (cdkDropListDropped)="droppedSpy($event)" (cdkDropListEntered)="enteredSpy($event)"> @for (item of todo; track item) { <div [cdkDragData]="item" (cdkDragEntered)="itemEnteredSpy($event)" cdkDrag>{{item}}</div> } </div> <div cdkDropList #doneZone="cdkDropList" [cdkDropListData]="done" [cdkDropListConnectedTo]="doneConnectedTo() || [todoZone]" (cdkDropListDropped)="droppedSpy($event)" (cdkDropListEntered)="enteredSpy($event)"> @for (item of done; track item) { <div [cdkDragData]="item" (cdkDragEntered)="itemEnteredSpy($event)" cdkDrag>{{item}}</div> } </div> <div cdkDropList #extraZone="cdkDropList" [cdkDropListData]="extra" [cdkDropListConnectedTo]="extraConnectedTo()" (cdkDropListDropped)="droppedSpy($event)" (cdkDropListEntered)="enteredSpy($event)"> @for (item of extra; track item) { <div [cdkDragData]="item" (cdkDragEntered)="itemEnteredSpy($event)" cdkDrag>{{item}}</div> } </div> `; @Component({ encapsulation: ViewEncapsulation.None, styles: CONNECTED_DROP_ZONES_STYLES, template: CONNECTED_DROP_ZONES_TEMPLATE, standalone: true, imports: [CdkDropList, CdkDrag], }) export class ConnectedDropZones implements AfterViewInit { @ViewChildren(CdkDrag) rawDragItems: QueryList<CdkDrag>; @ViewChildren(CdkDropList) dropInstances: QueryList<CdkDropList>; changeDetectorRef = inject(ChangeDetectorRef); groupedDragItems: CdkDrag[][] = []; todo = ['Zero', 'One', 'Two', 'Three']; done = ['Four', 'Five', 'Six']; extra = []; droppedSpy = jasmine.createSpy('dropped spy'); enteredSpy = jasmine.createSpy('entered spy'); itemEnteredSpy = jasmine.createSpy('item entered spy'); todoConnectedTo = signal<(CdkDropList | string)[] | undefined>(undefined); doneConnectedTo = signal<(CdkDropList | string)[] | undefined>(undefined); extraConnectedTo = signal<(CdkDropList | string)[] | undefined>(undefined); ngAfterViewInit() { this.dropInstances.forEach((dropZone, index) => { if (!this.groupedDragItems[index]) { this.groupedDragItems.push([]); } this.groupedDragItems[index].push(...dropZone.getSortedItems()); }); this.changeDetectorRef.markForCheck(); } } @Component({ encapsulation: ViewEncapsulation.ShadowDom, styles: CONNECTED_DROP_ZONES_STYLES, template: `@if (true) {${CONNECTED_DROP_ZONES_TEMPLATE}}`, standalone: true, imports: [CdkDropList, CdkDrag], }) class ConnectedDropZonesInsideShadowRootWithNgIf extends ConnectedDropZones {} @Component({ encapsulation: ViewEncapsulation.None, styles: ` .cdk-drop-list { display: block; width: 100px; min-height: ${ITEM_HEIGHT}px; background: hotpink; } .cdk-drag { display: block; height: ${ITEM_HEIGHT}px; background: red; } `, template: ` <div cdkDropListGroup [cdkDropListGroupDisabled]="groupDisabled"> <div cdkDropList [cdkDropListData]="todo" (cdkDropListDropped)="droppedSpy($event)"> @for (item of todo; track item) { <div [cdkDragData]="item" cdkDrag>{{item}}</div> } </div> <div cdkDropList [cdkDropListData]="done" (cdkDropListDropped)="droppedSpy($event)"> @for (item of done; track item) { <div [cdkDragData]="item" cdkDrag>{{item}}</div> } </div> </div> `, standalone: true, imports: [CdkDropList, CdkDrag, CdkDropListGroup], }) class ConnectedDropZonesViaGroupDirective extends ConnectedDropZones { groupDisabled = false; }
{ "commit_id": "ea0d1ba7b", "end_byte": 208510, "start_byte": 201501, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_208512_215540
@Component({ encapsulation: ViewEncapsulation.None, styles: ` .cdk-drop-list { display: block; width: 100px; min-height: ${ITEM_HEIGHT}px; background: hotpink; } .cdk-drag { display: block; height: ${ITEM_HEIGHT}px; background: red; } `, template: ` <div cdkDropList #todoZone="cdkDropList" [cdkDropListConnectedTo]="[doneZone]" (cdkDropListDropped)="droppedSpy($event)"> <div cdkDrag>One</div> </div> <div cdkDropList #doneZone="cdkDropList" [cdkDropListConnectedTo]="[todoZone]" (cdkDropListDropped)="droppedSpy($event)"> <div cdkDrag>Two</div> </div> `, standalone: true, imports: [CdkDropList, CdkDrag], }) class ConnectedDropZonesWithSingleItems { @ViewChildren(CdkDrag) dragItems: QueryList<CdkDrag>; @ViewChildren(CdkDropList) dropInstances: QueryList<CdkDropList>; droppedSpy = jasmine.createSpy('dropped spy'); } @Component({ template: ` <div cdkDropListGroup #group="cdkDropListGroup"> <div cdkDropList #listOne="cdkDropList"> <div cdkDropList #listThree="cdkDropList"></div> <div cdkDropList #listFour="cdkDropList"></div> </div> <div cdkDropList #listTwo="cdkDropList"></div> </div> `, standalone: true, imports: [CdkDropList, CdkDropListGroup], }) class NestedDropListGroups { @ViewChild('group') group: CdkDropListGroup<CdkDropList>; @ViewChild('listOne') listOne: CdkDropList; @ViewChild('listTwo') listTwo: CdkDropList; } @Component({ template: ` <ng-container cdkDropList></ng-container> `, standalone: true, imports: [CdkDropList], }) class DropListOnNgContainer {} @Component({ changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, imports: [CdkDropList, CdkDrag], template: ` <div cdkDropList style="width: 100px; background: pink;"> @for (item of items; track item) { <div cdkDrag [style.height.px]="item.height" style="width: 100%; background: red;">{{item.value}}</div> } </div> `, }) class DraggableInDropZoneWithoutEvents { @ViewChildren(CdkDrag) dragItems: QueryList<CdkDrag>; @ViewChild(CdkDropList) dropInstance: CdkDropList; items = [ {value: 'Zero', height: ITEM_HEIGHT}, {value: 'One', height: ITEM_HEIGHT}, {value: 'Two', height: ITEM_HEIGHT}, {value: 'Three', height: ITEM_HEIGHT}, ]; } /** Component that wraps a drop container and uses OnPush change detection. */ @Component({ selector: 'wrapped-drop-container', template: ` <div cdkDropList [cdkDropListData]="items"> @for (item of items; track item) { <div cdkDrag>{{item}}</div> } </div> `, standalone: true, imports: [CdkDropList, CdkDrag], changeDetection: ChangeDetectionStrategy.OnPush, }) class WrappedDropContainerComponent { @Input() items: string[]; } @Component({ encapsulation: ViewEncapsulation.None, styles: ` .cdk-drop-list { display: block; width: 100px; min-height: ${ITEM_HEIGHT}px; background: hotpink; } .cdk-drag { display: block; height: ${ITEM_HEIGHT}px; background: red; } `, template: ` <div cdkDropListGroup> <wrapped-drop-container [items]="todo"></wrapped-drop-container> <wrapped-drop-container [items]="done"></wrapped-drop-container> </div> `, standalone: true, imports: [CdkDropListGroup, WrappedDropContainerComponent], }) class ConnectedWrappedDropZones { todo = ['Zero', 'One', 'Two', 'Three']; done = ['Four', 'Five', 'Six']; } @Component({ template: ` <div class="drop-list scroll-container" cdkDropList style="width: 100px; background: pink;" [id]="dropZoneId" [cdkDropListData]="items" (cdkDropListSorted)="sortedSpy($event)" (cdkDropListDropped)="droppedSpy($event)"> @for (item of items; track item) { <div cdkDrag [cdkDragData]="item" [style.height.px]="item.height" [style.margin-bottom.px]="item.margin" style="width: 100%; background: red;"> {{item.value}} <canvas width="100px" height="100px"></canvas> </div> } </div> `, standalone: true, imports: [CdkDropList, CdkDrag], }) class DraggableWithCanvasInDropZone extends DraggableInDropZone implements AfterViewInit { override ngAfterViewInit() { super.ngAfterViewInit(); const canvases = this._elementRef.nativeElement.querySelectorAll('canvas'); // Add a circle to all the canvases. for (let i = 0; i < canvases.length; i++) { const canvas = canvases[i]; const context = canvas.getContext('2d')!; context.beginPath(); context.arc(50, 50, 40, 0, 2 * Math.PI); context.stroke(); } } } @Component({ template: ` <div class="drop-list scroll-container" cdkDropList style="width: 100px; background: pink;" [id]="dropZoneId" [cdkDropListData]="items" (cdkDropListSorted)="sortedSpy($event)" (cdkDropListDropped)="droppedSpy($event)"> @for (item of items; track item) { <div cdkDrag [cdkDragData]="item" [style.height.px]="item.height" [style.margin-bottom.px]="item.margin" style="width: 100%; background: red;"> {{item.value}} <canvas width="0" height="0"></canvas> </div> } </div> `, standalone: true, imports: [CdkDropList, CdkDrag], }) class DraggableWithInvalidCanvasInDropZone extends DraggableInDropZone {} @Component({ styles: ` :host { height: 400px; width: 400px; position: absolute; } .container { height: 200px; width: 200px; position: absolute; } .item { height: 50px; width: 50px; position: absolute; } `, template: ` <div cdkDrag #container class="container" (cdkDragStarted)="containerDragStartedSpy($event)" (cdkDragMoved)="containerDragMovedSpy($event)" (cdkDragReleased)="containerDragReleasedSpy($event)"> <div cdkDrag class="item" #item (cdkDragStarted)="itemDragStartedSpy($event)" (cdkDragMoved)="itemDragMovedSpy($event)" (cdkDragReleased)="itemDragReleasedSpy($event)"> </div> </div>`, standalone: true, imports: [CdkDrag], }) class NestedDragsComponent { @ViewChild('container') container: ElementRef; @ViewChild('item') item: ElementRef; containerDragStartedSpy = jasmine.createSpy('container drag started spy'); containerDragMovedSpy = jasmine.createSpy('container drag moved spy'); containerDragReleasedSpy = jasmine.createSpy('container drag released spy'); itemDragStartedSpy = jasmine.createSpy('item drag started spy'); itemDragMovedSpy = jasmine.createSpy('item drag moved spy'); itemDragReleasedSpy = jasmine.createSpy('item drag released spy'); }
{ "commit_id": "ea0d1ba7b", "end_byte": 215540, "start_byte": 208512, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_215542_222378
@Component({ styles: ` :host { height: 400px; width: 400px; position: absolute; } .container { height: 200px; width: 200px; position: absolute; } .item { height: 50px; width: 50px; position: absolute; } `, template: ` <div cdkDrag #container class="container" (cdkDragStarted)="containerDragStartedSpy($event)" (cdkDragMoved)="containerDragMovedSpy($event)" (cdkDragReleased)="containerDragReleasedSpy($event)"> <ng-container [ngTemplateOutlet]="itemTemplate"></ng-container> </div> <ng-template #itemTemplate> <div cdkDrag class="item" #item (cdkDragStarted)="itemDragStartedSpy($event)" (cdkDragMoved)="itemDragMovedSpy($event)" (cdkDragReleased)="itemDragReleasedSpy($event)"> </div> </ng-template> `, standalone: true, imports: [CdkDrag, NgTemplateOutlet], }) class NestedDragsThroughTemplate { @ViewChild('container') container: ElementRef; @ViewChild('item') item: ElementRef; } @Component({ styles: ` .drop-list { width: 100px; background: pink; } `, template: ` <div cdkDropList class="drop-list" #outerList> <div cdkDropList class="drop-list" #innerList> @for (item of items; track item) { <div cdkDrag style="width: 100%; background: red; height: ${ITEM_HEIGHT}px;">{{item}}</div> } </div> </div> `, standalone: true, imports: [CdkDropList, CdkDrag], }) class NestedDropZones { @ViewChildren(CdkDrag) dragItems: QueryList<CdkDrag>; @ViewChild('outerList') outerList: ElementRef<HTMLElement>; @ViewChild('innerList') innerList: ElementRef<HTMLElement>; items = ['Zero', 'One', 'Two', 'Three']; } @Component({ template: `<div cdkDropList></div>`, standalone: true, imports: [CdkDropList], }) class PlainStandaloneDropList { @ViewChild(CdkDropList) dropList: CdkDropList; } @Component({ styles: CONNECTED_DROP_ZONES_STYLES, template: ` <div cdkDropList #todoZone="cdkDropList" [cdkDropListData]="todo" [cdkDropListConnectedTo]="[doneZone]" (cdkDropListDropped)="droppedSpy($event)" (cdkDropListEntered)="enteredSpy($event)"> @for (item of todo; track item) { <div [cdkDragData]="item" (cdkDragEntered)="itemEnteredSpy($event)" cdkDrag>{{item}}</div> } </div> <div cdkDropList #doneZone="cdkDropList" [cdkDropListData]="done" [cdkDropListConnectedTo]="[todoZone]" (cdkDropListDropped)="droppedSpy($event)" (cdkDropListEntered)="enteredSpy($event)"> <div>Hello there</div> <div> @for (item of done; track item) { <div [cdkDragData]="item" (cdkDragEntered)="itemEnteredSpy($event)" cdkDrag>{{item}}</div> } </div> </div> `, standalone: true, imports: [CdkDropList, CdkDrag], }) class ConnectedDropZonesWithIntermediateSibling extends ConnectedDropZones {} @Component({ template: ` <div cdkDropList class="drop-list scroll-container" style="width: 100px; background: pink;" [id]="dropZoneId" [cdkDropListData]="items" (cdkDropListSorted)="sortedSpy($event)" (cdkDropListDropped)="droppedSpy($event)"> @for (item of items; track item) { <div cdkDrag [cdkDragData]="item" [style.height.px]="item.height" [style.margin-bottom.px]="item.margin" style="width: 100%; background: red;"> {{item.value}} <input [value]="inputValue"/> <textarea [value]="inputValue"></textarea> <select [value]="inputValue"> <option value="goodbye">Goodbye</option> <option value="hello">Hello</option> </select> </div> } </div> `, standalone: true, imports: [CdkDropList, CdkDrag], }) class DraggableWithInputsInDropZone extends DraggableInDropZone { inputValue = 'hello'; } @Component({ template: ` <div cdkDropList class="drop-list scroll-container" [cdkDropListData]="items"> @for (item of items; track item) { <div cdkDrag [cdkDragData]="item"> {{item.id}} <input type="radio" name="radio" [checked]="item.checked"/> </div> } </div> `, standalone: true, imports: [CdkDropList, CdkDrag], }) class DraggableWithRadioInputsInDropZone { @ViewChildren(CdkDrag) dragItems: QueryList<CdkDrag>; items = [ {id: 1, checked: false}, {id: 2, checked: false}, {id: 3, checked: true}, ]; } @Component({ encapsulation: ViewEncapsulation.ShadowDom, styles: [...CONNECTED_DROP_ZONES_STYLES, `.inner-container {min-height: 50px;}`], template: ` <div cdkDropList #todoZone="cdkDropList" [cdkDropListData]="todo" [cdkDropListConnectedTo]="[doneZone]" (cdkDropListDropped)="droppedSpy($event)" (cdkDropListEntered)="enteredSpy($event)" cdkDropListElementContainer=".inner-container"> <div class="inner-container"> @for (item of todo; track item) { <div [cdkDragData]="item" (cdkDragEntered)="itemEnteredSpy($event)" cdkDrag>{{item}}</div> } </div> </div> <div cdkDropList #doneZone="cdkDropList" [cdkDropListData]="done" [cdkDropListConnectedTo]="[todoZone]" (cdkDropListDropped)="droppedSpy($event)" (cdkDropListEntered)="enteredSpy($event)" cdkDropListElementContainer=".inner-container"> <div class="inner-container"> @for (item of done; track item) { <div [cdkDragData]="item" (cdkDragEntered)="itemEnteredSpy($event)" cdkDrag>{{item}}</div> } </div> </div> `, standalone: true, imports: [CdkDropList, CdkDrag], }) class ConnectedDropZonesWithAlternateContainer extends ConnectedDropZones { override done: string[] = []; } @Component({ template: ` <div cdkDropList cdkDropListElementContainer=".element-container" style="width: 100px; background: pink;"> <div class="element-container"></div> @for (item of items; track $index) { <div cdkDrag [cdkDragData]="item" style="width: 100%; height: 50px; background: red;">{{item}}</div> } </div> `, standalone: true, imports: [CdkDropList, CdkDrag], }) class DraggableWithInvalidAlternateContainer { @ViewChildren(CdkDrag) dragItems: QueryList<CdkDrag>; @ViewChild(CdkDropList) dropInstance: CdkDropList; items = ['Zero', 'One', 'Two', 'Three']; }
{ "commit_id": "ea0d1ba7b", "end_byte": 222378, "start_byte": 215542, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-shared.spec.ts_222380_222996
@Component({ template: ` <div cdkDropList cdkDropListElementContainer="does-not-exist" style="width: 100px; background: pink;"> @for (item of items; track $index) { <div cdkDrag [cdkDragData]="item" style="width: 100%; height: 50px; background: red;">{{item}}</div> } </div> `, standalone: true, imports: [CdkDropList, CdkDrag], }) class DraggableWithMissingAlternateContainer { @ViewChildren(CdkDrag) dragItems: QueryList<CdkDrag>; @ViewChild(CdkDropList) dropInstance: CdkDropList; items = ['Zero', 'One', 'Two', 'Three']; }
{ "commit_id": "ea0d1ba7b", "end_byte": 222996, "start_byte": 222380, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-shared.spec.ts" }
components/src/cdk/drag-drop/directives/drag-handle.ts_0_2026
/** * @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 { Directive, ElementRef, InjectionToken, Input, OnDestroy, booleanAttribute, inject, } from '@angular/core'; import {Subject} from 'rxjs'; import type {CdkDrag} from './drag'; import {CDK_DRAG_PARENT} from '../drag-parent'; import {assertElementNode} from './assertions'; /** * Injection token that can be used to reference instances of `CdkDragHandle`. It serves as * alternative token to the actual `CdkDragHandle` class which could cause unnecessary * retention of the class and its directive metadata. */ export const CDK_DRAG_HANDLE = new InjectionToken<CdkDragHandle>('CdkDragHandle'); /** Handle that can be used to drag a CdkDrag instance. */ @Directive({ selector: '[cdkDragHandle]', host: { 'class': 'cdk-drag-handle', }, providers: [{provide: CDK_DRAG_HANDLE, useExisting: CdkDragHandle}], }) export class CdkDragHandle implements OnDestroy { element = inject<ElementRef<HTMLElement>>(ElementRef); private _parentDrag = inject<CdkDrag>(CDK_DRAG_PARENT, {optional: true, skipSelf: true}); /** Emits when the state of the handle has changed. */ readonly _stateChanges = new Subject<CdkDragHandle>(); /** Whether starting to drag through this handle is disabled. */ @Input({alias: 'cdkDragHandleDisabled', transform: booleanAttribute}) get disabled(): boolean { return this._disabled; } set disabled(value: boolean) { this._disabled = value; this._stateChanges.next(this); } private _disabled = false; constructor(...args: unknown[]); constructor() { if (typeof ngDevMode === 'undefined' || ngDevMode) { assertElementNode(this.element.nativeElement, 'cdkDragHandle'); } this._parentDrag?._addHandle(this); } ngOnDestroy() { this._parentDrag?._removeHandle(this); this._stateChanges.complete(); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 2026, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drag-handle.ts" }
components/src/cdk/drag-drop/directives/drop-list.ts_0_1815
/** * @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 {NumberInput, coerceArray, coerceNumberProperty} from '@angular/cdk/coercion'; import { ElementRef, EventEmitter, Input, OnDestroy, Output, Directive, ChangeDetectorRef, booleanAttribute, inject, } from '@angular/core'; import {Directionality} from '@angular/cdk/bidi'; import {ScrollDispatcher} from '@angular/cdk/scrolling'; import {CDK_DROP_LIST, CdkDrag} from './drag'; import {CdkDragDrop, CdkDragEnter, CdkDragExit, CdkDragSortEvent} from '../drag-events'; import {CDK_DROP_LIST_GROUP, CdkDropListGroup} from './drop-list-group'; import {DropListRef} from '../drop-list-ref'; import {DragRef} from '../drag-ref'; import {DragDrop} from '../drag-drop'; import {DropListOrientation, DragAxis, DragDropConfig, CDK_DRAG_CONFIG} from './config'; import {merge, Subject} from 'rxjs'; import {startWith, takeUntil} from 'rxjs/operators'; import {assertElementNode} from './assertions'; /** Counter used to generate unique ids for drop zones. */ let _uniqueIdCounter = 0; /** Container that wraps a set of draggable items. */ @Directive({ selector: '[cdkDropList], cdk-drop-list', exportAs: 'cdkDropList', providers: [ // Prevent child drop lists from picking up the same group as their parent. {provide: CDK_DROP_LIST_GROUP, useValue: undefined}, {provide: CDK_DROP_LIST, useExisting: CdkDropList}, ], host: { 'class': 'cdk-drop-list', '[attr.id]': 'id', '[class.cdk-drop-list-disabled]': 'disabled', '[class.cdk-drop-list-dragging]': '_dropListRef.isDragging()', '[class.cdk-drop-list-receiving]': '_dropListRef.isReceiving()', }, }) export
{ "commit_id": "ea0d1ba7b", "end_byte": 1815, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list.ts" }
components/src/cdk/drag-drop/directives/drop-list.ts_1816_9750
class CdkDropList<T = any> implements OnDestroy { element = inject<ElementRef<HTMLElement>>(ElementRef); private _changeDetectorRef = inject(ChangeDetectorRef); private _scrollDispatcher = inject(ScrollDispatcher); private _dir = inject(Directionality, {optional: true}); private _group = inject<CdkDropListGroup<CdkDropList>>(CDK_DROP_LIST_GROUP, { optional: true, skipSelf: true, }); /** Emits when the list has been destroyed. */ private readonly _destroyed = new Subject<void>(); /** Whether the element's scrollable parents have been resolved. */ private _scrollableParentsResolved: boolean; /** Keeps track of the drop lists that are currently on the page. */ private static _dropLists: CdkDropList[] = []; /** Reference to the underlying drop list instance. */ _dropListRef: DropListRef<CdkDropList<T>>; /** * Other draggable containers that this container is connected to and into which the * container's items can be transferred. Can either be references to other drop containers, * or their unique IDs. */ @Input('cdkDropListConnectedTo') connectedTo: (CdkDropList | string)[] | CdkDropList | string = []; /** Arbitrary data to attach to this container. */ @Input('cdkDropListData') data: T; /** Direction in which the list is oriented. */ @Input('cdkDropListOrientation') orientation: DropListOrientation; /** * Unique ID for the drop zone. Can be used as a reference * in the `connectedTo` of another `CdkDropList`. */ @Input() id: string = `cdk-drop-list-${_uniqueIdCounter++}`; /** Locks the position of the draggable elements inside the container along the specified axis. */ @Input('cdkDropListLockAxis') lockAxis: DragAxis; /** Whether starting a dragging sequence from this container is disabled. */ @Input({alias: 'cdkDropListDisabled', transform: booleanAttribute}) get disabled(): boolean { return this._disabled || (!!this._group && this._group.disabled); } set disabled(value: boolean) { // Usually we sync the directive and ref state right before dragging starts, in order to have // a single point of failure and to avoid having to use setters for everything. `disabled` is // a special case, because it can prevent the `beforeStarted` event from firing, which can lock // the user in a disabled state, so we also need to sync it as it's being set. this._dropListRef.disabled = this._disabled = value; } private _disabled: boolean; /** Whether sorting within this drop list is disabled. */ @Input({alias: 'cdkDropListSortingDisabled', transform: booleanAttribute}) sortingDisabled: boolean; /** * Function that is used to determine whether an item * is allowed to be moved into a drop container. */ @Input('cdkDropListEnterPredicate') enterPredicate: (drag: CdkDrag, drop: CdkDropList) => boolean = () => true; /** Functions that is used to determine whether an item can be sorted into a particular index. */ @Input('cdkDropListSortPredicate') sortPredicate: (index: number, drag: CdkDrag, drop: CdkDropList) => boolean = () => true; /** Whether to auto-scroll the view when the user moves their pointer close to the edges. */ @Input({alias: 'cdkDropListAutoScrollDisabled', transform: booleanAttribute}) autoScrollDisabled: boolean; /** Number of pixels to scroll for each frame when auto-scrolling an element. */ @Input('cdkDropListAutoScrollStep') autoScrollStep: NumberInput; /** * Selector that will be used to resolve an alternate element container for the drop list. * Passing an alternate container is useful for the cases where one might not have control * over the parent node of the draggable items within the list (e.g. due to content projection). * This allows for usages like: * * ``` * <div cdkDropList cdkDropListElementContainer=".inner"> * <div class="inner"> * <div cdkDrag></div> * </div> * </div> * ``` */ @Input('cdkDropListElementContainer') elementContainerSelector: string | null; /** Emits when the user drops an item inside the container. */ @Output('cdkDropListDropped') readonly dropped: EventEmitter<CdkDragDrop<T, any>> = new EventEmitter<CdkDragDrop<T, any>>(); /** * Emits when the user has moved a new drag item into this container. */ @Output('cdkDropListEntered') readonly entered: EventEmitter<CdkDragEnter<T>> = new EventEmitter<CdkDragEnter<T>>(); /** * Emits when the user removes an item from the container * by dragging it into another container. */ @Output('cdkDropListExited') readonly exited: EventEmitter<CdkDragExit<T>> = new EventEmitter<CdkDragExit<T>>(); /** Emits as the user is swapping items while actively dragging. */ @Output('cdkDropListSorted') readonly sorted: EventEmitter<CdkDragSortEvent<T>> = new EventEmitter<CdkDragSortEvent<T>>(); /** * Keeps track of the items that are registered with this container. Historically we used to * do this with a `ContentChildren` query, however queries don't handle transplanted views very * well which means that we can't handle cases like dragging the headers of a `mat-table` * correctly. What we do instead is to have the items register themselves with the container * and then we sort them based on their position in the DOM. */ private _unsortedItems = new Set<CdkDrag>(); constructor(...args: unknown[]); constructor() { const dragDrop = inject(DragDrop); const config = inject<DragDropConfig>(CDK_DRAG_CONFIG, {optional: true}); if (typeof ngDevMode === 'undefined' || ngDevMode) { assertElementNode(this.element.nativeElement, 'cdkDropList'); } this._dropListRef = dragDrop.createDropList(this.element); this._dropListRef.data = this; if (config) { this._assignDefaults(config); } this._dropListRef.enterPredicate = (drag: DragRef<CdkDrag>, drop: DropListRef<CdkDropList>) => { return this.enterPredicate(drag.data, drop.data); }; this._dropListRef.sortPredicate = ( index: number, drag: DragRef<CdkDrag>, drop: DropListRef<CdkDropList>, ) => { return this.sortPredicate(index, drag.data, drop.data); }; this._setupInputSyncSubscription(this._dropListRef); this._handleEvents(this._dropListRef); CdkDropList._dropLists.push(this); if (this._group) { this._group._items.add(this); } } /** Registers an items with the drop list. */ addItem(item: CdkDrag): void { this._unsortedItems.add(item); if (this._dropListRef.isDragging()) { this._syncItemsWithRef(); } } /** Removes an item from the drop list. */ removeItem(item: CdkDrag): void { this._unsortedItems.delete(item); if (this._dropListRef.isDragging()) { this._syncItemsWithRef(); } } /** Gets the registered items in the list, sorted by their position in the DOM. */ getSortedItems(): CdkDrag[] { return Array.from(this._unsortedItems).sort((a: CdkDrag, b: CdkDrag) => { const documentPosition = a._dragRef .getVisibleElement() .compareDocumentPosition(b._dragRef.getVisibleElement()); // `compareDocumentPosition` returns a bitmask so we have to use a bitwise operator. // https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition // tslint:disable-next-line:no-bitwise return documentPosition & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1; }); } ngOnDestroy() { const index = CdkDropList._dropLists.indexOf(this); if (index > -1) { CdkDropList._dropLists.splice(index, 1); } if (this._group) { this._group._items.delete(this); } this._unsortedItems.clear(); this._dropListRef.dispose(); this._destroyed.next(); this._destroyed.complete(); } /** Syncs the inputs of the CdkDropList with the options of the underlying DropListRef. */
{ "commit_id": "ea0d1ba7b", "end_byte": 9750, "start_byte": 1816, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list.ts" }
components/src/cdk/drag-drop/directives/drop-list.ts_9753_14734
private _setupInputSyncSubscription(ref: DropListRef<CdkDropList>) { if (this._dir) { this._dir.change .pipe(startWith(this._dir.value), takeUntil(this._destroyed)) .subscribe(value => ref.withDirection(value)); } ref.beforeStarted.subscribe(() => { const siblings = coerceArray(this.connectedTo).map(drop => { if (typeof drop === 'string') { const correspondingDropList = CdkDropList._dropLists.find(list => list.id === drop); if (!correspondingDropList && (typeof ngDevMode === 'undefined' || ngDevMode)) { console.warn(`CdkDropList could not find connected drop list with id "${drop}"`); } return correspondingDropList!; } return drop; }); if (this._group) { this._group._items.forEach(drop => { if (siblings.indexOf(drop) === -1) { siblings.push(drop); } }); } // Note that we resolve the scrollable parents here so that we delay the resolution // as long as possible, ensuring that the element is in its final place in the DOM. if (!this._scrollableParentsResolved) { const scrollableParents = this._scrollDispatcher .getAncestorScrollContainers(this.element) .map(scrollable => scrollable.getElementRef().nativeElement); this._dropListRef.withScrollableParents(scrollableParents); // Only do this once since it involves traversing the DOM and the parents // shouldn't be able to change without the drop list being destroyed. this._scrollableParentsResolved = true; } if (this.elementContainerSelector) { const container = this.element.nativeElement.querySelector(this.elementContainerSelector); if (!container && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw new Error( `CdkDropList could not find an element container matching the selector "${this.elementContainerSelector}"`, ); } ref.withElementContainer(container as HTMLElement); } ref.disabled = this.disabled; ref.lockAxis = this.lockAxis; ref.sortingDisabled = this.sortingDisabled; ref.autoScrollDisabled = this.autoScrollDisabled; ref.autoScrollStep = coerceNumberProperty(this.autoScrollStep, 2); ref .connectedTo(siblings.filter(drop => drop && drop !== this).map(list => list._dropListRef)) .withOrientation(this.orientation); }); } /** Handles events from the underlying DropListRef. */ private _handleEvents(ref: DropListRef<CdkDropList>) { ref.beforeStarted.subscribe(() => { this._syncItemsWithRef(); this._changeDetectorRef.markForCheck(); }); ref.entered.subscribe(event => { this.entered.emit({ container: this, item: event.item.data, currentIndex: event.currentIndex, }); }); ref.exited.subscribe(event => { this.exited.emit({ container: this, item: event.item.data, }); this._changeDetectorRef.markForCheck(); }); ref.sorted.subscribe(event => { this.sorted.emit({ previousIndex: event.previousIndex, currentIndex: event.currentIndex, container: this, item: event.item.data, }); }); ref.dropped.subscribe(dropEvent => { this.dropped.emit({ previousIndex: dropEvent.previousIndex, currentIndex: dropEvent.currentIndex, previousContainer: dropEvent.previousContainer.data, container: dropEvent.container.data, item: dropEvent.item.data, isPointerOverContainer: dropEvent.isPointerOverContainer, distance: dropEvent.distance, dropPoint: dropEvent.dropPoint, event: dropEvent.event, }); // Mark for check since all of these events run outside of change // detection and we're not guaranteed for something else to have triggered it. this._changeDetectorRef.markForCheck(); }); merge(ref.receivingStarted, ref.receivingStopped).subscribe(() => this._changeDetectorRef.markForCheck(), ); } /** Assigns the default input values based on a provided config object. */ private _assignDefaults(config: DragDropConfig) { const {lockAxis, draggingDisabled, sortingDisabled, listAutoScrollDisabled, listOrientation} = config; this.disabled = draggingDisabled == null ? false : draggingDisabled; this.sortingDisabled = sortingDisabled == null ? false : sortingDisabled; this.autoScrollDisabled = listAutoScrollDisabled == null ? false : listAutoScrollDisabled; this.orientation = listOrientation || 'vertical'; if (lockAxis) { this.lockAxis = lockAxis; } } /** Syncs up the registered drag items with underlying drop list ref. */ private _syncItemsWithRef() { this._dropListRef.withItems(this.getSortedItems().map(item => item._dragRef)); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 14734, "start_byte": 9753, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list.ts" }
components/src/cdk/drag-drop/directives/config.ts_0_1600
/** * @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 {InjectionToken} from '@angular/core'; import {DragRefConfig, Point, DragRef} from '../drag-ref'; /** Possible values that can be used to configure the drag start delay. */ export type DragStartDelay = number | {touch: number; mouse: number}; /** Possible axis along which dragging can be locked. */ export type DragAxis = 'x' | 'y'; /** Function that can be used to constrain the position of a dragged element. */ export type DragConstrainPosition = (point: Point, dragRef: DragRef) => Point; /** Possible orientations for a drop list. */ export type DropListOrientation = 'horizontal' | 'vertical' | 'mixed'; /** * Injection token that can be used to configure the * behavior of the drag&drop-related components. */ export const CDK_DRAG_CONFIG = new InjectionToken<DragDropConfig>('CDK_DRAG_CONFIG'); /** * Object that can be used to configure the drag * items and drop lists within a module or a component. */ export interface DragDropConfig extends Partial<DragRefConfig> { lockAxis?: DragAxis; dragStartDelay?: DragStartDelay; constrainPosition?: DragConstrainPosition; previewClass?: string | string[]; boundaryElement?: string; rootElementSelector?: string; draggingDisabled?: boolean; sortingDisabled?: boolean; listAutoScrollDisabled?: boolean; listOrientation?: DropListOrientation; zIndex?: number; previewContainer?: 'global' | 'parent'; }
{ "commit_id": "ea0d1ba7b", "end_byte": 1600, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/config.ts" }
components/src/cdk/drag-drop/directives/test-utils.spec.ts_0_5415
import {EnvironmentProviders, Provider, Type, ViewEncapsulation} from '@angular/core'; import {ComponentFixture, TestBed, tick} from '@angular/core/testing'; import {dispatchMouseEvent, dispatchTouchEvent} from '@angular/cdk/testing/private'; import {CDK_DRAG_CONFIG, DragDropConfig, DropListOrientation} from './config'; /** Options that can be used to configure a test. */ export interface DragDropTestConfig { providers?: (Provider | EnvironmentProviders)[]; dragDistance?: number; encapsulation?: ViewEncapsulation; listOrientation?: DropListOrientation; } /** * Creates a component fixture that can be used in a test. * @param componentType Component for which to create the fixture. * @param config Object that can be used to further configure the test. */ export function createComponent<T>( componentType: Type<T>, config: DragDropTestConfig = {}, ): ComponentFixture<T> { const dragConfig: DragDropConfig = { // We default the `dragDistance` to zero, because the majority of the tests // don't care about it and drags are a lot easier to simulate when we don't // have to deal with thresholds. dragStartThreshold: config?.dragDistance ?? 0, pointerDirectionChangeThreshold: 5, listOrientation: config.listOrientation, }; TestBed.configureTestingModule({ imports: [componentType], providers: [ { provide: CDK_DRAG_CONFIG, useValue: dragConfig, }, ...(config.providers || []), ], }); if (config.encapsulation != null) { TestBed.overrideComponent(componentType, { set: {encapsulation: config.encapsulation}, }); } return TestBed.createComponent<T>(componentType); } /** * Drags an element to a position on the page using the mouse. * @param fixture Fixture on which to run change detection. * @param element Element which is being dragged. * @param x Position along the x axis to which to drag the element. * @param y Position along the y axis to which to drag the element. */ export function dragElementViaMouse( fixture: ComponentFixture<any>, element: Element, x: number, y: number, ) { startDraggingViaMouse(fixture, element); dispatchMouseEvent(document, 'mousemove', x, y); fixture.detectChanges(); dispatchMouseEvent(document, 'mouseup', x, y); fixture.detectChanges(); } /** * Dispatches the events for starting a drag sequence. * @param fixture Fixture on which to run change detection. * @param element Element on which to dispatch the events. * @param x Position along the x axis to which to drag the element. * @param y Position along the y axis to which to drag the element. */ export function startDraggingViaMouse( fixture: ComponentFixture<any>, element: Element, x?: number, y?: number, ) { dispatchMouseEvent(element, 'mousedown', x, y); fixture.detectChanges(); dispatchMouseEvent(document, 'mousemove', x, y); fixture.detectChanges(); } /** * Drags an element to a position on the page using a touch device. * @param fixture Fixture on which to run change detection. * @param element Element which is being dragged. * @param x Position along the x axis to which to drag the element. * @param y Position along the y axis to which to drag the element. */ export function dragElementViaTouch( fixture: ComponentFixture<any>, element: Element, x: number, y: number, ) { startDraggingViaTouch(fixture, element); continueDraggingViaTouch(fixture, x, y); stopDraggingViaTouch(fixture, x, y); } /** * @param fixture Fixture on which to run change detection. * @param element Element which is being dragged. */ export function startDraggingViaTouch(fixture: ComponentFixture<any>, element: Element) { dispatchTouchEvent(element, 'touchstart'); fixture.detectChanges(); dispatchTouchEvent(document, 'touchmove'); fixture.detectChanges(); } /** * @param fixture Fixture on which to run change detection. * @param x Position along the x axis to which to drag the element. * @param y Position along the y axis to which to drag the element. */ export function continueDraggingViaTouch(fixture: ComponentFixture<any>, x: number, y: number) { dispatchTouchEvent(document, 'touchmove', x, y); fixture.detectChanges(); } /** * @param fixture Fixture on which to run change detection. * @param x Position along the x axis to which to drag the element. * @param y Position along the y axis to which to drag the element. */ export function stopDraggingViaTouch(fixture: ComponentFixture<any>, x: number, y: number) { dispatchTouchEvent(document, 'touchend', x, y); fixture.detectChanges(); } /** * Adds a large element to the page in order to make it scrollable. * @returns Function that should be used to clean up after the test is done. */ export function makeScrollable( direction: 'vertical' | 'horizontal' = 'vertical', element = document.body, ) { const veryTallElement = document.createElement('div'); veryTallElement.style.width = direction === 'vertical' ? '100%' : '4000px'; veryTallElement.style.height = direction === 'vertical' ? '2000px' : '5px'; element.prepend(veryTallElement); return () => { scrollTo(0, 0); veryTallElement.remove(); }; } /** Ticks the specified amount of `requestAnimationFrame`-s. */ export function tickAnimationFrames(amount: number) { tick(16.6 * amount); // Angular turns rAF calls into 16.6ms timeouts in tests. }
{ "commit_id": "ea0d1ba7b", "end_byte": 5415, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/test-utils.spec.ts" }
components/src/cdk/drag-drop/directives/drop-list-group.ts_0_1487
/** * @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 {Directive, OnDestroy, Input, InjectionToken, booleanAttribute} from '@angular/core'; /** * Injection token that can be used to reference instances of `CdkDropListGroup`. It serves as * alternative token to the actual `CdkDropListGroup` class which could cause unnecessary * retention of the class and its directive metadata. */ export const CDK_DROP_LIST_GROUP = new InjectionToken<CdkDropListGroup<unknown>>( 'CdkDropListGroup', ); /** * Declaratively connects sibling `cdkDropList` instances together. All of the `cdkDropList` * elements that are placed inside a `cdkDropListGroup` will be connected to each other * automatically. Can be used as an alternative to the `cdkDropListConnectedTo` input * from `cdkDropList`. */ @Directive({ selector: '[cdkDropListGroup]', exportAs: 'cdkDropListGroup', providers: [{provide: CDK_DROP_LIST_GROUP, useExisting: CdkDropListGroup}], }) export class CdkDropListGroup<T> implements OnDestroy { /** Drop lists registered inside the group. */ readonly _items = new Set<T>(); /** Whether starting a dragging sequence from inside this group is disabled. */ @Input({alias: 'cdkDropListGroupDisabled', transform: booleanAttribute}) disabled: boolean = false; ngOnDestroy() { this._items.clear(); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 1487, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/directives/drop-list-group.ts" }
components/src/cdk/drag-drop/sorting/single-axis-sort-strategy.ts_0_1190
/** * @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 {Direction} from '@angular/cdk/bidi'; import {DragDropRegistry} from '../drag-drop-registry'; import {moveItemInArray} from '../drag-utils'; import {combineTransforms} from '../dom/styling'; import {adjustDomRect, getMutableClientRect, isInsideClientRect} from '../dom/dom-rect'; import {DropListSortStrategy, SortPredicate} from './drop-list-sort-strategy'; import type {DragRef} from '../drag-ref'; /** * Entry in the position cache for draggable items. * @docs-private */ interface CachedItemPosition<T> { /** Instance of the drag item. */ drag: T; /** Dimensions of the item. */ clientRect: DOMRect; /** Amount by which the item has been moved since dragging started. */ offset: number; /** Inline transform that the drag item had when dragging started. */ initialTransform: string; } /** * Strategy that only supports sorting along a single axis. * Items are reordered using CSS transforms which allows for sorting to be animated. * @docs-private */
{ "commit_id": "ea0d1ba7b", "end_byte": 1190, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/sorting/single-axis-sort-strategy.ts" }
components/src/cdk/drag-drop/sorting/single-axis-sort-strategy.ts_1191_9564
export class SingleAxisSortStrategy implements DropListSortStrategy { /** Root element container of the drop list. */ private _element: HTMLElement; /** Function used to determine if an item can be sorted into a specific index. */ private _sortPredicate: SortPredicate<DragRef>; /** Cache of the dimensions of all the items inside the container. */ private _itemPositions: CachedItemPosition<DragRef>[] = []; /** * Draggable items that are currently active inside the container. Includes the items * that were there at the start of the sequence, as well as any items that have been dragged * in, but haven't been dropped yet. */ private _activeDraggables: DragRef[]; /** Direction in which the list is oriented. */ orientation: 'vertical' | 'horizontal' = 'vertical'; /** Layout direction of the drop list. */ direction: Direction; constructor(private _dragDropRegistry: DragDropRegistry) {} /** * Keeps track of the item that was last swapped with the dragged item, as well as what direction * the pointer was moving in when the swap occurred and whether the user's pointer continued to * overlap with the swapped item after the swapping occurred. */ private _previousSwap = { drag: null as DragRef | null, delta: 0, overlaps: false, }; /** * To be called when the drag sequence starts. * @param items Items that are currently in the list. */ start(items: readonly DragRef[]) { this.withItems(items); } /** * To be called when an item is being sorted. * @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. */ sort(item: DragRef, pointerX: number, pointerY: number, pointerDelta: {x: number; y: number}) { const siblings = this._itemPositions; const newIndex = this._getItemIndexFromPointerPosition(item, pointerX, pointerY, pointerDelta); if (newIndex === -1 && siblings.length > 0) { return null; } const isHorizontal = this.orientation === 'horizontal'; const currentIndex = siblings.findIndex(currentItem => currentItem.drag === item); const siblingAtNewPosition = siblings[newIndex]; const currentPosition = siblings[currentIndex].clientRect; const newPosition = siblingAtNewPosition.clientRect; const delta = currentIndex > newIndex ? 1 : -1; // How many pixels the item's placeholder should be offset. const itemOffset = this._getItemOffsetPx(currentPosition, newPosition, delta); // How many pixels all the other items should be offset. const siblingOffset = this._getSiblingOffsetPx(currentIndex, siblings, delta); // Save the previous order of the items before moving the item to its new index. // We use this to check whether an item has been moved as a result of the sorting. const oldOrder = siblings.slice(); // Shuffle the array in place. moveItemInArray(siblings, currentIndex, newIndex); siblings.forEach((sibling, index) => { // Don't do anything if the position hasn't changed. if (oldOrder[index] === sibling) { return; } const isDraggedItem = sibling.drag === item; const offset = isDraggedItem ? itemOffset : siblingOffset; const elementToOffset = isDraggedItem ? item.getPlaceholderElement() : sibling.drag.getRootElement(); // Update the offset to reflect the new position. sibling.offset += offset; const transformAmount = Math.round(sibling.offset * (1 / sibling.drag.scale)); // Since we're moving the items with a `transform`, we need to adjust their cached // client rects to reflect their new position, as well as swap their positions in the cache. // Note that we shouldn't use `getBoundingClientRect` here to update the cache, because the // elements may be mid-animation which will give us a wrong result. if (isHorizontal) { // Round the transforms since some browsers will // blur the elements, for sub-pixel transforms. elementToOffset.style.transform = combineTransforms( `translate3d(${transformAmount}px, 0, 0)`, sibling.initialTransform, ); adjustDomRect(sibling.clientRect, 0, offset); } else { elementToOffset.style.transform = combineTransforms( `translate3d(0, ${transformAmount}px, 0)`, sibling.initialTransform, ); adjustDomRect(sibling.clientRect, offset, 0); } }); // Note that it's important that we do this after the client rects have been adjusted. this._previousSwap.overlaps = isInsideClientRect(newPosition, pointerX, pointerY); this._previousSwap.drag = siblingAtNewPosition.drag; this._previousSwap.delta = isHorizontal ? pointerDelta.x : pointerDelta.y; return {previousIndex: currentIndex, currentIndex: newIndex}; } /** * Called when an item is being moved 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 { const newIndex = index == null || index < 0 ? // We use the coordinates of where the item entered the drop // zone to figure out at which index it should be inserted. this._getItemIndexFromPointerPosition(item, pointerX, pointerY) : index; const activeDraggables = this._activeDraggables; const currentIndex = activeDraggables.indexOf(item); const placeholder = item.getPlaceholderElement(); let newPositionReference: DragRef | undefined = activeDraggables[newIndex]; // If the item at the new position is the same as the item that is being dragged, // it means that we're trying to restore the item to its initial position. In this // case we should use the next item from the list as the reference. if (newPositionReference === item) { newPositionReference = activeDraggables[newIndex + 1]; } // If we didn't find a new position reference, it means that either the item didn't start off // in this container, or that the item requested to be inserted at the end of the list. if ( !newPositionReference && (newIndex == null || newIndex === -1 || newIndex < activeDraggables.length - 1) && this._shouldEnterAsFirstChild(pointerX, pointerY) ) { newPositionReference = activeDraggables[0]; } // Since the item may be in the `activeDraggables` already (e.g. if the user dragged it // into another container and back again), we have to ensure that it isn't duplicated. if (currentIndex > -1) { activeDraggables.splice(currentIndex, 1); } // Don't use items that are being dragged as a reference, because // their element has been moved down to the bottom of the body. if (newPositionReference && !this._dragDropRegistry.isDragging(newPositionReference)) { const element = newPositionReference.getRootElement(); element.parentElement!.insertBefore(placeholder, element); activeDraggables.splice(newIndex, 0, item); } else { this._element.appendChild(placeholder); activeDraggables.push(item); } // The transform needs to be cleared so it doesn't throw off the measurements. placeholder.style.transform = ''; // Note that usually `start` is called together with `enter` when an item goes into a new // container. This will cache item positions, but we need to refresh them since the amount // of items has changed. this._cacheItemPositions(); } /** Sets the items that are currently part of the list. */ withItems(items: readonly DragRef[]): void { this._activeDraggables = items.slice(); this._cacheItemPositions(); } /** Assigns a sort predicate to the strategy. */ withSortPredicate(predicate: SortPredicate<DragRef>): void { this._sortPredicate = predicate; } /** Resets the strategy to its initial state before dragging was started. */
{ "commit_id": "ea0d1ba7b", "end_byte": 9564, "start_byte": 1191, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/sorting/single-axis-sort-strategy.ts" }
components/src/cdk/drag-drop/sorting/single-axis-sort-strategy.ts_9567_17759
reset() { // TODO(crisbeto): may have to wait for the animations to finish. this._activeDraggables?.forEach(item => { const rootElement = item.getRootElement(); if (rootElement) { const initialTransform = this._itemPositions.find(p => p.drag === item)?.initialTransform; rootElement.style.transform = initialTransform || ''; } }); this._itemPositions = []; this._activeDraggables = []; this._previousSwap.drag = null; this._previousSwap.delta = 0; this._previousSwap.overlaps = false; } /** * Gets a snapshot of items currently in the list. * Can include items that we dragged in from another list. */ getActiveItemsSnapshot(): readonly DragRef[] { return this._activeDraggables; } /** Gets the index of a specific item. */ getItemIndex(item: DragRef): number { // Items are sorted always by top/left in the cache, however they flow differently in RTL. // The rest of the logic still stands no matter what orientation we're in, however // we need to invert the array when determining the index. const items = this.orientation === 'horizontal' && this.direction === 'rtl' ? this._itemPositions.slice().reverse() : this._itemPositions; return items.findIndex(currentItem => currentItem.drag === item); } /** Used to notify the strategy that the scroll position has changed. */ updateOnScroll(topDifference: number, leftDifference: number) { // Since we know the amount that the user has scrolled we can shift all of the // client rectangles ourselves. This is cheaper than re-measuring everything and // we can avoid inconsistent behavior where we might be measuring the element before // its position has changed. this._itemPositions.forEach(({clientRect}) => { adjustDomRect(clientRect, topDifference, leftDifference); }); // We need two loops for this, because we want all of the cached // positions to be up-to-date before we re-sort the item. this._itemPositions.forEach(({drag}) => { if (this._dragDropRegistry.isDragging(drag)) { // We need to re-sort the item manually, because the pointer move // events won't be dispatched while the user is scrolling. drag._sortFromLastPointerPosition(); } }); } withElementContainer(container: HTMLElement): void { this._element = container; } /** Refreshes the position cache of the items and sibling containers. */ private _cacheItemPositions() { const isHorizontal = this.orientation === 'horizontal'; this._itemPositions = this._activeDraggables .map(drag => { const elementToMeasure = drag.getVisibleElement(); return { drag, offset: 0, initialTransform: elementToMeasure.style.transform || '', clientRect: getMutableClientRect(elementToMeasure), }; }) .sort((a, b) => { return isHorizontal ? a.clientRect.left - b.clientRect.left : a.clientRect.top - b.clientRect.top; }); } /** * Gets the offset in pixels by which the item that is being dragged should be moved. * @param currentPosition Current position of the item. * @param newPosition Position of the item where the current item should be moved. * @param delta Direction in which the user is moving. */ private _getItemOffsetPx(currentPosition: DOMRect, newPosition: DOMRect, delta: 1 | -1) { const isHorizontal = this.orientation === 'horizontal'; let itemOffset = isHorizontal ? newPosition.left - currentPosition.left : newPosition.top - currentPosition.top; // Account for differences in the item width/height. if (delta === -1) { itemOffset += isHorizontal ? newPosition.width - currentPosition.width : newPosition.height - currentPosition.height; } return itemOffset; } /** * Gets the offset in pixels by which the items that aren't being dragged should be moved. * @param currentIndex Index of the item currently being dragged. * @param siblings All of the items in the list. * @param delta Direction in which the user is moving. */ private _getSiblingOffsetPx( currentIndex: number, siblings: CachedItemPosition<DragRef>[], delta: 1 | -1, ) { const isHorizontal = this.orientation === 'horizontal'; const currentPosition = siblings[currentIndex].clientRect; const immediateSibling = siblings[currentIndex + delta * -1]; let siblingOffset = currentPosition[isHorizontal ? 'width' : 'height'] * delta; if (immediateSibling) { const start = isHorizontal ? 'left' : 'top'; const end = isHorizontal ? 'right' : 'bottom'; // Get the spacing between the start of the current item and the end of the one immediately // after it in the direction in which the user is dragging, or vice versa. We add it to the // offset in order to push the element to where it will be when it's inline and is influenced // by the `margin` of its siblings. if (delta === -1) { siblingOffset -= immediateSibling.clientRect[start] - currentPosition[end]; } else { siblingOffset += currentPosition[start] - immediateSibling.clientRect[end]; } } return siblingOffset; } /** * Checks if pointer is entering in the first position * @param pointerX Position of the user's pointer along the X axis. * @param pointerY Position of the user's pointer along the Y axis. */ private _shouldEnterAsFirstChild(pointerX: number, pointerY: number) { if (!this._activeDraggables.length) { return false; } const itemPositions = this._itemPositions; const isHorizontal = this.orientation === 'horizontal'; // `itemPositions` are sorted by position while `activeDraggables` are sorted by child index // check if container is using some sort of "reverse" ordering (eg: flex-direction: row-reverse) const reversed = itemPositions[0].drag !== this._activeDraggables[0]; if (reversed) { const lastItemRect = itemPositions[itemPositions.length - 1].clientRect; return isHorizontal ? pointerX >= lastItemRect.right : pointerY >= lastItemRect.bottom; } else { const firstItemRect = itemPositions[0].clientRect; return isHorizontal ? pointerX <= firstItemRect.left : pointerY <= firstItemRect.top; } } /** * Gets the index of an item in the drop container, based on the position of the user's pointer. * @param item Item that is being sorted. * @param pointerX Position of the user's pointer along the X axis. * @param pointerY Position of the user's pointer along the Y axis. * @param delta Direction in which the user is moving their pointer. */ private _getItemIndexFromPointerPosition( item: DragRef, pointerX: number, pointerY: number, delta?: {x: number; y: number}, ): number { const isHorizontal = this.orientation === 'horizontal'; const index = this._itemPositions.findIndex(({drag, clientRect}) => { // Skip the item itself. if (drag === item) { return false; } if (delta) { const direction = isHorizontal ? delta.x : delta.y; // If the user is still hovering over the same item as last time, their cursor hasn't left // the item after we made the swap, and they didn't change the direction in which they're // dragging, we don't consider it a direction swap. if ( drag === this._previousSwap.drag && this._previousSwap.overlaps && direction === this._previousSwap.delta ) { return false; } } return isHorizontal ? // Round these down since most browsers report client rects with // sub-pixel precision, whereas the pointer coordinates are rounded to pixels. pointerX >= Math.floor(clientRect.left) && pointerX < Math.floor(clientRect.right) : pointerY >= Math.floor(clientRect.top) && pointerY < Math.floor(clientRect.bottom); }); return index === -1 || !this._sortPredicate(index, item) ? -1 : index; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 17759, "start_byte": 9567, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/sorting/single-axis-sort-strategy.ts" }
components/src/cdk/drag-drop/sorting/drop-list-sort-strategy.ts_0_1198
/** * @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 type {DragRef} from '../drag-ref'; /** * Function that is used to determine whether an item can be sorted into a particular index. * @docs-private */ export type SortPredicate<T> = (index: number, item: T) => boolean; /** * Strategy used to sort and position items within a drop list. * @docs-private */ export interface DropListSortStrategy { start(items: readonly DragRef[]): void; sort( item: DragRef, pointerX: number, pointerY: number, pointerDelta: {x: number; y: number}, ): {previousIndex: number; currentIndex: number} | null; enter(item: DragRef, pointerX: number, pointerY: number, index?: number): void; withItems(items: readonly DragRef[]): void; withSortPredicate(predicate: SortPredicate<DragRef>): void; withElementContainer(container: HTMLElement): void; reset(): void; getActiveItemsSnapshot(): readonly DragRef[]; getItemIndex(item: DragRef): number; updateOnScroll(topDifference: number, leftDifference: number): void; }
{ "commit_id": "ea0d1ba7b", "end_byte": 1198, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/sorting/drop-list-sort-strategy.ts" }
components/src/cdk/drag-drop/sorting/mixed-sort-strategy.ts_0_630
/** * @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 {_getShadowRoot} from '@angular/cdk/platform'; import {moveItemInArray} from '../drag-utils'; import {DropListSortStrategy, SortPredicate} from './drop-list-sort-strategy'; import {DragDropRegistry} from '../drag-drop-registry'; import type {DragRef} from '../drag-ref'; /** * Strategy that only supports sorting on a list that might wrap. * Items are reordered by moving their DOM nodes around. * @docs-private */
{ "commit_id": "ea0d1ba7b", "end_byte": 630, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/sorting/mixed-sort-strategy.ts" }
components/src/cdk/drag-drop/sorting/mixed-sort-strategy.ts_631_8903
export class MixedSortStrategy implements DropListSortStrategy { /** Root element container of the drop list. */ private _element: HTMLElement; /** Function used to determine if an item can be sorted into a specific index. */ private _sortPredicate: SortPredicate<DragRef>; /** Lazily-resolved root node containing the list. Use `_getRootNode` to read this. */ private _rootNode: DocumentOrShadowRoot | undefined; /** * Draggable items that are currently active inside the container. Includes the items * that were there at the start of the sequence, as well as any items that have been dragged * in, but haven't been dropped yet. */ private _activeItems: DragRef[]; /** * Keeps track of the item that was last swapped with the dragged item, as well as what direction * the pointer was moving in when the swap occurred and whether the user's pointer continued to * overlap with the swapped item after the swapping occurred. */ private _previousSwap = { drag: null as DragRef | null, deltaX: 0, deltaY: 0, overlaps: false, }; /** * Keeps track of the relationship between a node and its next sibling. This information * is used to restore the DOM to the order it was in before dragging started. */ private _relatedNodes: [node: Node, nextSibling: Node | null][] = []; constructor( private _document: Document, private _dragDropRegistry: DragDropRegistry, ) {} /** * To be called when the drag sequence starts. * @param items Items that are currently in the list. */ start(items: readonly DragRef[]): void { const childNodes = this._element.childNodes; this._relatedNodes = []; for (let i = 0; i < childNodes.length; i++) { const node = childNodes[i]; this._relatedNodes.push([node, node.nextSibling]); } this.withItems(items); } /** * To be called when an item is being sorted. * @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. */ sort( item: DragRef, pointerX: number, pointerY: number, pointerDelta: {x: number; y: number}, ): {previousIndex: number; currentIndex: number} | null { const newIndex = this._getItemIndexFromPointerPosition(item, pointerX, pointerY); const previousSwap = this._previousSwap; if (newIndex === -1 || this._activeItems[newIndex] === item) { return null; } const toSwapWith = this._activeItems[newIndex]; // Prevent too many swaps over the same item. if ( previousSwap.drag === toSwapWith && previousSwap.overlaps && previousSwap.deltaX === pointerDelta.x && previousSwap.deltaY === pointerDelta.y ) { return null; } const previousIndex = this.getItemIndex(item); const current = item.getPlaceholderElement(); const overlapElement = toSwapWith.getRootElement(); if (newIndex > previousIndex) { overlapElement.after(current); } else { overlapElement.before(current); } moveItemInArray(this._activeItems, previousIndex, newIndex); const newOverlapElement = this._getRootNode().elementFromPoint(pointerX, pointerY); // Note: it's tempting to save the entire `pointerDelta` object here, however that'll // break this functionality, because the same object is passed for all `sort` calls. previousSwap.deltaX = pointerDelta.x; previousSwap.deltaY = pointerDelta.y; previousSwap.drag = toSwapWith; previousSwap.overlaps = overlapElement === newOverlapElement || overlapElement.contains(newOverlapElement); return { previousIndex, currentIndex: newIndex, }; } /** * Called when an item is being moved 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 { let enterIndex = index == null || index < 0 ? this._getItemIndexFromPointerPosition(item, pointerX, pointerY) : index; // In some cases (e.g. when the container has padding) we might not be able to figure // out which item to insert the dragged item next to, because the pointer didn't overlap // with anything. In that case we find the item that's closest to the pointer. if (enterIndex === -1) { enterIndex = this._getClosestItemIndexToPointer(item, pointerX, pointerY); } const targetItem = this._activeItems[enterIndex] as DragRef | undefined; const currentIndex = this._activeItems.indexOf(item); if (currentIndex > -1) { this._activeItems.splice(currentIndex, 1); } if (targetItem && !this._dragDropRegistry.isDragging(targetItem)) { this._activeItems.splice(enterIndex, 0, item); targetItem.getRootElement().before(item.getPlaceholderElement()); } else { this._activeItems.push(item); this._element.appendChild(item.getPlaceholderElement()); } } /** Sets the items that are currently part of the list. */ withItems(items: readonly DragRef[]): void { this._activeItems = items.slice(); } /** Assigns a sort predicate to the strategy. */ withSortPredicate(predicate: SortPredicate<DragRef>): void { this._sortPredicate = predicate; } /** Resets the strategy to its initial state before dragging was started. */ reset(): void { const root = this._element; const previousSwap = this._previousSwap; // Moving elements around in the DOM can break things like the `@for` loop, because it // uses comment nodes to know where to insert elements. To avoid such issues, we restore // the DOM nodes in the list to their original order when the list is reset. // Note that this could be simpler if we just saved all the nodes, cleared the root // and then appended them in the original order. We don't do it, because it can break // down depending on when the snapshot was taken. E.g. we may end up snapshotting the // placeholder element which is removed after dragging. for (let i = this._relatedNodes.length - 1; i > -1; i--) { const [node, nextSibling] = this._relatedNodes[i]; if (node.parentNode === root && node.nextSibling !== nextSibling) { if (nextSibling === null) { root.appendChild(node); } else if (nextSibling.parentNode === root) { root.insertBefore(node, nextSibling); } } } this._relatedNodes = []; this._activeItems = []; previousSwap.drag = null; previousSwap.deltaX = previousSwap.deltaY = 0; previousSwap.overlaps = false; } /** * Gets a snapshot of items currently in the list. * Can include items that we dragged in from another list. */ getActiveItemsSnapshot(): readonly DragRef[] { return this._activeItems; } /** Gets the index of a specific item. */ getItemIndex(item: DragRef): number { return this._activeItems.indexOf(item); } /** Used to notify the strategy that the scroll position has changed. */ updateOnScroll(): void { this._activeItems.forEach(item => { if (this._dragDropRegistry.isDragging(item)) { // We need to re-sort the item manually, because the pointer move // events won't be dispatched while the user is scrolling. item._sortFromLastPointerPosition(); } }); } withElementContainer(container: HTMLElement): void { if (container !== this._element) { this._element = container; this._rootNode = undefined; } } /** * Gets the index of an item in the drop container, based on the position of the user's pointer. * @param item Item that is being sorted. * @param pointerX Position of the user's pointer along the X axis. * @param pointerY Position of the user's pointer along the Y axis. * @param delta Direction in which the user is moving their pointer. */
{ "commit_id": "ea0d1ba7b", "end_byte": 8903, "start_byte": 631, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/sorting/mixed-sort-strategy.ts" }
components/src/cdk/drag-drop/sorting/mixed-sort-strategy.ts_8906_11079
private _getItemIndexFromPointerPosition( item: DragRef, pointerX: number, pointerY: number, ): number { const elementAtPoint = this._getRootNode().elementFromPoint( Math.floor(pointerX), Math.floor(pointerY), ); const index = elementAtPoint ? this._activeItems.findIndex(item => { const root = item.getRootElement(); return elementAtPoint === root || root.contains(elementAtPoint); }) : -1; return index === -1 || !this._sortPredicate(index, item) ? -1 : index; } /** Lazily resolves the list's root node. */ private _getRootNode(): DocumentOrShadowRoot { // Resolve the root node lazily to ensure that the drop list is in its final place in the DOM. if (!this._rootNode) { this._rootNode = _getShadowRoot(this._element) || this._document; } return this._rootNode; } /** * Finds the index of the item that's closest to the item being dragged. * @param item Item being dragged. * @param pointerX Position of the user's pointer along the X axis. * @param pointerY Position of the user's pointer along the Y axis. */ private _getClosestItemIndexToPointer(item: DragRef, pointerX: number, pointerY: number): number { if (this._activeItems.length === 0) { return -1; } if (this._activeItems.length === 1) { return 0; } let minDistance = Infinity; let minIndex = -1; // Find the Euclidean distance (https://en.wikipedia.org/wiki/Euclidean_distance) between each // item and the pointer, and return the smallest one. Note that this is a bit flawed in that DOM // nodes are rectangles, not points, so we use the top/left coordinates. It should be enough // for our purposes. for (let i = 0; i < this._activeItems.length; i++) { const current = this._activeItems[i]; if (current !== item) { const {x, y} = current.getRootElement().getBoundingClientRect(); const distance = Math.hypot(pointerX - x, pointerY - y); if (distance < minDistance) { minDistance = distance; minIndex = i; } } } return minIndex; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 11079, "start_byte": 8906, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/sorting/mixed-sort-strategy.ts" }
components/src/cdk/drag-drop/dom/clone-node.ts_0_2805
/** * @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 */ /** Creates a deep clone of an element. */ export function deepCloneNode(node: HTMLElement): HTMLElement { const clone = node.cloneNode(true) as HTMLElement; const descendantsWithId = clone.querySelectorAll('[id]'); const nodeName = node.nodeName.toLowerCase(); // Remove the `id` to avoid having multiple elements with the same id on the page. clone.removeAttribute('id'); for (let i = 0; i < descendantsWithId.length; i++) { descendantsWithId[i].removeAttribute('id'); } if (nodeName === 'canvas') { transferCanvasData(node as HTMLCanvasElement, clone as HTMLCanvasElement); } else if (nodeName === 'input' || nodeName === 'select' || nodeName === 'textarea') { transferInputData(node as HTMLInputElement, clone as HTMLInputElement); } transferData('canvas', node, clone, transferCanvasData); transferData('input, textarea, select', node, clone, transferInputData); return clone; } /** Matches elements between an element and its clone and allows for their data to be cloned. */ function transferData<T extends Element>( selector: string, node: HTMLElement, clone: HTMLElement, callback: (source: T, clone: T) => void, ) { const descendantElements = node.querySelectorAll<T>(selector); if (descendantElements.length) { const cloneElements = clone.querySelectorAll<T>(selector); for (let i = 0; i < descendantElements.length; i++) { callback(descendantElements[i], cloneElements[i]); } } } // Counter for unique cloned radio button names. let cloneUniqueId = 0; /** Transfers the data of one input element to another. */ function transferInputData( source: Element & {value: string}, clone: Element & {value: string; name: string; type: string}, ) { // Browsers throw an error when assigning the value of a file input programmatically. if (clone.type !== 'file') { clone.value = source.value; } // Radio button `name` attributes must be unique for radio button groups // otherwise original radio buttons can lose their checked state // once the clone is inserted in the DOM. if (clone.type === 'radio' && clone.name) { clone.name = `mat-clone-${clone.name}-${cloneUniqueId++}`; } } /** Transfers the data of one canvas element to another. */ function transferCanvasData(source: HTMLCanvasElement, clone: HTMLCanvasElement) { const context = clone.getContext('2d'); if (context) { // In some cases `drawImage` can throw (e.g. if the canvas size is 0x0). // We can't do much about it so just ignore the error. try { context.drawImage(source, 0, 0); } catch {} } }
{ "commit_id": "ea0d1ba7b", "end_byte": 2805, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/dom/clone-node.ts" }
components/src/cdk/drag-drop/dom/parent-position-tracker.ts_0_3150
/** * @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 {_getEventTarget} from '@angular/cdk/platform'; import {getMutableClientRect, adjustDomRect} from './dom-rect'; /** Object holding the scroll position of something. */ interface ScrollPosition { top: number; left: number; } /** Keeps track of the scroll position and dimensions of the parents of an element. */ export class ParentPositionTracker { /** Cached positions of the scrollable parent elements. */ readonly positions = new Map< Document | HTMLElement, { scrollPosition: ScrollPosition; clientRect?: DOMRect; } >(); constructor(private _document: Document) {} /** Clears the cached positions. */ clear() { this.positions.clear(); } /** Caches the positions. Should be called at the beginning of a drag sequence. */ cache(elements: readonly HTMLElement[]) { this.clear(); this.positions.set(this._document, { scrollPosition: this.getViewportScrollPosition(), }); elements.forEach(element => { this.positions.set(element, { scrollPosition: {top: element.scrollTop, left: element.scrollLeft}, clientRect: getMutableClientRect(element), }); }); } /** Handles scrolling while a drag is taking place. */ handleScroll(event: Event): ScrollPosition | null { const target = _getEventTarget<HTMLElement | Document>(event)!; const cachedPosition = this.positions.get(target); if (!cachedPosition) { return null; } const scrollPosition = cachedPosition.scrollPosition; let newTop: number; let newLeft: number; if (target === this._document) { const viewportScrollPosition = this.getViewportScrollPosition(); newTop = viewportScrollPosition.top; newLeft = viewportScrollPosition.left; } else { newTop = (target as HTMLElement).scrollTop; newLeft = (target as HTMLElement).scrollLeft; } const topDifference = scrollPosition.top - newTop; const leftDifference = scrollPosition.left - newLeft; // Go through and update the cached positions of the scroll // parents that are inside the element that was scrolled. this.positions.forEach((position, node) => { if (position.clientRect && target !== node && target.contains(node)) { adjustDomRect(position.clientRect, topDifference, leftDifference); } }); scrollPosition.top = newTop; scrollPosition.left = newLeft; return {top: topDifference, left: leftDifference}; } /** * Gets the scroll position of the viewport. Note that we use the scrollX and scrollY directly, * instead of going through the `ViewportRuler`, because the first value the ruler looks at is * the top/left offset of the `document.documentElement` which works for most cases, but breaks * if the element is offset by something like the `BlockScrollStrategy`. */ getViewportScrollPosition() { return {top: window.scrollY, left: window.scrollX}; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 3150, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/dom/parent-position-tracker.ts" }
components/src/cdk/drag-drop/dom/root-node.ts_0_771
/** * @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 {EmbeddedViewRef} from '@angular/core'; /** * Gets the root HTML element of an embedded view. * If the root is not an HTML element it gets wrapped in one. */ export function getRootNode(viewRef: EmbeddedViewRef<any>, _document: Document): HTMLElement { const rootNodes: Node[] = viewRef.rootNodes; if (rootNodes.length === 1 && rootNodes[0].nodeType === _document.ELEMENT_NODE) { return rootNodes[0] as HTMLElement; } const wrapper = _document.createElement('div'); rootNodes.forEach(node => wrapper.appendChild(node)); return wrapper; }
{ "commit_id": "ea0d1ba7b", "end_byte": 771, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/dom/root-node.ts" }
components/src/cdk/drag-drop/dom/dom-rect.ts_0_2593
/** * @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 */ /** Gets a mutable version of an element's bounding `DOMRect`. */ export function getMutableClientRect(element: Element): DOMRect { const rect = element.getBoundingClientRect(); // We need to clone the `clientRect` here, because all the values on it are readonly // and we need to be able to update them. Also we can't use a spread here, because // the values on a `DOMRect` aren't own properties. See: // https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect#Notes return { top: rect.top, right: rect.right, bottom: rect.bottom, left: rect.left, width: rect.width, height: rect.height, x: rect.x, y: rect.y, } as DOMRect; } /** * Checks whether some coordinates are within a `DOMRect`. * @param clientRect DOMRect that is being checked. * @param x Coordinates along the X axis. * @param y Coordinates along the Y axis. */ export function isInsideClientRect(clientRect: DOMRect, x: number, y: number) { const {top, bottom, left, right} = clientRect; return y >= top && y <= bottom && x >= left && x <= right; } /** * Updates the top/left positions of a `DOMRect`, as well as their bottom/right counterparts. * @param domRect `DOMRect` that should be updated. * @param top Amount to add to the `top` position. * @param left Amount to add to the `left` position. */ export function adjustDomRect( domRect: { top: number; bottom: number; left: number; right: number; width: number; height: number; }, top: number, left: number, ) { domRect.top += top; domRect.bottom = domRect.top + domRect.height; domRect.left += left; domRect.right = domRect.left + domRect.width; } /** * Checks whether the pointer coordinates are close to a DOMRect. * @param rect DOMRect to check against. * @param threshold Threshold around the DOMRect. * @param pointerX Coordinates along the X axis. * @param pointerY Coordinates along the Y axis. */ export function isPointerNearDomRect( rect: DOMRect, threshold: number, pointerX: number, pointerY: number, ): boolean { const {top, right, bottom, left, width, height} = rect; const xThreshold = width * threshold; const yThreshold = height * threshold; return ( pointerY > top - yThreshold && pointerY < bottom + yThreshold && pointerX > left - xThreshold && pointerX < right + xThreshold ); }
{ "commit_id": "ea0d1ba7b", "end_byte": 2593, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/dom/dom-rect.ts" }
components/src/cdk/drag-drop/dom/styling.ts_0_3591
/** * @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 */ /** * Extended CSSStyleDeclaration that includes a couple of drag-related * properties that aren't in the built-in TS typings. */ export interface DragCSSStyleDeclaration extends CSSStyleDeclaration { msScrollSnapType: string; scrollSnapType: string; webkitTapHighlightColor: string; } /** * Shallow-extends a stylesheet object with another stylesheet-like object. * Note that the keys in `source` have to be dash-cased. * @docs-private */ export function extendStyles( dest: CSSStyleDeclaration, source: Record<string, string>, importantProperties?: Set<string>, ) { for (let key in source) { if (source.hasOwnProperty(key)) { const value = source[key]; if (value) { dest.setProperty(key, value, importantProperties?.has(key) ? 'important' : ''); } else { dest.removeProperty(key); } } } return dest; } /** * Toggles whether the native drag interactions should be enabled for an element. * @param element Element on which to toggle the drag interactions. * @param enable Whether the drag interactions should be enabled. * @docs-private */ export function toggleNativeDragInteractions(element: HTMLElement, enable: boolean) { const userSelect = enable ? '' : 'none'; extendStyles(element.style, { 'touch-action': enable ? '' : 'none', '-webkit-user-drag': enable ? '' : 'none', '-webkit-tap-highlight-color': enable ? '' : 'transparent', 'user-select': userSelect, '-ms-user-select': userSelect, '-webkit-user-select': userSelect, '-moz-user-select': userSelect, }); } /** * Toggles whether an element is visible while preserving its dimensions. * @param element Element whose visibility to toggle * @param enable Whether the element should be visible. * @param importantProperties Properties to be set as `!important`. * @docs-private */ export function toggleVisibility( element: HTMLElement, enable: boolean, importantProperties?: Set<string>, ) { extendStyles( element.style, { position: enable ? '' : 'fixed', top: enable ? '' : '0', opacity: enable ? '' : '0', left: enable ? '' : '-999em', }, importantProperties, ); } /** * Combines a transform string with an optional other transform * that exited before the base transform was applied. */ export function combineTransforms(transform: string, initialTransform?: string): string { return initialTransform && initialTransform != 'none' ? transform + ' ' + initialTransform : transform; } /** * Matches the target element's size to the source's size. * @param target Element that needs to be resized. * @param sourceRect Dimensions of the source element. */ export function matchElementSize(target: HTMLElement, sourceRect: DOMRect): void { target.style.width = `${sourceRect.width}px`; target.style.height = `${sourceRect.height}px`; target.style.transform = getTransform(sourceRect.left, sourceRect.top); } /** * Gets a 3d `transform` that can be applied to an element. * @param x Desired position of the element along the X axis. * @param y Desired position of the element along the Y axis. */ export function getTransform(x: number, y: number): string { // Round the transforms since some browsers will // blur the elements for sub-pixel transforms. return `translate3d(${Math.round(x)}px, ${Math.round(y)}px, 0)`; }
{ "commit_id": "ea0d1ba7b", "end_byte": 3591, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/dom/styling.ts" }
components/src/cdk/drag-drop/dom/transition-duration.ts_0_1832
/** * @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 */ /** Parses a CSS time value to milliseconds. */ function parseCssTimeUnitsToMs(value: string): number { // Some browsers will return it in seconds, whereas others will return milliseconds. const multiplier = value.toLowerCase().indexOf('ms') > -1 ? 1 : 1000; return parseFloat(value) * multiplier; } /** Gets the transform transition duration, including the delay, of an element in milliseconds. */ export function getTransformTransitionDurationInMs(element: HTMLElement): number { const computedStyle = getComputedStyle(element); const transitionedProperties = parseCssPropertyValue(computedStyle, 'transition-property'); const property = transitionedProperties.find(prop => prop === 'transform' || prop === 'all'); // If there's no transition for `all` or `transform`, we shouldn't do anything. if (!property) { return 0; } // Get the index of the property that we're interested in and match // it up to the same index in `transition-delay` and `transition-duration`. const propertyIndex = transitionedProperties.indexOf(property); const rawDurations = parseCssPropertyValue(computedStyle, 'transition-duration'); const rawDelays = parseCssPropertyValue(computedStyle, 'transition-delay'); return ( parseCssTimeUnitsToMs(rawDurations[propertyIndex]) + parseCssTimeUnitsToMs(rawDelays[propertyIndex]) ); } /** Parses out multiple values from a computed style into an array. */ function parseCssPropertyValue(computedStyle: CSSStyleDeclaration, name: string): string[] { const value = computedStyle.getPropertyValue(name); return value.split(',').map(part => part.trim()); }
{ "commit_id": "ea0d1ba7b", "end_byte": 1832, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk/drag-drop/dom/transition-duration.ts" }