From 290b9ee2cde5a0182e1a53116ef626bd6c0c9cad Mon Sep 17 00:00:00 2001 From: alpadev <2838324+alpadev@users.noreply.github.com> Date: Tue, 22 Jun 2021 12:11:03 +0200 Subject: [PATCH] fix(carousel): arrow keys break animation if carousel sliding (#34307) --- js/src/carousel.js | 25 ++++++------ js/tests/unit/carousel.spec.js | 71 ++++++++++++++++++++++++++++++++-- 2 files changed, 81 insertions(+), 15 deletions(-) diff --git a/js/src/carousel.js b/js/src/carousel.js index fa401535af6e..3c64829db3bc 100644 --- a/js/src/carousel.js +++ b/js/src/carousel.js @@ -59,6 +59,11 @@ const ORDER_PREV = 'prev' const DIRECTION_LEFT = 'left' const DIRECTION_RIGHT = 'right' +const KEY_TO_DIRECTION = { + [ARROW_LEFT_KEY]: DIRECTION_RIGHT, + [ARROW_RIGHT_KEY]: DIRECTION_LEFT +} + const EVENT_SLIDE = `slide${EVENT_KEY}` const EVENT_SLID = `slid${EVENT_KEY}` const EVENT_KEYDOWN = `keydown${EVENT_KEY}` @@ -134,9 +139,7 @@ class Carousel extends BaseComponent { // Public next() { - if (!this._isSliding) { - this._slide(ORDER_NEXT) - } + this._slide(ORDER_NEXT) } nextWhenVisible() { @@ -148,9 +151,7 @@ class Carousel extends BaseComponent { } prev() { - if (!this._isSliding) { - this._slide(ORDER_PREV) - } + this._slide(ORDER_PREV) } pause(event) { @@ -319,12 +320,10 @@ class Carousel extends BaseComponent { return } - if (event.key === ARROW_LEFT_KEY) { - event.preventDefault() - this._slide(DIRECTION_RIGHT) - } else if (event.key === ARROW_RIGHT_KEY) { + const direction = KEY_TO_DIRECTION[event.key] + if (direction) { event.preventDefault() - this._slide(DIRECTION_LEFT) + this._slide(direction) } } @@ -408,6 +407,10 @@ class Carousel extends BaseComponent { return } + if (this._isSliding) { + return + } + const slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName) if (slideEvent.defaultPrevented) { return diff --git a/js/tests/unit/carousel.spec.js b/js/tests/unit/carousel.spec.js index 74f82ce1f0ed..97482537a0e9 100644 --- a/js/tests/unit/carousel.spec.js +++ b/js/tests/unit/carousel.spec.js @@ -203,6 +203,26 @@ describe('Carousel', () => { expect(spySlide).not.toHaveBeenCalled() }) + it('should not slide if arrow key is pressed and carousel is sliding', () => { + fixtureEl.innerHTML = '
' + + const carouselEl = fixtureEl.querySelector('div') + const carousel = new Carousel(carouselEl, {}) + + spyOn(carousel, '_triggerSlideEvent') + + carousel._isSliding = true; + + ['ArrowLeft', 'ArrowRight'].forEach(key => { + const keydown = createEvent('keydown') + keydown.key = key + + carouselEl.dispatchEvent(keydown) + }) + + expect(carousel._triggerSlideEvent).not.toHaveBeenCalled() + }) + it('should wrap around from end to start when wrap option is true', done => { fixtureEl.innerHTML = [ '