Skip to content

Commit

Permalink
Fix race
Browse files Browse the repository at this point in the history
  • Loading branch information
Micajuine Ho committed Feb 23, 2021
1 parent b47b3d2 commit c6a17c4
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 20 deletions.
10 changes: 6 additions & 4 deletions extensions/amp-carousel/0.1/slidescroll.js
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,11 @@ export class AmpSlideScroll extends BaseSlides {
* @return {number} a number representing the next slide index.
*/
getNextSlideIndex_(currentScrollLeft) {
// Addresses race where slideWidth is 0, due to being hidden
// while snapping is occuring.
if (!currentScrollLeft && !this.slideWidth_) {
return 0;
}
// This can be only 0, 1 or 2, since only a max of 3 slides are shown at
// a time.
const scrolledSlideIndex = Math.round(currentScrollLeft / this.slideWidth_);
Expand Down Expand Up @@ -686,10 +691,7 @@ export class AmpSlideScroll extends BaseSlides {
*/
showSlide_(newIndex) {
const {noOfSlides_} = this;
if (isNaN(newIndex)) {
dev().error(TAG, 'Attempted to show slide that is not a number');
return;
}
newIndex = dev().assertNumber(newIndex);
if (
newIndex < 0 ||
newIndex >= noOfSlides_ ||
Expand Down
22 changes: 6 additions & 16 deletions extensions/amp-carousel/0.1/test/test-slidescroll.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ import {
createElementWithAttributes,
whenUpgradedToCustomElement,
} from '../../../../src/dom';
import {dev, user} from '../../../../src/log';
import {installResizeObserverStub} from '../../../../testing/resize-observer-stub';
import {user} from '../../../../src/log';

describes.realWin(
'SlideScroll',
Expand Down Expand Up @@ -1271,25 +1271,15 @@ describes.realWin(
expect(showSlideSpy).to.have.been.calledWith(4);
});

it('should error on a non-number goToSlide', async () => {
it('should handle carousel snapping & hiding race', async () => {
const ampSlideScroll = await getAmpSlideScroll(true);
const impl = await ampSlideScroll.getImpl();
const devErrorSpy = env.sandbox.spy(dev(), 'error');

impl.showSlideAndTriggerAction_(NaN);
expect(devErrorSpy).to.be.calledOnce;
expect(devErrorSpy.args[0][1]).to.match(
/Attempted to show slide that is not a number/
);
});

it('should return false for invalid slide number', async () => {
const ampSlideScroll = await getAmpSlideScroll(true);
const impl = await ampSlideScroll.getImpl();
// simluate carousel hidding
impl.slideWidth_ = 0;

impl.noOfSlides_ = 10;
expect(impl.showSlide_(Infinity)).to.be.false;
expect(impl.showSlide_(-Infinity)).to.be.false;
// simulate snapping
expect(impl.getNextSlideIndex_(0)).to.equal(0);
});

it('should NOT call showSlide_ before layout', async () => {
Expand Down

0 comments on commit c6a17c4

Please sign in to comment.