Skip to content

fix(cdk/drag-drop): throw if drop list or handle are set on a non-element node #20668

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/cdk/drag-drop/directives/assertions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* @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.io/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}".`);
}
}
6 changes: 6 additions & 0 deletions src/cdk/drag-drop/directives/drag-handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
} from '@angular/core';
import {Subject} from 'rxjs';
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
Expand Down Expand Up @@ -54,6 +55,11 @@ export class CdkDragHandle implements OnDestroy {
constructor(
public element: ElementRef<HTMLElement>,
@Inject(CDK_DRAG_PARENT) @Optional() @SkipSelf() parentDrag?: any) {

if (typeof ngDevMode === 'undefined' || ngDevMode) {
assertElementNode(element.nativeElement, 'cdkDragHandle');
}

this._parentDrag = parentDrag;
}

Expand Down
34 changes: 33 additions & 1 deletion src/cdk/drag-drop/directives/drag.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -952,7 +952,7 @@ describe('CdkDrag', () => {
expect(dragElement.style.transform).toBe('translate3d(50px, 50px, 0px)');
}));

it('should throw if attached to an ng-container', fakeAsync(() => {
it('should throw if drag item is attached to an ng-container', fakeAsync(() => {
expect(() => {
createComponent(DraggableOnNgContainer).detectChanges();
flush();
Expand Down Expand Up @@ -1459,6 +1459,13 @@ describe('CdkDrag', () => {
expect(dragElement.style.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/);
}));

});

describe('in a drop container', () => {
Expand Down Expand Up @@ -4209,6 +4216,13 @@ describe('CdkDrag', () => {
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/);
}));

});

describe('in a connected drop container', () => {
Expand Down Expand Up @@ -6201,6 +6215,24 @@ class NestedDropListGroups {
class DraggableOnNgContainer {}


@Component({
template: `
<div cdkDrag>
<ng-container cdkDragHandle></ng-container>
</div>
`
})
class DragHandleOnNgContainer {}


@Component({
template: `
<ng-container cdkDropList></ng-container>
`
})
class DropListOnNgContainer {}


@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
Expand Down
13 changes: 8 additions & 5 deletions src/cdk/drag-drop/directives/drag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import {DragRef, Point} from '../drag-ref';
import {CDK_DROP_LIST, CdkDropListInternal as CdkDropList} from './drop-list';
import {DragDrop} from '../drag-drop';
import {CDK_DRAG_CONFIG, DragDropConfig, DragStartDelay, DragAxis} from './config';
import {assertElementNode} from './assertions';

/** Element that can be moved inside a CdkDropList container. */
@Directive({
Expand Down Expand Up @@ -182,7 +183,11 @@ export class CdkDrag<T = any> implements AfterViewInit, OnChanges, OnDestroy {
public element: ElementRef<HTMLElement>,
/** Droppable container that the draggable is a part of. */
@Inject(CDK_DROP_LIST) @Optional() @SkipSelf() public dropContainer: CdkDropList,
@Inject(DOCUMENT) private _document: any, private _ngZone: NgZone,
/**
* @deprecated `_document` parameter no longer being used and will be removed.
* @breaking-change 12.0.0
*/
@Inject(DOCUMENT) _document: any, private _ngZone: NgZone,
private _viewContainerRef: ViewContainerRef,
@Optional() @Inject(CDK_DRAG_CONFIG) config: DragDropConfig,
@Optional() private _dir: Directionality, dragDrop: DragDrop,
Expand Down Expand Up @@ -322,10 +327,8 @@ export class CdkDrag<T = any> implements AfterViewInit, OnChanges, OnDestroy {
const rootElement = this.rootElementSelector ?
getClosestMatchingAncestor(element, this.rootElementSelector) : element;

if (rootElement && rootElement.nodeType !== this._document.ELEMENT_NODE &&
(typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error(`cdkDrag must be attached to an element node. ` +
`Currently attached to "${rootElement.nodeName}".`);
if (rootElement && (typeof ngDevMode === 'undefined' || ngDevMode)) {
assertElementNode(rootElement, 'cdkDrag');
}

this._dragRef.withRootElement(rootElement || element);
Expand Down
8 changes: 7 additions & 1 deletion src/cdk/drag-drop/directives/drop-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {DragDrop} from '../drag-drop';
import {DropListOrientation, DragAxis, DragDropConfig, CDK_DRAG_CONFIG} from './config';
import {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;
Expand Down Expand Up @@ -60,7 +61,7 @@ export const CDK_DROP_LIST = new InjectionToken<CdkDropList>('CdkDropList');
],
host: {
'class': 'cdk-drop-list',
'[id]': 'id',
'[attr.id]': 'id',
'[class.cdk-drop-list-disabled]': 'disabled',
'[class.cdk-drop-list-dragging]': '_dropListRef.isDragging()',
'[class.cdk-drop-list-receiving]': '_dropListRef.isReceiving()',
Expand Down Expand Up @@ -174,6 +175,11 @@ export class CdkDropList<T = any> implements OnDestroy {
@Optional() @Inject(CDK_DROP_LIST_GROUP) @SkipSelf()
private _group?: CdkDropListGroup<CdkDropList>,
@Optional() @Inject(CDK_DRAG_CONFIG) config?: DragDropConfig) {

if (typeof ngDevMode === 'undefined' || ngDevMode) {
assertElementNode(element.nativeElement, 'cdkDropList');
}

this._dropListRef = dragDrop.createDropList(element);
this._dropListRef.data = this;

Expand Down
2 changes: 1 addition & 1 deletion src/dev-app/drag-drop/drag-drop-demo.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ <h2>To do</h2>
[cdkDropListData]="todo">
<div *ngFor="let item of todo" cdkDrag>
{{item}}
<mat-icon cdkDragHandle svgIcon="dnd-move"></mat-icon>
<ng-container cdkDragHandle>move</ng-container>
</div>
</div>
</div>
Expand Down
3 changes: 2 additions & 1 deletion tools/public_api_guard/cdk/drag-drop.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ export declare class CdkDrag<T = any> implements AfterViewInit, OnChanges, OnDes
started: EventEmitter<CdkDragStart>;
constructor(
element: ElementRef<HTMLElement>,
dropContainer: CdkDropList, _document: any, _ngZone: NgZone, _viewContainerRef: ViewContainerRef, config: DragDropConfig, _dir: Directionality, dragDrop: DragDrop, _changeDetectorRef: ChangeDetectorRef, _selfHandle?: CdkDragHandle | undefined);
dropContainer: CdkDropList,
_document: any, _ngZone: NgZone, _viewContainerRef: ViewContainerRef, config: DragDropConfig, _dir: Directionality, dragDrop: DragDrop, _changeDetectorRef: ChangeDetectorRef, _selfHandle?: CdkDragHandle | undefined);
getFreeDragPosition(): {
readonly x: number;
readonly y: number;
Expand Down