diff --git a/.eslintrc b/.eslintrc index 6152540354cf..8b8c53e5eef5 100644 --- a/.eslintrc +++ b/.eslintrc @@ -46,6 +46,7 @@ "no-useless-call": 2, "no-useless-concat": 2, "no-warning-comments": [2, { "terms": ["do not submit"], "location": "anywhere" }], + "prefer-const": 2, "radix": 2, "semi": 2, "space-after-keywords": 2, diff --git a/build-system/tasks/lint.js b/build-system/tasks/lint.js index c59b2c2a3416..f4f9b406f55d 100644 --- a/build-system/tasks/lint.js +++ b/build-system/tasks/lint.js @@ -53,7 +53,7 @@ function lint() { } return stream.pipe(eslint(options)) - .pipe(eslint.formatEach('compact', function(msg) { + .pipe(eslint.formatEach('stylish', function(msg) { errorsFound = true; util.log(util.colors.red(msg)); })) diff --git a/builtins/amp-ad.js b/builtins/amp-ad.js index a784d5c70e02..c18fec6f1d90 100644 --- a/builtins/amp-ad.js +++ b/builtins/amp-ad.js @@ -63,15 +63,15 @@ const POSITION_FIXED_TAG_WHITELIST = { */ export function scoreDimensions_(dims, maxWidth, maxHeight) { return dims.map(function(dim) { - let width = dim[0]; - let height = dim[1]; - let widthScore = Math.abs(width - maxWidth); + const width = dim[0]; + const height = dim[1]; + const widthScore = Math.abs(width - maxWidth); // if the width is over the max then we need to penalize it - let widthPenalty = Math.abs((maxWidth - width) * 3); + const widthPenalty = Math.abs((maxWidth - width) * 3); // we add a multiplier to height as we prioritize it more than width - let heightScore = Math.abs(height - maxHeight) * 2; + const heightScore = Math.abs(height - maxHeight) * 2; // if the height is over the max then we need to penalize it - let heightPenalty = Math.abs((maxHeight - height) * 2.5); + const heightPenalty = Math.abs((maxHeight - height) * 2.5); return (widthScore - widthPenalty) + (heightScore - heightPenalty); }); @@ -84,7 +84,7 @@ export function scoreDimensions_(dims, maxWidth, maxHeight) { */ export function upgradeImages_(images) { Object.keys(images).forEach(key => { - let curDimImgs = images[key]; + const curDimImgs = images[key]; curDimImgs.forEach((item, index) => { curDimImgs[index] = item.replace(/@1x\.png$/, '@2x.png'); }); @@ -148,9 +148,9 @@ export function installAd(win) { prefetchAd_() { // We always need the bootstrap. prefetchBootstrap(this.getWin()); - let type = this.element.getAttribute('type'); - let prefetch = adPrefetch[type]; - let preconnect = adPreconnect[type]; + const type = this.element.getAttribute('type'); + const prefetch = adPrefetch[type]; + const preconnect = adPreconnect[type]; if (typeof prefetch == 'string') { this.preconnect.prefetch(prefetch); } else if (prefetch) { @@ -166,7 +166,7 @@ export function installAd(win) { }); } // If fully qualified src for ad script is specified we prefetch that. - let src = this.element.getAttribute('src'); + const src = this.element.getAttribute('src'); if (src) { this.preconnect.prefetch(src); } @@ -187,7 +187,7 @@ export function installAd(win) { */ isPositionFixed() { let el = this.element; - let body = el.ownerDocument.body; + const body = el.ownerDocument.body; do { if (POSITION_FIXED_TAG_WHITELIST[el.tagName]) { return false; @@ -248,7 +248,7 @@ export function installAd(win) { margin: 'auto', }); - let winner = this.getPlaceholderImage_(); + const winner = this.getPlaceholderImage_(); img.src = `https://ampproject.org/backfill/${winner}`; this.placeholder_ = a; a.appendChild(img); @@ -261,12 +261,12 @@ export function installAd(win) { * @return {string} The image URL. */ getPlaceholderImage_() { - let scores = scoreDimensions_(BACKFILL_DIMENSIONS_, + const scores = scoreDimensions_(BACKFILL_DIMENSIONS_, this.element./*REVIEW*/clientWidth, this.element./*REVIEW*/clientHeight); - let dims = BACKFILL_DIMENSIONS_[ + const dims = BACKFILL_DIMENSIONS_[ scores.indexOf(Math.max.apply(Math, scores))]; - let images = BACKFILL_IMGS_[dims.join('x')]; + const images = BACKFILL_IMGS_[dims.join('x')]; // do we need a more sophisticated randomizer? return images[Math.floor(Math.random() * images.length)]; } diff --git a/builtins/amp-img.js b/builtins/amp-img.js index 423970a78f25..9bb0a62dc52c 100644 --- a/builtins/amp-img.js +++ b/builtins/amp-img.js @@ -82,7 +82,7 @@ export function installImg(win) { if (this.getLayoutWidth() <= 0) { return Promise.resolve(); } - let src = this.srcset_.select(this.getLayoutWidth(), this.getDpr()).url; + const src = this.srcset_.select(this.getLayoutWidth(), this.getDpr()).url; if (src == this.img_.getAttribute('src')) { return Promise.resolve(); } diff --git a/builtins/amp-pixel.js b/builtins/amp-pixel.js index f619d345e54e..6178035dc0be 100644 --- a/builtins/amp-pixel.js +++ b/builtins/amp-pixel.js @@ -51,7 +51,7 @@ export function installPixel(win) { * Returns the host of the canonical URL for this AMP document. */ 'CANONICAL_HOST': () => { - let url = parseUrl(documentInfoFor(win).canonicalUrl); + const url = parseUrl(documentInfoFor(win).canonicalUrl); return url && url.hostname; }, @@ -59,7 +59,7 @@ export function installPixel(win) { * Returns the path of the canonical URL for this AMP document. */ 'CANONICAL_PATH': () => { - let url = parseUrl(documentInfoFor(win).canonicalUrl); + const url = parseUrl(documentInfoFor(win).canonicalUrl); return url && url.pathname; }, @@ -88,7 +88,7 @@ export function installPixel(win) { * Returns the host of the URL for this AMP document. */ 'AMPDOC_HOST': () => { - let url = parseUrl(win.location.href); + const url = parseUrl(win.location.href); return url && url.hostname; } }; @@ -98,7 +98,7 @@ export function installPixel(win) { */ const REPLACEMENT_EXPR = (() => { let all = ''; - for (let k in REPLACEMENTS) { + for (const k in REPLACEMENTS) { all += (all.length > 0 ? '|' : '') + k; } return new RegExp('\\$(' + all + ')', 'g'); diff --git a/builtins/amp-video.js b/builtins/amp-video.js index 73d69c307641..6f72373e27a7 100644 --- a/builtins/amp-video.js +++ b/builtins/amp-video.js @@ -37,9 +37,9 @@ export function installVideo(win) { /** @override */ layoutCallback() { - let width = this.element.getAttribute('width'); - let height = this.element.getAttribute('height'); - let video = document.createElement('video'); + const width = this.element.getAttribute('width'); + const height = this.element.getAttribute('height'); + const video = document.createElement('video'); if (!video.play) { this.toggleFallback(true); return Promise.resolve(); diff --git a/extensions/amp-anim/0.1/amp-anim.js b/extensions/amp-anim/0.1/amp-anim.js index 97771c836d8e..ab97c3d884ad 100644 --- a/extensions/amp-anim/0.1/amp-anim.js +++ b/extensions/amp-anim/0.1/amp-anim.js @@ -86,7 +86,7 @@ class AmpAnim extends AMP.BaseElement { /** @private */ updateInViewport_() { - let inViewport = this.isInViewport(); + const inViewport = this.isInViewport(); this.togglePlaceholder(!inViewport); st.toggle(this.img_, inViewport); } @@ -99,7 +99,7 @@ class AmpAnim extends AMP.BaseElement { if (this.getLayoutWidth() <= 0) { return Promise.resolve(); } - let src = this.srcset_.select(this.getLayoutWidth(), + const src = this.srcset_.select(this.getLayoutWidth(), this.getDpr()).url; if (src == this.img_.getAttribute('src')) { return Promise.resolve(); diff --git a/extensions/amp-audio/0.1/amp-audio.js b/extensions/amp-audio/0.1/amp-audio.js index 1e2648346912..2c3d798f0810 100644 --- a/extensions/amp-audio/0.1/amp-audio.js +++ b/extensions/amp-audio/0.1/amp-audio.js @@ -31,7 +31,7 @@ export class AmpAudio extends AMP.BaseElement { /** @override */ layoutCallback() { - let audio = document.createElement('audio'); + const audio = document.createElement('audio'); if (!audio.play) { this.toggleFallback(true); return Promise.resolve(); diff --git a/extensions/amp-audio/0.1/test/test-amp-audio.js b/extensions/amp-audio/0.1/test/test-amp-audio.js index 3db11e76a6ab..c35df92eddb4 100644 --- a/extensions/amp-audio/0.1/test/test-amp-audio.js +++ b/extensions/amp-audio/0.1/test/test-amp-audio.js @@ -53,7 +53,7 @@ describe('amp-audio', () => { child = iframe.doc.createTextNode(childNodeAttrs.text); } else { child = iframe.doc.createElement(childNodeAttrs.tag); - for (let key in childNodeAttrs) { + for (const key in childNodeAttrs) { if (key !== 'tag') { child.setAttribute(key, childNodeAttrs[key]); } @@ -148,17 +148,17 @@ describe('amp-audio', () => { }); it('should fallback when not available', () => { - let savedCreateElement = document.createElement; + const savedCreateElement = document.createElement; document.createElement = name => { if (name == 'audio') { return savedCreateElement.call(document, 'audio2'); } return savedCreateElement.call(document, name); }; - let element = document.createElement('div'); + const element = document.createElement('div'); element.toggleFallback = sinon.spy(); - let audio = new AmpAudio(element); - let promise = audio.layoutCallback(); + const audio = new AmpAudio(element); + const promise = audio.layoutCallback(); document.createElement = savedCreateElement; return promise.then(() => { expect(audio.audio_).to.be.undefined; diff --git a/extensions/amp-carousel/0.1/carousel.js b/extensions/amp-carousel/0.1/carousel.js index 0d9c13b7db15..ecc87ae7327d 100644 --- a/extensions/amp-carousel/0.1/carousel.js +++ b/extensions/amp-carousel/0.1/carousel.js @@ -115,9 +115,9 @@ export class AmpCarousel extends BaseCarousel { * @private */ nextPos_(pos, dir) { - let containerWidth = this.element./*OK*/offsetWidth; - let fullWidth = this.container_./*OK*/scrollWidth; - let newPos = pos + dir * containerWidth; + const containerWidth = this.element./*OK*/offsetWidth; + const fullWidth = this.container_./*OK*/scrollWidth; + const newPos = pos + dir * containerWidth; if (newPos < 0) { return 0; } @@ -134,9 +134,9 @@ export class AmpCarousel extends BaseCarousel { * @private */ withinWindow_(pos, callback) { - let containerWidth = this.getLayoutWidth(); + const containerWidth = this.getLayoutWidth(); for (let i = 0; i < this.cells_.length; i++) { - let cell = this.cells_[i]; + const cell = this.cells_[i]; if (cell./*OK*/offsetLeft + cell./*OK*/offsetWidth >= pos && cell./*OK*/offsetLeft <= pos + containerWidth) { callback(cell); @@ -174,7 +174,7 @@ export class AmpCarousel extends BaseCarousel { * @private */ updateInViewport_(newPos, oldPos) { - let seen = []; + const seen = []; this.withinWindow_(newPos, cell => { seen.push(cell); this.updateInViewport(cell, true); @@ -201,7 +201,7 @@ export class AmpCarousel extends BaseCarousel { /** @private {?Motion} */ this.motion_ = null; - let gestures = Gestures.get(this.element); + const gestures = Gestures.get(this.element); gestures.onGesture(SwipeXRecognizer, e => { if (e.data.first) { this.onSwipeStart_(e.data); @@ -253,7 +253,7 @@ export class AmpCarousel extends BaseCarousel { if (Math.abs(swipe.velocityX) > 0.1) { this.motion_ = continueMotion(this.pos_, 0, -swipe.velocityX, 0, (x, y) => { - let newPos = (this.boundPos_(x, true) + + const newPos = (this.boundPos_(x, true) + this.boundPos_(x, false)) * 0.5; if (Math.abs(newPos - this.pos_) <= 1) { // Hit the wall: stop motion. @@ -270,11 +270,11 @@ export class AmpCarousel extends BaseCarousel { promise = Promise.resolve(); } return promise.then(() => { - let newPos = this.boundPos_(this.pos_, false); + const newPos = this.boundPos_(this.pos_, false); if (Math.abs(newPos - this.pos_) < 1) { return undefined; } - let posFunc = tr.numeric(this.pos_, newPos); + const posFunc = tr.numeric(this.pos_, newPos); return Animation.animate(time => { this.pos_ = posFunc(time); st.setStyles(this.container_, { @@ -290,8 +290,8 @@ export class AmpCarousel extends BaseCarousel { /** @private */ updateBounds_() { - let containerWidth = this.element./*OK*/offsetWidth; - let scrollWidth = this.container_./*OK*/scrollWidth; + const containerWidth = this.element./*OK*/offsetWidth; + const scrollWidth = this.container_./*OK*/scrollWidth; this.minPos_ = 0; this.maxPos_ = Math.max(scrollWidth - containerWidth, 0); this.extent_ = Math.min(containerWidth * 0.4, 200); @@ -304,7 +304,7 @@ export class AmpCarousel extends BaseCarousel { * @private */ boundPos_(pos, allowExtent) { - let extent = allowExtent ? this.extent_ : 0; + const extent = allowExtent ? this.extent_ : 0; return Math.min(this.maxPos_ + extent, Math.max(this.minPos_ - extent, pos)); } @@ -316,9 +316,9 @@ export class AmpCarousel extends BaseCarousel { /** @override */ hasNext() { - let containerWidth = this.getLayoutWidth(); - let scrollWidth = this.container_./*OK*/scrollWidth; - let maxPos = Math.max(scrollWidth - containerWidth, 0); + const containerWidth = this.getLayoutWidth(); + const scrollWidth = this.container_./*OK*/scrollWidth; + const maxPos = Math.max(scrollWidth - containerWidth, 0); return this.pos_ != maxPos; } } diff --git a/extensions/amp-carousel/0.1/slides.js b/extensions/amp-carousel/0.1/slides.js index c6b3590e848d..170c8e5bd133 100644 --- a/extensions/amp-carousel/0.1/slides.js +++ b/extensions/amp-carousel/0.1/slides.js @@ -106,7 +106,7 @@ export class AmpSlides extends BaseCarousel { return; } - let autoplayValue = Number(this.element.getAttribute('autoplay')); + const autoplayValue = Number(this.element.getAttribute('autoplay')); // If it isn't a number and is not greater than 0 then don't assign // and use the default. if (autoplayValue > 0) { @@ -253,7 +253,7 @@ export class AmpSlides extends BaseCarousel { * }} */ this.swipeState_ = null; - let gestures = Gestures.get(this.element); + const gestures = Gestures.get(this.element); gestures.onGesture(SwipeXRecognizer, e => { if (e.data.first) { this.onSwipeStart_(e.data); @@ -270,25 +270,25 @@ export class AmpSlides extends BaseCarousel { * @private */ onSwipeStart_(swipe) { - let currentSlide = this.slides_[this.currentIndex_]; - let containerWidth = this.element./*OK*/offsetWidth; + const currentSlide = this.slides_[this.currentIndex_]; + const containerWidth = this.element./*OK*/offsetWidth; let minDelta = 0; let maxDelta = 0; let prevTr = tr.NOOP; let nextTr = tr.NOOP; - let prevIndex = AmpSlides.getRelativeIndex(this.currentIndex_, + const prevIndex = AmpSlides.getRelativeIndex(this.currentIndex_, -1, this.slides_.length); - let nextIndex = AmpSlides.getRelativeIndex(this.currentIndex_, + const nextIndex = AmpSlides.getRelativeIndex(this.currentIndex_, 1, this.slides_.length); if (this.isLooping_ || this.currentIndex_ - 1 >= 0) { - let prevSlide = this.slides_[prevIndex]; + const prevSlide = this.slides_[prevIndex]; this.prepareSlide_(prevSlide, -1); prevTr = this.createTransition_(currentSlide, prevSlide, -1); minDelta = -1; } if (this.isLooping_ || this.currentIndex_ + 1 < this.slides_.length) { - let nextSlide = this.slides_[nextIndex]; + const nextSlide = this.slides_[nextIndex]; this.prepareSlide_(nextSlide, 1); nextTr = this.createTransition_(currentSlide, nextSlide, 1); maxDelta = 1; @@ -311,7 +311,7 @@ export class AmpSlides extends BaseCarousel { * @private */ onSwipe_(swipe) { - let s = this.swipeState_; + const s = this.swipeState_; if (!s || s.currentIndex != this.currentIndex_) { return; } @@ -319,7 +319,7 @@ export class AmpSlides extends BaseCarousel { // Translate the gesture position to be a number between -1 and 1, // with negative values indiamping sliding to the previous slide and // positive indiamping sliding to the next slide. - let pos = Math.min(s.max, Math.max(s.min, + const pos = Math.min(s.max, Math.max(s.min, -swipe.deltaX / s.containerWidth)); s.nextTr(pos > 0 ? pos : 0); @@ -333,7 +333,7 @@ export class AmpSlides extends BaseCarousel { * @private */ onSwipeEnd_(swipe) { - let s = this.swipeState_; + const s = this.swipeState_; if (!s || s.currentIndex != this.currentIndex_) { return; } @@ -345,12 +345,12 @@ export class AmpSlides extends BaseCarousel { (Math.abs(swipe.velocityX) > 0.2 ? 1 : 0); } advPos = Math.min(s.max, Math.max(s.min, advPos)); - let newPos = Math.abs(advPos) >= 0.55 ? Math.sign(advPos) : 0; + const newPos = Math.abs(advPos) >= 0.55 ? Math.sign(advPos) : 0; let promise; if (newPos != s.pos) { - let posFunc = tr.numeric(s.pos, newPos); + const posFunc = tr.numeric(s.pos, newPos); promise = Animation.animate(time => { - let pos = posFunc(time); + const pos = posFunc(time); s.nextTr(pos > 0 ? pos : 0); s.prevTr(pos < 0 ? -pos : 0); s.pos = pos; @@ -362,7 +362,7 @@ export class AmpSlides extends BaseCarousel { if (s.currentIndex != this.currentIndex_) { return; } - let oldSlide = this.slides_[this.currentIndex_]; + const oldSlide = this.slides_[this.currentIndex_]; if (newPos > 0.5) { s.nextTr(1); this.currentIndex_ = s.nextIndex; diff --git a/extensions/amp-carousel/0.1/test/test-carousel.js b/extensions/amp-carousel/0.1/test/test-carousel.js index f214a1b0b911..cb69ad2d6c29 100644 --- a/extensions/amp-carousel/0.1/test/test-carousel.js +++ b/extensions/amp-carousel/0.1/test/test-carousel.js @@ -97,13 +97,13 @@ describe('Carousel gestures', () => { it('should continue innertia', () => { carousel.onSwipeStart_({}); - let promise = carousel.onSwipeEnd_({deltaX: 0, velocityX: -0.11}); + const promise = carousel.onSwipeEnd_({deltaX: 0, velocityX: -0.11}); expect(carousel.motion_).to.not.equal(null); }); it('should not continue innertia', () => { carousel.onSwipeStart_({}); - let promise = carousel.onSwipeEnd_({deltaX: 0, velocityX: -0.01}); + const promise = carousel.onSwipeEnd_({deltaX: 0, velocityX: -0.01}); expect(carousel.motion_).to.equal(null); }); }); diff --git a/extensions/amp-carousel/0.1/test/test-slides.js b/extensions/amp-carousel/0.1/test/test-slides.js index 07a819de8d46..49cacc3bb0a0 100644 --- a/extensions/amp-carousel/0.1/test/test-slides.js +++ b/extensions/amp-carousel/0.1/test/test-slides.js @@ -150,8 +150,8 @@ describe('Slides functional', () => { }); it('should update on swipe within range in neg direction', () => { - let prevTr = sinon.spy(); - let nextTr = sinon.spy(); + const prevTr = sinon.spy(); + const nextTr = sinon.spy(); slides.currentIndex_ = 0; slides.swipeState_ = { currentIndex: 0, @@ -173,8 +173,8 @@ describe('Slides functional', () => { }); it('should update on swipe within range in pos direction', () => { - let prevTr = sinon.spy(); - let nextTr = sinon.spy(); + const prevTr = sinon.spy(); + const nextTr = sinon.spy(); slides.currentIndex_ = 1; slides.swipeState_ = { currentIndex: 1, @@ -196,8 +196,8 @@ describe('Slides functional', () => { }); it('should stay in-bounds on swipe', () => { - let prevTr = sinon.spy(); - let nextTr = sinon.spy(); + const prevTr = sinon.spy(); + const nextTr = sinon.spy(); slides.currentIndex_ = 0; slides.swipeState_ = { currentIndex: 0, @@ -235,10 +235,10 @@ describe('Slides functional', () => { }); it.skip('should go next after threshold', () => { - let prevTr = sinon.spy(); - let nextTr = sinon.spy(); + const prevTr = sinon.spy(); + const nextTr = sinon.spy(); slides.currentIndex_ = 0; - let s = { + const s = { currentIndex: 0, prevIndex: 2, nextIndex: 1, @@ -250,7 +250,7 @@ describe('Slides functional', () => { nextTr: nextTr }; slides.swipeState_ = s; - let promise = slides.onSwipeEnd_({velocityX: 0}); + const promise = slides.onSwipeEnd_({velocityX: 0}); expect(slides.swipeState_).to.equal(null); return promise.then(() => { expect(nextTr.callCount).to.be.gt(1); @@ -266,10 +266,10 @@ describe('Slides functional', () => { it('should not go past first item with a negative value when not ' + ' looping', () => { slides.isLooping_ = true; - let prevTr = sinon.spy(); - let nextTr = sinon.spy(); + const prevTr = sinon.spy(); + const nextTr = sinon.spy(); slides.currentIndex_ = 0; - let s = { + const s = { currentIndex: 0, prevIndex: 2, nextIndex: 1, @@ -281,7 +281,7 @@ describe('Slides functional', () => { nextTr: nextTr }; slides.swipeState_ = s; - let promise = slides.onSwipeEnd_({velocityX: 0}); + const promise = slides.onSwipeEnd_({velocityX: 0}); return promise.then(() => { expect(slides.currentIndex_).to.equal(0); expect(switchCallback.callCount).to.equal(0); @@ -290,10 +290,10 @@ describe('Slides functional', () => { it('should go past first item with a negative value when looping', () => { slides.isLooping_ = true; - let prevTr = sinon.spy(); - let nextTr = sinon.spy(); + const prevTr = sinon.spy(); + const nextTr = sinon.spy(); slides.currentIndex_ = 0; - let s = { + const s = { currentIndex: 0, prevIndex: 2, nextIndex: 1, @@ -305,7 +305,7 @@ describe('Slides functional', () => { nextTr: nextTr }; slides.swipeState_ = s; - let promise = slides.onSwipeEnd_({velocityX: 0}); + const promise = slides.onSwipeEnd_({velocityX: 0}); return promise.then(() => { expect(slides.currentIndex_).to.equal(2); expect(switchCallback.firstCall.args[0]).to.equal(slide0); @@ -316,10 +316,10 @@ describe('Slides functional', () => { it('should not go past last item with a positive value when ' + 'not looping', () => { slides.isLooping_ = true; - let prevTr = sinon.spy(); - let nextTr = sinon.spy(); + const prevTr = sinon.spy(); + const nextTr = sinon.spy(); slides.currentIndex_ = 2; - let s = { + const s = { currentIndex: 2, prevIndex: 1, nextIndex: 0, @@ -331,7 +331,7 @@ describe('Slides functional', () => { nextTr: nextTr }; slides.swipeState_ = s; - let promise = slides.onSwipeEnd_({velocityX: 0}); + const promise = slides.onSwipeEnd_({velocityX: 0}); return promise.then(() => { expect(slides.currentIndex_).to.equal(2); expect(switchCallback.callCount).to.equal(0); @@ -340,10 +340,10 @@ describe('Slides functional', () => { it('should go past last item with a positive value when looping', () => { slides.isLooping_ = true; - let prevTr = sinon.spy(); - let nextTr = sinon.spy(); + const prevTr = sinon.spy(); + const nextTr = sinon.spy(); slides.currentIndex_ = 2; - let s = { + const s = { currentIndex: 2, prevIndex: 1, nextIndex: 0, @@ -355,7 +355,7 @@ describe('Slides functional', () => { nextTr: nextTr }; slides.swipeState_ = s; - let promise = slides.onSwipeEnd_({velocityX: 0}); + const promise = slides.onSwipeEnd_({velocityX: 0}); return promise.then(() => { expect(slides.currentIndex_).to.equal(0); expect(switchCallback.firstCall.args[0]).to.equal(slide2); @@ -364,10 +364,10 @@ describe('Slides functional', () => { }); it('should go next before threshold but with velocity', () => { - let prevTr = sinon.spy(); - let nextTr = sinon.spy(); + const prevTr = sinon.spy(); + const nextTr = sinon.spy(); slides.currentIndex_ = 0; - let s = { + const s = { currentIndex: 0, prevIndex: 2, nextIndex: 1, @@ -379,7 +379,7 @@ describe('Slides functional', () => { nextTr: nextTr }; slides.swipeState_ = s; - let promise = slides.onSwipeEnd_({velocityX: -0.5}); + const promise = slides.onSwipeEnd_({velocityX: -0.5}); expect(slides.swipeState_).to.equal(null); return promise.then(() => { expect(nextTr.callCount).to.be.gt(1); @@ -393,10 +393,10 @@ describe('Slides functional', () => { }); it('should bounce back before threshold and no velocity', () => { - let prevTr = sinon.spy(); - let nextTr = sinon.spy(); + const prevTr = sinon.spy(); + const nextTr = sinon.spy(); slides.currentIndex_ = 0; - let s = { + const s = { currentIndex: 0, prevIndex: 2, nextIndex: 1, @@ -408,7 +408,7 @@ describe('Slides functional', () => { nextTr: nextTr }; slides.swipeState_ = s; - let promise = slides.onSwipeEnd_({velocityX: 0}); + const promise = slides.onSwipeEnd_({velocityX: 0}); expect(slides.swipeState_).to.equal(null); return promise.then(() => { expect(nextTr.callCount).to.be.gt(1); @@ -420,10 +420,10 @@ describe('Slides functional', () => { }); it('should bounce back before threshold and opposite velocity', () => { - let prevTr = sinon.spy(); - let nextTr = sinon.spy(); + const prevTr = sinon.spy(); + const nextTr = sinon.spy(); slides.currentIndex_ = 0; - let s = { + const s = { currentIndex: 0, prevIndex: 2, nextIndex: 1, @@ -435,7 +435,7 @@ describe('Slides functional', () => { nextTr: nextTr }; slides.swipeState_ = s; - let promise = slides.onSwipeEnd_({velocityX: 0.5}); + const promise = slides.onSwipeEnd_({velocityX: 0.5}); expect(slides.swipeState_).to.equal(null); return promise.then(() => { expect(nextTr.callCount).to.be.gt(1); diff --git a/extensions/amp-fit-text/0.1/amp-fit-text.js b/extensions/amp-fit-text/0.1/amp-fit-text.js index 8ad69286886d..2828d5850272 100644 --- a/extensions/amp-fit-text/0.1/amp-fit-text.js +++ b/extensions/amp-fit-text/0.1/amp-fit-text.js @@ -96,8 +96,8 @@ class AmpFitText extends AMP.BaseElement { /** @private */ updateFontSize_() { - let maxHeight = this.element./*OK*/offsetHeight; - let fontSize = calculateFontSize_(this.measurer_, maxHeight, + const maxHeight = this.element./*OK*/offsetHeight; + const fontSize = calculateFontSize_(this.measurer_, maxHeight, this.minFontSize_, this.maxFontSize_); this.contentWrapper_.style.fontSize = st.px(fontSize); updateOverflow_(this.contentWrapper_, this.measurer_, maxHeight, @@ -119,9 +119,9 @@ export function calculateFontSize_(measurer, expectedHeight, maxFontSize++; // Binomial search for the best font size. while (maxFontSize - minFontSize > 1) { - let mid = Math.floor((minFontSize + maxFontSize) / 2); + const mid = Math.floor((minFontSize + maxFontSize) / 2); measurer.style.fontSize = st.px(mid); - let height = measurer./*OK*/offsetHeight; + const height = measurer./*OK*/offsetHeight; if (height > expectedHeight) { maxFontSize = mid; } else { @@ -141,9 +141,9 @@ export function calculateFontSize_(measurer, expectedHeight, */ export function updateOverflow_(content, measurer, maxHeight, fontSize) { measurer.style.fontSize = st.px(fontSize); - let overflown = measurer./*OK*/offsetHeight > maxHeight; - let lineHeight = fontSize * LINE_HEIGHT_EM_; - let numberOfLines = Math.floor(maxHeight / lineHeight); + const overflown = measurer./*OK*/offsetHeight > maxHeight; + const lineHeight = fontSize * LINE_HEIGHT_EM_; + const numberOfLines = Math.floor(maxHeight / lineHeight); content.classList.toggle('-amp-fit-text-content-overflown', overflown); st.setStyles(content, { lineClamp: overflown ? numberOfLines : '', diff --git a/extensions/amp-fit-text/0.1/test/test-amp-fit-text.js b/extensions/amp-fit-text/0.1/test/test-amp-fit-text.js index a3342a2fc155..276d8a6be926 100644 --- a/extensions/amp-fit-text/0.1/test/test-amp-fit-text.js +++ b/extensions/amp-fit-text/0.1/test/test-amp-fit-text.js @@ -135,7 +135,7 @@ describe('amp-fit-text updateOverflow', () => { }); function getLineClamp() { - for (let k in content.style) { + for (const k in content.style) { if (k == 'lineClamp' || k.match(/.*LineClamp/)) { return content.style[k]; } diff --git a/extensions/amp-iframe/0.1/amp-iframe.js b/extensions/amp-iframe/0.1/amp-iframe.js index 4c9e57a43c7f..4e74506bec21 100644 --- a/extensions/amp-iframe/0.1/amp-iframe.js +++ b/extensions/amp-iframe/0.1/amp-iframe.js @@ -154,8 +154,8 @@ class AmpIframe extends AMP.BaseElement { this.element.setAttribute('width', data.width); } if (data.height !== undefined) { - let newHeight = Math.max(this.element./*OK*/offsetHeight + data.height - - this.iframe_./*OK*/offsetHeight, data.height); + const newHeight = Math.max(this.element./*OK*/offsetHeight + + data.height - this.iframe_./*OK*/offsetHeight, data.height); iframe.height = data.height; this.element.setAttribute('height', newHeight); this.updateHeight_(newHeight); @@ -223,8 +223,8 @@ function makeIOsScrollable(element, iframe) { */ function listen(iframe, typeOfMessage, callback) { assert(iframe.src, 'only iframes with src supported'); - let origin = parseUrl(iframe.src).origin; - let win = iframe.ownerDocument.defaultView; + const origin = parseUrl(iframe.src).origin; + const win = iframe.ownerDocument.defaultView; win.addEventListener('message', function(event) { if (event.origin != origin) { return; diff --git a/extensions/amp-iframe/0.1/test/test-amp-iframe.js b/extensions/amp-iframe/0.1/test/test-amp-iframe.js index dbb43a6462ab..8b66b8714ecd 100644 --- a/extensions/amp-iframe/0.1/test/test-amp-iframe.js +++ b/extensions/amp-iframe/0.1/test/test-amp-iframe.js @@ -56,7 +56,7 @@ describe('amp-iframe', () => { i.style.transform = 'translateY(' + opt_translateY + ')'; } if (attributes.resizable !== undefined) { - let overflowEl = iframe.doc.createElement('div'); + const overflowEl = iframe.doc.createElement('div'); overflowEl.setAttribute('overflow', ''); i.appendChild(overflowEl); } @@ -266,9 +266,9 @@ describe('amp-iframe', () => { height: 100, resizable: '' }).then(amp => { - let impl = amp.container.implementation_; + const impl = amp.container.implementation_; impl.layoutCallback(); - let p = new Promise((resolve, reject) => { + const p = new Promise((resolve, reject) => { impl.updateHeight_ = newHeight => { resolve({amp: amp, newHeight: newHeight}); }; @@ -293,7 +293,7 @@ describe('amp-iframe', () => { height: 100, resizable: '' }).then(amp => { - let impl = amp.container.implementation_; + const impl = amp.container.implementation_; impl.requestChangeHeight = sinon.spy(); impl.changeHeight = sinon.spy(); impl.updateHeight_(217); @@ -301,7 +301,7 @@ describe('amp-iframe', () => { expect(impl.requestChangeHeight.callCount).to.equal(1); expect(impl.requestChangeHeight.firstCall.args[0]).to.equal(217); - let fallback = impl.requestChangeHeight.firstCall.args[1]; + const fallback = impl.requestChangeHeight.firstCall.args[1]; fallback(219); expect(impl.overflowElement_).to.not.be.null; expect(impl.overflowElement_).to.have.class('-amp-overflow'); @@ -320,7 +320,7 @@ describe('amp-iframe', () => { width: 100, height: 100 }).then(amp => { - let impl = amp.container.implementation_; + const impl = amp.container.implementation_; impl.requestChangeHeight = sinon.spy(); impl.changeHeight = sinon.spy(); impl.updateHeight_(217); diff --git a/extensions/amp-image-lightbox/0.1/amp-image-lightbox.js b/extensions/amp-image-lightbox/0.1/amp-image-lightbox.js index 6e4f1b60ec7e..bac95bb9eb55 100644 --- a/extensions/amp-image-lightbox/0.1/amp-image-lightbox.js +++ b/extensions/amp-image-lightbox/0.1/amp-image-lightbox.js @@ -222,7 +222,7 @@ export class ImageViewer { this.viewerBox_ = layoutRectFromDomRect(this.viewer_ ./*OK*/getBoundingClientRect()); - let sf = Math.min(this.viewerBox_.width / this.sourceWidth_, + const sf = Math.min(this.viewerBox_.width / this.sourceWidth_, this.viewerBox_.height / this.sourceHeight_); let width = Math.min(this.sourceWidth_ * sf, this.viewerBox_.width); let height = Math.min(this.sourceHeight_ * sf, this.viewerBox_.height); @@ -264,8 +264,8 @@ export class ImageViewer { */ updateSrc_() { this.maxSeenScale_ = Math.max(this.maxSeenScale_, this.scale_); - let width = this.imageBox_.width * this.maxSeenScale_; - let src = this.srcset_.select(width, this.lightbox_.getDpr()).url; + const width = this.imageBox_.width * this.maxSeenScale_; + const src = this.srcset_.select(width, this.lightbox_.getDpr()).url; if (src == this.image_.getAttribute('src')) { return Promise.resolve(); } @@ -280,7 +280,7 @@ export class ImageViewer { /** @private */ setupGestures_() { - let gestures = Gestures.get(this.image_); + const gestures = Gestures.get(this.image_); // Toggle viewer mode. gestures.onGesture(TapRecognizer, () => { @@ -308,8 +308,8 @@ export class ImageViewer { } else { newScale = this.minScale_; } - let deltaX = this.viewerBox_.width / 2 - e.data.clientX; - let deltaY = this.viewerBox_.height / 2 - e.data.clientY; + const deltaX = this.viewerBox_.width / 2 - e.data.clientX; + const deltaY = this.viewerBox_.height / 2 - e.data.clientY; this.onZoom_(newScale, deltaX, deltaY, true).then(() => { return this.onZoomRelease_(0, 0, 0, 0, 0, 0); }); @@ -383,7 +383,7 @@ export class ImageViewer { updatePanZoomBounds_(scale) { let maxY = 0; let minY = 0; - let dh = this.viewerBox_.height - this.imageBox_.height * scale; + const dh = this.viewerBox_.height - this.imageBox_.height * scale; if (dh >= 0) { minY = maxY = 0; } else { @@ -393,7 +393,7 @@ export class ImageViewer { let maxX = 0; let minX = 0; - let dw = this.viewerBox_.width - this.imageBox_.width * scale; + const dw = this.viewerBox_.width - this.imageBox_.width * scale; if (dw >= 0) { minX = maxX = 0; } else { @@ -429,8 +429,8 @@ export class ImageViewer { * @private */ onMove_(deltaX, deltaY, animate) { - let newPosX = this.boundX_(this.startX_ + deltaX, true); - let newPosY = this.boundY_(this.startY_ + deltaY, true); + const newPosX = this.boundX_(this.startX_ + deltaX, true); + const newPosY = this.boundY_(this.startY_ + deltaY, true); this.set_(this.scale_, newPosX, newPosY, animate); } @@ -442,7 +442,7 @@ export class ImageViewer { * @private */ onMoveRelease_(veloX, veloY) { - let deltaY = this.posY_ - this.startY_; + const deltaY = this.posY_ - this.startY_; if (this.scale_ == 1 && Math.abs(deltaY) > 10) { this.lightbox_.close(); return; @@ -451,8 +451,8 @@ export class ImageViewer { // Continue motion. this.motion_ = continueMotion(this.posX_, this.posY_, veloX, veloY, (x, y) => { - let newPosX = this.boundX_(x, true); - let newPosY = this.boundY_(y, true); + const newPosX = this.boundX_(x, true); + const newPosY = this.boundY_(y, true); if (Math.abs(newPosX - this.posX_) < 1 && Math.abs(newPosY - this.posY_) < 1) { // Hit the wall: stop motion. @@ -478,17 +478,17 @@ export class ImageViewer { * @private */ onZoomInc_(centerClientX, centerClientY, deltaX, deltaY) { - let dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY); + const dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY); - let zoomSign = Math.abs(deltaY) > Math.abs(deltaX) ? + const zoomSign = Math.abs(deltaY) > Math.abs(deltaX) ? Math.sign(deltaY) : Math.sign(-deltaX); if (zoomSign == 0) { return; } - let newScale = this.startScale_ * (1 + zoomSign * dist / 100); - let deltaCenterX = this.viewerBox_.width / 2 - centerClientX; - let deltaCenterY = this.viewerBox_.height / 2 - centerClientY; + const newScale = this.startScale_ * (1 + zoomSign * dist / 100); + const deltaCenterX = this.viewerBox_.width / 2 - centerClientX; + const deltaCenterY = this.viewerBox_.height / 2 - centerClientY; deltaX = Math.min(deltaCenterX, deltaCenterX * (dist / 100)); deltaY = Math.min(deltaCenterY, deltaCenterY * (dist / 100)); this.onZoom_(newScale, deltaX, deltaY, false); @@ -504,15 +504,15 @@ export class ImageViewer { * @private */ onZoom_(scale, deltaX, deltaY, animate) { - let newScale = this.boundScale_(scale, true); + const newScale = this.boundScale_(scale, true); if (newScale == this.scale_) { return; } this.updatePanZoomBounds_(newScale); - let newPosX = this.boundX_(this.startX_ + deltaX * newScale, false); - let newPosY = this.boundY_(this.startY_ + deltaY * newScale, false); + const newPosX = this.boundX_(this.startX_ + deltaX * newScale, false); + const newPosY = this.boundY_(this.startY_ + deltaY * newScale, false); return this.set_(newScale, newPosX, newPosY, animate); } @@ -539,7 +539,7 @@ export class ImageViewer { }).thenAlways(); } - let relayout = this.scale_ > this.startScale_; + const relayout = this.scale_ > this.startScale_; return promise.then(() => { return this.release_(); }).then(() => { @@ -559,14 +559,14 @@ export class ImageViewer { * @private */ set_(newScale, newPosX, newPosY, animate) { - let ds = newScale - this.scale_; - let dx = newPosX - this.posX_; - let dy = newPosY - this.posY_; - let dist = Math.sqrt(dx * dx + dy * dy); + const ds = newScale - this.scale_; + const dx = newPosX - this.posX_; + const dy = newPosY - this.posY_; + const dist = Math.sqrt(dx * dx + dy * dy); let dur = 0; if (animate) { - let maxDur = 250; + const maxDur = 250; dur = Math.min(maxDur, Math.max( maxDur * dist * 0.01, // Moving component. maxDur * Math.abs(ds))); // Zooming component. @@ -574,9 +574,9 @@ export class ImageViewer { let promise; if (dur > 16 && animate) { - let scaleFunc = tr.numeric(this.scale_, newScale); - let xFunc = tr.numeric(this.posX_, newPosX); - let yFunc = tr.numeric(this.posY_, newPosY); + const scaleFunc = tr.numeric(this.scale_, newScale); + const xFunc = tr.numeric(this.posX_, newPosX); + const yFunc = tr.numeric(this.posY_, newPosY); promise = Animation.animate(time => { this.scale_ = scaleFunc(time); this.posX_ = xFunc(time); @@ -609,12 +609,12 @@ export class ImageViewer { * @private */ release_() { - let newScale = this.boundScale_(this.scale_, false); + const newScale = this.boundScale_(this.scale_, false); if (newScale != this.scale_) { this.updatePanZoomBounds_(newScale); } - let newPosX = this.boundX_(this.posX_ / this.scale_ * newScale, false); - let newPosY = this.boundY_(this.posY_ / this.scale_ * newScale, false); + const newPosX = this.boundX_(this.posX_ / this.scale_ * newScale, false); + const newPosY = this.boundY_(this.posY_ / this.scale_ * newScale, false); return this.set_(newScale, newPosX, newPosY, true).then(() => { this.startScale_ = this.scale_; this.startX_ = this.posX_; @@ -675,7 +675,7 @@ class AmpImageLightbox extends AMP.BaseElement { this.captionElement_.classList.add('-amp-image-lightbox-caption'); this.container_.appendChild(this.captionElement_); - let gestures = Gestures.get(this.element); + const gestures = Gestures.get(this.element); this.element.addEventListener('click', e => { if (!this.entering_ && !this.imageViewer_.getImage().contains(e.target)) { @@ -698,7 +698,7 @@ class AmpImageLightbox extends AMP.BaseElement { return; } - let source = invocation.source; + const source = invocation.source; assert(source && SUPPORTED_ELEMENTS_[source.tagName.toLowerCase()], 'Unsupported element: %s', source.tagName); @@ -776,7 +776,7 @@ class AmpImageLightbox extends AMP.BaseElement { // 1. Check
and
. if (!caption) { - let figure = dom.closestByTag(sourceElement, 'figure'); + const figure = dom.closestByTag(sourceElement, 'figure'); if (figure) { caption = dom.elementByTag(figure, 'figcaption'); } @@ -784,7 +784,7 @@ class AmpImageLightbox extends AMP.BaseElement { // 2. Check "aria-describedby". if (!caption) { - let describedBy = sourceElement.getAttribute('aria-describedby'); + const describedBy = sourceElement.getAttribute('aria-describedby'); caption = document.getElementById(describedBy); } @@ -816,8 +816,8 @@ class AmpImageLightbox extends AMP.BaseElement { }); this.imageViewer_.measure(); - let anim = new Animation(); - let dur = 500; + const anim = new Animation(); + const dur = 500; // Lightbox background fades in. anim.add(0, tr.setStyles(this.element, { @@ -832,9 +832,9 @@ class AmpImageLightbox extends AMP.BaseElement { transLayer.classList.add('-amp-image-lightbox-trans'); document.body.appendChild(transLayer); - let rect = layoutRectFromDomRect(this.sourceImage_ + const rect = layoutRectFromDomRect(this.sourceImage_ ./*OK*/getBoundingClientRect()); - let clone = this.sourceImage_.cloneNode(true); + const clone = this.sourceImage_.cloneNode(true); st.setStyles(clone, { position: 'absolute', top: st.px(rect.top), @@ -847,12 +847,12 @@ class AmpImageLightbox extends AMP.BaseElement { this.sourceImage_.classList.add('-amp-ghost'); // Move the image to the location given by the lightbox. - let imageBox = this.imageViewer_.getImageBox(); - let dx = imageBox.left - rect.left; - let dy = imageBox.top - rect.top; + const imageBox = this.imageViewer_.getImageBox(); + const dx = imageBox.left - rect.left; + const dy = imageBox.top - rect.top; // Duration will be somewhere between 0.2 and 0.8 depending on how far // the image needs to move. - let motionTime = Math.max(0.2, Math.min(0.8, Math.abs(dy) / 250 * 0.8)); + const motionTime = Math.max(0.2, Math.min(0.8, Math.abs(dy) / 250 * 0.8)); anim.add(0, tr.setStyles(clone, { transform: tr.translate(tr.numeric(0, dx), tr.numeric(0, dy)) }), motionTime, ENTER_CURVE_); @@ -884,10 +884,10 @@ class AmpImageLightbox extends AMP.BaseElement { * @private */ exit_() { - let image = this.imageViewer_.getImage(); - let imageBox = this.imageViewer_.getImageBoxWithOffset(); + const image = this.imageViewer_.getImage(); + const imageBox = this.imageViewer_.getImageBoxWithOffset(); - let anim = new Animation(); + const anim = new Animation(); let dur = 500; // Lightbox background fades out. @@ -902,11 +902,11 @@ class AmpImageLightbox extends AMP.BaseElement { transLayer.classList.add('-amp-image-lightbox-trans'); document.body.appendChild(transLayer); - let rect = layoutRectFromDomRect(this.sourceImage_ + const rect = layoutRectFromDomRect(this.sourceImage_ ./*OK*/getBoundingClientRect()); - let newLeft = imageBox.left + (imageBox.width - rect.width) / 2; - let newTop = imageBox.top + (imageBox.height - rect.height) / 2; - let clone = image.cloneNode(true); + const newLeft = imageBox.left + (imageBox.width - rect.width) / 2; + const newTop = imageBox.top + (imageBox.height - rect.height) / 2; + const clone = image.cloneNode(true); st.setStyles(clone, { position: 'absolute', top: st.px(newTop), @@ -923,15 +923,15 @@ class AmpImageLightbox extends AMP.BaseElement { }), 0.1, EXIT_CURVE_); // Move the image back to where it is in the article. - let dx = rect.left - newLeft; - let dy = rect.top - newTop; - let move = tr.setStyles(clone, { + const dx = rect.left - newLeft; + const dy = rect.top - newTop; + const move = tr.setStyles(clone, { transform: tr.translate(tr.numeric(0, dx), tr.numeric(0, dy)) }); // Duration will be somewhere between 0.2 and 0.8 depending on how far // the image needs to move. Start the motion later too, but no later // than 0.2. - let motionTime = Math.max(0.2, Math.min(0.8, Math.abs(dy) / 250 * 0.8)); + const motionTime = Math.max(0.2, Math.min(0.8, Math.abs(dy) / 250 * 0.8)); anim.add(Math.min(0.8 - motionTime, 0.2), (time, complete) => { move(time); if (complete) { diff --git a/extensions/amp-image-lightbox/0.1/test/test-amp-image-lightbox.js b/extensions/amp-image-lightbox/0.1/test/test-amp-image-lightbox.js index 4f0f9c6a1276..a848cb1ea33e 100644 --- a/extensions/amp-image-lightbox/0.1/test/test-amp-image-lightbox.js +++ b/extensions/amp-image-lightbox/0.1/test/test-amp-image-lightbox.js @@ -42,22 +42,23 @@ describe('amp-image-lightbox component', () => { it('should render correctly', () => { return getImageLightbox().then(lightbox => { - let container = lightbox.querySelector('.-amp-image-lightbox-container'); + const container = lightbox + .querySelector('.-amp-image-lightbox-container'); expect(container).to.not.equal(null); - let caption = container.querySelector('.-amp-image-lightbox-caption'); + const caption = container.querySelector('.-amp-image-lightbox-caption'); expect(caption).to.not.equal(null); expect(caption.classList.contains('amp-image-lightbox-caption')).to .equal(true); - let viewer = container.querySelector('.-amp-image-lightbox-viewer'); + const viewer = container.querySelector('.-amp-image-lightbox-viewer'); expect(viewer).to.not.equal(null); - let image = viewer.querySelector('.-amp-image-lightbox-viewer-image'); + const image = viewer.querySelector('.-amp-image-lightbox-viewer-image'); expect(image).to.not.equal(null); // Very important. Image must have transform-origin=50% 50%. - let win = image.ownerDocument.defaultView; + const win = image.ownerDocument.defaultView; expect(win.getComputedStyle(image)['transform-origin']).to.equal( '50% 50%'); }); @@ -65,26 +66,26 @@ describe('amp-image-lightbox component', () => { it('should activate all steps', () => { return getImageLightbox().then(lightbox => { - let impl = lightbox.implementation_; - let requestFullOverlay = sinon.spy(); + const impl = lightbox.implementation_; + const requestFullOverlay = sinon.spy(); impl.requestFullOverlay = requestFullOverlay; - let viewportOnChanged = sinon.spy(); - let disableTouchZoom = sinon.spy(); + const viewportOnChanged = sinon.spy(); + const disableTouchZoom = sinon.spy(); impl.getViewport = () => {return { onChanged: viewportOnChanged, disableTouchZoom: disableTouchZoom };}; - let historyPush = sinon.spy(); + const historyPush = sinon.spy(); impl.getHistory_ = () => { return {push: () => { historyPush(); return Promise.resolve(11); }}; }; - let enter = sinon.spy(); + const enter = sinon.spy(); impl.enter_ = enter; - let ampImage = document.createElement('amp-img'); + const ampImage = document.createElement('amp-img'); ampImage.setAttribute('src', 'data:'); impl.activate({source: ampImage}); @@ -100,25 +101,25 @@ describe('amp-image-lightbox component', () => { it('should deactivate all steps', () => { return getImageLightbox().then(lightbox => { - let impl = lightbox.implementation_; + const impl = lightbox.implementation_; impl.active_ = true; impl.historyId_ = 11; - let cancelFullOverlay = sinon.spy(); + const cancelFullOverlay = sinon.spy(); impl.cancelFullOverlay = cancelFullOverlay; - let viewportOnChangedUnsubscribed = sinon.spy(); + const viewportOnChangedUnsubscribed = sinon.spy(); impl.unlistenViewport_ = viewportOnChangedUnsubscribed; - let restoreOriginalTouchZoom = sinon.spy(); + const restoreOriginalTouchZoom = sinon.spy(); impl.getViewport = () => {return { restoreOriginalTouchZoom: restoreOriginalTouchZoom };}; - let historyPop = sinon.spy(); + const historyPop = sinon.spy(); impl.getHistory_ = () => { return {pop: historyPop}; }; - let exit = sinon.spy(); + const exit = sinon.spy(); impl.exit_ = exit; - let ampImage = document.createElement('amp-img'); + const ampImage = document.createElement('amp-img'); ampImage.setAttribute('src', 'data:'); impl.close(); @@ -177,7 +178,7 @@ describe('amp-image-lightbox image viewer', () => { it('should init to the source element without image', () => { - let sourceElement = { + const sourceElement = { offsetWidth: 101, offsetHeight: 201, getAttribute: name => { @@ -197,7 +198,7 @@ describe('amp-image-lightbox image viewer', () => { }); it('should init to the source element with unloaded image', () => { - let sourceElement = { + const sourceElement = { offsetWidth: 101, offsetHeight: 201, getAttribute: name => { @@ -207,7 +208,7 @@ describe('amp-image-lightbox image viewer', () => { return undefined; } }; - let sourceImage = { + const sourceImage = { complete: false, src: 'image1-smaller' }; @@ -218,7 +219,7 @@ describe('amp-image-lightbox image viewer', () => { }); it('should init to the source element with loaded image', () => { - let sourceElement = { + const sourceElement = { offsetWidth: 101, offsetHeight: 201, getAttribute: name => { @@ -228,7 +229,7 @@ describe('amp-image-lightbox image viewer', () => { return undefined; } }; - let sourceImage = { + const sourceImage = { complete: true, src: 'image1-smaller' }; @@ -261,7 +262,7 @@ describe('amp-image-lightbox image viewer', () => { imageViewer.sourceWidth_ = 80; imageViewer.sourceHeight_ = 60; - let promise = imageViewer.measure(); + const promise = imageViewer.measure(); expect(imageViewer.viewerBox_.width).to.equal(100); expect(imageViewer.viewerBox_.height).to.equal(200); @@ -277,7 +278,7 @@ describe('amp-image-lightbox image viewer', () => { expect(imageViewer.getImage().style.height).to.equal('75px'); clock.tick(10); - let checkSrc = () => { + const checkSrc = () => { expect(imageViewer.getImage().getAttribute('src')).to.equal('image1'); }; return promise.then(checkSrc, checkSrc); @@ -422,7 +423,7 @@ describe('amp-image-lightbox image viewer gestures', () => { }); it('should zoom release', () => { - let updateSrc = sinon.spy(); + const updateSrc = sinon.spy(); imageViewer.updateSrc_ = updateSrc; imageViewer.onZoomInc_(10, 10, -10, -10); return imageViewer.onZoomRelease_(10, 10, -10, -10, 0, 0).then(() => { diff --git a/extensions/amp-lightbox/0.1/amp-lightbox.js b/extensions/amp-lightbox/0.1/amp-lightbox.js index 1cda6965b1ba..76508ba4ca83 100644 --- a/extensions/amp-lightbox/0.1/amp-lightbox.js +++ b/extensions/amp-lightbox/0.1/amp-lightbox.js @@ -46,7 +46,7 @@ class AmpLightbox extends AMP.BaseElement { right: 0 }); - let children = this.getRealChildren(); + const children = this.getRealChildren(); /** @private {!Element} */ this.container_ = document.createElement('div'); @@ -56,7 +56,7 @@ class AmpLightbox extends AMP.BaseElement { this.container_.appendChild(child); }); - let gestures = Gestures.get(this.element); + const gestures = Gestures.get(this.element); // TODO(dvoytenko): configure how to close. Or maybe leave it completely // up to "on" element. this.element.addEventListener('click', () => this.close()); diff --git a/extensions/amp-pinterest/0.1/amp-pinterest.js b/extensions/amp-pinterest/0.1/amp-pinterest.js index a036bccbfcb3..fda021b6f59d 100644 --- a/extensions/amp-pinterest/0.1/amp-pinterest.js +++ b/extensions/amp-pinterest/0.1/amp-pinterest.js @@ -60,15 +60,15 @@ class AmpPinterest extends AMP.BaseElement { /** @override */ layoutCallback() { - let height = this.element.getAttribute('height'); + const height = this.element.getAttribute('height'); - let width = this.element.getAttribute('width'); + const width = this.element.getAttribute('width'); - let pinDo = AMP.assert(this.element.getAttribute('data-do'), + const pinDo = AMP.assert(this.element.getAttribute('data-do'), 'The data-do attribute is required for %s', this.element); - let pinUrl = AMP.assert(this.element.getAttribute('data-url'), + const pinUrl = AMP.assert(this.element.getAttribute('data-url'), 'The data-url attribute is required for %s', this.element); @@ -79,7 +79,7 @@ class AmpPinterest extends AMP.BaseElement { } // open a new window - let pop = function(url, shouldPop) { + const pop = function(url, shouldPop) { if (shouldPop) { // amp=1&guid=guid are already in the query before long fields window.open(url, '_pinit', POP); @@ -90,8 +90,8 @@ class AmpPinterest extends AMP.BaseElement { }; // log a string - let log = function(str) { - let call = new Image(); + const log = function(str) { + const call = new Image(); let query = 'https://log.pinterest.com/?guid=' + guid; query = query + '&=1'; // add optional string &foo=bar @@ -103,15 +103,15 @@ class AmpPinterest extends AMP.BaseElement { }; // load data from API via XHR - let call = function(url) { + const call = function(url) { return new Promise((resolve, reject) => { - let xhr = new XMLHttpRequest(); + const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { // all replies are JSON and should parse try { - let data = JSON.parse(xhr.responseText); + const data = JSON.parse(xhr.responseText); resolve(data); } catch (err) { reject(new Error('API reply was not JSON: ' + url)); @@ -127,7 +127,7 @@ class AmpPinterest extends AMP.BaseElement { }; // set a DOM property or text attribute - let set = function(el, att, string) { + const set = function(el, att, string) { if (typeof el[att] === 'string') { el[att] = string; } else { @@ -136,7 +136,7 @@ class AmpPinterest extends AMP.BaseElement { }; // create a DOM element - let make = function(obj) { + const make = function(obj) { let el = false, tag, att; for (tag in obj) { el = document.createElement(tag); @@ -151,7 +151,7 @@ class AmpPinterest extends AMP.BaseElement { }; // filter tags from API input - let filter = function(str) { + const filter = function(str) { let decoded, ret; decoded = ''; ret = ''; @@ -164,9 +164,9 @@ class AmpPinterest extends AMP.BaseElement { }; // save our outside context so we can return properly after rendering - let that = this; + const that = this; - let makePin = function() { + const makePin = function() { // make an embedded pin widget // pinId will be inferred from pinUrl @@ -179,14 +179,14 @@ class AmpPinterest extends AMP.BaseElement { return; } - let width = that.element.getAttribute('data-width'); + const width = that.element.getAttribute('data-width'); - let structure = make({'span': {}}); + const structure = make({'span': {}}); - let renderPin = function(r) { + const renderPin = function(r) { if (r && r.data && r.data[0] && !r.data[0].error) { - let p = r.data[0]; + const p = r.data[0]; // start setting our class name let className = '-amp-pinterest-embed-pin'; @@ -203,12 +203,12 @@ class AmpPinterest extends AMP.BaseElement { structure.className = className; - let container = make({'span': { + const container = make({'span': { 'className': '-amp-pinterest-embed-pin-inner', 'data-pin-log': 'embed_pin' }}); - let img = make({'img': { + const img = make({'img': { 'src': imgUrl, 'className': '-amp-pinterest-embed-pin-image', 'data-pin-no-hover': true, @@ -218,7 +218,7 @@ class AmpPinterest extends AMP.BaseElement { container.appendChild(img); // repin button - let repin = make({'span': { + const repin = make({'span': { 'className': '-amp-pinterest-rect -amp-pinterest-en-red' + ' -amp-pinterest-embed-pin-repin', 'data-pin-log': 'embed_pin_repin', @@ -229,13 +229,13 @@ class AmpPinterest extends AMP.BaseElement { container.appendChild(repin); // text container - let text = make({'span': { + const text = make({'span': { 'className': '-amp-pinterest-embed-pin-text' }}); // description if (p.description) { - let description = make({'span': { + const description = make({'span': { 'className': '-amp-pinterest-embed-pin-text-block ' + '-amp-pinterest-embed-pin-description', 'textContent': filter(p.description) @@ -245,7 +245,7 @@ class AmpPinterest extends AMP.BaseElement { // attribution if (p.attribution) { - let attribution = make({'span': { + const attribution = make({'span': { 'className': '-amp-pinterest-embed-pin-text-block' + ' -amp-pinterest-embed-pin-attribution' }}); @@ -265,12 +265,12 @@ class AmpPinterest extends AMP.BaseElement { // likes and repins if (p.repin_count || p.like_count) { - let stats = make({'span': { + const stats = make({'span': { 'className': '-amp-pinterest-embed-pin-text-block' + ' -amp-pinterest-embed-pin-stats' }}); if (p.repin_count) { - let repinCount = make({'span': { + const repinCount = make({'span': { 'className': '-amp-pinterest-embed-pin-stats-repins', 'textContent': String(p.repin_count) }}); @@ -278,7 +278,7 @@ class AmpPinterest extends AMP.BaseElement { } if (p.like_count) { - let likeCount = make({'span': { + const likeCount = make({'span': { 'className': '-amp-pinterest-embed-pin-stats-likes', 'textContent': String(p.like_count) }}); @@ -290,7 +290,7 @@ class AmpPinterest extends AMP.BaseElement { // pinner if (p.pinner) { - let pinner = make({'span': { + const pinner = make({'span': { 'className': '-amp-pinterest-embed-pin-text-block' + ' -amp-pinterest-embed-pin-pinner' }}); @@ -327,14 +327,14 @@ class AmpPinterest extends AMP.BaseElement { // listen for clicks structure.addEventListener('click', function(e) { - let el = e.target; - let logMe = el.getAttribute('data-pin-log'); + const el = e.target; + const logMe = el.getAttribute('data-pin-log'); if (logMe) { log('&type=' + logMe); } - let href = el.getAttribute('data-pin-href'); + const href = el.getAttribute('data-pin-href'); if (href) { - let popThis = el.getAttribute('data-pin-pop') || false; + const popThis = el.getAttribute('data-pin-pop') || false; pop(href, popThis); } e.preventDefault(); @@ -349,7 +349,7 @@ class AmpPinterest extends AMP.BaseElement { } }; - let query = 'https://widgets.pinterest.com/v3/pidgets/pins/info/' + + const query = 'https://widgets.pinterest.com/v3/pidgets/pins/info/' + '?pin_ids=' + pinId + '&sub=www&base_scheme=https'; return call(query).then(r => { @@ -357,31 +357,31 @@ class AmpPinterest extends AMP.BaseElement { }); }; - let makeButton = function() { + const makeButton = function() { // render a Pin It button // required: media and description // optional: round, color, tall, lang, count - let pinMedia = + const pinMedia = AMP.assert(that.element.getAttribute('data-media'), 'The data-media attribute is required when ' + 'makes a Pin It button %s', that.element); - let pinDescription = + const pinDescription = AMP.assert(that.element.getAttribute('data-description'), 'The data-description attribute is required when ' + 'makes a Pin It button %s', that.element); // options - let round = that.element.getAttribute('data-round'); + const round = that.element.getAttribute('data-round'); let color = that.element.getAttribute('data-color'); - let tall = that.element.getAttribute('data-tall'); + const tall = that.element.getAttribute('data-tall'); let lang = that.element.getAttribute('data-lang'); - let count = that.element.getAttribute('data-count'); + const count = that.element.getAttribute('data-count'); // pass a known guid when testing - let theGuid = that.element.getAttribute('data-volkswagen-guid') || guid; + const theGuid = that.element.getAttribute('data-volkswagen-guid') || guid; // build our link let link = 'https://www.pinterest.com/pin/create/button/'; @@ -392,15 +392,15 @@ class AmpPinterest extends AMP.BaseElement { encodeURIComponent(pinDescription); // start building a link - let a = make({'A': { + const a = make({'A': { 'href': link }}); // built it - let render = function(r) { + const render = function(r) { // shorten the pin count so it will fit in our bubble - let prettyPinCount = function(n) { + const prettyPinCount = function(n) { if (n > 999) { if (n < 1000000) { n = parseInt(n / 1000, 10) + 'K+'; @@ -460,7 +460,7 @@ class AmpPinterest extends AMP.BaseElement { if (r) { - let countBubble = document.createElement('SPAN'); + const countBubble = document.createElement('SPAN'); // position the count if (count === 'above') { @@ -511,7 +511,7 @@ class AmpPinterest extends AMP.BaseElement { // only ask for a count if the operator requires it if (count === 'above' || count === 'beside') { // call the API - let query = 'https://widgets.pinterest.com/v1/urls/count.json?' + + const query = 'https://widgets.pinterest.com/v1/urls/count.json?' + '&return_jsonp=false' + '&url=' + encodeURIComponent(pinUrl); return call(query).then(r => { diff --git a/src/action.js b/src/action.js index 1c7f4b14e32e..61ef1e29e729 100644 --- a/src/action.js +++ b/src/action.js @@ -128,13 +128,13 @@ export class Action { * @private */ action_(source, actionEventType, event) { - let action = this.findAction_(source, actionEventType); + const action = this.findAction_(source, actionEventType); if (!action) { // TODO(dvoytenko): implement default (catch-all) actions. return; } - let target = document.getElementById(action.actionInfo.target); + const target = document.getElementById(action.actionInfo.target); if (!target) { this.actionInfoError_('target not found', action.actionInfo, target); return; @@ -166,7 +166,7 @@ export class Action { * @param {?ActionInfo} actionInfo */ invoke_(target, method, source, event, actionInfo) { - let invocation = new ActionInvocation(target, method, source, event); + const invocation = new ActionInvocation(target, method, source, event); // TODO(dvoytenko): implement common method handlers, e.g. "toggleClass" @@ -213,7 +213,7 @@ export class Action { * @return {?ActionInfo_} */ matchActionInfo_(node, actionEventType) { - let actionMap = this.getActionMap_(node); + const actionMap = this.getActionMap_(node); if (!actionMap) { return null; } @@ -242,11 +242,11 @@ export class Action { */ parseActionMap_(s) { let actionMap = null; - let actions = s.split(';'); + const actions = s.split(';'); if (actions && actions.length > 0) { for (let i = 0; i < actions.length; i++) { - let actionStr = actions[i]; - let actionInfo = this.parseAction_(actionStr); + const actionStr = actions[i]; + const actionInfo = this.parseAction_(actionStr); if (actionInfo) { if (!actionMap) { actionMap = {}; @@ -268,13 +268,13 @@ export class Action { return null; } - let eventSep = s.indexOf(':'); - let methodSep = s.indexOf('.', eventSep + 1); - let event = (eventSep != -1 ? s.substring(0, eventSep) : '').toLowerCase() + const eventSep = s.indexOf(':'); + const methodSep = s.indexOf('.', eventSep + 1); + const event = (eventSep != -1 ? s.substring(0, eventSep) : '').toLowerCase() .trim() || null; - let target = s.substring(eventSep + 1, methodSep != -1 ? methodSep : + const target = s.substring(eventSep + 1, methodSep != -1 ? methodSep : s.length).trim(); - let method = (methodSep != -1 ? s.substring(methodSep + 1) : '') + const method = (methodSep != -1 ? s.substring(methodSep + 1) : '') .trim() || DEFAULT_METHOD_; if (!event || !target) { diff --git a/src/animation.js b/src/animation.js index 005701ec6089..81cad4e89efe 100644 --- a/src/animation.js +++ b/src/animation.js @@ -19,9 +19,9 @@ import {log} from './log'; import {timer} from './timer'; import {vsync} from './vsync'; -let TAG_ = 'Animation'; +const TAG_ = 'Animation'; -let NOOP_CALLBACK = function() {}; +const NOOP_CALLBACK = function() {}; /** @@ -106,7 +106,7 @@ export class Animation { * @return {!AnimationPlayer} */ start(duration) { - let player = new AnimationPlayer(this.vsync_, this.segments_, this.curve_, + const player = new AnimationPlayer(this.vsync_, this.segments_, this.curve_, duration); player.start_(); return player; @@ -135,7 +135,7 @@ class AnimationPlayer { /** @private @const {!Array} */ this.segments_ = []; for (let i = 0; i < segments.length; i++) { - let segment = segments[i]; + const segment = segments[i]; this.segments_.push({ delay: segment.delay, func: segment.func, @@ -205,7 +205,7 @@ class AnimationPlayer { * @return {!Promise} */ thenAlways(opt_callback) { - let callback = opt_callback || NOOP_CALLBACK; + const callback = opt_callback || NOOP_CALLBACK; return this.then(callback, callback); } @@ -281,13 +281,13 @@ class AnimationPlayer { if (!this.running_) { return; } - let currentTime = timer.now(); - let normLinearTime = Math.min((currentTime - this.startTime_) / + const currentTime = timer.now(); + const normLinearTime = Math.min((currentTime - this.startTime_) / this.duration_, 1); // Start segments due to be started for (let i = 0; i < this.segments_.length; i++) { - let segment = this.segments_[i]; + const segment = this.segments_[i]; if (!segment.started && normLinearTime >= segment.delay) { segment.started = true; } @@ -295,7 +295,7 @@ class AnimationPlayer { // Execute all pending segments. for (let i = 0; i < this.segments_.length; i++) { - let segment = this.segments_[i]; + const segment = this.segments_[i]; if (!segment.started || segment.completed) { continue; } diff --git a/src/base-element.js b/src/base-element.js index e9c2df3bde04..3bb7c446e112 100644 --- a/src/base-element.js +++ b/src/base-element.js @@ -320,7 +320,7 @@ export class BaseElement { if (invocation.method == 'activate') { this.activate(invocation); } else { - let handler = this.actionMap_[invocation.method]; + const handler = this.actionMap_[invocation.method]; if (!handler) { throw new Error(`Method not found: ${invocation.method}`); } @@ -353,7 +353,7 @@ export class BaseElement { */ propagateAttributes(attributes, element) { for (let i = 0; i < attributes.length; i++) { - let attr = attributes[i]; + const attr = attributes[i]; if (!this.element.hasAttribute(attr)) { continue; } diff --git a/src/curve.js b/src/curve.js index efca09c2285b..50bdc08d9f99 100644 --- a/src/curve.js +++ b/src/curve.js @@ -32,7 +32,7 @@ class Curve {}; * @return {!Curve} */ export function bezierCurve(x1, y1, x2, y2) { - let bezier = new Bezier(0, 0, x1, y1, x2, y2, 1, 1); + const bezier = new Bezier(0, 0, x1, y1, x2, y2, 1, 1); return bezier.solveYValueFromXValue.bind(bezier); } diff --git a/src/custom-element.js b/src/custom-element.js index b0b3254a3981..e0267ca16579 100644 --- a/src/custom-element.js +++ b/src/custom-element.js @@ -55,7 +55,7 @@ const PREPARE_LOADING_THRESHOLD_ = 1000; * Map from element name to implementation class. * @const {Object} */ -let knownElements = {}; +const knownElements = {}; /** @@ -72,7 +72,7 @@ export function upgradeOrRegisterElement(win, name, toClass) { assert(knownElements[name] == ElementStub, 'Expected ' + name + ' to be an ElementStub.'); for (let i = 0; i < stubbedElements.length; i++) { - let stub = stubbedElements[i]; + const stub = stubbedElements[i]; // There are 3 possible states here: // 1. We never made the stub because the extended impl. loaded first. // In that case the element won't be in the array. @@ -98,9 +98,9 @@ export function upgradeOrRegisterElement(win, name, toClass) { * @param {!Window} win */ export function stubElements(win) { - let list = win.document.querySelectorAll('[custom-element]'); + const list = win.document.querySelectorAll('[custom-element]'); for (let i = 0; i < list.length; i++) { - let name = list[i].getAttribute('custom-element'); + const name = list[i].getAttribute('custom-element'); if (knownElements[name]) { continue; } @@ -116,15 +116,15 @@ export function stubElements(win) { export function applyLayout_(element) { let widthAttr = element.getAttribute('width'); let heightAttr = element.getAttribute('height'); - let sizesAttr = element.getAttribute('sizes'); - let layoutAttr = element.getAttribute('layout'); + const sizesAttr = element.getAttribute('sizes'); + const layoutAttr = element.getAttribute('layout'); // Handle elements that do not specify a width/height and are defined to have // natural browser dimensions. if ((!layoutAttr || layoutAttr == Layout.FIXED || layoutAttr == Layout.FIXED_HEIGHT) && (!widthAttr || !heightAttr) && hasNaturalDimensions(element.tagName)) { - let dimensions = getNaturalDimensions(element.tagName); + const dimensions = getNaturalDimensions(element.tagName); if (layoutAttr != Layout.FIXED_HEIGHT) { widthAttr = widthAttr || dimensions.width; } @@ -168,7 +168,7 @@ export function applyLayout_(element) { 'integer/length value: ' + widthAttr); } } - let height = parseLength(heightAttr); + const height = parseLength(heightAttr); if (!height) { throw new Error('Expected height to be available and be an ' + 'integer/length value: ' + heightAttr); @@ -178,7 +178,7 @@ export function applyLayout_(element) { throw new Error('Length units should be the same for width ' + width + ' and height ' + height); } - let sizer = element.ownerDocument.createElement('i-amp-sizer'); + const sizer = element.ownerDocument.createElement('i-amp-sizer'); sizer.style.display = 'block'; sizer.style.paddingTop = ((getLengthNumeral(height) / getLengthNumeral(width)) * 100) + '%'; @@ -332,8 +332,8 @@ export function createAmpElementProto(win, name, implementationClass) { * @final @package */ ElementProto.upgrade = function(newImplClass) { - let registeredStub = this.implementation_; - let newImpl = new newImplClass(this); + const registeredStub = this.implementation_; + const newImpl = new newImplClass(this); this.implementation_ = newImpl; if (registeredStub) { registeredStub.upgrade(newImpl); @@ -465,7 +465,7 @@ export function createAmpElementProto(win, name, implementationClass) { // Sizes. if (this.sizeList_ === undefined) { - let sizesAttr = this.getAttribute('sizes'); + const sizesAttr = this.getAttribute('sizes'); this.sizeList_ = sizesAttr ? parseSizeList(sizesAttr) : null; } if (this.sizeList_) { @@ -714,7 +714,7 @@ export function createAmpElementProto(win, name, implementationClass) { return; } - let actionQueue = assert(this.actionQueue_); + const actionQueue = assert(this.actionQueue_); this.actionQueue_ = null; actionQueue.forEach(invocation => { @@ -746,7 +746,7 @@ export function createAmpElementProto(win, name, implementationClass) { * @package @final */ ElementProto.getRealChildNodes = function() { - let nodes = []; + const nodes = []; for (let n = this.firstChild; n; n = n.nextSibling) { if (!isInternalOrServiceNode(n)) { nodes.push(n); @@ -762,9 +762,9 @@ export function createAmpElementProto(win, name, implementationClass) { * @package @final */ ElementProto.getRealChildren = function() { - let elements = []; + const elements = []; for (let i = 0; i < this.children.length; i++) { - let child = this.children[i]; + const child = this.children[i]; if (!isInternalOrServiceNode(child)) { elements.push(child); } @@ -787,7 +787,7 @@ export function createAmpElementProto(win, name, implementationClass) { * @package @final */ ElementProto.togglePlaceholder = function(state) { - let placeholder = this.getPlaceholder(); + const placeholder = this.getPlaceholder(); if (placeholder) { placeholder.classList.toggle('amp-hidden', !state); } @@ -842,12 +842,12 @@ export function createAmpElementProto(win, name, implementationClass) { */ ElementProto.prepareLoading_ = function() { if (!this.loadingContainer_) { - let container = document.createElement('div'); + const container = document.createElement('div'); container.classList.add('-amp-loading-container'); container.classList.add('-amp-fill-content'); container.classList.add('amp-hidden'); - let element = createLoaderElement(); + const element = createLoaderElement(); container.appendChild(element); this.appendChild(container); @@ -884,7 +884,7 @@ export function createAmpElementProto(win, name, implementationClass) { this.loadingElement_.classList.toggle('amp-active', state); if (!state && opt_cleanup) { - let loadingContainer = this.loadingContainer_; + const loadingContainer = this.loadingContainer_; this.loadingContainer_ = null; this.loadingElement_ = null; this.resources_.deferMutate(this, () => { diff --git a/src/document-click.js b/src/document-click.js index 1434714c4579..232139ee0ab4 100644 --- a/src/document-click.js +++ b/src/document-click.js @@ -97,23 +97,23 @@ export function onDocumentElementClick_(e, viewport) { return; } - let target = closestByTag(e.target, 'A'); + const target = closestByTag(e.target, 'A'); if (!target) { return; } let elem = null; - let docElement = e.currentTarget; - let doc = docElement.ownerDocument; + const docElement = e.currentTarget; + const doc = docElement.ownerDocument; - let tgtLoc = parseUrl(target.href); + const tgtLoc = parseUrl(target.href); if (!tgtLoc.hash) { return; } - let curLoc = parseUrl(doc.location.href); - let tgtHref = `${tgtLoc.origin}${tgtLoc.pathname}${tgtLoc.search}`; - let curHref = `${curLoc.origin}${curLoc.pathname}${curLoc.search}`; + const curLoc = parseUrl(doc.location.href); + const tgtHref = `${tgtLoc.origin}${tgtLoc.pathname}${tgtLoc.search}`; + const curHref = `${curLoc.origin}${curLoc.pathname}${curLoc.search}`; // If the current target anchor link is the same origin + path // as the current document then we know we are just linking to an @@ -127,7 +127,7 @@ export function onDocumentElementClick_(e, viewport) { // history which contains the amp document. e.preventDefault(); - let hash = tgtLoc.hash.slice(1); + const hash = tgtLoc.hash.slice(1); elem = doc.getElementById(hash); if (!elem) { diff --git a/src/document-state.js b/src/document-state.js index 3cb4af9f050c..b94ce467d5e9 100644 --- a/src/document-state.js +++ b/src/document-state.js @@ -86,7 +86,7 @@ export class DocumentState { this.visibilityChangeEvent_ = null; if (this.hiddenProp_) { this.visibilityChangeEvent_ = 'visibilitychange'; - let vendorStop = this.hiddenProp_.indexOf('Hidden'); + const vendorStop = this.hiddenProp_.indexOf('Hidden'); if (vendorStop != -1) { this.visibilityChangeEvent_ = this.hiddenProp_.substring(0, vendorStop) + 'Visibilitychange'; diff --git a/src/dom.js b/src/dom.js index 014f49828db3..b12afa2364d9 100644 --- a/src/dom.js +++ b/src/dom.js @@ -45,7 +45,7 @@ export function removeChildren(parent) { * @param {!Element} to */ export function copyChildren(from, to) { - let frag = to.ownerDocument.createDocumentFragment(); + const frag = to.ownerDocument.createDocumentFragment(); for (let n = from.firstChild; n; n = n.nextSibling) { frag.appendChild(n.cloneNode(true)); } @@ -92,7 +92,7 @@ export function closestByTag(element, tagName) { * @return {?Element} */ export function elementByTag(element, tagName) { - let elements = element.getElementsByTagName(tagName); + const elements = element.getElementsByTagName(tagName); return elements.length > 0 ? elements[0] : null; } @@ -104,7 +104,7 @@ export function elementByTag(element, tagName) { * @return {?Element} */ export function childElement(parent, callback) { - let children = parent.children; + const children = parent.children; for (let i = 0; i < children.length; i++) { if (callback(children[i])) { return children[i]; diff --git a/src/event-helper.js b/src/event-helper.js index 413d6632a1ef..16a9dfe53a9c 100644 --- a/src/event-helper.js +++ b/src/event-helper.js @@ -27,9 +27,9 @@ import {timer} from './timer'; * @return {!Unlisten} */ export function listenOnce(element, eventType, listener, opt_capture) { - let capture = opt_capture || false; + const capture = opt_capture || false; let unlisten; - let proxy = event => { + const proxy = event => { listener(event); unlisten(); }; @@ -54,7 +54,7 @@ export function listenOnce(element, eventType, listener, opt_capture) { export function listenOncePromise(element, eventType, opt_capture, opt_timeout) { let unlisten; - let eventPromise = new Promise((resolve, reject) => { + const eventPromise = new Promise((resolve, reject) => { unlisten = listenOnce(element, eventType, resolve, opt_capture); }); return racePromise_(eventPromise, unlisten, opt_timeout); @@ -82,7 +82,7 @@ export function isLoaded(element) { export function loadPromise(element, opt_timeout) { let unlistenLoad; let unlistenError; - let loadingPromise = new Promise((resolve, reject) => { + const loadingPromise = new Promise((resolve, reject) => { if (isLoaded(element)) { resolve(element); } else { diff --git a/src/focus-history.js b/src/focus-history.js index e66a22e2cd00..f4ba7ad66881 100644 --- a/src/focus-history.js +++ b/src/focus-history.js @@ -66,7 +66,7 @@ export class FocusHistory { * @private */ pushFocus_(element) { - let now = timer.now(); + const now = timer.now(); if (this.history_.length == 0 || this.history_[this.history_.length - 1].el != element) { this.history_.push({el: element, time: now}); diff --git a/src/gesture-recognizers.js b/src/gesture-recognizers.js index 1db6c245a1d2..49a425ea178f 100644 --- a/src/gesture-recognizers.js +++ b/src/gesture-recognizers.js @@ -56,7 +56,7 @@ export class TapRecognizer extends GestureRecognizer { /** @override */ onTouchStart(e) { - let touches = e.touches; + const touches = e.touches; if (!touches || touches.length != 1) { return false; } @@ -67,12 +67,12 @@ export class TapRecognizer extends GestureRecognizer { /** @override */ onTouchMove(e) { - let touches = e.changedTouches || e.touches; + const touches = e.changedTouches || e.touches; if (touches && touches.length == 1) { this.lastX_ = touches[0].clientX; this.lastY_ = touches[0].clientY; - let dx = Math.abs(this.lastX_ - this.startX_) >= 8; - let dy = Math.abs(this.lastY_ - this.startY_) >= 8; + const dx = Math.abs(this.lastX_ - this.startX_) >= 8; + const dy = Math.abs(this.lastY_ - this.startY_) >= 8; if (dx || dy) { return false; } @@ -137,7 +137,7 @@ export class DoubletapRecognizer extends GestureRecognizer { if (this.tapCount_ > 1) { return false; } - let touches = e.touches; + const touches = e.touches; if (!touches || touches.length != 1) { return false; } @@ -148,12 +148,12 @@ export class DoubletapRecognizer extends GestureRecognizer { /** @override */ onTouchMove(e) { - let touches = e.changedTouches || e.touches; + const touches = e.changedTouches || e.touches; if (touches && touches.length == 1) { this.lastX_ = touches[0].clientX; this.lastY_ = touches[0].clientY; - let dx = Math.abs(this.lastX_ - this.startX_) >= 8; - let dy = Math.abs(this.lastY_ - this.startY_) >= 8; + const dx = Math.abs(this.lastX_ - this.startX_) >= 8; + const dy = Math.abs(this.lastY_ - this.startY_) >= 8; if (dx || dy) { this.acceptCancel(); return false; @@ -259,7 +259,7 @@ class SwipeRecognizer extends GestureRecognizer { /** @override */ onTouchStart(e) { - let touches = e.touches; + const touches = e.touches; if (!touches || touches.length != 1) { return false; } @@ -271,17 +271,17 @@ class SwipeRecognizer extends GestureRecognizer { /** @override */ onTouchMove(e) { - let touches = e.changedTouches || e.touches; + const touches = e.changedTouches || e.touches; if (touches && touches.length == 1) { - let x = touches[0].clientX; - let y = touches[0].clientY; + const x = touches[0].clientX; + const y = touches[0].clientY; this.lastX_ = x; this.lastY_ = y; if (this.eventing_) { this.emit_(false, false, e); } else { - let dx = Math.abs(x - this.startX_); - let dy = Math.abs(y - this.startY_); + const dx = Math.abs(x - this.startX_); + const dy = Math.abs(y - this.startY_); // Swipe is penalized slightly since it's one of the least demanding // gesture, thus -10 in signalReady. if (this.horiz_ && this.vert_) { @@ -340,7 +340,7 @@ class SwipeRecognizer extends GestureRecognizer { */ emit_(first, last, event) { this.lastTime_ = timer.now(); - let deltaTime = this.lastTime_ - this.prevTime_; + const deltaTime = this.lastTime_ - this.prevTime_; // It's often that `touchend` arrives on the next frame. These should // be ignored to avoid a significant velocity downgrade. if (!last && deltaTime > 4 || last && deltaTime > 16) { @@ -500,7 +500,7 @@ export class TapzoomRecognizer extends GestureRecognizer { if (this.eventing_) { return false; } - let touches = e.touches; + const touches = e.touches; if (!touches || touches.length != 1) { return false; } @@ -511,15 +511,15 @@ export class TapzoomRecognizer extends GestureRecognizer { /** @override */ onTouchMove(e) { - let touches = e.changedTouches || e.touches; + const touches = e.changedTouches || e.touches; if (touches && touches.length == 1) { this.lastX_ = touches[0].clientX; this.lastY_ = touches[0].clientY; if (this.eventing_) { this.emit_(false, false, e); } else { - let dx = Math.abs(this.lastX_ - this.startX_) >= 8; - let dy = Math.abs(this.lastY_ - this.startY_) >= 8; + const dx = Math.abs(this.lastX_ - this.startX_) >= 8; + const dy = Math.abs(this.lastY_ - this.startY_) >= 8; if (dx || dy) { if (this.tapCount_ == 0) { this.acceptCancel(); @@ -690,7 +690,7 @@ export class PinchRecognizer extends GestureRecognizer { /** @override */ onTouchStart(e) { - let touches = e.touches; + const touches = e.touches; if (!touches || touches.length != 2) { return false; } @@ -704,7 +704,7 @@ export class PinchRecognizer extends GestureRecognizer { /** @override */ onTouchMove(e) { - let touches = e.touches; + const touches = e.touches; if (!touches || touches.length != 2) { return false; } @@ -715,10 +715,10 @@ export class PinchRecognizer extends GestureRecognizer { if (this.eventing_) { this.emit_(false, false, e); } else { - let dx1 = this.lastX1_ - this.startX1_; - let dy1 = this.lastY1_ - this.startY1_; - let dx2 = this.lastX2_ - this.startX2_; - let dy2 = this.lastY2_ - this.startY2_; + const dx1 = this.lastX1_ - this.startX1_; + const dy1 = this.lastY1_ - this.startY1_; + const dx2 = this.lastX2_ - this.startX2_; + const dy2 = this.lastY2_ - this.startY2_; // Fingers should move in opposite directions and go over the threshold. if (dx1 * dx2 <= 0 && dy1 * dy2 <= 0) { if (Math.abs(dx1 - dx2) >= 8 || Math.abs(dy1 - dy2) >= 8) { @@ -761,9 +761,9 @@ export class PinchRecognizer extends GestureRecognizer { */ emit_(first, last, event) { this.lastTime_ = timer.now(); - let deltaTime = this.lastTime_ - this.prevTime_; - let deltaX = this.deltaX_(); - let deltaY = this.deltaY_(); + const deltaTime = this.lastTime_ - this.prevTime_; + const deltaX = this.deltaX_(); + const deltaY = this.deltaY_(); // It's often that `touchend` arrives on the next frame. These should // be ignored to avoid a significant velocity downgrade. if (!last && deltaTime > 4 || last && deltaTime > 16) { @@ -778,9 +778,9 @@ export class PinchRecognizer extends GestureRecognizer { this.prevTime_ = this.lastTime_; } - let startSq = this.sqDist_(this.startX1_, this.startX2_, + const startSq = this.sqDist_(this.startX1_, this.startX2_, this.startY1_, this.startY2_); - let lastSq = this.sqDist_(this.lastX1_, this.lastX2_, + const lastSq = this.sqDist_(this.lastX1_, this.lastX2_, this.lastY1_, this.lastY2_); this.signalEmit({ first: first, diff --git a/src/gesture.js b/src/gesture.js index 36c14639b6fc..ab0020344916 100644 --- a/src/gesture.js +++ b/src/gesture.js @@ -154,8 +154,8 @@ export class Gestures { * @template DATA */ onGesture(recognizerConstr, handler) { - let recognizer = new recognizerConstr(this); - let type = recognizer.getType(); + const recognizer = new recognizerConstr(this); + const type = recognizer.getType(); let overserver = this.overservers_[type]; if (!overserver) { this.recognizers_.push(recognizer); @@ -181,7 +181,7 @@ export class Gestures { * @private */ onTouchStart_(event) { - let now = timer.now(); + const now = timer.now(); this.wasEventing_ = false; this.pointerDownObservable_.fire(event); @@ -216,7 +216,7 @@ export class Gestures { * @private */ onTouchMove_(event) { - let now = timer.now(); + const now = timer.now(); for (let i = 0; i < this.recognizers_.length; i++) { if (!this.tracking_[i]) { @@ -244,7 +244,7 @@ export class Gestures { * @private */ onTouchEnd_(event) { - let now = timer.now(); + const now = timer.now(); for (let i = 0; i < this.recognizers_.length; i++) { if (!this.tracking_[i]) { @@ -295,7 +295,7 @@ export class Gestures { // Set the recognizer as ready and wait for the pass to // make the decision. - let now = timer.now(); + const now = timer.now(); for (let i = 0; i < this.recognizers_.length; i++) { if (this.recognizers_[i] == recognizer) { this.ready_[i] = now + offset; @@ -321,7 +321,7 @@ export class Gestures { return; } - let now = timer.now(); + const now = timer.now(); for (let i = 0; i < this.recognizers_.length; i++) { if (this.recognizers_[i] == recognizer) { this.pending_[i] = now + timeLeft; @@ -353,7 +353,7 @@ export class Gestures { signalEmit_(recognizer, data, event) { assert(this.eventing_ == recognizer, 'Recognizer is not currently allowed: %s', recognizer.getType()); - let overserver = this.overservers_[recognizer.getType()]; + const overserver = this.overservers_[recognizer.getType()]; if (overserver) { overserver.fire(new Gesture(recognizer.getType(), data, timer.now(), event)); @@ -368,7 +368,7 @@ export class Gestures { let cancelEvent = !!this.eventing_ || this.wasEventing_; this.wasEventing_ = false; if (!cancelEvent) { - let now = timer.now(); + const now = timer.now(); for (let i = 0; i < this.recognizers_.length; i++) { if (this.ready_[i] || this.pending_[i] && this.pending_[i] >= now) { @@ -394,7 +394,7 @@ export class Gestures { * @private */ doPass_() { - let now = timer.now(); + const now = timer.now(); // The "most ready" recognizer is the youngest in the "ready" set. // Otherwise we wouldn't wait for it at all. @@ -442,7 +442,7 @@ export class Gestures { * @private */ startEventing_(index) { - let recognizer = this.recognizers_[index]; + const recognizer = this.recognizers_[index]; for (let i = 0; i < this.recognizers_.length; i++) { if (i != index) { this.cancelEventing_(i); diff --git a/src/history.js b/src/history.js index e4eb52c59989..c3bbb54c0182 100644 --- a/src/history.js +++ b/src/history.js @@ -23,11 +23,11 @@ import {viewerFor} from './viewer'; /** @private @const */ -let TAG_ = 'History'; +const TAG_ = 'History'; /** @private @const */ -let HISTORY_PROP_ = 'AMP.History'; +const HISTORY_PROP_ = 'AMP.History'; /** @@ -35,7 +35,7 @@ let HISTORY_PROP_ = 'AMP.History'; * @private */ function historyState_(stackIndex) { - let state = {}; + const state = {}; state[HISTORY_PROP_] = stackIndex; return state; } @@ -119,7 +119,7 @@ export class History { return; } - let toPop = []; + const toPop = []; for (let i = this.stackOnPop_.length - 1; i > this.stackIndex_; i--) { if (this.stackOnPop_[i]) { toPop.push(this.stackOnPop_[i]); @@ -167,7 +167,7 @@ export class History { return; } - let task = this.queue_[0]; + const task = this.queue_[0]; let promise; try { promise = task.callback(); @@ -240,7 +240,7 @@ export class HistoryBindingNatural_ { /** @const {!Window} */ this.win = win; - let history = this.win.history; + const history = this.win.history; /** @private {number} */ this.startIndex_ = history.length - 1; @@ -314,7 +314,7 @@ export class HistoryBindingNatural_ { history.pushState = this.historyPushState_.bind(this); history.replaceState = this.historyReplaceState_.bind(this); - let eventPass = new Pass(this.onHistoryEvent_.bind(this), 50); + const eventPass = new Pass(this.onHistoryEvent_.bind(this), 50); this.popstateHandler_ = e => { log.fine(TAG_, 'popstate event: ' + this.win.history.length + ', ' + JSON.stringify(e.state)); @@ -380,9 +380,9 @@ export class HistoryBindingNatural_ { let state = this.getState_(); log.fine(TAG_, 'history event: ' + this.win.history.length + ', ' + JSON.stringify(state)); - let stackIndex = state ? state[HISTORY_PROP_] : undefined; + const stackIndex = state ? state[HISTORY_PROP_] : undefined; let newStackIndex = this.stackIndex_; - let waitingState = this.waitingState_; + const waitingState = this.waitingState_; this.waitingState_ = undefined; if (newStackIndex > this.win.history.length - 2) { @@ -461,7 +461,7 @@ export class HistoryBindingNatural_ { this.assertReady_(); let resolve; let reject; - let promise = timer.timeoutPromise(500, + const promise = timer.timeoutPromise(500, new Promise((aResolve, aReject) => { resolve = aResolve; reject = aReject; @@ -484,7 +484,7 @@ export class HistoryBindingNatural_ { return Promise.resolve(this.stackIndex_); } this.unsupportedState_ = historyState_(this.stackIndex_ - steps); - let promise = this.wait_(); + const promise = this.wait_(); this.win.history.go(-steps); return promise.then(() => { return Promise.resolve(this.stackIndex_); @@ -502,7 +502,7 @@ export class HistoryBindingNatural_ { if (!state) { state = {}; } - let len = this.win.history.length; + const len = this.win.history.length; let stackIndex = this.stackIndex_ + 1; state[HISTORY_PROP_] = stackIndex; this.pushState_(state, title, url); @@ -525,7 +525,7 @@ export class HistoryBindingNatural_ { if (!state) { state = {}; } - let stackIndex = Math.min(this.stackIndex_, this.win.history.length - 1); + const stackIndex = Math.min(this.stackIndex_, this.win.history.length - 1); state[HISTORY_PROP_] = stackIndex; this.replaceState_(state, title, url); this.updateStackIndex_(stackIndex); @@ -638,7 +638,7 @@ export class HistoryBindingVirtual_ { * @private */ function createHistory_(window) { - let viewer = viewerFor(window); + const viewer = viewerFor(window); let binding; if (viewer.isOvertakeHistory()) { binding = new HistoryBindingVirtual_(viewer); diff --git a/src/input.js b/src/input.js index a5c57ecde1f5..8d61caddf029 100644 --- a/src/input.js +++ b/src/input.js @@ -21,10 +21,10 @@ import {listenOnce, listenOncePromise} from './event-helper'; import {timer} from './timer'; -let TAG_ = 'Input'; +const TAG_ = 'Input'; -let MAX_MOUSE_CONFIRM_ATTEMPS_ = 3; -let CLICK_TIMEOUT_ = 300; +const MAX_MOUSE_CONFIRM_ATTEMPS_ = 3; +const CLICK_TIMEOUT_ = 300; /** @@ -172,7 +172,7 @@ export class Input { } // Ignore inputs. - let target = e.target; + const target = e.target; if (target && (target.tagName == 'INPUT' || target.tagName == 'TEXTAREA' || target.tagName == 'SELECT' || diff --git a/src/layout.js b/src/layout.js index 6dcdba5076d4..cd483b7009a1 100644 --- a/src/layout.js +++ b/src/layout.js @@ -86,7 +86,7 @@ export const LOADING_ELEMENTS_ = { * the layout string. */ export function parseLayout(s) { - for (let k in Layout) { + for (const k in Layout) { if (Layout[k] == s) { return Layout[k]; } @@ -123,7 +123,7 @@ export function isLayoutSizeDefined(layout) { * @return {boolean} */ export function isInternalElement(tag) { - let tagName = (typeof tag == 'string') ? tag : tag.tagName; + const tagName = (typeof tag == 'string') ? tag : tag.tagName; return tagName && tagName.toLowerCase().indexOf('i-') == 0; } @@ -170,7 +170,7 @@ export function assertLength(length) { */ export function getLengthUnits(length) { assertLength(length); - let m = assert(length.match(/[a-z]+/i), + const m = assert(length.match(/[a-z]+/i), 'Failed to read units from %s', length); return m[0]; } @@ -207,8 +207,8 @@ export function hasNaturalDimensions(tagName) { export function getNaturalDimensions(tagName) { tagName = tagName.toUpperCase(); if (!naturalDimensions_[tagName]) { - let naturalTagName = tagName.replace(/^AMP\-/, ''); - let temp = document.createElement(naturalTagName); + const naturalTagName = tagName.replace(/^AMP\-/, ''); + const temp = document.createElement(naturalTagName); // For audio, should no-op elsewhere. temp.controls = true; temp.style.position = 'absolute'; diff --git a/src/loader.js b/src/loader.js index de8b081c4e3d..7d3f1f80352f 100644 --- a/src/loader.js +++ b/src/loader.js @@ -21,10 +21,10 @@ * @return {!Element} */ export function createLoaderElement() { - let loader = document.createElement('div'); + const loader = document.createElement('div'); loader.classList.add('-amp-loader'); for (let i = 0; i < 3; i++) { - let dot = document.createElement('div'); + const dot = document.createElement('div'); dot.classList.add('-amp-loader-dot'); loader.appendChild(dot); } diff --git a/src/motion.js b/src/motion.js index 268eb94c5267..40821925262b 100644 --- a/src/motion.js +++ b/src/motion.js @@ -53,7 +53,7 @@ export function calcVelocity(deltaV, deltaTime, prevVelocity) { } // Calculate speed and speed depreciation. - let speed = deltaV / deltaTime; + const speed = deltaV / deltaTime; // Depreciation is simply an informational quality. It basically means: // we can't ignore the velocity we knew recently, but we'd only consider @@ -61,7 +61,7 @@ export function calcVelocity(deltaV, deltaTime, prevVelocity) { // depreciation factor is 1/100 of a millisecond. New average velocity is // calculated by weighing toward the new velocity and away from old // velocity based on the depreciation. - let depr = 0.5 + Math.min(deltaTime / VELOCITY_DEPR_FACTOR_, 0.5); + const depr = 0.5 + Math.min(deltaTime / VELOCITY_DEPR_FACTOR_, 0.5); return speed * depr + prevVelocity * (1 - depr); } @@ -191,7 +191,7 @@ class Motion { * @return {!Promise} */ thenAlways(opt_callback) { - let callback = opt_callback || NOOP_CALLBACK_; + const callback = opt_callback || NOOP_CALLBACK_; return this.then(callback, callback); } @@ -202,8 +202,8 @@ class Motion { runContinuing_() { this.velocityX_ = this.maxVelocityX_; this.velocityY_ = this.maxVelocityY_; - let boundStep = this.stepContinue_.bind(this); - let boundComplete = this.completeContinue_.bind(this, true); + const boundStep = this.stepContinue_.bind(this); + const boundComplete = this.completeContinue_.bind(this, true); return this.vsync_.runMutateSeries(boundStep, 5000) .then(boundComplete, boundComplete); } @@ -220,8 +220,8 @@ class Motion { return false; } - let prevX = this.lastX_; - let prevY = this.lastY_; + const prevX = this.lastX_; + const prevY = this.lastY_; this.lastTime_ = timer.now(); this.lastX_ += timeSincePrev * this.velocityX_; @@ -230,7 +230,7 @@ class Motion { return false; } - let decel = Math.exp(-timeSinceStart / EXP_FRAME_CONST_); + const decel = Math.exp(-timeSinceStart / EXP_FRAME_CONST_); this.velocityX_ = this.maxVelocityX_ * decel; this.velocityY_ = this.maxVelocityY_ * decel; return (Math.abs(this.velocityX_) > MIN_VELOCITY_ || diff --git a/src/pull-to-refresh.js b/src/pull-to-refresh.js index fac4d21ec40f..31cebd6420d8 100644 --- a/src/pull-to-refresh.js +++ b/src/pull-to-refresh.js @@ -120,7 +120,7 @@ export class PullToRefreshBlocker { return; } - let dy = event.touches[0].clientY - this.startPos_; + const dy = event.touches[0].clientY - this.startPos_; // Immediately cancel the P2R if dragging down. if (dy > 0) { diff --git a/src/resources.js b/src/resources.js index f29d6e0ce40e..6dcfb8d87422 100644 --- a/src/resources.js +++ b/src/resources.js @@ -30,18 +30,18 @@ import {viewerFor} from './viewer'; import {viewportFor} from './viewport'; import {vsync} from './vsync'; -let TAG_ = 'Resources'; -let RESOURCE_PROP_ = '__AMP__RESOURCE'; -let OWNER_PROP_ = '__AMP__OWNER'; -let LAYOUT_TASK_ID_ = 'L'; -let LAYOUT_TASK_OFFSET_ = 0; -let PRELOAD_TASK_ID_ = 'P'; -let PRELOAD_TASK_OFFSET_ = 2; -let PRIORITY_BASE_ = 10; -let PRIORITY_PENALTY_TIME_ = 1000; -let POST_TASK_PASS_DELAY_ = 1000; -let MUTATE_DEFER_DELAY_ = 500; -let FOCUS_HISTORY_TIMEOUT_ = 1000 * 60; // 1min +const TAG_ = 'Resources'; +const RESOURCE_PROP_ = '__AMP__RESOURCE'; +const OWNER_PROP_ = '__AMP__OWNER'; +const LAYOUT_TASK_ID_ = 'L'; +const LAYOUT_TASK_OFFSET_ = 0; +const PRELOAD_TASK_ID_ = 'P'; +const PRELOAD_TASK_OFFSET_ = 2; +const PRIORITY_BASE_ = 10; +const PRIORITY_PENALTY_TIME_ = 1000; +const POST_TASK_PASS_DELAY_ = 1000; +const MUTATE_DEFER_DELAY_ = 500; +const FOCUS_HISTORY_TIMEOUT_ = 1000 * 60; // 1min /** @@ -192,7 +192,7 @@ export class Resources { /** @private */ monitorInput_() { - let input = inputFor(this.win); + const input = inputFor(this.win); input.onTouchDetected(detected => { this.toggleInputClass_('amp-mode-touch', detected); }, true); @@ -220,7 +220,7 @@ export class Resources { if (!this.win.document.body) { return; } - let scrollHeight = this.win.document.body./*OK*/scrollHeight; + const scrollHeight = this.win.document.body./*OK*/scrollHeight; if (scrollHeight != this./*OK*/scrollHeight_) { this./*OK*/scrollHeight_ = scrollHeight; this.viewer_.postDocumentResized(this.viewport_.getSize().width, @@ -264,7 +264,7 @@ export class Resources { * @package */ add(element) { - let resource = new Resource((++this.resourceIdCounter_), element, this); + const resource = new Resource((++this.resourceIdCounter_), element, this); if (!element.id) { element.id = 'AMP_' + resource.getId(); } @@ -287,8 +287,8 @@ export class Resources { * @package */ remove(element) { - let resource = this.getResourceForElement(element); - let index = resource ? this.resources_.indexOf(resource) : -1; + const resource = this.getResourceForElement(element); + const index = resource ? this.resources_.indexOf(resource) : -1; if (index != -1) { this.resources_.splice(index, 1); } @@ -302,7 +302,7 @@ export class Resources { * @package */ upgraded(element) { - let resource = this.getResourceForElement(element); + const resource = this.getResourceForElement(element); if (this.isRuntimeOn_) { resource.build(this.forceBuild_); this.schedulePass(); @@ -441,7 +441,7 @@ export class Resources { return; } - let prevVisible = this.visible_; + const prevVisible = this.visible_; this.visible_ = this.viewer_.isVisible(); this.prerenderSize_ = this.viewer_.getPrerenderSize(); @@ -452,8 +452,8 @@ export class Resources { this.updateScrollHeight_(); } - let viewportSize = this.viewport_.getSize(); - let now = timer.now(); + const viewportSize = this.viewport_.getSize(); + const now = timer.now(); log.fine(TAG_, 'PASS: at ' + now + ', visible=', this.visible_, ', forceBuild=', this.forceBuild_, @@ -508,16 +508,16 @@ export class Resources { */ mutateWork_() { // Read all necessary data before mutates. - let now = timer.now(); - let viewportRect = this.viewport_.getRect(); - let isScrollingStopped = (Math.abs(this.lastVelocity_) < 1e-2 && + const now = timer.now(); + const viewportRect = this.viewport_.getRect(); + const isScrollingStopped = (Math.abs(this.lastVelocity_) < 1e-2 && now - this.lastScrollTime_ > MUTATE_DEFER_DELAY_ || now - this.lastScrollTime_ > MUTATE_DEFER_DELAY_ * 2); - let offset = 10; + const offset = 10; if (this.deferredMutates_.length > 0) { log.fine(TAG_, 'deferred mutates:', this.deferredMutates_.length); - let deferredMutates = this.deferredMutates_; + const deferredMutates = this.deferredMutates_; this.deferredMutates_ = []; for (let i = 0; i < deferredMutates.length; i++) { deferredMutates[i](); @@ -527,15 +527,15 @@ export class Resources { if (this.changeHeightRequests_.length > 0) { log.fine(TAG_, 'change height requests:', this.changeHeightRequests_.length); - let changeHeightRequests = this.changeHeightRequests_; + const changeHeightRequests = this.changeHeightRequests_; this.changeHeightRequests_ = []; // Find minimum top position and run all mutates. let minTop = -1; for (let i = 0; i < changeHeightRequests.length; i++) { - let request = changeHeightRequests[i]; - let resource = request.resource; - let box = request.resource.getLayoutBox(); + const request = changeHeightRequests[i]; + const resource = request.resource; + const box = request.resource.getLayoutBox(); if (box.height == request.newHeight) { // Nothing to do. continue; @@ -608,19 +608,19 @@ export class Resources { // TODO(dvoytenko): vsync separation may be needed for different phases - let now = timer.now(); + const now = timer.now(); // Ensure all resources layout phase complete; when relayoutAll is requested // force re-layout. - let relayoutAll = this.relayoutAll_; + const relayoutAll = this.relayoutAll_; this.relayoutAll_ = false; - let relayoutTop = this.relayoutTop_; + const relayoutTop = this.relayoutTop_; this.relayoutTop_ = -1; // Phase 1: Build and relayout as needed. All mutations happen here. let relayoutCount = 0; for (let i = 0; i < this.resources_.length; i++) { - let r = this.resources_[i]; + const r = this.resources_[i]; if (r.getState() == ResourceState_.NOT_BUILT) { r.build(this.forceBuild_); } @@ -634,7 +634,7 @@ export class Resources { // there's no way to optimize this. All reads happen here. if (relayoutCount > 0 || relayoutAll || relayoutTop != -1) { for (let i = 0; i < this.resources_.length; i++) { - let r = this.resources_[i]; + const r = this.resources_[i]; if (r.getState() == ResourceState_.NOT_BUILT || r.hasOwner()) { continue; } @@ -646,7 +646,7 @@ export class Resources { } } - let viewportRect = this.viewport_.getRect(); + const viewportRect = this.viewport_.getRect(); // Load viewport = viewport + 3x up/down when document is visible or // depending on prerenderSize in pre-render mode. let loadRect; @@ -660,13 +660,13 @@ export class Resources { } // Visible viewport = viewport + 25% up/down. - let visibleRect = expandLayoutRect(viewportRect, 0.25, 0.25); + const visibleRect = expandLayoutRect(viewportRect, 0.25, 0.25); // Phase 3: Schedule elements for layout within a reasonable distance from // current viewport. if (loadRect) { for (let i = 0; i < this.resources_.length; i++) { - let r = this.resources_[i]; + const r = this.resources_[i]; if (r.getState() != ResourceState_.READY_FOR_LAYOUT || r.hasOwner()) { continue; } @@ -678,7 +678,7 @@ export class Resources { // Phase 4: Trigger "viewport enter/exit" events. for (let i = 0; i < this.resources_.length; i++) { - let r = this.resources_[i]; + const r = this.resources_[i]; if (r.hasOwner()) { continue; } @@ -699,7 +699,7 @@ export class Resources { now > this.exec_.getLastDequeueTime() + 5000) { let idleScheduledCount = 0; for (let i = 0; i < this.resources_.length; i++) { - let r = this.resources_[i]; + const r = this.resources_[i]; if (r.getState() == ResourceState_.READY_FOR_LAYOUT && !r.hasOwner() && r.isDisplayed()) { log.fine(TAG_, 'idle layout:', r.debugid); @@ -720,7 +720,7 @@ export class Resources { */ documentBecameInactive_() { for (let i = 0; i < this.resources_.length; i++) { - let r = this.resources_[i]; + const r = this.resources_[i]; r.documentBecameInactive(); } } @@ -738,9 +738,9 @@ export class Resources { * @private */ work_() { - let now = timer.now(); + const now = timer.now(); - let scorer = this.calcTaskScore_.bind(this, this.viewport_.getRect(), + const scorer = this.calcTaskScore_.bind(this, this.viewport_.getRect(), Math.sign(this.lastVelocity_)); let timeout = -1; @@ -760,7 +760,7 @@ export class Resources { // Do not override a task in execution. This task will have to wait // until the current one finished the execution. - let executing = this.exec_.getTaskById(task.id); + const executing = this.exec_.getTaskById(task.id); if (!executing) { // Ensure that task can prerender task.promise = task.callback(this.visible_); @@ -820,7 +820,7 @@ export class Resources { * @private */ calcTaskScore_(viewportRect, dir, task) { - let box = task.resource.getLayoutBox(); + const box = task.resource.getLayoutBox(); let posPriority = Math.floor((box.top - viewportRect.top) / viewportRect.height); if (posPriority != 0 && Math.sign(posPriority) != (dir || 1)) { @@ -849,12 +849,12 @@ export class Resources { return 0; } - let now = timer.now(); + const now = timer.now(); let timeout = 0; this.exec_.forEach(other => { // Higher priority tasks get the head start. Currently 500ms per a drop // in priority (note that priority is 10-based). - let penalty = Math.max((task.priority - other.priority) * + const penalty = Math.max((task.priority - other.priority) * PRIORITY_PENALTY_TIME_, 0); // TODO(dvoytenko): Consider running total and not maximum. timeout = Math.max(timeout, penalty - (now - other.startTime)); @@ -978,7 +978,7 @@ export class Resources { * @private */ scheduleLayoutOrPreloadForSubresources_(parentResource, layout, subElements) { - let resources = []; + const resources = []; this.discoverResourcesForArray_(parentResource, subElements, resource => { if (resource.getState() != ResourceState_.NOT_BUILT) { resources.push(resource); @@ -1006,9 +1006,9 @@ export class Resources { * @private */ schedule_(resource, localId, priorityOffset, parentPriority, callback) { - let taskId = resource.debugid + '#' + localId; + const taskId = resource.debugid + '#' + localId; - let task = { + const task = { id: taskId, resource: resource, priority: Math.max(resource.getPriority(), parentPriority) + @@ -1020,7 +1020,7 @@ export class Resources { // Only schedule a new task if there's no one enqueued yet or if this task // has a higher priority. - let queued = this.queue_.getTaskById(taskId); + const queued = this.queue_.getTaskById(taskId); if (!queued || task.priority < queued.priority) { if (queued) { this.queue_.dequeue(queued); @@ -1040,7 +1040,7 @@ export class Resources { */ updateInViewportForSubresources_(parentResource, subElements, inLocalViewport) { - let inViewport = parentResource.isInViewport() && inLocalViewport; + const inViewport = parentResource.isInViewport() && inLocalViewport; this.discoverResourcesForArray_(parentResource, subElements, resource => { resource.setInViewport(inViewport); }); @@ -1068,10 +1068,10 @@ export class Resources { if (element.classList.contains('-amp-element')) { callback(this.getResourceForElement(element)); } else { - let ampElements = element.getElementsByClassName('-amp-element'); - let seen = []; + const ampElements = element.getElementsByClassName('-amp-element'); + const seen = []; for (let i = 0; i < ampElements.length; i++) { - let ampElement = ampElements[i]; + const ampElement = ampElements[i]; let covered = false; for (let j = 0; j < seen.length; j++) { if (seen[j].contains(ampElement)) { @@ -1158,7 +1158,7 @@ export class Resource { */ getOwner() { if (this.owner_ === undefined) { - let n = this.element; + const n = this.element; for (let n = this.element; n; n = n.parentElement) { if (n[OWNER_PROP_]) { this.owner_ = n[OWNER_PROP_]; @@ -1251,7 +1251,7 @@ export class Resource { // Can't measure unbuilt element. return; } - let box = this.resources_.viewport_.getLayoutRect(this.element); + const box = this.resources_.viewport_.getLayoutRect(this.element); // Note that "left" doesn't affect readiness for the layout. if (this.state_ == ResourceState_.NOT_LAID_OUT || this.layoutBox_.top != box.top || @@ -1557,7 +1557,7 @@ export class TaskQueue_ { * @return {boolean} */ dequeue(task) { - let existing = this.taskIdMap_[task.id]; + const existing = this.taskIdMap_[task.id]; if (!existing) { return false; } @@ -1577,8 +1577,8 @@ export class TaskQueue_ { let minScore = 1e6; let minTask = null; for (let i = 0; i < this.tasks_.length; i++) { - let task = this.tasks_[i]; - let score = scorer(task); + const task = this.tasks_[i]; + const score = scorer(task); if (score < minScore) { minScore = score; minTask = task; diff --git a/src/runtime.js b/src/runtime.js index 9a110a1e29a9..5684a1103146 100644 --- a/src/runtime.js +++ b/src/runtime.js @@ -42,7 +42,7 @@ export function adopt(global) { global.AMP_TAG = true; // If there is already a global AMP object we assume it is an array // of functions - let preregisteredElements = global.AMP || []; + const preregisteredElements = global.AMP || []; global.AMP = {}; /** @@ -75,7 +75,7 @@ export function adopt(global) { /** @const */ global.AMP.assert = assert; - let viewer = viewerFor(global); + const viewer = viewerFor(global); /** @const */ global.AMP.viewer = viewer; @@ -87,7 +87,7 @@ export function adopt(global) { global.AMP.resources = resourcesFor(global); } - let viewport = viewportFor(global); + const viewport = viewportFor(global); /** @const */ global.AMP.viewport = {}; @@ -106,7 +106,7 @@ export function adopt(global) { // Execute asynchronously scheduled elements. for (let i = 0; i < preregisteredElements.length; i++) { - let fn = preregisteredElements[i]; + const fn = preregisteredElements[i]; fn(global.AMP); } } @@ -121,7 +121,7 @@ export function adopt(global) { */ export function registerForUnitTest(win) { for (let i = 0; i < elementsForTesting.length; i++) { - let element = elementsForTesting[i]; + const element = elementsForTesting[i]; registerElement(win, element.name, element.implementationClass); } } diff --git a/src/size-list.js b/src/size-list.js index 4ad6b14d1211..825b69229c1f 100644 --- a/src/size-list.js +++ b/src/size-list.js @@ -42,9 +42,9 @@ var SizeListOption; * @return {!SizeList} */ export function parseSizeList(s) { - let sSizes = s.split(','); + const sSizes = s.split(','); assert(sSizes.length > 0, 'sizes has to have at least one size'); - let sizes = []; + const sizes = []; sSizes.forEach(sSize => { sSize = sSize.replace(/\s+/g, ' ').trim(); if (sSize.length == 0) { @@ -53,7 +53,7 @@ export function parseSizeList(s) { let mediaStr; let sizeStr; - let spaceIndex = sSize.lastIndexOf(' '); + const spaceIndex = sSize.lastIndexOf(' '); if (spaceIndex != -1) { mediaStr = sSize.substring(0, spaceIndex).trim(); sizeStr = sSize.substring(spaceIndex + 1).trim(); @@ -88,7 +88,7 @@ export class SizeList { // All sources except for last must have a media query. The last one must // not. for (let i = 0; i < sizes.length; i++) { - let option = sizes[i]; + const option = sizes[i]; if (i < sizes.length - 1) { assert(option.mediaQuery, 'All options except for the last must have a media condition'); @@ -109,7 +109,7 @@ export class SizeList { */ select(win) { for (let i = 0; i < this.sizes_.length - 1; i++) { - let option = this.sizes_[i]; + const option = this.sizes_[i]; if (win.matchMedia(option.mediaQuery).matches) { return option.size; } diff --git a/src/srcset.js b/src/srcset.js index e3484d5499ed..0d88e2b78bd2 100644 --- a/src/srcset.js +++ b/src/srcset.js @@ -41,28 +41,28 @@ export function parseSrcset(s) { // Example 1: "image1.png 100w, image2.png 50w" // Example 2: "image1.png 2x, image2.png" // Example 3: "image1,100w.png 100w, image2.png 50w" - let sSources = s.match( + const sSources = s.match( /\s*([^\s]*)(\s+(-?(\d+(\.(\d+)?)?|\.\d+)[a-zA-Z]))?(\s*,)?/g); assert(sSources.length > 0, 'srcset has to have at least one source'); - let sources = []; + const sources = []; sSources.forEach(sSource => { sSource = sSource.trim(); if (sSource.substr(-1) == ',') { sSource = sSource.substr(0, sSource.length - 1).trim(); } - let parts = sSource.split(/\s+/, 2); + const parts = sSource.split(/\s+/, 2); if (parts.length == 0 || parts.length == 1 && !parts[0] || parts.length == 2 && !parts[0] && !parts[1]) { return; } - let url = parts[0].trim(); + const url = parts[0].trim(); if (parts.length == 1 || parts.length == 2 && !parts[1]) { // If no "w" or "x" specified, we assume it's "1x". sources.push({url: url, dpr: 1}); } else { - let spec = parts[1].trim().toLowerCase(); - let lastChar = spec.substring(spec.length - 1); + const spec = parts[1].trim().toLowerCase(); + const lastChar = spec.substring(spec.length - 1); if (lastChar == 'w') { sources.push({url: url, width: parseFloat(spec)}); } else if (lastChar == 'x') { @@ -181,7 +181,7 @@ export class Srcset { let minWidth = 1000000; let minScore = 1000000; for (let i = 0; i < this.sources_.length; i++) { - let source = this.sources_[i]; + const source = this.sources_[i]; let sourceWidth; if (source.width) { sourceWidth = source.width / dpr; @@ -193,7 +193,7 @@ export class Srcset { minWidth = Math.min(minWidth, sourceWidth); // The calculation is slightly biased toward higher width by offsetting // score by negative 0.2. - let score = Math.abs((sourceWidth - width) / width - 0.2); + const score = Math.abs((sourceWidth - width) / width - 0.2); if (score < minScore) { minScore = score; minIndex = i; @@ -212,10 +212,10 @@ export class Srcset { let minIndex = -1; let minScore = 1000000; for (let i = 0; i < this.sources_.length; i++) { - let source = this.sources_[i]; + const source = this.sources_[i]; // Default DPR = 1. - let sourceDpr = source.dpr || 1; - let score = Math.abs(sourceDpr - dpr); + const sourceDpr = source.dpr || 1; + const score = Math.abs(sourceDpr - dpr); if (score < minScore) { minScore = score; minIndex = i; diff --git a/src/style.js b/src/style.js index 02092b9cb475..e571742252ed 100644 --- a/src/style.js +++ b/src/style.js @@ -43,7 +43,7 @@ export function camelCaseToTitleCase(camelCase) { */ function getVendorJsPropertyName_(object, titleCase) { for (let i = 0; i < vendorPrefixes_.length; i++) { - let propertyName = vendorPrefixes_[i] + titleCase; + const propertyName = vendorPrefixes_[i] + titleCase; if (object[propertyName] !== undefined) { return propertyName; } @@ -67,8 +67,8 @@ export function getVendorJsPropertyName(object, camelCase, opt_bypassCache) { if (!propertyName || opt_bypassCache) { propertyName = camelCase; if (object[camelCase] === undefined) { - let titleCase = camelCaseToTitleCase(camelCase); - let prefixedPropertyName = getVendorJsPropertyName_(object, titleCase); + const titleCase = camelCaseToTitleCase(camelCase); + const prefixedPropertyName = getVendorJsPropertyName_(object, titleCase); if (object[prefixedPropertyName] !== undefined) { propertyName = prefixedPropertyName; @@ -91,7 +91,7 @@ export function getVendorJsPropertyName(object, camelCase, opt_bypassCache) { * @param {boolean=} opt_bypassCache */ export function setStyle(element, property, value, opt_units, opt_bypassCache) { - let propertyName = getVendorJsPropertyName(element.style, property, + const propertyName = getVendorJsPropertyName(element.style, property, opt_bypassCache); if (propertyName) { element.style[propertyName] = opt_units ? value + opt_units : value; @@ -107,7 +107,7 @@ export function setStyle(element, property, value, opt_units, opt_bypassCache) { * @return {*} */ export function getStyle(element, property, opt_bypassCache) { - let propertyName = getVendorJsPropertyName(element.style, property, + const propertyName = getVendorJsPropertyName(element.style, property, opt_bypassCache); if (!propertyName) { return undefined; @@ -123,7 +123,7 @@ export function getStyle(element, property, opt_bypassCache) { * @param {!Object} styles */ export function setStyles(element, styles) { - for (let k in styles) { + for (const k in styles) { setStyle(element, k, styles[k]); } } diff --git a/src/styles.js b/src/styles.js index b433449198b8..3c7ce60e6e8b 100644 --- a/src/styles.js +++ b/src/styles.js @@ -80,7 +80,7 @@ export function installStyles(doc, cssText, cb, opt_isRuntimeCss) { */ export function makeBodyVisible(doc) { let interval; - let set = () => { + const set = () => { if (doc.body) { doc.body.style.opacity = 1; clearInterval(interval); diff --git a/src/swipe.js b/src/swipe.js index ced910d5e1e4..37c73db37869 100644 --- a/src/swipe.js +++ b/src/swipe.js @@ -246,7 +246,7 @@ export class SwipeXRecognizer { this.velocity_ = 0; this.end_(/* allowContinuing */ false); } - let touches = e.changedTouches || e.touches; + const touches = e.changedTouches || e.touches; if (touches && touches.length == 1) { this.tracking_ = true; this.startX_ = touches[0].clientX; @@ -262,10 +262,10 @@ export class SwipeXRecognizer { if (!this.tracking_) { return; } - let touches = e.changedTouches || e.touches; + const touches = e.changedTouches || e.touches; if (touches && touches.length > 0) { - let x = touches[0].clientX; - let y = touches[0].clientY; + const x = touches[0].clientX; + const y = touches[0].clientY; if (this.eventing_) { this.move_(x); } else { @@ -286,7 +286,7 @@ export class SwipeXRecognizer { if (!this.tracking_) { return; } - let touches = e.changedTouches || e.touches; + const touches = e.changedTouches || e.touches; if (this.eventing_ && touches && touches.length > 0) { if (this.lastX != touches[0].clientX) { this.move_(touches[0].clientX); @@ -324,8 +324,8 @@ export class SwipeXRecognizer { * @private */ move_(x) { - let prevX = this.lastX_; - let prevTime = this.lastTime_; + const prevX = this.lastX_; + const prevTime = this.lastTime_; this.lastX_ = x; this.lastTime_ = timer.now(); if (this.lastTime_ - prevTime > 2) { @@ -341,7 +341,7 @@ export class SwipeXRecognizer { * @private */ fireMove_(synthetic, continued) { - let delta = this.calcDelta_(this.startX_, this.lastX_); + const delta = this.calcDelta_(this.startX_, this.lastX_); this.moveObservable_.fire({ delta: delta, velocity: this.velocity_, @@ -364,7 +364,7 @@ export class SwipeXRecognizer { if (!this.eventing_) { return; } - let endTime = timer.now(); + const endTime = timer.now(); if (endTime - this.lastTime_ > 2) { this.velocity_ = this.calcVelocity_(this.lastX_, this.lastX_, this.lastTime_, endTime, this.velocity_); @@ -381,7 +381,7 @@ export class SwipeXRecognizer { endFinal_() { this.continuing_ = false; this.eventing_ = false; - let delta = this.calcDelta_(this.startX_, this.lastX_); + const delta = this.calcDelta_(this.startX_, this.lastX_); this.endObservable_.fire({ delta: delta, velocity: this.velocity_, @@ -397,28 +397,28 @@ export class SwipeXRecognizer { startContinuing_() { this.continuing_ = true; - let delta = this.calcDelta_(this.startX_, this.lastX_); + const delta = this.calcDelta_(this.startX_, this.lastX_); // 1. The user overpulls - spring back if (delta > this.maxDelta_ || delta < this.minDelta_) { - let retDelta = delta > this.maxDelta_ ? this.maxDelta_ - delta : + const retDelta = delta > this.maxDelta_ ? this.maxDelta_ - delta : this.minDelta_ - delta; // Reverse the velocity. - let maxVelocity = Math.sign(retDelta) * + const maxVelocity = Math.sign(retDelta) * Math.max(Math.abs(this.velocity_) * 0.8, 0.25); this.lastX_ = this.startX_ + delta; - let endX = this.lastX_ + retDelta; - let overshoot = Math.abs(retDelta) * maxVelocity; - let spring = tr.spring(this.lastX_, endX, endX + overshoot, 0.8); + const endX = this.lastX_ + retDelta; + const overshoot = Math.abs(retDelta) * maxVelocity; + const spring = tr.spring(this.lastX_, endX, endX + overshoot, 0.8); return this.runContinuing_(maxVelocity, false, velocity => { - let vnorm = 1 - Math.abs(velocity / maxVelocity); + const vnorm = 1 - Math.abs(velocity / maxVelocity); return spring(vnorm); }); } // 2. Pull to one of the boundaries if (this.snapPoint_) { - let snapPoint = Math.abs(this.snapPoint_ / this.positionMultiplier_); + const snapPoint = Math.abs(this.snapPoint_ / this.positionMultiplier_); let newDelta = 0; if (delta < 0 && Math.abs(delta) > snapPoint || this.velocity_ < -0.1) { @@ -431,13 +431,13 @@ export class SwipeXRecognizer { } if (newDelta != delta) { // Reverse the velocity. - let maxVelocity = Math.sign(newDelta - delta) * + const maxVelocity = Math.sign(newDelta - delta) * Math.max(Math.abs(this.velocity_) * 0.95, 0.5); this.lastX_ = this.startX_ + delta; - let endX = this.startX_ + newDelta; - let func = tr.numeric(this.lastX_, endX); + const endX = this.startX_ + newDelta; + const func = tr.numeric(this.lastX_, endX); return this.runContinuing_(maxVelocity, false, velocity => { - let vnorm = 1 - Math.abs(velocity / maxVelocity); + const vnorm = 1 - Math.abs(velocity / maxVelocity); return func(vnorm); }); } @@ -445,7 +445,7 @@ export class SwipeXRecognizer { // Intertia. if (Math.abs(this.velocity_) > MIN_VELOCITY_) { - let maxVelocity = this.velocity_ * 0.95; // First exponential order + const maxVelocity = this.velocity_ * 0.95; // First exponential order return this.runContinuing_(maxVelocity, true, (velocity, timeSinceStart, timeSincePrev) => { return this.lastX_ + timeSincePrev * velocity; @@ -472,7 +472,7 @@ export class SwipeXRecognizer { } this.velocity_ = maxVelocity; - let completeContinue = () => { + const completeContinue = () => { this.lastTime_ = timer.now(); this.lastX_ = velocityFunc(0, 0, 0); this.fireMove_(/* synthetic */ true, /* continued */ true); @@ -490,7 +490,7 @@ export class SwipeXRecognizer { this.lastX_ = velocityFunc(this.velocity_, timeSinceStart, timeSincePrev); this.fireMove_(/* synthetic */ true, /* continued */ true); - let prevVelocity = this.velocity_; + const prevVelocity = this.velocity_; this.velocity_ = maxVelocity * Math.exp(-timeSinceStart / FRAME_CONST_); return Math.abs(this.velocity_) > MIN_VELOCITY_; }, 5000).then(completeContinue, completeContinue); @@ -515,14 +515,14 @@ export class SwipeXRecognizer { * @private */ calcVelocity_(prevX, newX, prevTime, newTime, prevVelocity) { - let dx = newX - prevX; - let dt = newTime - prevTime; + const dx = newX - prevX; + const dt = newTime - prevTime; if (Math.abs(dt) < 2) { return 0; } // Calculate speed and speed depreciation. - let speed = dx / dt; + const speed = dx / dt; // Depreciation is simply an informational quality. It basically means: // we can't ignore the velocity we knew recently, but we'd only consider @@ -530,8 +530,8 @@ export class SwipeXRecognizer { // depreciation factor is 1/100 of a millisecond. New average velocity is // calculated by weighing toward the new velocity and away from old // velocity based on the depreciation. - let deprFactor = 100; - let depr = 0.5 + Math.min(dt / deprFactor, 0.5); + const deprFactor = 100; + const depr = 0.5 + Math.min(dt / deprFactor, 0.5); return speed * depr + prevVelocity * (1 - depr); } } diff --git a/src/transition.js b/src/transition.js index e5639930e03d..194a9a63417a 100644 --- a/src/transition.js +++ b/src/transition.js @@ -42,7 +42,7 @@ export const NOOP = function(time) {return null;}; export function all(transitions) { return (time, complete) => { for (let i = 0; i < transitions.length; i++) { - let tr = transitions[i]; + const tr = transitions[i]; tr(time, complete); } }; @@ -75,7 +75,7 @@ export function withCurve(transition, curve) { */ export function setStyles(element, styles) { return (time, complete) => { - for (let k in styles) { + for (const k in styles) { st.setStyle(element, k, styles[k](time, complete)); } }; @@ -138,7 +138,7 @@ export function px(transition) { */ export function translateX(transition) { return time => { - let res = transition(time); + const res = transition(time); if (typeof res == 'string') { return `translateX(${res})`; } diff --git a/src/url.js b/src/url.js index a856ac62c332..e85edce46650 100644 --- a/src/url.js +++ b/src/url.js @@ -81,10 +81,10 @@ export function parseQueryString(queryString) { if (queryString.indexOf('?') == 0 || queryString.indexOf('#') == 0) { queryString = queryString.substr(1); } - let pairs = queryString.split('&'); + const pairs = queryString.split('&'); for (let i = 0; i < pairs.length; i++) { - let pair = pairs[i]; - let eqIndex = pair.indexOf('='); + const pair = pairs[i]; + const eqIndex = pair.indexOf('='); let name; let value; if (eqIndex != -1) { @@ -125,7 +125,7 @@ export function getOrigin(info) { * @return {string} */ export function removeFragment(url) { - let index = url.indexOf('#'); + const index = url.indexOf('#'); if (index == -1) { return url; } diff --git a/src/viewer.js b/src/viewer.js index 4178e52ceff5..ee5fe490c6ef 100644 --- a/src/viewer.js +++ b/src/viewer.js @@ -23,8 +23,8 @@ import {parseQueryString, removeFragment} from './url'; import {platform} from './platform'; -let TAG_ = 'Viewer'; -let SENTINEL_ = '__AMP__'; +const TAG_ = 'Viewer'; +const SENTINEL_ = '__AMP__'; /** @@ -478,7 +478,7 @@ export class Viewer { assert(!this.messageDeliverer_, 'message deliverer can only be set once'); this.messageDeliverer_ = deliverer; if (this.messageQueue_.length > 0) { - let queue = this.messageQueue_.slice(0); + const queue = this.messageQueue_.slice(0); this.messageQueue_ = []; queue.forEach(message => { this.messageDeliverer_(message.eventType, message.data, false); @@ -531,8 +531,8 @@ export class Viewer { * @private */ export function parseParams_(str, allParams) { - let params = parseQueryString(str); - for (let k in params) { + const params = parseQueryString(str); + for (const k in params) { allParams[k] = params[k]; } } diff --git a/src/viewport.js b/src/viewport.js index 33d2dcd0f7b2..c40aab71782c 100644 --- a/src/viewport.js +++ b/src/viewport.js @@ -26,7 +26,7 @@ import {timer} from './timer'; import {viewerFor} from './viewer'; -let TAG_ = 'Viewport'; +const TAG_ = 'Viewport'; /** @@ -100,7 +100,7 @@ export class Viewport { this.viewer_.onViewportEvent(() => { this.binding_.updateViewerViewport(this.viewer_); - let paddingTop = this.viewer_.getPaddingTop(); + const paddingTop = this.viewer_.getPaddingTop(); if (paddingTop != this.paddingTop_) { this.paddingTop_ = paddingTop; this.binding_.updatePaddingTop(this.paddingTop_); @@ -220,8 +220,8 @@ export class Viewport { * @param {!Element} element */ scrollIntoView(element) { - let elementTop = this.binding_.getLayoutRect(element).top; - let newScrollTop = Math.max(0, elementTop - this.paddingTop_); + const elementTop = this.binding_.getLayoutRect(element).top; + const newScrollTop = Math.max(0, elementTop - this.paddingTop_); this.binding_.setScrollTop(newScrollTop); } @@ -251,8 +251,9 @@ export class Viewport { * Resets touch zoom to initial scale of 1. */ resetTouchZoom() { - let windowHeight = this.win_./*OK*/innerHeight; - let documentHeight = this.win_.document.documentElement./*OK*/clientHeight; + const windowHeight = this.win_./*OK*/innerHeight; + const documentHeight = this.win_.document + .documentElement./*OK*/clientHeight; if (windowHeight && documentHeight && windowHeight === documentHeight) { // This code only works when scrollbar overlay content and take no space, // which is fine on mobile. For non-mobile devices this code is @@ -272,14 +273,14 @@ export class Viewport { * @return {boolean} */ disableTouchZoom() { - let viewportMeta = this.getViewportMeta_(); + const viewportMeta = this.getViewportMeta_(); if (!viewportMeta) { // This should never happen in a valid AMP document, thus shortcircuit. return false; } // Setting maximum-scale=1 and user-scalable=no zooms page back to normal // and prohibit further default zooming. - let newValue = updateViewportMetaString(viewportMeta.content, { + const newValue = updateViewportMetaString(viewportMeta.content, { 'maximum-scale': '1', 'user-scalable': 'no' }); @@ -304,7 +305,7 @@ export class Viewport { * @return {boolean} */ setViewportMetaString_(viewportMetaString) { - let viewportMeta = this.getViewportMeta_(); + const viewportMeta = this.getViewportMeta_(); if (viewportMeta && viewportMeta.content != viewportMetaString) { log.fine(TAG_, 'changed viewport meta to:', viewportMetaString); viewportMeta.content = viewportMetaString; @@ -338,8 +339,8 @@ export class Viewport { * @private */ changed_(relayoutAll, velocity) { - let size = this.getSize(); - let scrollTop = this.getScrollTop(); + const size = this.getSize(); + const scrollTop = this.getScrollTop(); log.fine(TAG_, 'changed event:', 'relayoutAll=', relayoutAll, 'top=', scrollTop, @@ -414,9 +415,9 @@ export class Viewport { /** @private */ resize_() { - let oldSize = this.size_; + const oldSize = this.size_; this.size_ = null; // Need to recalc. - let newSize = this.getSize(); + const newSize = this.getSize(); this.changed_(!oldSize || oldSize.width != newSize.width, 0); } } @@ -668,8 +669,8 @@ export class ViewportBindingNaturalIosEmbed_ { /** @private */ setup_() { - let documentElement = this.win.document.documentElement; - let documentBody = this.win.document.body; + const documentElement = this.win.document.documentElement; + const documentBody = this.win.document.body; // TODO(dvoytenko): need to also find a way to do this on resize. this.scrollWidth_ = documentBody./*OK*/scrollWidth || 0; @@ -821,7 +822,7 @@ export class ViewportBindingNaturalIosEmbed_ { return; } this.adjustScrollPos_(event); - let rect = this.scrollPosEl_./*OK*/getBoundingClientRect(); + const rect = this.scrollPosEl_./*OK*/getBoundingClientRect(); if (this.pos_.x != -rect.left || this.pos_.y != -rect.top) { this.pos_.x = -rect.left; this.pos_.y = -rect.top; @@ -850,7 +851,7 @@ export class ViewportBindingNaturalIosEmbed_ { // Scroll document into a safe position to avoid scroll freeze on iOS. // This means avoiding scrollTop to be minimum (0) or maximum value. // This is very sad but very necessary. See #330 for more details. - let scrollTop = -this.scrollPosEl_./*OK*/getBoundingClientRect().top; + const scrollTop = -this.scrollPosEl_./*OK*/getBoundingClientRect().top; if (scrollTop == 0) { this.setScrollPos_(1); if (opt_event) { @@ -989,15 +990,15 @@ export class ViewportBindingVirtual_ { */ export function parseViewportMeta(content) { // Ex: width=device-width,initial-scale=1,minimal-ui - let params = Object.create(null); + const params = Object.create(null); if (!content) { return params; } - let pairs = content.split(','); + const pairs = content.split(','); for (let i = 0; i < pairs.length; i++) { - let pair = pairs[i]; - let split = pair.split('='); - let name = split[0].trim(); + const pair = pairs[i]; + const split = pair.split('='); + const name = split[0].trim(); let value = split[1]; value = (value || '').trim(); if (name) { @@ -1021,7 +1022,7 @@ export function parseViewportMeta(content) { export function stringifyViewportMeta(params) { // Ex: width=device-width,initial-scale=1,minimal-ui let content = ''; - for (let k in params) { + for (const k in params) { if (content.length > 0) { content += ','; } @@ -1046,9 +1047,9 @@ export function stringifyViewportMeta(params) { * @private Visible for testing only. */ export function updateViewportMetaString(currentValue, updateParams) { - let params = parseViewportMeta(currentValue); + const params = parseViewportMeta(currentValue); let changed = false; - for (let k in updateParams) { + for (const k in updateParams) { if (params[k] !== updateParams[k]) { changed = true; if (updateParams[k] !== undefined) { @@ -1071,7 +1072,7 @@ export function updateViewportMetaString(currentValue, updateParams) { * @private */ function createViewport_(window) { - let viewer = viewerFor(window); + const viewer = viewerFor(window); let binding; if (viewer.getViewportType() == 'virtual') { binding = new ViewportBindingVirtual_(window, viewer); diff --git a/src/vsync.js b/src/vsync.js index 0ebc760fae00..71429931e67b 100644 --- a/src/vsync.js +++ b/src/vsync.js @@ -51,7 +51,7 @@ export class Vsync { * @param {!Object|undefined} opt_state */ run(task, opt_state) { - let state = opt_state || {}; + const state = opt_state || {}; this.win.requestAnimationFrame(() => { if (task.measure) { task.measure(state); @@ -93,12 +93,12 @@ export class Vsync { */ runMutateSeries(mutator, opt_timeout) { return new Promise((resolve, reject) => { - let startTime = timer.now(); + const startTime = timer.now(); let prevTime = 0; - let task = this.createTask({ + const task = this.createTask({ mutate: state => { - let timeSinceStart = timer.now() - startTime; - let res = mutator(timeSinceStart, timeSinceStart - prevTime, state); + const timeSinceStart = timer.now() - startTime; + const res = mutator(timeSinceStart, timeSinceStart - prevTime, state); if (!res) { resolve(); } else if (opt_timeout && timeSinceStart > opt_timeout) { diff --git a/test/functional/test-3p-frame.js b/test/functional/test-3p-frame.js index 76b74628373c..02494b50407c 100644 --- a/test/functional/test-3p-frame.js +++ b/test/functional/test-3p-frame.js @@ -25,7 +25,7 @@ describe('3p-frame', () => { afterEach(() => { resetServiceForTesting(window, 'bootstrapBaseUrl'); setModeForTesting(null); - let m = document.querySelector( + const m = document.querySelector( '[name="amp-3p-iframe-src"]'); if (m) { m.parentElement.removeChild(m); @@ -33,7 +33,7 @@ describe('3p-frame', () => { }); function addCustomBootstrap(url) { - let meta = document.createElement('meta'); + const meta = document.createElement('meta'); meta.setAttribute('name', 'amp-3p-iframe-src'); meta.setAttribute('content', url); document.head.appendChild(meta); diff --git a/test/functional/test-action.js b/test/functional/test-action.js index 2331abe65c41..4526bd23aa05 100644 --- a/test/functional/test-action.js +++ b/test/functional/test-action.js @@ -35,33 +35,33 @@ describe('Action parseAction', () => { it('should fail parse without event', () => { - let a = action.parseAction_('target1.method1'); + const a = action.parseAction_('target1.method1'); expect(a).to.equal(null); }); it('should parse with default method', () => { - let a = action.parseAction_('event1:target1'); + const a = action.parseAction_('event1:target1'); expect(a.event).to.equal('event1'); expect(a.target).to.equal('target1'); expect(a.method).to.equal('activate'); }); it('should parse full form', () => { - let a = action.parseAction_('event1:target1.method1'); + const a = action.parseAction_('event1:target1.method1'); expect(a.event).to.equal('event1'); expect(a.target).to.equal('target1'); expect(a.method).to.equal('method1'); }); it('should parse with lots of whitespace', () => { - let a = action.parseAction_(' event1 : target1 . method1 '); + const a = action.parseAction_(' event1 : target1 . method1 '); expect(a.event).to.equal('event1'); expect(a.target).to.equal('target1'); expect(a.method).to.equal('method1'); }); it('should parse empty to null', () => { - let a = action.parseAction_(''); + const a = action.parseAction_(''); expect(a).to.equal(null); }); @@ -72,7 +72,7 @@ describe('Action parseAction', () => { }); it('should parse with period in event or method', () => { - let a = action.parseAction_('event.1:target1.method.1'); + const a = action.parseAction_('event.1:target1.method.1'); expect(a.event).to.equal('event.1'); expect(a.target).to.equal('target1'); expect(a.method).to.equal('method.1'); @@ -97,18 +97,18 @@ describe('Action parseActionMap', () => { }); it('should parse with a single action', () => { - let m = action.parseActionMap_('event1:action1'); + const m = action.parseActionMap_('event1:action1'); expect(m['event1'].target).to.equal('action1'); }); it('should parse with two actions', () => { - let m = action.parseActionMap_('event1:action1; event2: action2'); + const m = action.parseActionMap_('event1:action1; event2: action2'); expect(m['event1'].target).to.equal('action1'); expect(m['event2'].target).to.equal('action2'); }); it('should parse with dupe actions by overriding with last', () => { - let m = action.parseActionMap_('event1:action1; event1: action2'); + const m = action.parseActionMap_('event1:action1; event1: action2'); // Currently, we overwrite the events. expect(m['event1'].target).to.equal('action2'); }); @@ -140,15 +140,15 @@ describe('Action findAction', () => { it('should create action map in getActionMap_', () => { var element = document.createElement('div'); element.setAttribute('on', 'event1:action1'); - let m = action.getActionMap_(element); + const m = action.getActionMap_(element); expect(m['event1'].target).to.equal('action1'); }); it('should cache action map', () => { var element = document.createElement('div'); element.setAttribute('on', 'event1:action1'); - let m1 = action.getActionMap_(element); - let m2 = action.getActionMap_(element); + const m1 = action.getActionMap_(element); + const m2 = action.getActionMap_(element); expect(m1).to.equal(m2); }); @@ -156,7 +156,7 @@ describe('Action findAction', () => { it('should find action on the same element', () => { var element = document.createElement('div'); element.setAttribute('on', 'event1:action1'); - let a = action.findAction_(element, 'event1'); + const a = action.findAction_(element, 'event1'); expect(a.node).to.equal(element); expect(a.actionInfo.target).to.equal('action1'); @@ -195,7 +195,7 @@ describe('Action method', () => { action = new Action(window); onEnqueue = sinon.spy(); targetElement = document.createElement('target'); - let id = ('E' + Math.random()).replace('.', ''); + const id = ('E' + Math.random()).replace('.', ''); targetElement.setAttribute('on', 'tap:' + id + '.method1'); parent = document.createElement('parent'); child = document.createElement('child'); @@ -220,7 +220,7 @@ describe('Action method', () => { it('should invoke on the AMP element', () => { action.invoke_(execElement, 'method1', 'source1', 'event1'); expect(onEnqueue.callCount).to.equal(1); - let inv = onEnqueue.getCall(0).args[0]; + const inv = onEnqueue.getCall(0).args[0]; expect(inv.target).to.equal(execElement); expect(inv.method).to.equal('method1'); expect(inv.source).to.equal('source1'); @@ -244,7 +244,7 @@ describe('Action method', () => { it('should trigger event', () => { action.trigger(child, 'tap', null); expect(onEnqueue.callCount).to.equal(1); - let inv = onEnqueue.getCall(0).args[0]; + const inv = onEnqueue.getCall(0).args[0]; expect(inv.target).to.equal(execElement); expect(inv.method).to.equal('method1'); expect(inv.source).to.equal(targetElement); @@ -253,7 +253,7 @@ describe('Action method', () => { it('should execute method', () => { action.execute(execElement, 'method1', child, null); expect(onEnqueue.callCount).to.equal(1); - let inv = onEnqueue.getCall(0).args[0]; + const inv = onEnqueue.getCall(0).args[0]; expect(inv.target).to.equal(execElement); expect(inv.method).to.equal('method1'); expect(inv.source).to.equal(child); diff --git a/test/functional/test-amp-ad.js b/test/functional/test-amp-ad.js index 8ee6a9f7ea8b..042eca5b3662 100644 --- a/test/functional/test-amp-ad.js +++ b/test/functional/test-amp-ad.js @@ -147,16 +147,16 @@ describe('amp-ad', () => { describe('scoreDimensions_', () => { it('should choose a matching dimension', () => { - let dims = [[320, 200], [320, 210], [320, 200]]; - let scores = scoreDimensions_(dims, 320, 200); - let winner = scores.indexOf(Math.max.apply(Math, scores)); + const dims = [[320, 200], [320, 210], [320, 200]]; + const scores = scoreDimensions_(dims, 320, 200); + const winner = scores.indexOf(Math.max.apply(Math, scores)); expect(winner).to.equal(0); }); it('should be biased to a smaller height delta', () => { - let dims = [[300, 200], [320, 50]]; - let scores = scoreDimensions_(dims, 300, 50); - let winner = scores.indexOf(Math.max.apply(Math, scores)); + const dims = [[300, 200], [320, 50]]; + const scores = scoreDimensions_(dims, 300, 50); + const winner = scores.indexOf(Math.max.apply(Math, scores)); expect(winner).to.equal(1); }); }); diff --git a/test/functional/test-amp-img.js b/test/functional/test-amp-img.js index 3ef97259202f..852e1119e357 100644 --- a/test/functional/test-amp-img.js +++ b/test/functional/test-amp-img.js @@ -38,13 +38,13 @@ describe('amp-img', () => { .returns(true); return createIframePromise().then(iframe => { installImg(iframe.win); - let img = iframe.doc.createElement('amp-img'); - for (let key in attributes) { + const img = iframe.doc.createElement('amp-img'); + for (const key in attributes) { img.setAttribute(key, attributes[key]); } if (children != null) { - for (let key in children) { + for (const key in children) { img.appendChild(children[key]); } } @@ -58,7 +58,7 @@ describe('amp-img', () => { width: 300, height: 200 }).then(ampImg => { - let img = ampImg.querySelector('img'); + const img = ampImg.querySelector('img'); expect(img).to.be.an.instanceof(Element); expect(img.tagName).to.equal('IMG'); expect(img.getAttribute('src')).to.equal('test.jpg'); diff --git a/test/functional/test-amp-pixel.js b/test/functional/test-amp-pixel.js index 13330cfb49be..af74f27cbb55 100644 --- a/test/functional/test-amp-pixel.js +++ b/test/functional/test-amp-pixel.js @@ -121,7 +121,7 @@ describe('amp-pixel', () => { 'https://foo.com?ref=$AMPDOC_URL' ).then(p => { expect(p.querySelector('img')).to.not.be.null; - let query = parseQueryString(parseUrl(p.children[0].src).search); + const query = parseQueryString(parseUrl(p.children[0].src).search); expect(query['ref']).to.not.equal('$AMPDOC_URL'); }); }); @@ -131,7 +131,7 @@ describe('amp-pixel', () => { 'https://foo.com?ref=$AMPDOC_HOST' ).then(p => { expect(p.querySelector('img')).to.not.be.null; - let query = parseQueryString(parseUrl(p.children[0].src).search); + const query = parseQueryString(parseUrl(p.children[0].src).search); expect(query['ref']).to.not.equal('$AMPDOC_HOST'); }); }); diff --git a/test/functional/test-amp-video.js b/test/functional/test-amp-video.js index 6b619ea839b4..866c5399c5b3 100644 --- a/test/functional/test-amp-video.js +++ b/test/functional/test-amp-video.js @@ -27,11 +27,11 @@ describe('amp-video', () => { return createIframePromise().then(iframe => { installVideo(iframe.win); var v = iframe.doc.createElement('amp-video'); - for (let key in attributes) { + for (const key in attributes) { v.setAttribute(key, attributes[key]); } if (children != null) { - for (let key in children) { + for (const key in children) { v.appendChild(children[key]); } } diff --git a/test/functional/test-animation.js b/test/functional/test-animation.js index 1dbfea842983..f8ef46a4dc37 100644 --- a/test/functional/test-animation.js +++ b/test/functional/test-animation.js @@ -51,10 +51,10 @@ describe('Animation', () => { }); function runVsync() { - let tasks = vsyncTasks.slice(0); + const tasks = vsyncTasks.slice(0); vsyncTasks = []; tasks.forEach(function(task) { - let state = {}; + const state = {}; if (task.measure) { task.measure(state); } @@ -68,7 +68,7 @@ describe('Animation', () => { anim.add(0, time => {tr1 = time;}, 0.8); anim.add(0.2, time => {tr2 = time;}, 0.8); - let ap = anim.start(1000); + const ap = anim.start(1000); let resolveCalled = false; ap.resolve_ = () => { resolveCalled = true; @@ -140,10 +140,10 @@ describe('Animation', () => { it('should animate out-of-bounds time', () => { let tr1 = -1; // Linear curve between -0.5 and 1.5 - let curve = time => {return time * 2 - 0.5;}; + const curve = time => {return time * 2 - 0.5;}; anim.add(0, time => {tr1 = time;}, 1, curve); - let ap = anim.start(1000); + const ap = anim.start(1000); let resolveCalled = false; ap.resolve_ = () => { resolveCalled = true; @@ -174,7 +174,7 @@ describe('Animation', () => { anim.add(0, time => {tr1 = time;}, 0.8); anim.add(0.2, time => {tr2 = time;}, 0.8); - let ap = anim.start(1000); + const ap = anim.start(1000); let rejectCalled = false; ap.reject_ = () => { rejectCalled = true; @@ -200,7 +200,7 @@ describe('Animation', () => { anim.add(0, time => {tr1 = time;}, 0.8); anim.add(0.2, time => {tr2 = time;}, 0.8); - let ap = anim.start(1000); + const ap = anim.start(1000); let rejectCalled = false; ap.reject_ = () => { rejectCalled = true; @@ -226,7 +226,7 @@ describe('Animation', () => { anim.add(0, time => {tr1 = time;}, 0.8); anim.add(0.2, time => {tr2 = time;}, 0.8); - let ap = anim.start(1000); + const ap = anim.start(1000); let rejectCalled = false; ap.reject_ = () => { rejectCalled = true; diff --git a/test/functional/test-base-element.js b/test/functional/test-base-element.js index 9e39aee0de6d..3a3855eda6ee 100644 --- a/test/functional/test-base-element.js +++ b/test/functional/test-base-element.js @@ -28,7 +28,7 @@ describe('BaseElement', () => { }); it('propagateAttributes - niente', () => { - let target = document.createElement('div'); + const target = document.createElement('div'); expect(target.hasAttributes()).to.be.false; element.propagateAttributes(['data-test1'], target); @@ -39,7 +39,7 @@ describe('BaseElement', () => { }); it('propagateAttributes', () => { - let target = document.createElement('div'); + const target = document.createElement('div'); expect(target.hasAttributes()).to.be.false; div.setAttribute('data-test1', 'abc'); @@ -59,7 +59,7 @@ describe('BaseElement', () => { }); it('should register action', () => { - let handler = () => {}; + const handler = () => {}; element.registerAction('method1', handler); expect(element.actionMap_['method1']).to.equal(handler); }); @@ -71,14 +71,14 @@ describe('BaseElement', () => { }); it('should execute registered action', () => { - let handler = sinon.spy(); + const handler = sinon.spy(); element.registerAction('method1', handler); element.executeAction({method: 'method1'}, false); expect(handler.callCount).to.equal(1); }); it('should execute "activate" action without registration', () => { - let handler = sinon.spy(); + const handler = sinon.spy(); element.activate = handler; element.executeAction({method: 'activate'}, false); expect(handler.callCount).to.equal(1); diff --git a/test/functional/test-curve.js b/test/functional/test-curve.js index 35b6d002c4dd..3d0ac1256700 100644 --- a/test/functional/test-curve.js +++ b/test/functional/test-curve.js @@ -47,7 +47,7 @@ describe('Curve', () => { expect(getCurve(undefined)).to.equal(null); // Function is passed through. - let func = () => {}; + const func = () => {}; expect(getCurve(func)).to.equal(func); // String is translated. diff --git a/test/functional/test-custom-element.js b/test/functional/test-custom-element.js index a16f7dc20877..eae76e2526a6 100644 --- a/test/functional/test-custom-element.js +++ b/test/functional/test-custom-element.js @@ -25,7 +25,7 @@ import * as sinon from 'sinon'; describe('CustomElement', () => { - let resources = resourcesFor(window); + const resources = resourcesFor(window); let testElementCreatedCallback; let testElementFirstAttachedCallback; let testElementBuildCallback; @@ -67,11 +67,11 @@ describe('CustomElement', () => { } } - let ElementClass = document.registerElement('amp-test', { + const ElementClass = document.registerElement('amp-test', { prototype: createAmpElementProto(window, 'amp-test', TestElement) }); - let StubElementClass = document.registerElement('amp-stub', { + const StubElementClass = document.registerElement('amp-stub', { prototype: createAmpElementProto(window, 'amp-stub', ElementStub) }); @@ -104,7 +104,7 @@ describe('CustomElement', () => { it('Element - createdCallback', () => { - let element = new ElementClass(); + const element = new ElementClass(); expect(element.classList.contains('-amp-element')).to.equal(true); expect(element.isBuilt()).to.equal(false); expect(element.classList.contains('-amp-notbuilt')).to.equal(true); @@ -117,7 +117,7 @@ describe('CustomElement', () => { }); it('StubElement - createdCallback', () => { - let element = new StubElementClass(); + const element = new StubElementClass(); expect(element.classList.contains('-amp-element')).to.equal(true); expect(element.isBuilt()).to.equal(false); expect(element.classList.contains('-amp-notbuilt')).to.equal(true); @@ -131,7 +131,7 @@ describe('CustomElement', () => { it('Element - updateLayoutBox', () => { - let element = new ElementClass(); + const element = new ElementClass(); expect(element.layoutWidth_).to.equal(-1); expect(element.implementation_.layoutWidth_).to.equal(-1); @@ -141,7 +141,7 @@ describe('CustomElement', () => { }); it('StubElement - upgrade', () => { - let element = new StubElementClass(); + const element = new StubElementClass(); expect(element.isUpgraded()).to.equal(false); expect(testElementCreatedCallback.callCount).to.equal(0); @@ -162,7 +162,7 @@ describe('CustomElement', () => { it('Element - build allowed', () => { - let element = new ElementClass(); + const element = new ElementClass(); expect(element.classList.contains('-amp-element')).to.equal(true); expect(element.isBuilt()).to.equal(false); expect(element.classList.contains('-amp-notbuilt')).to.equal(true); @@ -179,7 +179,7 @@ describe('CustomElement', () => { }); it('Element - buildCallback cannot be called twice', () => { - let element = new ElementClass(); + const element = new ElementClass(); expect(element.isBuilt()).to.equal(false); expect(testElementBuildCallback.callCount).to.equal(0); @@ -197,7 +197,7 @@ describe('CustomElement', () => { }); it('Element - build not allowed', () => { - let element = new ElementClass(); + const element = new ElementClass(); expect(element.classList.contains('-amp-element')).to.equal(true); expect(element.isBuilt()).to.equal(false); expect(element.classList.contains('-amp-notbuilt')).to.equal(true); @@ -214,7 +214,7 @@ describe('CustomElement', () => { }); it('Element - build not allowed but forced', () => { - let element = new ElementClass(); + const element = new ElementClass(); expect(element.classList.contains('-amp-element')).to.equal(true); expect(element.isBuilt()).to.equal(false); expect(element.classList.contains('-amp-notbuilt')).to.equal(true); @@ -231,7 +231,7 @@ describe('CustomElement', () => { }); it('StubElement - build never allowed', () => { - let element = new StubElementClass(); + const element = new StubElementClass(); expect(element.classList.contains('-amp-element')).to.equal(true); expect(element.isBuilt()).to.equal(false); expect(element.classList.contains('-amp-notbuilt')).to.equal(true); @@ -248,7 +248,7 @@ describe('CustomElement', () => { it('Element - attachedCallback', () => { - let element = new ElementClass(); + const element = new ElementClass(); element.setAttribute('layout', 'fill'); expect(testElementFirstAttachedCallback.callCount).to.equal(0); expect(element.everAttached).to.equal(false); @@ -264,7 +264,7 @@ describe('CustomElement', () => { }); it('StubElement - attachedCallback', () => { - let element = new StubElementClass(); + const element = new StubElementClass(); element.setAttribute('layout', 'fill'); expect(testElementFirstAttachedCallback.callCount).to.equal(0); expect(element.everAttached).to.equal(false); @@ -292,7 +292,7 @@ describe('CustomElement', () => { }); it('Element - detachedCallback', () => { - let element = new ElementClass(); + const element = new ElementClass(); element.setAttribute('layout', 'fill'); expect(testElementFirstAttachedCallback.callCount).to.equal(0); expect(element.everAttached).to.equal(false); @@ -312,7 +312,7 @@ describe('CustomElement', () => { it('Element - layoutCallback before build', () => { - let element = new ElementClass(); + const element = new ElementClass(); element.setAttribute('layout', 'fill'); expect(testElementLayoutCallback.callCount).to.equal(0); @@ -325,7 +325,7 @@ describe('CustomElement', () => { }); it('StubElement - layoutCallback before build or upgrade', () => { - let element = new StubElementClass(); + const element = new StubElementClass(); element.setAttribute('layout', 'fill'); expect(testElementLayoutCallback.callCount).to.equal(0); @@ -348,13 +348,13 @@ describe('CustomElement', () => { }); it('Element - layoutCallback', () => { - let element = new ElementClass(); + const element = new ElementClass(); element.setAttribute('layout', 'fill'); element.build(true); expect(element.isBuilt()).to.equal(true); expect(testElementLayoutCallback.callCount).to.equal(0); - let p = element.layoutCallback(); + const p = element.layoutCallback(); expect(testElementLayoutCallback.callCount).to.equal(1); return p.then(() => { expect(element.readyState).to.equal('complete'); @@ -363,18 +363,18 @@ describe('CustomElement', () => { it('Element - layoutCallback should call firstLayoutCompleted only once', () => { - let element = new ElementClass(); + const element = new ElementClass(); element.setAttribute('layout', 'fill'); element.build(true); - let p = element.layoutCallback(); + const p = element.layoutCallback(); expect(testElementLayoutCallback.callCount).to.equal(1); expect(testElementFirstLayoutCompleted.callCount).to.equal(0); return p.then(() => { expect(testElementFirstLayoutCompleted.callCount).to.equal(1); // But not second time. - let p2 = element.layoutCallback(); + const p2 = element.layoutCallback(); expect(testElementLayoutCallback.callCount).to.equal(2); expect(testElementFirstLayoutCompleted.callCount).to.equal(1); return p2.then(() => { @@ -384,7 +384,7 @@ describe('CustomElement', () => { }); it('StubElement - layoutCallback', () => { - let element = new StubElementClass(); + const element = new StubElementClass(); element.setAttribute('layout', 'fill'); resourcesMock.expects('upgraded').withExactArgs(element).once(); element.upgrade(TestElement); @@ -393,7 +393,7 @@ describe('CustomElement', () => { expect(element.isBuilt()).to.equal(true); expect(testElementLayoutCallback.callCount).to.equal(0); - let p = element.layoutCallback(); + const p = element.layoutCallback(); expect(testElementLayoutCallback.callCount).to.equal(1); return p.then(() => { expect(element.readyState).to.equal('complete'); @@ -402,12 +402,12 @@ describe('CustomElement', () => { it('should enqueue actions until built', () => { - let element = new ElementClass(); - let handler = sinon.spy(); + const element = new ElementClass(); + const handler = sinon.spy(); element.implementation_.executeAction = handler; expect(element.actionQueue_).to.not.equal(null); - let inv = {}; + const inv = {}; element.enqueAction(inv); expect(element.actionQueue_.length).to.equal(1); expect(element.actionQueue_[0]).to.equal(inv); @@ -415,12 +415,12 @@ describe('CustomElement', () => { }); it('should execute action immediately after built', () => { - let element = new ElementClass(); - let handler = sinon.spy(); + const element = new ElementClass(); + const handler = sinon.spy(); element.implementation_.executeAction = handler; element.build(true); - let inv = {}; + const inv = {}; element.enqueAction(inv); expect(handler.callCount).to.equal(1); expect(handler.getCall(0).args[0]).to.equal(inv); @@ -428,12 +428,12 @@ describe('CustomElement', () => { }); it('should dequeue all actions after build', () => { - let element = new ElementClass(); - let handler = sinon.spy(); + const element = new ElementClass(); + const handler = sinon.spy(); element.implementation_.executeAction = handler; - let inv1 = {}; - let inv2 = {}; + const inv1 = {}; + const inv2 = {}; element.enqueAction(inv1); element.enqueAction(inv2); expect(element.actionQueue_.length).to.equal(2); @@ -453,37 +453,37 @@ describe('CustomElement', () => { it('should apply media condition', () => { - let element1 = new ElementClass(); + const element1 = new ElementClass(); element1.setAttribute('media', '(min-width: 1px)'); element1.applySizesAndMediaQuery(); expect(element1).to.not.have.class('-amp-hidden-by-media-query'); - let element2 = new ElementClass(); + const element2 = new ElementClass(); element2.setAttribute('media', '(min-width: 1111111px)'); element2.applySizesAndMediaQuery(); expect(element2).to.have.class('-amp-hidden-by-media-query'); }); it('should apply sizes condition', () => { - let element1 = new ElementClass(); + const element1 = new ElementClass(); element1.setAttribute('sizes', '(min-width: 1px) 200px, 50vw'); element1.applySizesAndMediaQuery(); expect(element1.style.width).to.equal('200px'); - let element2 = new ElementClass(); + const element2 = new ElementClass(); element2.setAttribute('sizes', '(min-width: 1111111px) 200px, 50vw'); element2.applySizesAndMediaQuery(); expect(element2.style.width).to.equal('50vw'); }); it('should change height without sizer', () => { - let element = new ElementClass(); + const element = new ElementClass(); element.changeHeight(111); expect(element.style.height).to.equal('111px'); }); it('should change height with sizer', () => { - let element = new ElementClass(); + const element = new ElementClass(); element.sizerElement_ = document.createElement('div'); element.changeHeight(111); expect(parseInt(element.sizerElement_.style.paddingTop, 10)).to.equal(0); @@ -492,7 +492,7 @@ describe('CustomElement', () => { it('Element - documentInactiveCallback', () => { - let element = new ElementClass(); + const element = new ElementClass(); // Non-built element doesn't receive documentInactiveCallback. element.documentInactiveCallback(); @@ -505,7 +505,7 @@ describe('CustomElement', () => { }); it('StubElement - documentInactiveCallback', () => { - let element = new StubElementClass(); + const element = new StubElementClass(); // Unupgraded document doesn't receive documentInactiveCallback. element.documentInactiveCallback(); @@ -514,7 +514,7 @@ describe('CustomElement', () => { describe('viewportCallback', () => { it('Element should allow, but not delegate before build', () => { - let element = new ElementClass(); + const element = new ElementClass(); element.setAttribute('layout', 'fill'); expect(testElementViewportCallback.callCount).to.equal(0); @@ -525,7 +525,7 @@ describe('CustomElement', () => { }); it('StubElement - should not delegate before build or upgrade', () => { - let element = new StubElementClass(); + const element = new StubElementClass(); element.setAttribute('layout', 'fill'); expect(testElementViewportCallback.callCount).to.equal(0); @@ -546,7 +546,7 @@ describe('CustomElement', () => { }); it('Element - should be called once built', () => { - let element = new ElementClass(); + const element = new ElementClass(); element.setAttribute('layout', 'fill'); element.build(true); expect(element.isBuilt()).to.equal(true); @@ -558,7 +558,7 @@ describe('CustomElement', () => { }); it('StubElement - should be called once upgraded', () => { - let element = new StubElementClass(); + const element = new StubElementClass(); element.setAttribute('layout', 'fill'); resourcesMock.expects('upgraded').withExactArgs(element).once(); element.upgrade(TestElement); @@ -573,7 +573,7 @@ describe('CustomElement', () => { }); it('Element - should be called on built if in viewport', () => { - let element = new ElementClass(); + const element = new ElementClass(); element.setAttribute('layout', 'fill'); element.viewportCallback(true); expect(element.isInViewport_).to.equal(true); @@ -589,7 +589,7 @@ describe('CustomElement', () => { describe('CustomElement Service Elements', () => { - let StubElementClass = document.registerElement('amp-stub2', { + const StubElementClass = document.registerElement('amp-stub2', { prototype: createAmpElementProto(window, 'amp-stub2', ElementStub) }); @@ -607,7 +607,7 @@ describe('CustomElement Service Elements', () => { }); function createWithAttr(attr) { - let child = document.createElement('div'); + const child = document.createElement('div'); child.setAttribute(attr, ''); return child; } @@ -624,12 +624,12 @@ describe('CustomElement Service Elements', () => { element.appendChild(document.createTextNode('abc')); element.appendChild(document.createElement('content')); - let nodes = element.getRealChildNodes(); + const nodes = element.getRealChildNodes(); expect(nodes.length).to.equal(2); expect(nodes[0].textContent).to.equal('abc'); expect(nodes[1].tagName.toLowerCase()).to.equal('content'); - let elements = element.getRealChildren(); + const elements = element.getRealChildren(); expect(elements.length).to.equal(1); expect(elements[0].tagName.toLowerCase()).to.equal('content'); }); @@ -640,8 +640,8 @@ describe('CustomElement Service Elements', () => { }); it('getPlaceholder should return the first placeholder', () => { - let placeholder1 = element.appendChild(createWithAttr('placeholder')); - let placeholder2 = element.appendChild(createWithAttr('placeholder')); + const placeholder1 = element.appendChild(createWithAttr('placeholder')); + const placeholder2 = element.appendChild(createWithAttr('placeholder')); expect(element.getPlaceholder()).to.equal(placeholder1); }); @@ -651,8 +651,8 @@ describe('CustomElement Service Elements', () => { }); it('togglePlaceholder should do hide placeholder when found', () => { - let placeholder1 = element.appendChild(createWithAttr('placeholder')); - let placeholder2 = element.appendChild(createWithAttr('placeholder')); + const placeholder1 = element.appendChild(createWithAttr('placeholder')); + const placeholder2 = element.appendChild(createWithAttr('placeholder')); element.togglePlaceholder(false); expect(placeholder1).to.have.class('amp-hidden'); expect(placeholder2).to.not.have.class('amp-hidden'); @@ -675,11 +675,11 @@ describe('CustomElement Loading Indicator', () => { class TestElement extends BaseElement { } - let ElementClass = document.registerElement('amp-test2', { + const ElementClass = document.registerElement('amp-test2', { prototype: createAmpElementProto(window, 'amp-test2', TestElement) }); - let resources = resourcesFor(window); + const resources = resourcesFor(window); let sandbox; let clock; let element; @@ -778,8 +778,8 @@ describe('CustomElement Loading Indicator', () => { it('should turn on already created', () => { element.prepareLoading_(); - let container = element.loadingContainer_; - let indicator = element.loadingElement_; + const container = element.loadingContainer_; + const indicator = element.loadingElement_; element.toggleLoading_(true); expect(vsyncTasks).to.have.length.of(1); @@ -817,7 +817,7 @@ describe('CustomElement Loading Indicator', () => { it('should turn off when exits viewport', () => { - let toggle = sandbox.spy(element, 'toggleLoading_'); + const toggle = sandbox.spy(element, 'toggleLoading_'); element.viewportCallback(false); expect(toggle.callCount).to.equal(1); expect(toggle.firstCall.args[0]).to.equal(false); @@ -825,14 +825,14 @@ describe('CustomElement Loading Indicator', () => { }); it('should NOT turn off when exits viewport but already laid out', () => { - let toggle = sandbox.spy(element, 'toggleLoading_'); + const toggle = sandbox.spy(element, 'toggleLoading_'); element.layoutCount_ = 1; element.viewportCallback(false); expect(toggle.callCount).to.equal(0); }); it('should turn on when enters viewport', () => { - let toggle = sandbox.spy(element, 'toggleLoading_'); + const toggle = sandbox.spy(element, 'toggleLoading_'); element.viewportCallback(true); clock.tick(1000); expect(toggle.callCount).to.equal(1); @@ -840,7 +840,7 @@ describe('CustomElement Loading Indicator', () => { }); it('should NOT turn on when enters viewport but already laid out', () => { - let toggle = sandbox.spy(element, 'toggleLoading_'); + const toggle = sandbox.spy(element, 'toggleLoading_'); element.layoutCount_ = 1; element.viewportCallback(true); clock.tick(1000); @@ -849,7 +849,7 @@ describe('CustomElement Loading Indicator', () => { it('should start loading when measured if already in viewport', () => { - let toggle = sandbox.spy(element, 'toggleLoading_'); + const toggle = sandbox.spy(element, 'toggleLoading_'); element.isInViewport_ = true; element.updateLayoutBox({top: 0, width: 300}); expect(toggle.callCount).to.equal(1); @@ -857,7 +857,7 @@ describe('CustomElement Loading Indicator', () => { }); it('should create loading when measured if in the top window', () => { - let toggle = sandbox.spy(element, 'toggleLoading_'); + const toggle = sandbox.spy(element, 'toggleLoading_'); element.updateLayoutBox({top: 0, width: 300}); expect(toggle.callCount).to.equal(0); expect(vsyncTasks).to.have.length.of(1); @@ -868,7 +868,7 @@ describe('CustomElement Loading Indicator', () => { it('should toggle loading off after layout complete', () => { - let toggle = sandbox.spy(element, 'toggleLoading_'); + const toggle = sandbox.spy(element, 'toggleLoading_'); element.build(true); return element.layoutCallback().then(() => { expect(toggle.callCount).to.equal(1); @@ -880,8 +880,8 @@ describe('CustomElement Loading Indicator', () => { }); it('should toggle loading off after layout failed', () => { - let toggle = sandbox.spy(element, 'toggleLoading_'); - let implMock = sandbox.mock(element.implementation_); + const toggle = sandbox.spy(element, 'toggleLoading_'); + const implMock = sandbox.mock(element.implementation_); implMock.expects('layoutCallback').returns(Promise.reject()); element.build(true); return element.layoutCallback().then(() => { diff --git a/test/functional/test-document-state.js b/test/functional/test-document-state.js index 427dfa321cc1..cfd2dcb0ecfb 100644 --- a/test/functional/test-document-state.js +++ b/test/functional/test-document-state.js @@ -51,14 +51,14 @@ describe('documentReady', () => { it('should call callback immediately when ready', () => { testDoc.readyState = 'complete'; - let callback = sinon.spy(); + const callback = sinon.spy(); onDocumentReady(testDoc, callback); expect(callback.callCount).to.equal(1); }); it('should wait to call callback until ready', () => { testDoc.readyState = 'loading'; - let callback = sinon.spy(); + const callback = sinon.spy(); onDocumentReady(testDoc, callback); expect(callback.callCount).to.equal(0); expect(eventListeners['readystatechange']).to.not.equal(undefined); @@ -72,7 +72,7 @@ describe('documentReady', () => { it('should wait to call callback for several loading events', () => { testDoc.readyState = 'loading'; - let callback = sinon.spy(); + const callback = sinon.spy(); onDocumentReady(testDoc, callback); expect(callback.callCount).to.equal(0); expect(eventListeners['readystatechange']).to.not.equal(undefined); @@ -125,41 +125,41 @@ describe('DocumentState', () => { }); it('resolve vendor-prefixed properties', () => { - let otherDoc = { + const otherDoc = { webkitHidden: false, webkitVisibilityState: 'visible', addEventListener: (eventType, handler) => {}, removeEventListener: (eventType, handler) => {} }; - let other = new DocumentState({document: otherDoc}); + const other = new DocumentState({document: otherDoc}); expect(other.hiddenProp_).to.equal('webkitHidden'); expect(other.visibilityStateProp_).to.equal('webkitVisibilityState'); expect(other.visibilityChangeEvent_).to.equal('webkitVisibilitychange'); }); it('resolve no properties', () => { - let otherDoc = { + const otherDoc = { addEventListener: (eventType, handler) => {}, removeEventListener: (eventType, handler) => {} }; - let other = new DocumentState({document: otherDoc}); + const other = new DocumentState({document: otherDoc}); expect(other.hiddenProp_).to.equal(null); expect(other.visibilityStateProp_).to.equal(null); expect(other.visibilityChangeEvent_).to.equal(null); }); it('should default hidden and visibilityState if unknown', () => { - let otherDoc = { + const otherDoc = { addEventListener: (eventType, handler) => {}, removeEventListener: (eventType, handler) => {} }; - let other = new DocumentState({document: otherDoc}); + const other = new DocumentState({document: otherDoc}); expect(other.isHidden()).to.equal(false); expect(other.getVisibilityState()).to.equal('visible'); }); it('should fire visibility change', () => { - let callback = sinon.spy(); + const callback = sinon.spy(); docState.onVisibilityChanged(callback); expect(docState.isHidden()).to.equal(false); diff --git a/test/functional/test-dom.js b/test/functional/test-dom.js index bb42bb26aa3b..3f23f2a6e029 100644 --- a/test/functional/test-dom.js +++ b/test/functional/test-dom.js @@ -20,7 +20,7 @@ import * as dom from '../../src/dom'; describe('DOM', () => { it('should remove all children', () => { - let element = document.createElement('div'); + const element = document.createElement('div'); element.appendChild(document.createElement('div')); element.appendChild(document.createTextNode('ABC')); expect(element.children.length).to.equal(1); @@ -34,11 +34,11 @@ describe('DOM', () => { }); it('should copy all children', () => { - let element = document.createElement('div'); + const element = document.createElement('div'); element.appendChild(document.createElement('div')); element.appendChild(document.createTextNode('ABC')); - let other = document.createElement('div'); + const other = document.createElement('div'); dom.copyChildren(element, other); expect(element.children.length).to.equal(1); @@ -52,9 +52,9 @@ describe('DOM', () => { }); it('closest should find itself', () => { - let element = document.createElement('div'); + const element = document.createElement('div'); - let child = document.createElement('div'); + const child = document.createElement('div'); element.appendChild(child); expect(dom.closest(child, () => true)).to.equal(child); @@ -63,12 +63,12 @@ describe('DOM', () => { }); it('closest should find first match', () => { - let parent = document.createElement('parent'); + const parent = document.createElement('parent'); - let element = document.createElement('element'); + const element = document.createElement('element'); parent.appendChild(element); - let child = document.createElement('child'); + const child = document.createElement('child'); element.appendChild(child); expect(dom.closest(child, e => e.tagName == 'CHILD')).to.equal(child); @@ -82,12 +82,12 @@ describe('DOM', () => { }); it('closest should find first match', () => { - let parent = document.createElement('parent'); + const parent = document.createElement('parent'); - let element1 = document.createElement('element'); + const element1 = document.createElement('element'); parent.appendChild(element1); - let element2 = document.createElement('element'); + const element2 = document.createElement('element'); parent.appendChild(element2); expect(dom.elementByTag(parent, 'element')).to.equal(element1); @@ -96,12 +96,12 @@ describe('DOM', () => { it('childElement should find first match', () => { - let parent = document.createElement('parent'); + const parent = document.createElement('parent'); - let element1 = document.createElement('element1'); + const element1 = document.createElement('element1'); parent.appendChild(element1); - let element2 = document.createElement('element2'); + const element2 = document.createElement('element2'); parent.appendChild(element2); expect(dom.childElement(parent, e => true)).to.equal(element1); @@ -114,14 +114,14 @@ describe('DOM', () => { }); it('childElementByAttr should find first match', () => { - let parent = document.createElement('parent'); + const parent = document.createElement('parent'); - let element1 = document.createElement('element1'); + const element1 = document.createElement('element1'); element1.setAttribute('attr1', '1'); element1.setAttribute('attr12', '1'); parent.appendChild(element1); - let element2 = document.createElement('element2'); + const element2 = document.createElement('element2'); element2.setAttribute('attr2', '2'); element2.setAttribute('attr12', '2'); parent.appendChild(element2); diff --git a/test/functional/test-event-helper.js b/test/functional/test-event-helper.js index 21b3e304f069..dbabb3fd09d9 100644 --- a/test/functional/test-event-helper.js +++ b/test/functional/test-event-helper.js @@ -74,9 +74,9 @@ describe('EventHelper', () => { }); it('listenOnce', () => { - let event = getEvent('load'); + const event = getEvent('load'); let c = 0; - let handler = e => { + const handler = e => { c++; expect(e).to.equal(event); }; @@ -95,13 +95,13 @@ describe('EventHelper', () => { }); it('listenOnce - cancel', () => { - let event = getEvent('load'); + const event = getEvent('load'); let c = 0; - let handler = e => { + const handler = e => { c++; expect(e).to.equal(event); }; - let unlisten = listenOnce(element, 'load', handler); + const unlisten = listenOnce(element, 'load', handler); // Not fired yet. expect(c).to.equal(0); @@ -115,8 +115,8 @@ describe('EventHelper', () => { }); it('listenOncePromise - load event', () => { - let event = getEvent('load'); - let promise = listenOncePromise(element, 'load').then(result => { + const event = getEvent('load'); + const promise = listenOncePromise(element, 'load').then(result => { expect(result).to.equal(event); }); loadObservable.fire(event); @@ -124,8 +124,8 @@ describe('EventHelper', () => { }); it('listenOncePromise - with time limit', () => { - let event = getEvent('load'); - let promise = expect(listenOncePromise(element, 'load', false, 100)) + const event = getEvent('load'); + const promise = expect(listenOncePromise(element, 'load', false, 100)) .to.eventually.become(event); sandbox.clock.tick(99); loadObservable.fire(event); @@ -133,7 +133,7 @@ describe('EventHelper', () => { }); it('listenOncePromise - timeout', () => { - let promise = expect(listenOncePromise(element, 'load', false, 100)) + const promise = expect(listenOncePromise(element, 'load', false, 100)) .to.eventually.be.rejectedWith('timeout'); sandbox.clock.tick(101); return promise; @@ -166,7 +166,7 @@ describe('EventHelper', () => { }); it('loadPromise - load event', () => { - let promise = loadPromise(element).then(result => { + const promise = loadPromise(element).then(result => { expect(result).to.equal(element); }); loadObservable.fire(getEvent('load')); @@ -174,7 +174,7 @@ describe('EventHelper', () => { }); it('loadPromise - error event', () => { - let promise = loadPromise(element).then(result => { + const promise = loadPromise(element).then(result => { assert.fail('must never be here: ' + result); }).catch(reason => { }); diff --git a/test/functional/test-focus-history.js b/test/functional/test-focus-history.js index 94f7900c8c34..e84d673883fb 100644 --- a/test/functional/test-focus-history.js +++ b/test/functional/test-focus-history.js @@ -65,8 +65,8 @@ describe('FocusHistory', () => { }); it('should push focused elements with timestamp', () => { - let el1 = document.createElement('div'); - let el2 = document.createElement('div'); + const el1 = document.createElement('div'); + const el2 = document.createElement('div'); eventListeners['focus']({target: el1}); clock.tick(100); eventListeners['focus']({target: el2}); @@ -81,7 +81,7 @@ describe('FocusHistory', () => { windowEventListeners['blur']({}); expect(focusHistory.history_.length).to.equal(0); - let el1 = document.createElement('div'); + const el1 = document.createElement('div'); testDoc.activeElement = el1; clock.tick(1000); expect(focusHistory.history_.length).to.equal(1); @@ -89,8 +89,8 @@ describe('FocusHistory', () => { }); it('should push and purge', () => { - let el1 = document.createElement('div'); - let el2 = document.createElement('div'); + const el1 = document.createElement('div'); + const el2 = document.createElement('div'); eventListeners['focus']({target: el1}); clock.tick(100000); eventListeners['focus']({target: el2}); @@ -101,8 +101,8 @@ describe('FocusHistory', () => { }); it('should replace second push with a new timestamp', () => { - let el1 = document.createElement('div'); - let el2 = document.createElement('div'); + const el1 = document.createElement('div'); + const el2 = document.createElement('div'); eventListeners['focus']({target: el1}); clock.tick(100); eventListeners['focus']({target: el2}); @@ -117,8 +117,8 @@ describe('FocusHistory', () => { }); it('should purge elements before timestamp', () => { - let el1 = document.createElement('div'); - let el2 = document.createElement('div'); + const el1 = document.createElement('div'); + const el2 = document.createElement('div'); clock.tick(100); eventListeners['focus']({target: el1}); // time=100 clock.tick(100); @@ -139,7 +139,7 @@ describe('FocusHistory', () => { }); it('should return false when nothing matches descendants', () => { - let el0 = document.createElement('div'); + const el0 = document.createElement('div'); expect(focusHistory.hasDescendantsOf(el0)).to.be.false; eventListeners['focus']({target: document.createElement('div')}); @@ -147,8 +147,8 @@ describe('FocusHistory', () => { }); it('should check active element for descendants', () => { - let el0 = document.createElement('div'); - let el01 = document.createElement('div'); + const el0 = document.createElement('div'); + const el01 = document.createElement('div'); el0.appendChild(el01); testDoc.activeElement = el0; @@ -161,8 +161,8 @@ describe('FocusHistory', () => { }); it('should check history descendants', () => { - let el0 = document.createElement('div'); - let el01 = document.createElement('div'); + const el0 = document.createElement('div'); + const el01 = document.createElement('div'); el0.appendChild(el01); eventListeners['focus']({target: el01}); expect(focusHistory.hasDescendantsOf(el0)).to.be.true; diff --git a/test/functional/test-gesture-recognizers.js b/test/functional/test-gesture-recognizers.js index 79d294098f55..7de136e43e6c 100644 --- a/test/functional/test-gesture-recognizers.js +++ b/test/functional/test-gesture-recognizers.js @@ -55,7 +55,7 @@ describe('TapRecognizer', () => { it('should allow single-point touchstart', () => { - let res = recognizer.onTouchStart({touches: + const res = recognizer.onTouchStart({touches: [{clientX: 101, clientY: 201}]}); expect(res).to.equal(true); expect(recognizer.startX_).to.equal(101); @@ -63,7 +63,7 @@ describe('TapRecognizer', () => { }); it('should deny two-point touchstart', () => { - let res = recognizer.onTouchStart({touches: + const res = recognizer.onTouchStart({touches: [{clientX: 101, clientY: 201}, {}]}); expect(res).to.equal(false); expect(recognizer.startX_).to.equal(0); @@ -151,7 +151,7 @@ describe('DoubletapRecognizer', () => { it('should allow single-point touchstart', () => { - let res = recognizer.onTouchStart({touches: + const res = recognizer.onTouchStart({touches: [{clientX: 101, clientY: 201}]}); expect(res).to.equal(true); expect(recognizer.startX_).to.equal(101); @@ -159,7 +159,7 @@ describe('DoubletapRecognizer', () => { }); it('should deny two-point touchstart', () => { - let res = recognizer.onTouchStart({touches: + const res = recognizer.onTouchStart({touches: [{clientX: 101, clientY: 201}, {}]}); expect(res).to.equal(false); expect(recognizer.startX_).to.equal(0); @@ -265,7 +265,7 @@ describe('SwipeXYRecognizer', () => { it('should allow single-point touchstart', () => { - let res = recognizer.onTouchStart({touches: + const res = recognizer.onTouchStart({touches: [{clientX: 101, clientY: 201}]}); expect(res).to.equal(true); expect(recognizer.startX_).to.equal(101); @@ -273,7 +273,7 @@ describe('SwipeXYRecognizer', () => { }); it('should deny two-point touchstart', () => { - let res = recognizer.onTouchStart({touches: + const res = recognizer.onTouchStart({touches: [{clientX: 101, clientY: 201}, {}]}); expect(res).to.equal(false); expect(recognizer.startX_).to.equal(0); @@ -341,7 +341,7 @@ describe('SwipeXYRecognizer', () => { }); it('should emit on touchmove after start', () => { - let event = {touches: [{clientX: 111, clientY: 211}]}; + const event = {touches: [{clientX: 111, clientY: 211}]}; recognizer.startX_ = recognizer.prevX_ = 101; recognizer.startY_ = recognizer.prevY_ = 201; @@ -357,14 +357,14 @@ describe('SwipeXYRecognizer', () => { gesturesMock.expects('signalEnd_').never(); clock.tick(10); - let res = recognizer.onTouchMove(event); + const res = recognizer.onTouchMove(event); expect(res).to.equal(true); expect(recognizer.lastX_).to.equal(111); expect(recognizer.lastY_).to.equal(211); }); it('should stop on touchend; velocity doesn\'t change', () => { - let event = {}; + const event = {}; recognizer.startX_ = recognizer.prevX_ = 101; recognizer.startY_ = recognizer.prevY_ = 201; @@ -389,7 +389,7 @@ describe('SwipeXYRecognizer', () => { }); it('should stop on touchend; velocity changes', () => { - let event = {}; + const event = {}; recognizer.startX_ = 101; recognizer.startY_ = 201; @@ -450,7 +450,7 @@ describe('TapzoomRecognizer', () => { it('should allow single-point touchstart', () => { - let res = recognizer.onTouchStart({touches: + const res = recognizer.onTouchStart({touches: [{clientX: 101, clientY: 201}]}); expect(res).to.equal(true); expect(recognizer.startX_).to.equal(101); @@ -458,7 +458,7 @@ describe('TapzoomRecognizer', () => { }); it('should deny two-point touchstart', () => { - let res = recognizer.onTouchStart({touches: + const res = recognizer.onTouchStart({touches: [{clientX: 101, clientY: 201}, {}]}); expect(res).to.equal(false); expect(recognizer.startX_).to.equal(0); @@ -552,7 +552,7 @@ describe('TapzoomRecognizer', () => { }); it('should emit on touchmove after start', () => { - let event = {touches: [{clientX: 111, clientY: 211}]}; + const event = {touches: [{clientX: 111, clientY: 211}]}; recognizer.startX_ = recognizer.prevX_ = 101; recognizer.startY_ = recognizer.prevY_ = 201; @@ -567,14 +567,14 @@ describe('TapzoomRecognizer', () => { gesturesMock.expects('signalEnd_').never(); clock.tick(10); - let res = recognizer.onTouchMove(event); + const res = recognizer.onTouchMove(event); expect(res).to.equal(true); expect(recognizer.lastX_).to.equal(111); expect(recognizer.lastY_).to.equal(211); }); it('should stop on touchend', () => { - let event = {}; + const event = {}; recognizer.startX_ = recognizer.prevX_ = 101; recognizer.startY_ = recognizer.prevY_ = 201; @@ -637,7 +637,7 @@ describe('PinchRecognizer', () => { it('should deny single-point touchstart', () => { - let res = recognizer.onTouchStart({touches: + const res = recognizer.onTouchStart({touches: [{clientX: 101, clientY: 201}]}); expect(res).to.equal(false); expect(recognizer.startX1_).to.equal(0); @@ -647,7 +647,7 @@ describe('PinchRecognizer', () => { }); it('should allow two-point touchstart', () => { - let res = recognizer.onTouchStart({touches: + const res = recognizer.onTouchStart({touches: [{clientX: 90, clientY: 80}, {clientX: 110, clientY: 120}]}); expect(res).to.equal(true); @@ -767,7 +767,7 @@ describe('PinchRecognizer', () => { clock.tick(10); recognizer.acceptStart(); - let event = {touches: + const event = {touches: [{clientX: 70, clientY: 60}, {clientX: 130, clientY: 140}]}; gesturesMock.expects('signalEmit_').withExactArgs(recognizer, @@ -784,7 +784,7 @@ describe('PinchRecognizer', () => { gesturesMock.expects('signalEnd_').never(); clock.tick(10); - let res = recognizer.onTouchMove(event); + const res = recognizer.onTouchMove(event); expect(res).to.equal(true); }); @@ -801,7 +801,7 @@ describe('PinchRecognizer', () => { clock.tick(10); recognizer.acceptStart(); - let event = {}; + const event = {}; gesturesMock.expects('signalEmit_').withExactArgs(recognizer, sinon.match(data => { return (data.first === false && data.last === true && @@ -831,7 +831,7 @@ describe('PinchRecognizer', () => { clock.tick(10); recognizer.acceptStart(); - let event = {}; + const event = {}; gesturesMock.expects('signalEmit_').withExactArgs(recognizer, sinon.match(data => { return (data.first === false && data.last === true && diff --git a/test/functional/test-gesture.js b/test/functional/test-gesture.js index 0bb81b23c423..dfa3f6e0fad3 100644 --- a/test/functional/test-gesture.js +++ b/test/functional/test-gesture.js @@ -79,7 +79,7 @@ describe('Gestures', () => { it('onPointerDown should be called', () => { - let handler = sinon.spy(); + const handler = sinon.spy(); gestures.onPointerDown(handler); sendEvent({type: 'touchstart'}); expect(handler.callCount).to.equal(1); @@ -223,13 +223,13 @@ describe('Gestures', () => { }); it('should allow emit', () => { - let data = {}; - let event = {}; + const data = {}; + const event = {}; clock.tick(1); gestures.eventing_ = recognizer; gestures.signalEmit_(recognizer, data, event); expect(onGesture.callCount).to.equal(1); - let gesture = onGesture.getCall(0).args[0]; + const gesture = onGesture.getCall(0).args[0]; expect(gesture.type).to.equal('test'); expect(gesture.data).to.equal(data); expect(gesture.event).to.equal(event); @@ -267,7 +267,7 @@ describe('Gestures', () => { it('should allow youngest to start', () => { gestures.onGesture(Test2Recognizer, () => {}); - let recognizer2Mock = sandbox.mock(gestures.recognizers_[1]); + const recognizer2Mock = sandbox.mock(gestures.recognizers_[1]); gestures.ready_[0] = 10; gestures.ready_[1] = 9; @@ -281,7 +281,7 @@ describe('Gestures', () => { it('should allow event to propagate when nothing happening', () => { - let event = { + const event = { type: 'touchend', preventDefault: sinon.spy(), stopPropagation: sinon.spy(), @@ -293,7 +293,7 @@ describe('Gestures', () => { it('should cancel event when eventing', () => { gestures.eventing_ = recognizer; - let event = { + const event = { type: 'touchend', preventDefault: sinon.spy(), stopPropagation: sinon.spy(), @@ -309,7 +309,7 @@ describe('Gestures', () => { expect(gestures.eventing_).to.equal(null); expect(gestures.wasEventing_).to.equal(true); - let event = { + const event = { type: 'touchend', preventDefault: sinon.spy(), stopPropagation: sinon.spy(), @@ -322,7 +322,7 @@ describe('Gestures', () => { it('should cancel event when anyone is ready', () => { gestures.ready_[0] = 1; - let event = { + const event = { type: 'touchend', preventDefault: sinon.spy(), stopPropagation: sinon.spy(), diff --git a/test/functional/test-history.js b/test/functional/test-history.js index 1f1a778c14df..c49c17a612f7 100644 --- a/test/functional/test-history.js +++ b/test/functional/test-history.js @@ -32,7 +32,7 @@ describe('History', () => { sandbox = sinon.sandbox.create(); clock = sandbox.useFakeTimers(); - let binding = { + const binding = { cleanup_: () => {}, setOnStackIndexUpdated: callback => { onStackIndexUpdated = callback; @@ -63,7 +63,7 @@ describe('History', () => { }); it('should push new state', () => { - let onPop = sinon.spy(); + const onPop = sinon.spy(); bindingMock.expects('push').withExactArgs() .returns(Promise.resolve(11)).once(); return history.push(onPop).then(historyId => { @@ -75,7 +75,7 @@ describe('History', () => { }); it('should pop previously pushed state', () => { - let onPop = sinon.spy(); + const onPop = sinon.spy(); bindingMock.expects('push').withExactArgs() .returns(Promise.resolve(11)).once(); bindingMock.expects('pop').withExactArgs(11) @@ -95,7 +95,7 @@ describe('History', () => { }); it('should return and call callback when history popped', () => { - let onPop = sinon.spy(); + const onPop = sinon.spy(); bindingMock.expects('push').withExactArgs() .returns(Promise.resolve(11)).once(); return history.push(onPop).then(historyId => { @@ -147,7 +147,7 @@ describe('HistoryBindingNatural', () => { history.origPushState_({'AMP.History': window.history.length}, undefined); history.origReplaceState_({'AMP.History': window.history.length - 2}, undefined); - let history2 = new HistoryBindingNatural_(window); + const history2 = new HistoryBindingNatural_(window); expect(history2.stackIndex_).to.equal(window.history.length - 2); expect(history2.startIndex_).to.equal(window.history.length - 2); expect(history.unsupportedState_['AMP.History']).to.equal( @@ -180,12 +180,12 @@ describe('HistoryBindingNatural', () => { it('should not pass in `url` argument to original replace state if ' + 'parameter is undefined', () => { let argumentLength = 0; - let origReplace = window.history.replaceState; + const origReplace = window.history.replaceState; window.history.replaceState = function() { argumentLength = arguments.length; }; - let history2 = new HistoryBindingNatural_(window); + const history2 = new HistoryBindingNatural_(window); expect(argumentLength).to.equal(2); @@ -209,10 +209,10 @@ describe('HistoryBindingNatural', () => { expect(onStackIndexUpdated.callCount).to.equal(1); expect(onStackIndexUpdated.getCall(0).args[0]).to.equal( window.history.length - 1); - let histPromise = listenOncePromise(window, 'popstate').then(() => { + const histPromise = listenOncePromise(window, 'popstate').then(() => { clock.tick(100); }); - let popPromise = history.pop(stackIndex); + const popPromise = history.pop(stackIndex); return histPromise.then(hist => { return popPromise.then(pop => { expect(pop).to.equal(window.history.length - 2); @@ -232,7 +232,7 @@ describe('HistoryBindingNatural', () => { expect(onStackIndexUpdated.callCount).to.equal(1); expect(onStackIndexUpdated.getCall(0).args[0]).to.equal( window.history.length - 1); - let histPromise = listenOncePromise(window, 'popstate').then(() => { + const histPromise = listenOncePromise(window, 'popstate').then(() => { clock.tick(100); }); window.history.go(-1); @@ -264,7 +264,7 @@ describe('HistoryBindingVirtual', () => { clock = sandbox.useFakeTimers(); onStackIndexUpdated = sinon.spy(); viewerHistoryPoppedHandler = undefined; - let viewer = { + const viewer = { onHistoryPoppedEvent: handler => { viewerHistoryPoppedHandler = handler; return () => {}; diff --git a/test/functional/test-input.js b/test/functional/test-input.js index 781a94b28fcd..71c734b7ab7d 100644 --- a/test/functional/test-input.js +++ b/test/functional/test-input.js @@ -106,7 +106,7 @@ describe('Input', () => { }); expect(mouseDetected).to.equal(undefined); - let p = input.onMouseMove_(); + const p = input.onMouseMove_(); expect(eventListeners['click']).to.not.equal(undefined); clock.tick(350); @@ -126,7 +126,7 @@ describe('Input', () => { }); expect(mouseDetected).to.equal(undefined); - let p = input.onMouseMove_(); + const p = input.onMouseMove_(); eventListeners['click'](); return p.then(() => { @@ -146,7 +146,7 @@ describe('Input', () => { }); expect(mouseDetected).to.equal(undefined); - let p = input.onMouseMove_(); + const p = input.onMouseMove_(); input.mouseConfirmAttemptCount_ = 100; eventListeners['mousemove'] = undefined; eventListeners['click'](); diff --git a/test/functional/test-layout-rect.js b/test/functional/test-layout-rect.js index 4215c4202a03..537fcc0e38be 100644 --- a/test/functional/test-layout-rect.js +++ b/test/functional/test-layout-rect.js @@ -19,7 +19,7 @@ import * as lr from '../../src/layout-rect'; describe('LayoutRect', () => { it('layoutRectLtwh', () => { - let rect = lr.layoutRectLtwh(1, 2, 3, 4); + const rect = lr.layoutRectLtwh(1, 2, 3, 4); expect(rect.left).to.equal(1); expect(rect.top).to.equal(2); expect(rect.width).to.equal(3); @@ -29,17 +29,17 @@ describe('LayoutRect', () => { }); it('layoutRectsOverlap', () => { - let rect1 = lr.layoutRectLtwh(10, 20, 30, 40); - let rect2 = lr.layoutRectLtwh(40, 60, 10, 10); - let rect3 = lr.layoutRectLtwh(41, 60, 10, 10); + const rect1 = lr.layoutRectLtwh(10, 20, 30, 40); + const rect2 = lr.layoutRectLtwh(40, 60, 10, 10); + const rect3 = lr.layoutRectLtwh(41, 60, 10, 10); expect(lr.layoutRectsOverlap(rect1, rect2)).to.equal(true); expect(lr.layoutRectsOverlap(rect1, rect3)).to.equal(false); expect(lr.layoutRectsOverlap(rect2, rect3)).to.equal(true); }); it('expandLayoutRect', () => { - let rect1 = lr.layoutRectLtwh(10, 20, 30, 40); - let rect2 = lr.expandLayoutRect(rect1, 2, 3); + const rect1 = lr.layoutRectLtwh(10, 20, 30, 40); + const rect2 = lr.expandLayoutRect(rect1, 2, 3); expect(rect2.left).to.equal(10 - 30 * 2); expect(rect2.right).to.equal(40 + 30 * 2); expect(rect2.width).to.equal(30 + 30 * 4); @@ -49,8 +49,8 @@ describe('LayoutRect', () => { }); it('moveLayoutRect', () => { - let rect1 = lr.layoutRectLtwh(10, 20, 30, 40); - let rect2 = lr.moveLayoutRect(rect1, 2, 3); + const rect1 = lr.layoutRectLtwh(10, 20, 30, 40); + const rect2 = lr.moveLayoutRect(rect1, 2, 3); expect(rect2.left).to.equal(rect1.left + 2); expect(rect2.right).to.equal(rect1.right + 2); expect(rect2.width).to.equal(rect1.width); @@ -60,7 +60,7 @@ describe('LayoutRect', () => { }); it('layoutRectFromDomRect', () => { - let rect = lr.layoutRectFromDomRect({top: 11, left: 12, width: 111, + const rect = lr.layoutRectFromDomRect({top: 11, left: 12, width: 111, height: 222}); expect(rect.top).to.equal(11); expect(rect.left).to.equal(12); diff --git a/test/functional/test-layout.js b/test/functional/test-layout.js index 34cb0dcc5597..5ffbf9523e15 100644 --- a/test/functional/test-layout.js +++ b/test/functional/test-layout.js @@ -257,14 +257,14 @@ describe('Layout', () => { it('should configure natural dimensions; default layout', () => { - let pixel = document.createElement('amp-pixel'); + const pixel = document.createElement('amp-pixel'); expect(applyLayout_(pixel)).to.equal(Layout.FIXED); expect(pixel.style.width).to.equal('1px'); expect(pixel.style.height).to.equal('1px'); }); it('should configure natural dimensions; default layout; with width', () => { - let pixel = document.createElement('amp-pixel'); + const pixel = document.createElement('amp-pixel'); pixel.setAttribute('width', '11'); expect(applyLayout_(pixel)).to.equal(Layout.FIXED); expect(pixel.style.width).to.equal('11px'); @@ -272,7 +272,7 @@ describe('Layout', () => { }); it('should configure natural dimensions; default layout; with height', () => { - let pixel = document.createElement('amp-pixel'); + const pixel = document.createElement('amp-pixel'); pixel.setAttribute('height', '11'); expect(applyLayout_(pixel)).to.equal(Layout.FIXED); expect(pixel.style.width).to.equal('1px'); @@ -280,7 +280,7 @@ describe('Layout', () => { }); it('should configure natural dimensions; layout=fixed', () => { - let pixel = document.createElement('amp-pixel'); + const pixel = document.createElement('amp-pixel'); pixel.setAttribute('layout', 'fixed'); expect(applyLayout_(pixel)).to.equal(Layout.FIXED); expect(pixel.style.width).to.equal('1px'); @@ -288,7 +288,7 @@ describe('Layout', () => { }); it('should configure natural dimensions; layout=fixed-height', () => { - let pixel = document.createElement('amp-pixel'); + const pixel = document.createElement('amp-pixel'); pixel.setAttribute('layout', 'fixed-height'); expect(applyLayout_(pixel)).to.equal(Layout.FIXED_HEIGHT); expect(pixel.style.height).to.equal('1px'); diff --git a/test/functional/test-motion.js b/test/functional/test-motion.js index 942617f24dc2..255d25d6e225 100644 --- a/test/functional/test-motion.js +++ b/test/functional/test-motion.js @@ -87,14 +87,16 @@ describe('Motion continueMotion', () => { function testContinuation(maxVelocity, haltAfterTime) { let resultX = null; let resultY = null; - let motion = continueMotion(141, 104, maxVelocity, maxVelocity, (x, y) => { - resultX = x; - resultY = y; - return true; - }, vsync); + const motion = continueMotion(141, 104, maxVelocity, maxVelocity, + (x, y) => { + resultX = x; + resultY = y; + return true; + }, + vsync); expect(vsyncTasks.length).to.equal(1); - let mutator = vsyncTasks[0]; + const mutator = vsyncTasks[0]; vsyncTasks = []; resultX = resultY = null; @@ -102,13 +104,13 @@ describe('Motion continueMotion', () => { expect(resultX).to.be.closeTo(141, 1e-3); expect(resultY).to.be.closeTo(104, 1e-3); - let values = []; + const values = []; let time = 0; let continuing = true; do { resultX = resultY = null; clock.tick(100); - let prev = time; + const prev = time; time += 100; continuing = mutator(time, time - prev, {}); if (resultX != null) { @@ -124,7 +126,7 @@ describe('Motion continueMotion', () => { } it('should follow positive inertia', () => { - let values = testContinuation(0.665, 0); + const values = testContinuation(0.665, 0); expect(values.length).to.equal(12); expect(values[0]).to.be.closeTo(66, 1); expect(values[1]).to.be.closeTo(115, 1); @@ -134,7 +136,7 @@ describe('Motion continueMotion', () => { }); it('should halt when requested while following positive inertia', () => { - let values = testContinuation(0.665, 300); + const values = testContinuation(0.665, 300); expect(values.length).to.equal(3); expect(values[0]).to.be.closeTo(66, 1); expect(values[1]).to.be.closeTo(115, 1); @@ -142,7 +144,7 @@ describe('Motion continueMotion', () => { }); it('should follow negative inertia', () => { - let values = testContinuation(-0.665, 0); + const values = testContinuation(-0.665, 0); expect(values.length).to.equal(12); expect(values[0]).to.be.closeTo(-66, 1); expect(values[1]).to.be.closeTo(-115, 1); @@ -152,7 +154,7 @@ describe('Motion continueMotion', () => { }); it('should halt when requested while following negative inertia', () => { - let values = testContinuation(-0.665, 300); + const values = testContinuation(-0.665, 300); expect(values.length).to.equal(3); expect(values[0]).to.be.closeTo(-66, 1); expect(values[1]).to.be.closeTo(-115, 1); diff --git a/test/functional/test-observable.js b/test/functional/test-observable.js index aa736abbb45c..f0811cb4a00a 100644 --- a/test/functional/test-observable.js +++ b/test/functional/test-observable.js @@ -34,16 +34,16 @@ describe('Observable', () => { it('add-remove-fire', () => { let observer1Called = 0; - let observer1 = () => { + const observer1 = () => { observer1Called++; }; - let observer1Key = observable.add(observer1); + const observer1Key = observable.add(observer1); let observer2Called = 0; - let observer2 = () => { + const observer2 = () => { observer2Called++; }; - let observer2Key = observable.add(observer2); + const observer2Key = observable.add(observer2); expect(observer1Called).to.equal(0); expect(observer2Called).to.equal(0); diff --git a/test/functional/test-pass.js b/test/functional/test-pass.js index 95966b8f0838..7fff2ce68610 100644 --- a/test/functional/test-pass.js +++ b/test/functional/test-pass.js @@ -80,7 +80,7 @@ describe('Pass', () => { timerMock.expects('cancel').never(); pass.schedule(111); // Will never schedule b/c there's an earlier pass still pending. - let isScheduled = pass.schedule(222); + const isScheduled = pass.schedule(222); expect(isScheduled).to.equal(false); }); @@ -92,7 +92,7 @@ describe('Pass', () => { timerMock.expects('cancel').withExactArgs(1).once(); pass.schedule(222); // Will re-schedule b/c the existing pass is later. - let isScheduled = pass.schedule(111); + const isScheduled = pass.schedule(111); expect(isScheduled).to.equal(true); }); diff --git a/test/functional/test-platform.js b/test/functional/test-platform.js index dc33e324fbea..f44c047fbcb0 100644 --- a/test/functional/test-platform.js +++ b/test/functional/test-platform.js @@ -28,7 +28,7 @@ describe('Platform', () => { }); function testUserAgent(userAgentString) { - let platform = new Platform({navigator: {userAgent: userAgentString}}); + const platform = new Platform({navigator: {userAgent: userAgentString}}); expect(platform.isIos()).to.equal(isIos); expect(platform.isChrome()).to.equal(isChrome); expect(platform.isSafari()).to.equal(isSafari); diff --git a/test/functional/test-pull-to-refresh.js b/test/functional/test-pull-to-refresh.js index b85201dfd37f..7fafc91ca9d8 100644 --- a/test/functional/test-pull-to-refresh.js +++ b/test/functional/test-pull-to-refresh.js @@ -29,7 +29,7 @@ describe('PullToRefreshBlocker', () => { sandbox = sinon.sandbox.create(); eventListeners = {}; - let documentApi = { + const documentApi = { addEventListener: (eventType, handler) => { eventListeners[eventType] = handler; }, @@ -40,7 +40,7 @@ describe('PullToRefreshBlocker', () => { } }; - let viewportApi = { + const viewportApi = { getTop: () => 0 }; viewportMock = sandbox.mock(viewportApi); @@ -134,7 +134,7 @@ describe('PullToRefreshBlocker', () => { sendEvent({type: 'touchstart', touches: [{clientY: 111}]}); expect(blocker.tracking_).to.equal(true); - let preventDefault = sinon.spy(); + const preventDefault = sinon.spy(); sendEvent({type: 'touchmove', touches: [{clientY: 112}]}, preventDefault); expect(blocker.tracking_).to.equal(false); @@ -150,7 +150,7 @@ describe('PullToRefreshBlocker', () => { sendEvent({type: 'touchstart', touches: [{clientY: 111}]}); expect(blocker.tracking_).to.equal(true); - let preventDefault = sinon.spy(); + const preventDefault = sinon.spy(); sendEvent({type: 'touchmove', touches: [{clientY: 100}]}, preventDefault); expect(blocker.tracking_).to.equal(false); @@ -166,7 +166,7 @@ describe('PullToRefreshBlocker', () => { sendEvent({type: 'touchstart', touches: [{clientY: 111}]}); expect(blocker.tracking_).to.equal(true); - let preventDefault = sinon.spy(); + const preventDefault = sinon.spy(); sendEvent({type: 'touchmove', touches: [{clientY: 111}]}, preventDefault); expect(blocker.tracking_).to.equal(true); diff --git a/test/functional/test-resources.js b/test/functional/test-resources.js index c6053acf593b..bcc8f5349226 100644 --- a/test/functional/test-resources.js +++ b/test/functional/test-resources.js @@ -41,9 +41,9 @@ describe('Resources', () => { }); it('should calculate correct calcTaskScore', () => { - let viewportRect = layoutRectLtwh(0, 100, 300, 400); + const viewportRect = layoutRectLtwh(0, 100, 300, 400); // Task 1 is right in the middle of the viewport and priority 0 - let task_vp0_p0 = { + const task_vp0_p0 = { resource: { getLayoutBox() { return layoutRectLtwh(0, 100, 300, 100); @@ -52,7 +52,7 @@ describe('Resources', () => { priority: 0 }; // Task 2 is in the viewport and priority 1 - let task_vp0_p1 = { + const task_vp0_p1 = { resource: { getLayoutBox() { return layoutRectLtwh(0, 100, 300, 100); @@ -61,7 +61,7 @@ describe('Resources', () => { priority: 1 }; // Task 3 is above viewport and priority 0 - let task_vpu_p0 = { + const task_vpu_p0 = { resource: { getLayoutBox() { return layoutRectLtwh(0, 0, 300, 50); @@ -70,7 +70,7 @@ describe('Resources', () => { priority: 0 }; // Task 4 is above viewport and priority 0 - let task_vpu_p1 = { + const task_vpu_p1 = { resource: { getLayoutBox() { return layoutRectLtwh(0, 0, 300, 50); @@ -79,7 +79,7 @@ describe('Resources', () => { priority: 1 }; // Task 5 is below viewport and priority 0 - let task_vpd_p0 = { + const task_vpd_p0 = { resource: { getLayoutBox() { return layoutRectLtwh(0, 600, 300, 50); @@ -88,7 +88,7 @@ describe('Resources', () => { priority: 0 }; // Task 6 is below viewport and priority 0 - let task_vpd_p1 = { + const task_vpd_p1 = { resource: { getLayoutBox() { return layoutRectLtwh(0, 600, 300, 50); @@ -111,12 +111,12 @@ describe('Resources', () => { it('should calculate correct calcTaskTimeout', () => { // Task 1 is priority 0 - let task_p0 = { + const task_p0 = { priority: 0, startTime: 0 }; // Task 2 is priority 1 - let task_p1 = { + const task_p1 = { priority: 1, startTime: 0 }; @@ -150,7 +150,7 @@ describe('Resources', () => { it('should not schedule non-prerenderable resource when' + ' document is hidden', () => { - let resource = { + const resource = { getState: () => {return ResourceState_.READY_FOR_LAYOUT;}, isDisplayed: () => {return true;}, isInViewport: () => {return true;}, @@ -164,7 +164,7 @@ describe('Resources', () => { it('should schedule prerenderable resource when' + ' document is hidden', () => { - let resource = { + const resource = { getState: () => {return ResourceState_.READY_FOR_LAYOUT;}, isDisplayed: () => {return true;}, isInViewport: () => {return true;}, @@ -181,7 +181,7 @@ describe('Resources', () => { it('should not schedule non-renderOutsideViewport resource when' + ' resource is not visible', () => { - let resource = { + const resource = { getState: () => {return ResourceState_.READY_FOR_LAYOUT;}, isDisplayed: () => {return true;}, isInViewport: () => {return false;}, @@ -195,7 +195,7 @@ describe('Resources', () => { it('should schedule renderOutsideViewport resource when' + ' resource is not visible', () => { - let resource = { + const resource = { getState: () => {return ResourceState_.READY_FOR_LAYOUT;}, isDisplayed: () => {return true;}, isInViewport: () => {return false;}, @@ -236,7 +236,7 @@ describe('Resources discoverWork', () => { } function createResource(id, rect) { - let resource = new Resource(id, createElement(rect), resources); + const resource = new Resource(id, createElement(rect), resources); resource.state_ = ResourceState_.READY_FOR_LAYOUT; resource.layoutBox_ = rect; return resource; @@ -365,7 +365,7 @@ describe('Resources changeHeight', () => { } function createResource(id, rect) { - let resource = new Resource(id, createElement(rect), resources); + const resource = new Resource(id, createElement(rect), resources); resource.state_ = ResourceState_.READY_FOR_LAYOUT; resource.layoutBox_ = rect; resource.changeHeight = sinon.spy(); @@ -401,7 +401,7 @@ describe('Resources changeHeight', () => { }); it('should schedule separate requests', () => { - let fallback2 = () => {}; + const fallback2 = () => {}; resources.scheduleChangeHeight_(resource1, 111, false, null); resources.scheduleChangeHeight_(resource2, 222, true, fallback2); @@ -418,7 +418,7 @@ describe('Resources changeHeight', () => { }); it('should only schedule latest request for the same resource', () => { - let fallback1 = () => {}; + const fallback1 = () => {}; resources.scheduleChangeHeight_(resource1, 111, true, fallback1); resources.scheduleChangeHeight_(resource1, 222, false, null); @@ -462,7 +462,7 @@ describe('Resources changeHeight', () => { }); it('should NOT change height and calls fallback', () => { - let fallback = sinon.spy(); + const fallback = sinon.spy(); resources.scheduleChangeHeight_(resource1, 111, false, fallback); resources.mutateWork_(); expect(resources.changeHeightRequests_.length).to.equal(0); @@ -581,7 +581,7 @@ describe('Resources.TaskQueue', () => { queue.enqueue({id: 'B', v: 2}); queue.enqueue({id: 'C', v: 1}); - let task = queue.peek(task => 10 - task.v); + const task = queue.peek(task => 10 - task.v); expect(task.id).to.equal('B'); }); }); @@ -903,7 +903,7 @@ describe('Resources.Resource', () => { resource.state_ = ResourceState_.READY_FOR_LAYOUT; resource.layoutBox_ = {left: 11, top: 12, width: 10, height: 10}; - let promise = resource.startLayout(true); + const promise = resource.startLayout(true); expect(resource.layoutPromise_).to.not.equal(null); expect(resource.getState()).to.equal(ResourceState_.LAYOUT_SCHEDULED); @@ -922,7 +922,7 @@ describe('Resources.Resource', () => { resource.state_ = ResourceState_.READY_FOR_LAYOUT; resource.layoutBox_ = {left: 11, top: 12, width: 10, height: 10}; - let promise = resource.startLayout(true); + const promise = resource.startLayout(true); expect(resource.layoutPromise_).to.not.equal(null); expect(resource.getState()).to.equal(ResourceState_.LAYOUT_SCHEDULED); diff --git a/test/functional/test-size-list.js b/test/functional/test-size-list.js index c735cf13c911..569b479ff19c 100644 --- a/test/functional/test-size-list.js +++ b/test/functional/test-size-list.js @@ -102,7 +102,7 @@ describe('SizeList construct', () => { describe('SizeList select', () => { it('should select default last option', () => { - let sizeList = new SizeList([ + const sizeList = new SizeList([ {mediaQuery: 'media1', size: '444px'}, {mediaQuery: 'media2', size: '333px'}, {mediaQuery: 'media3', size: '222px'}, @@ -114,7 +114,7 @@ describe('SizeList select', () => { }); it('should select a matching option', () => { - let sizeList = new SizeList([ + const sizeList = new SizeList([ {mediaQuery: 'media1', size: '444px'}, {mediaQuery: 'media2', size: '333px'}, {mediaQuery: 'media3', size: '222px'}, @@ -129,7 +129,7 @@ describe('SizeList select', () => { }); it('should select first matching option', () => { - let sizeList = new SizeList([ + const sizeList = new SizeList([ {mediaQuery: 'media1', size: '444px'}, {mediaQuery: 'media2', size: '333px'}, {mediaQuery: 'media3', size: '222px'}, diff --git a/test/functional/test-srcset.js b/test/functional/test-srcset.js index 2a73430f6fed..14e068b7f903 100644 --- a/test/functional/test-srcset.js +++ b/test/functional/test-srcset.js @@ -23,8 +23,8 @@ describe('Srcset parseSrcset', () => { var res = parseSrcset(s); expect(res.sources_.length).to.equal(expected.length); for (let i = 0; i < expected.length; i++) { - let r = res.sources_[i]; - let e = expected[i]; + const r = res.sources_[i]; + const e = expected[i]; expect(r.url).to.equal(e.url); expect(r.width).to.equal(e.width); expect(r.dpr).to.equal(e.dpr); @@ -244,7 +244,7 @@ describe('Srcset construct', () => { describe('Srcset select', () => { it('select by width', () => { - let srcset = new Srcset([ + const srcset = new Srcset([ {url: 'image-1000', width: 1000}, {url: 'image-500', width: 500}, {url: 'image-250', width: 250}, @@ -283,7 +283,7 @@ describe('Srcset select', () => { }); it('select by dpr', () => { - let srcset = new Srcset([ + const srcset = new Srcset([ {url: 'image-3x', dpr: 3}, {url: 'image-2x', dpr: 2}, {url: 'image', dpr: 1} diff --git a/test/functional/test-style.js b/test/functional/test-style.js index 44ffe08241cd..112958186dc1 100644 --- a/test/functional/test-style.js +++ b/test/functional/test-style.js @@ -30,7 +30,7 @@ describe('Style', () => { }); it('toggle', () => { - let element = document.createElement('div'); + const element = document.createElement('div'); st.toggle(element); expect(element.style.display).to.equal('none'); st.toggle(element); @@ -42,19 +42,19 @@ describe('Style', () => { }); it('setStyle', () => { - let element = document.createElement('div'); + const element = document.createElement('div'); st.setStyle(element, 'width', '1px'); expect(element.style.width).to.equal('1px'); }); it('setStyle with vendor prefix', () => { - let element = { style: { WebkitTransitionDuration: '' } }; + const element = { style: { WebkitTransitionDuration: '' } }; st.setStyle(element, 'transitionDuration', '1s', undefined, true); expect(element.style.WebkitTransitionDuration).to.equal('1s'); }); it('setStyles', () => { - let element = document.createElement('div'); + const element = document.createElement('div'); st.setStyles(element, { width: st.px(101), height: st.px(102) @@ -81,15 +81,15 @@ describe('Style', () => { }); it('camelCaseToTitleCase', () => { - let str = 'theQuickBrownFox'; + const str = 'theQuickBrownFox'; expect(st.camelCaseToTitleCase(str)).to.equal('TheQuickBrownFox'); }); describe('getVendorJsPropertyName', () => { it('no prefix', () => { - let element = { style: { transitionDuration: '' } }; - let prop = st + const element = { style: { transitionDuration: '' } }; + const prop = st .getVendorJsPropertyName(element.style, 'transitionDuration', true); expect(prop).to.equal('transitionDuration'); }); @@ -107,29 +107,29 @@ describe('Style', () => { }); it('Webkit', () => { - let element = { style: { WebkitTransitionDuration: '' } }; - let prop = st + const element = { style: { WebkitTransitionDuration: '' } }; + const prop = st .getVendorJsPropertyName(element.style, 'transitionDuration', true); expect(prop).to.equal('WebkitTransitionDuration'); }); it('Moz', () => { - let element = { style: { MozTransitionDuration: '' } }; - let prop = st + const element = { style: { MozTransitionDuration: '' } }; + const prop = st .getVendorJsPropertyName(element.style, 'transitionDuration', true); expect(prop).to.equal('MozTransitionDuration'); }); it('ms', () => { - let element = { style: { msTransitionDuration: '' } }; - let prop = st + const element = { style: { msTransitionDuration: '' } }; + const prop = st .getVendorJsPropertyName(element.style, 'transitionDuration', true); expect(prop).to.equal('msTransitionDuration'); }); it('O opera', () => { - let element = { style: { OTransitionDuration: '' } }; - let prop = st + const element = { style: { OTransitionDuration: '' } }; + const prop = st .getVendorJsPropertyName(element.style, 'transitionDuration', true); expect(prop).to.equal('OTransitionDuration'); }); diff --git a/test/functional/test-swipe.js b/test/functional/test-swipe.js index 2233d0995957..1a941ea575a2 100644 --- a/test/functional/test-swipe.js +++ b/test/functional/test-swipe.js @@ -304,7 +304,7 @@ describe('Swipe', () => { swipeX.touchEnd_({}); expect(vsyncTasks.length).to.equal(1); - let mutator = vsyncTasks[0]; + const mutator = vsyncTasks[0]; vsyncTasks = []; let cont = false; diff --git a/test/functional/test-timer.js b/test/functional/test-timer.js index e1f4950f26dd..525f12e68be8 100644 --- a/test/functional/test-timer.js +++ b/test/functional/test-timer.js @@ -41,7 +41,7 @@ describe('Timer', () => { }); it('delay', () => { - let handler = () => {}; + const handler = () => {}; windowMock.expects('setTimeout').withExactArgs(handler, 111) .returns(1).once(); windowMock.expects('clearTimeout').never(); diff --git a/test/functional/test-transition.js b/test/functional/test-transition.js index 13260f9f1add..13656ba3c85c 100644 --- a/test/functional/test-transition.js +++ b/test/functional/test-transition.js @@ -30,9 +30,9 @@ describe('Transition', () => { }); it('all', () => { - let func1 = sinon.spy(); - let func2 = sinon.spy(); - let all = tr.all([func1, func2]); + const func1 = sinon.spy(); + const func2 = sinon.spy(); + const all = tr.all([func1, func2]); expect(func1.callCount).to.equal(0); expect(func2.callCount).to.equal(0); @@ -57,9 +57,9 @@ describe('Transition', () => { }); it('withCurve', () => { - let func1 = (time, complete) => `${time * 2};${complete}`; - let curve = time => 0.2; - let curved = tr.withCurve(func1, curve); + const func1 = (time, complete) => `${time * 2};${complete}`; + const curve = time => 0.2; + const curved = tr.withCurve(func1, curve); expect(curved(0, false)).to.equal('0.4;false'); expect(curved(0.5, false)).to.equal('0.4;false'); @@ -68,8 +68,8 @@ describe('Transition', () => { }); it('setStyles', () => { - let element = document.createElement('div'); - let func = tr.setStyles(element, { + const element = document.createElement('div'); + const func = tr.setStyles(element, { width: tr.px(function(n) {return n * 100 + 1;}), height: tr.px(function(n) {return n * 100 + 2;}), }); @@ -126,7 +126,7 @@ describe('Transition', () => { }); it('px', () => { - let func = tr.px(tr.numeric(0, 10)); + const func = tr.px(tr.numeric(0, 10)); expect(func(0)).to.equal('0px'); expect(func(0.3)).to.equal('3px'); expect(func(0.6)).to.equal('6px'); diff --git a/test/functional/test-uuid.js b/test/functional/test-uuid.js index 3e2374ae6bce..64f0ba8ebd8c 100644 --- a/test/functional/test-uuid.js +++ b/test/functional/test-uuid.js @@ -19,7 +19,7 @@ import {randomUUID} from '../../src/uuid'; describe('UUID', () => { it('should generate randomUUID with right pattern', () => { - let uuid = randomUUID(); + const uuid = randomUUID(); expect(uuid.indexOf('-', 0)).to.equal(8); expect(uuid.indexOf('-', 9)).to.equal(13); expect(uuid.indexOf('-', 14)).to.equal(18); @@ -34,8 +34,8 @@ describe('UUID', () => { // 0 1 2 3 // 012345678901234567890123456789012345 // aaaaaaaa-aaaa-4aaa-baaa-aaaaaaaaaaaa - let v = randomUUID().substring(19, 20); - let n = parseInt(v, 16); + const v = randomUUID().substring(19, 20); + const n = parseInt(v, 16); expect(n & 0x8).to.not.equal(0, '|0x8'); expect((n - 0x8) & ~0x3).to.equal(0, '&0x3'); }); diff --git a/test/functional/test-viewer.js b/test/functional/test-viewer.js index 964c45bfdf49..20e3a2acf800 100644 --- a/test/functional/test-viewer.js +++ b/test/functional/test-viewer.js @@ -56,7 +56,7 @@ describe('Viewer', () => { '&scrollTop=15'; windowApi.location.hash = '#width=111&paddingTop=17&other=something'; windowApi.document = {body: {style: {}}}; - let viewer = new Viewer(windowApi); + const viewer = new Viewer(windowApi); expect(viewer.getViewportType()).to.equal('virtual'); expect(viewer.getViewportWidth()).to.equal(111); expect(viewer.getViewportHeight()).to.equal(333); @@ -77,7 +77,7 @@ describe('Viewer', () => { it('should configure visibilityState and prerender', () => { windowApi.location.hash = '#visibilityState=hidden&prerenderSize=3'; - let viewer = new Viewer(windowApi); + const viewer = new Viewer(windowApi); expect(viewer.getVisibilityState()).to.equal('hidden'); expect(viewer.isVisible()).to.equal(false); expect(viewer.getPrerenderSize()).to.equal(3); @@ -86,11 +86,11 @@ describe('Viewer', () => { it('should configure correctly for iOS embedding', () => { windowApi.name = '__AMP__viewportType=natural'; windowApi.parent = {}; - let body = {style: {}}; - let documentElement = {style: {}}; + const body = {style: {}}; + const documentElement = {style: {}}; windowApi.document = {body: body, documentElement: documentElement}; sandbox.mock(platform).expects('isIos').returns(true).once(); - let viewer = new Viewer(windowApi); + const viewer = new Viewer(windowApi); expect(viewer.getViewportType()).to.equal('natural-ios-embed'); }); @@ -98,8 +98,8 @@ describe('Viewer', () => { it('should NOT configure for iOS embedding if not embedded', () => { windowApi.name = '__AMP__viewportType=natural'; windowApi.parent = windowApi; - let body = {style: {}}; - let documentElement = {style: {}}; + const body = {style: {}}; + const documentElement = {style: {}}; windowApi.document = {body: body, documentElement: documentElement}; sandbox.mock(platform).expects('isIos').returns(true).once(); expect(new Viewer(windowApi).getViewportType()).to.equal('natural'); @@ -144,7 +144,7 @@ describe('Viewer', () => { it('should post documentLoaded event', () => { viewer.postDocumentReady(11, 12); - let m = viewer.messageQueue_[0]; + const m = viewer.messageQueue_[0]; expect(m.eventType).to.equal('documentLoaded'); expect(m.data.width).to.equal(11); expect(m.data.height).to.equal(12); @@ -152,7 +152,7 @@ describe('Viewer', () => { it('should post documentResized event', () => { viewer.postDocumentResized(13, 14); - let m = viewer.messageQueue_[0]; + const m = viewer.messageQueue_[0]; expect(m.eventType).to.equal('documentResized'); expect(m.data.width).to.equal(13); expect(m.data.height).to.equal(14); @@ -171,7 +171,7 @@ describe('Viewer', () => { viewer.postDocumentResized(15, 16); expect(viewer.messageQueue_.length).to.equal(2); expect(viewer.messageQueue_[0].eventType).to.equal('documentLoaded'); - let m = viewer.messageQueue_[1]; + const m = viewer.messageQueue_[1]; expect(m.eventType).to.equal('documentResized'); expect(m.data.width).to.equal(15); expect(m.data.height).to.equal(16); @@ -182,7 +182,7 @@ describe('Viewer', () => { viewer.postDocumentResized(13, 14); expect(viewer.messageQueue_.length).to.equal(2); - let delivered = []; + const delivered = []; viewer.setMessageDeliverer((eventType, data) => { delivered.push({eventType: eventType, data: data}); }); diff --git a/test/functional/test-viewport.js b/test/functional/test-viewport.js index fede11ed735a..2fed7491f758 100644 --- a/test/functional/test-viewport.js +++ b/test/functional/test-viewport.js @@ -120,7 +120,7 @@ describe('Viewport', () => { }); it('should call binding.updateViewerViewport', () => { - let bindingMock = sandbox.mock(binding); + const bindingMock = sandbox.mock(binding); bindingMock.expects('updateViewerViewport').once(); viewerViewportHandler(); bindingMock.verify(); @@ -173,15 +173,15 @@ describe('Viewport', () => { }); it('should update scroll pos and reset cache', () => { - let bindingMock = sandbox.mock(binding); + const bindingMock = sandbox.mock(binding); bindingMock.expects('setScrollTop').withArgs(117).once(); viewport.setScrollTop(117); expect(viewport./*OK*/scrollTop_).to.be.null; }); it('should change scrollTop for scrollIntoView and respect padding', () => { - let element = document.createElement('div'); - let bindingMock = sandbox.mock(binding); + const element = document.createElement('div'); + const bindingMock = sandbox.mock(binding); bindingMock.expects('getLayoutRect').withArgs(element) .returns({top: 111}).once(); bindingMock.expects('setScrollTop').withArgs(111 - /* padding */ 19).once(); @@ -189,7 +189,7 @@ describe('Viewport', () => { }); it('should deletegate scrollWidth', () => { - let bindingMock = sandbox.mock(binding); + const bindingMock = sandbox.mock(binding); bindingMock.expects('getScrollWidth').withArgs().returns(111).once(); expect(viewport.getScrollWidth()).to.equal(111); }); @@ -247,7 +247,7 @@ describe('Viewport META', () => { .to.equal('width=device-width'); }); it('should stringify two key-values', () => { - let res = stringifyViewportMeta({ + const res = stringifyViewportMeta({ 'width': 'device-width', 'minimum-scale': '1' }); @@ -256,7 +256,7 @@ describe('Viewport META', () => { .to.be.true; }); it('should stringify empty values', () => { - let res = stringifyViewportMeta({ + const res = stringifyViewportMeta({ 'width': 'device-width', 'minimal-ui': '' }); @@ -495,7 +495,7 @@ describe('ViewportBindingNatural', () => { clientHeight: 222 } }; - let size = binding.getSize(); + const size = binding.getSize(); expect(size.width).to.equal(111); expect(size.height).to.equal(222); }); @@ -541,12 +541,12 @@ describe('ViewportBindingNatural', () => { windowApi.pageXOffset = 100; windowApi.pageYOffset = 200; windowApi.document = {scrollingElement: {}}; - let el = { + const el = { getBoundingClientRect: () => { return {left: 11.5, top: 12.5, width: 13.5, height: 14.5}; } }; - let rect = binding.getLayoutRect(el); + const rect = binding.getLayoutRect(el); expect(rect.left).to.equal(112); // round(100 + 11.5) expect(rect.top).to.equal(213); // round(200 + 12.5) expect(rect.width).to.equal(14); // round(13.5) @@ -633,8 +633,8 @@ describe('ViewportBindingNaturalIosEmbed', () => { }); it('should setup document for embed scrolling', () => { - let documentElement = windowApi.document.documentElement; - let body = windowApi.document.body; + const documentElement = windowApi.document.documentElement; + const body = windowApi.document.body; expect(documentElement.style.overflow).to.equal('auto'); expect(documentElement.style.webkitOverflowScrolling).to.equal('touch'); expect(body.style.overflow).to.equal('auto'); @@ -676,7 +676,7 @@ describe('ViewportBindingNaturalIosEmbed', () => { it('should calculate size', () => { windowApi.innerWidth = 111; windowApi.innerHeight = 222; - let size = binding.getSize(); + const size = binding.getSize(); expect(size.width).to.equal(111); expect(size.height).to.equal(222); }); @@ -690,7 +690,7 @@ describe('ViewportBindingNaturalIosEmbed', () => { }); it('should update scroll position via moving element', () => { - let moveEl = bodyChildren[1]; + const moveEl = bodyChildren[1]; binding.setScrollTop(17); expect(getStyle(moveEl, 'transform')).to.equal('translateY(17px)'); expect(moveEl.scrollIntoView.callCount).to.equal(1); @@ -702,12 +702,12 @@ describe('ViewportBindingNaturalIosEmbed', () => { return {top: -200, left: -100}; }; binding.onScrolled_(); - let el = { + const el = { getBoundingClientRect: () => { return {left: 11.5, top: 12.5, width: 13.5, height: 14.5}; } }; - let rect = binding.getLayoutRect(el); + const rect = binding.getLayoutRect(el); expect(rect.left).to.equal(112); // round(100 + 11.5) expect(rect.top).to.equal(213); // round(200 + 12.5) expect(rect.width).to.equal(14); // round(13.5) @@ -715,7 +715,7 @@ describe('ViewportBindingNaturalIosEmbed', () => { }); it('should set scroll position via moving element', () => { - let moveEl = bodyChildren[1]; + const moveEl = bodyChildren[1]; binding.setScrollPos_(10); expect(getStyle(moveEl, 'transform')).to.equal('translateY(10px)'); expect(moveEl.scrollIntoView.callCount).to.equal(1); @@ -723,10 +723,10 @@ describe('ViewportBindingNaturalIosEmbed', () => { }); it('should adjust scroll position when scrolled to 0', () => { - let posEl = bodyChildren[0]; + const posEl = bodyChildren[0]; posEl.getBoundingClientRect = () => {return {top: 0, left: 0};}; - let moveEl = bodyChildren[1]; - let event = {preventDefault: sinon.spy()}; + const moveEl = bodyChildren[1]; + const event = {preventDefault: sinon.spy()}; binding.adjustScrollPos_(event); expect(getStyle(moveEl, 'transform')).to.equal('translateY(1px)'); expect(moveEl.scrollIntoView.callCount).to.equal(1); @@ -735,28 +735,28 @@ describe('ViewportBindingNaturalIosEmbed', () => { }); it('should adjust scroll position when scrolled to 0; w/o event', () => { - let posEl = bodyChildren[0]; + const posEl = bodyChildren[0]; posEl.getBoundingClientRect = () => {return {top: 0, left: 0};}; - let moveEl = bodyChildren[1]; + const moveEl = bodyChildren[1]; binding.adjustScrollPos_(); expect(moveEl.scrollIntoView.callCount).to.equal(1); }); it('should NOT adjust scroll position when scrolled away from 0', () => { - let posEl = bodyChildren[0]; + const posEl = bodyChildren[0]; posEl.getBoundingClientRect = () => {return {top: -10, left: 0};}; - let moveEl = bodyChildren[1]; - let event = {preventDefault: sinon.spy()}; + const moveEl = bodyChildren[1]; + const event = {preventDefault: sinon.spy()}; binding.adjustScrollPos_(event); expect(moveEl.scrollIntoView.callCount).to.equal(0); expect(event.preventDefault.callCount).to.equal(0); }); it('should NOT adjust scroll position when overscrolled', () => { - let posEl = bodyChildren[0]; + const posEl = bodyChildren[0]; posEl.getBoundingClientRect = () => {return {top: 10, left: 0};}; - let moveEl = bodyChildren[1]; - let event = {preventDefault: sinon.spy()}; + const moveEl = bodyChildren[1]; + const event = {preventDefault: sinon.spy()}; binding.adjustScrollPos_(event); expect(moveEl.scrollIntoView.callCount).to.equal(0); expect(event.preventDefault.callCount).to.equal(0); @@ -811,7 +811,7 @@ describe('ViewportBindingVirtual', () => { }); it('should send event on scroll changed', () => { - let scrollHandler = sinon.spy(); + const scrollHandler = sinon.spy(); binding.onScroll(scrollHandler); expect(scrollHandler.callCount).to.equal(0); @@ -834,7 +834,7 @@ describe('ViewportBindingVirtual', () => { }); it('should send event on size changed', () => { - let resizeHandler = sinon.spy(); + const resizeHandler = sinon.spy(); binding.onResize(resizeHandler); expect(resizeHandler.callCount).to.equal(0); @@ -867,12 +867,12 @@ describe('ViewportBindingVirtual', () => { }); it('should NOT offset client rect for layout', () => { - let el = { + const el = { getBoundingClientRect: () => { return {left: 11.5, top: 12.5, width: 13.5, height: 14.5}; } }; - let rect = binding.getLayoutRect(el); + const rect = binding.getLayoutRect(el); expect(rect.left).to.equal(12); // round(11.5) expect(rect.top).to.equal(13); // round(12.5) expect(rect.width).to.equal(14); // round(13.5) diff --git a/test/integration/test-amp-carousel.js b/test/integration/test-amp-carousel.js index 93ae73c1987c..049e58020f8a 100644 --- a/test/integration/test-amp-carousel.js +++ b/test/integration/test-amp-carousel.js @@ -49,11 +49,11 @@ describe('integration amp-carousel', () => { it.skip('should only have the next button visible' + 'when on first item', () => { return fixture.awaitEvent('amp:load:start', 1).then(() => { - let amp = fixture.doc.querySelector('#carousel-1'); + const amp = fixture.doc.querySelector('#carousel-1'); expect(fixture.doc.body).to.have.class('amp-mode-mouse'); - let prevBtn = amp.querySelector('.amp-carousel-button-prev'); - let nextBtn = amp.querySelector('.amp-carousel-button-next'); + const prevBtn = amp.querySelector('.amp-carousel-button-prev'); + const nextBtn = amp.querySelector('.amp-carousel-button-next'); expect(prevBtn).to.be.hidden; expect(nextBtn).to.be.visible; }); @@ -61,11 +61,11 @@ describe('integration amp-carousel', () => { it.skip('should not be able to go past the first or last item', () => { return fixture.awaitEvent('amp:load:start', 1).then(() => { - let amp = fixture.doc.querySelector('#carousel-1'); + const amp = fixture.doc.querySelector('#carousel-1'); expect(fixture.doc.body).to.have.class('amp-mode-mouse'); - let prevBtn = amp.querySelector('.amp-carousel-button-prev'); - let nextBtn = amp.querySelector('.amp-carousel-button-next'); + const prevBtn = amp.querySelector('.amp-carousel-button-prev'); + const nextBtn = amp.querySelector('.amp-carousel-button-next'); prevBtn.style.visibility = 'visible'; nextBtn.style.visibility = 'visible'; expect(prevBtn).to.be.visible; @@ -88,11 +88,11 @@ describe('integration amp-carousel', () => { it.skip('(type=slide) should only have the next button visible when on ' + 'first item', () => { return fixture.awaitEvent('amp:load:start', 4).then(() => { - let amp = fixture.doc.querySelector('#carousel-4'); + const amp = fixture.doc.querySelector('#carousel-4'); expect(fixture.doc.body).to.have.class('amp-mode-mouse'); - let prevBtn = amp.querySelector('.amp-carousel-button-prev'); - let nextBtn = amp.querySelector('.amp-carousel-button-next'); + const prevBtn = amp.querySelector('.amp-carousel-button-prev'); + const nextBtn = amp.querySelector('.amp-carousel-button-next'); expect(prevBtn).to.be.hidden; expect(nextBtn).to.be.visible; }); @@ -101,10 +101,10 @@ describe('integration amp-carousel', () => { it.skip('should only have the prev button visible' + 'when on last item', () => { return fixture.awaitEvent('amp:load:start', 1).then(() => { - let amp = fixture.doc.querySelector('#carousel-1'); + const amp = fixture.doc.querySelector('#carousel-1'); expect(fixture.doc.body).to.have.class('amp-mode-mouse'); - let prevBtn = amp.querySelector('.amp-carousel-button-prev'); - let nextBtn = amp.querySelector('.amp-carousel-button-next'); + const prevBtn = amp.querySelector('.amp-carousel-button-prev'); + const nextBtn = amp.querySelector('.amp-carousel-button-next'); expect(prevBtn).to.be.hidden; expect(nextBtn).to.be.visible; nextBtn.click(); @@ -118,10 +118,10 @@ describe('integration amp-carousel', () => { it.skip('(type=slides) should only have the prev button visible when ' + 'on last item', () => { return fixture.awaitEvent('amp:load:start', 4).then(() => { - let amp = fixture.doc.querySelector('#carousel-4'); + const amp = fixture.doc.querySelector('#carousel-4'); expect(fixture.doc.body).to.have.class('amp-mode-mouse'); - let prevBtn = amp.querySelector('.amp-carousel-button-prev'); - let nextBtn = amp.querySelector('.amp-carousel-button-next'); + const prevBtn = amp.querySelector('.amp-carousel-button-prev'); + const nextBtn = amp.querySelector('.amp-carousel-button-next'); expect(prevBtn).to.be.hidden; expect(nextBtn).to.be.visible; nextBtn.click(); @@ -138,10 +138,10 @@ describe('integration amp-carousel', () => { it.skip('(type=slides loop) should always have a prev and next button be ' + 'able to get past the first and last item', () => { return fixture.awaitEvent('amp:load:start', 7).then(() => { - let amp = fixture.doc.querySelector('#carousel-7'); + const amp = fixture.doc.querySelector('#carousel-7'); expect(fixture.doc.body).to.have.class('amp-mode-mouse'); - let prevBtn = amp.querySelector('.amp-carousel-button-prev'); - let nextBtn = amp.querySelector('.amp-carousel-button-next'); + const prevBtn = amp.querySelector('.amp-carousel-button-prev'); + const nextBtn = amp.querySelector('.amp-carousel-button-next'); expect(prevBtn).to.not.have.class('-amp-disabled'); expect(nextBtn).to.not.have.class('-amp-disabled'); nextBtn.click(); @@ -167,11 +167,11 @@ describe('integration amp-carousel', () => { 'item', () => { return fixture.awaitEvent('amp:load:start', 2).then(() => { fixture.doc.body.classList.add('amp-mode-mouse'); - let amp = fixture.doc.querySelector('#carousel-2'); + const amp = fixture.doc.querySelector('#carousel-2'); expect(fixture.doc.body).to.have.class('amp-mode-mouse'); - let prevBtn = amp.querySelector('.amp-carousel-button-prev'); - let nextBtn = amp.querySelector('.amp-carousel-button-next'); + const prevBtn = amp.querySelector('.amp-carousel-button-prev'); + const nextBtn = amp.querySelector('.amp-carousel-button-next'); expect(prevBtn).to.be.hidden; expect(nextBtn).to.be.hidden; expect(prevBtn).to.have.class('amp-disabled'); @@ -183,11 +183,11 @@ describe('integration amp-carousel', () => { 'only a single item', () => { return fixture.awaitEvent('amp:load:start', 5).then(() => { fixture.doc.body.classList.add('amp-mode-mouse'); - let amp = fixture.doc.querySelector('#carousel-5'); + const amp = fixture.doc.querySelector('#carousel-5'); expect(fixture.doc.body).to.have.class('amp-mode-mouse'); - let prevBtn = amp.querySelector('.amp-carousel-button-prev'); - let nextBtn = amp.querySelector('.amp-carousel-button-next'); + const prevBtn = amp.querySelector('.amp-carousel-button-prev'); + const nextBtn = amp.querySelector('.amp-carousel-button-next'); expect(prevBtn).to.be.hidden; expect(nextBtn).to.be.hidden; expect(prevBtn).to.have.class('amp-disabled'); @@ -201,11 +201,11 @@ describe('integration amp-carousel', () => { it.skip('should not have the buttons visible', () => { return fixture.awaitEvent('amp:load:start', 1).then(() => { fixture.doc.body.classList.remove('amp-mode-mouse'); - let amp = fixture.doc.querySelector('#carousel-1'); + const amp = fixture.doc.querySelector('#carousel-1'); expect(fixture.doc.body).to.not.have.class('amp-mode-mouse'); - let prevBtn = amp.querySelector('.amp-carousel-button-prev'); - let nextBtn = amp.querySelector('.amp-carousel-button-next'); + const prevBtn = amp.querySelector('.amp-carousel-button-prev'); + const nextBtn = amp.querySelector('.amp-carousel-button-next'); expect(prevBtn).to.be.hidden; expect(nextBtn).to.be.hidden; }); @@ -214,11 +214,11 @@ describe('integration amp-carousel', () => { it.skip('(type=slides) should not have the buttons visible', () => { return fixture.awaitEvent('amp:load:start', 4).then(() => { fixture.doc.body.classList.remove('amp-mode-mouse'); - let amp = fixture.doc.querySelector('#carousel-4'); + const amp = fixture.doc.querySelector('#carousel-4'); expect(fixture.doc.body).to.not.have.class('amp-mode-mouse'); - let prevBtn = amp.querySelector('.amp-carousel-button-prev'); - let nextBtn = amp.querySelector('.amp-carousel-button-next'); + const prevBtn = amp.querySelector('.amp-carousel-button-prev'); + const nextBtn = amp.querySelector('.amp-carousel-button-next'); expect(prevBtn).to.be.hidden; expect(nextBtn).to.be.hidden; }); @@ -231,14 +231,14 @@ describe('integration amp-carousel', () => { 'is not on body', () => { return fixture.awaitEvent('amp:load:start', 3).then(() => { fixture.doc.body.classList.remove('amp-mode-mouse'); - let amp = fixture.doc.querySelector('#carousel-3'); + const amp = fixture.doc.querySelector('#carousel-3'); expect(fixture.doc.body).to.not.have.class('amp-mode-mouse'); expect(amp).to.have.attribute('controls'); expect(amp).to.have.class('-amp-carousel-has-controls'); - let prevBtn = amp.querySelector('.amp-carousel-button-prev'); - let nextBtn = amp.querySelector('.amp-carousel-button-next'); + const prevBtn = amp.querySelector('.amp-carousel-button-prev'); + const nextBtn = amp.querySelector('.amp-carousel-button-next'); expect(prevBtn).to.be.hidden; expect(nextBtn).to.be.visible; }); @@ -248,14 +248,14 @@ describe('integration amp-carousel', () => { 'even when `amp-mode-mouse` is not on body', () => { return fixture.awaitEvent('amp:load:start', 6).then(() => { fixture.doc.body.classList.remove('amp-mode-mouse'); - let amp = fixture.doc.querySelector('#carousel-6'); + const amp = fixture.doc.querySelector('#carousel-6'); expect(fixture.doc.body).to.not.have.class('amp-mode-mouse'); expect(amp).to.have.attribute('controls'); expect(amp).to.have.class('-amp-carousel-has-controls'); - let prevBtn = amp.querySelector('.amp-carousel-button-prev'); - let nextBtn = amp.querySelector('.amp-carousel-button-next'); + const prevBtn = amp.querySelector('.amp-carousel-button-prev'); + const nextBtn = amp.querySelector('.amp-carousel-button-next'); expect(prevBtn).to.be.hidden; expect(nextBtn).to.be.visible; }); diff --git a/testing/iframe.js b/testing/iframe.js index 668a31a80692..6389cb6490c0 100644 --- a/testing/iframe.js +++ b/testing/iframe.js @@ -86,7 +86,7 @@ export function createFixtureIframe(fixture, initialIframeHeight, done) { }); }; // Record firing of custom events. - for (let name in events) { + for (const name in events) { win.addEventListener(name, () => { events[name]++; });