Skip to content

Commit e587f4b

Browse files
crisbetojosephperrott
authored andcommitted
fix(overlay): avoid same overlay being added to the keyboard event stack multiple times (#12222)
1 parent 1e847f1 commit e587f4b

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

src/cdk/overlay/keyboard/overlay-keyboard-dispatcher.spec.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,27 @@ describe('OverlayKeyboardDispatcher', () => {
157157
expect(overlayOneSpy).toHaveBeenCalled();
158158
});
159159

160+
it('should not add the same overlay to the stack multiple times', () => {
161+
const overlayOne = overlay.create();
162+
const overlayTwo = overlay.create();
163+
const overlayOneSpy = jasmine.createSpy('overlayOne keyboard event spy');
164+
const overlayTwoSpy = jasmine.createSpy('overlayTwo keyboard event spy');
165+
166+
overlayOne.keydownEvents().subscribe(overlayOneSpy);
167+
overlayTwo.keydownEvents().subscribe(overlayTwoSpy);
168+
169+
keyboardDispatcher.add(overlayOne);
170+
keyboardDispatcher.add(overlayTwo);
171+
keyboardDispatcher.add(overlayOne);
172+
173+
dispatchKeyboardEvent(document.body, 'keydown', ESCAPE);
174+
175+
expect(keyboardDispatcher._attachedOverlays).toEqual([overlayTwo, overlayOne]);
176+
177+
expect(overlayTwoSpy).not.toHaveBeenCalled();
178+
expect(overlayOneSpy).toHaveBeenCalled();
179+
});
180+
160181
});
161182

162183

src/cdk/overlay/keyboard/overlay-keyboard-dispatcher.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ export class OverlayKeyboardDispatcher implements OnDestroy {
4242

4343
/** Add a new overlay to the list of attached overlay refs. */
4444
add(overlayRef: OverlayRef): void {
45+
// Ensure that we don't get the same overlay multiple times.
46+
this.remove(overlayRef);
47+
4548
// Lazily start dispatcher once first overlay is added
4649
if (!this._isAttached) {
4750
this._document.body.addEventListener('keydown', this._keydownListener, true);

0 commit comments

Comments
 (0)