fix(drag-drop): clear duplicate ids from descendants (#15135)

Fixes `CdkDrag` generating elements with duplicate ids, if one of its descendants has an id.

Fixes #15120.
This commit is contained in:
Kristiyan Kostadinov
2019-02-22 16:09:19 +01:00
committed by Jeremy Elbourn
parent f1e1528e8d
commit 751fe8a0b3
2 changed files with 37 additions and 0 deletions
+30
View File
@@ -1392,6 +1392,21 @@ describe('CdkDrag', () => {
expect(preview.getAttribute('id')).toBeFalsy();
}));
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, [], 5);
fixture.detectChanges();
@@ -1597,6 +1612,21 @@ describe('CdkDrag', () => {
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);
}));
it('should not create placeholder if the element was not dragged far enough', fakeAsync(() => {
const fixture = createComponent(DraggableInDropZone, [], 5);
fixture.detectChanges();
+7
View File
@@ -1003,8 +1003,15 @@ function getTransform(x: number, y: number): string {
/** Creates a deep clone of an element. */
function deepCloneNode(node: HTMLElement): HTMLElement {
const clone = node.cloneNode(true) as HTMLElement;
const descendantsWithId = clone.querySelectorAll('[id]');
// 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');
}
return clone;
}