From eb00810e5effd5392115905759376217e418600b Mon Sep 17 00:00:00 2001 From: Erwin Mombay Date: Mon, 9 Nov 2015 17:25:09 -0800 Subject: [PATCH] switch `var` to `let` or `const` --- .eslintrc | 1 + 3p/integration.js | 12 +++--- 3p/twitter.js | 12 +++--- ads/adreactor.js | 2 +- ads/adsense.js | 4 +- ads/adtech.js | 2 +- ads/doubleclick.js | 6 +-- build-system/config.js | 6 ++- builtins/amp-ad.js | 2 +- builtins/amp-img.js | 3 -- builtins/amp-pixel.js | 6 +-- .../amp-audio/0.1/test/test-amp-audio.js | 18 ++++---- extensions/amp-carousel/0.1/carousel.js | 6 +-- extensions/amp-carousel/0.1/slides.js | 12 +++--- extensions/amp-fit-text/0.1/amp-fit-text.js | 2 +- .../0.1/test/test-amp-fit-text.js | 6 +-- extensions/amp-iframe/0.1/amp-iframe.js | 27 ++++++------ .../amp-iframe/0.1/test/test-amp-iframe.js | 16 +++---- .../0.1/test/test-amp-image-lightbox.js | 2 +- extensions/amp-instagram/0.1/amp-instagram.js | 8 ++-- .../0.1/test/test-amp-instagram.js | 8 ++-- .../0.1/test/test-amp-pinterest.js | 6 +-- extensions/amp-slides/0.1/amp-slides.js | 14 +++---- extensions/amp-twitter/0.1/amp-twitter.js | 4 +- extensions/amp-youtube/0.1/amp-youtube.js | 8 ++-- .../amp-youtube/0.1/test/test-amp-youtube.js | 6 +-- src/3p-frame.js | 42 +++++++++---------- src/3p.js | 6 +-- src/asserts.js | 18 ++++---- src/curve.js | 28 ++++++------- src/custom-element.js | 12 +++--- src/document-state.js | 2 +- src/error.js | 12 +++--- src/exponential-backoff.js | 6 +-- src/gesture-recognizers.js | 10 ++--- src/history.js | 4 +- src/layout-rect.js | 2 +- src/log.js | 8 ++-- src/mode.js | 10 ++--- src/pass.js | 4 +- src/resources.js | 6 +-- src/runtime.js | 2 +- src/service.js | 4 +- src/size-list.js | 2 +- src/srcset.js | 2 +- src/styles.js | 16 +++---- src/timer.js | 8 ++-- src/url.js | 8 ++-- src/uuid.js | 4 +- src/validator-integration.js | 4 +- src/viewer.js | 4 +- src/viewport.js | 28 ++++++------- test/_init_tests.js | 36 ++++++++-------- test/functional/test-3p-frame.js | 24 +++++------ test/functional/test-action.js | 10 ++--- test/functional/test-amp-ad.js | 28 ++++++------- test/functional/test-amp-pixel.js | 4 +- test/functional/test-amp-video.js | 32 +++++++------- test/functional/test-asserts.js | 8 ++-- test/functional/test-document-info.js | 2 +- test/functional/test-error.js | 24 +++++------ test/functional/test-event-helper.js | 2 +- test/functional/test-exponential-backoff.js | 8 ++-- test/functional/test-layout.js | 2 +- test/functional/test-pass.js | 2 +- test/functional/test-preconnect.js | 2 +- test/functional/test-service.js | 10 ++--- test/functional/test-size-list.js | 10 ++--- test/functional/test-srcset.js | 2 +- test/functional/test-timer.js | 6 +-- test/functional/test-url.js | 8 ++-- test/functional/test-viewer.js | 2 +- test/functional/test-viewport.js | 4 +- test/functional/test-vsync.js | 4 +- test/integration/test-amp-img.js | 8 ++-- test/integration/test-errors.js | 4 +- test/integration/test-example-validation.js | 22 +++++----- test/integration/test-released.js | 2 +- testing/iframe.js | 22 +++++----- 79 files changed, 371 insertions(+), 368 deletions(-) diff --git a/.eslintrc b/.eslintrc index 0961c79c998f..7e90aeb4eff6 100644 --- a/.eslintrc +++ b/.eslintrc @@ -50,6 +50,7 @@ "no-unused-expressions": 0, "no-useless-call": 2, "no-useless-concat": 2, + "no-var": 2, "no-warning-comments": [2, { "terms": ["do not submit"], "location": "anywhere" }], "object-curly-spacing": [2, "never", { "objectsInObjects": false, diff --git a/3p/integration.js b/3p/integration.js index 3229ff7d5ba8..8ca7ab19badf 100644 --- a/3p/integration.js +++ b/3p/integration.js @@ -50,7 +50,7 @@ register('twitter', twitter); * @param {!Object} data */ export function draw3p(win, data) { - var type = data.type; + const type = data.type; assert(window.context.location.originValidated != null, 'Origin should have been validated'); run(type, win, data); @@ -65,8 +65,8 @@ export function draw3p(win, data) { */ function masterSelection(type) { // The master has a special name. - var masterName = 'frame_' + type + '_master'; - var master; + const masterName = 'frame_' + type + '_master'; + let master; try { // Try to get the master from the parent. If it does not // exist yet we get a security exception that we catch @@ -87,8 +87,8 @@ function masterSelection(type) { * Draws an optionally synchronously to the DOM. */ window.draw3p = function() { - var fragment = location.hash; - var data = fragment ? JSON.parse(fragment.substr(1)) : {}; + const fragment = location.hash; + const data = fragment ? JSON.parse(fragment.substr(1)) : {}; window.context = data._context; window.context.location = parseUrl(data._context.location.href); validateParentOrigin(window, window.context.location); @@ -120,7 +120,7 @@ function triggerDimensions(width, height) { } function nonSensitiveDataPostMessage(type, opt_object) { - var object = opt_object || {}; + const object = opt_object || {}; object.type = type; object.sentinel = 'amp-3p'; window.parent./*OK*/postMessage(object, diff --git a/3p/twitter.js b/3p/twitter.js index 44da15c21c53..c337e9f3c1de 100644 --- a/3p/twitter.js +++ b/3p/twitter.js @@ -50,10 +50,10 @@ function getTwttr(global, cb) { * @param {!Object} data */ export function twitter(global, data) { - var tweet = document.createElement('div'); + const tweet = document.createElement('div'); tweet.id = 'tweet'; - var width = data.initialWindowWidth; - var height = data.initialWindowHeight; + const width = data.initialWindowWidth; + const height = data.initialWindowHeight; tweet.style.width = '100%'; global.document.getElementById('c').appendChild(tweet); getTwttr(global, function(twttr) { @@ -61,7 +61,7 @@ export function twitter(global, data) { delete data.width; delete data.height; twttr.widgets.createTweet(data.tweetid, tweet, data)./*OK*/then(() => { - var iframe = global.document.querySelector('#c iframe'); + const iframe = global.document.querySelector('#c iframe'); // Unfortunately the tweet isn't really done at this time. // We listen for resize to learn when things are // really done. @@ -74,8 +74,8 @@ export function twitter(global, data) { function render() { - var iframe = global.document.querySelector('#c iframe'); - var body = iframe.contentWindow.document.body; + const iframe = global.document.querySelector('#c iframe'); + const body = iframe.contentWindow.document.body; context.updateDimensions( body./*OK*/offsetWidth, body./*OK*/offsetHeight + /* margins */ 20); diff --git a/ads/adreactor.js b/ads/adreactor.js index d1ea47706a38..bc6f2b54003f 100644 --- a/ads/adreactor.js +++ b/ads/adreactor.js @@ -21,7 +21,7 @@ import {writeScript} from '../src/3p'; * @param {!Object} data */ export function adreactor(global, data) { - var url = 'https://adserver.adreactor.com' + + const url = 'https://adserver.adreactor.com' + '/servlet/view/banner/javascript/zone?' + 'zid=' + encodeURIComponent(data.zid) + '&pid=' + encodeURIComponent(data.pid) + diff --git a/ads/adsense.js b/ads/adsense.js index 0d32107a0992..c8c9d1257dcf 100644 --- a/ads/adsense.js +++ b/ads/adsense.js @@ -23,11 +23,11 @@ import {writeScript} from '../src/3p'; export function adsense(global, data) { /*eslint "google-camelcase/google-camelcase": 0*/ global.google_page_url = global.context.canonicalUrl; - var s = document.createElement('script'); + const s = document.createElement('script'); s.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js'; global.document.body.appendChild(s); - var i = document.createElement('ins'); + const i = document.createElement('ins'); i.setAttribute('data-ad-client', data['adClient']); if (data['adSlot']) { i.setAttribute('data-ad-slot', data['adSlot']); diff --git a/ads/adtech.js b/ads/adtech.js index 2320fc64171d..1f6c261fb008 100644 --- a/ads/adtech.js +++ b/ads/adtech.js @@ -21,7 +21,7 @@ import {writeScript, validateSrcPrefix, validateSrcContains} from '../src/3p'; * @param {!Object} data */ export function adtech(global, data) { - var src = data.src; + const src = data.src; validateSrcPrefix('https:', src); validateSrcContains('/addyn/', src); writeScript(global, src); diff --git a/ads/doubleclick.js b/ads/doubleclick.js index 80d7319aa505..b4e6c95b158d 100644 --- a/ads/doubleclick.js +++ b/ads/doubleclick.js @@ -23,18 +23,18 @@ import {loadScript} from '../src/3p'; export function doubleclick(global, data) { loadScript(global, 'https://www.googletagservices.com/tag/js/gpt.js', () => { global.googletag.cmd.push(function() { - var dimensions = [[ + const dimensions = [[ parseInt(data.width, 10), parseInt(data.height, 10) ]]; - var slot = googletag.defineSlot(data.slot, dimensions, 'c') + const slot = googletag.defineSlot(data.slot, dimensions, 'c') .addService(googletag.pubads()); googletag.pubads().enableSingleRequest(); googletag.pubads().set('page_url', context.canonicalUrl); googletag.enableServices(); if (data.targeting) { - for (var key in data.targeting) { + for (const key in data.targeting) { slot.setTargeting(key, data.targeting[key]); } } diff --git a/build-system/config.js b/build-system/config.js index 93ff3295c87b..9185f484f2e2 100644 --- a/build-system/config.js +++ b/build-system/config.js @@ -96,7 +96,11 @@ module.exports = { karma: karma, lintGlobs: [ '**/*.js', - '!{node_modules,build,dist,dist.3p,third_party,build-system}/**/*.*' + '!{node_modules,build,dist,dist.3p,third_party,build-system}/**/*.*', + '!{testing,examples}/**/*.*', + '!gulpfile.js', + '!karma.conf.js', + '!**/local-amp-chrome-extension/background.js', ], presubmitGlobs: [ '**/*.{css,js}', diff --git a/builtins/amp-ad.js b/builtins/amp-ad.js index f6d4c19528d7..385660aa9a3f 100644 --- a/builtins/amp-ad.js +++ b/builtins/amp-ad.js @@ -371,7 +371,7 @@ export function installAd(win) { a.href = 'https://www.ampproject.org'; a.target = '_blank'; a.setAttribute('fallback', ''); - var img = new Image(); + const img = new Image(); setStyles(img, { width: 'auto', height: '100%', diff --git a/builtins/amp-img.js b/builtins/amp-img.js index 9bb0a62dc52c..b9558b2ddc81 100644 --- a/builtins/amp-img.js +++ b/builtins/amp-img.js @@ -28,9 +28,6 @@ import {registerElement} from '../src/custom-element'; */ export function installImg(win) { - /** @type {number} Count of images */ - var count = 0; - class AmpImg extends BaseElement { /** @override */ diff --git a/builtins/amp-pixel.js b/builtins/amp-pixel.js index 70141031d158..aba052807892 100644 --- a/builtins/amp-pixel.js +++ b/builtins/amp-pixel.js @@ -122,16 +122,16 @@ export function installPixel(win) { /** @override */ layoutCallback() { - var src = this.element.getAttribute('src'); + let src = this.element.getAttribute('src'); src = this.assertSource(src); src = src.replace(REPLACEMENT_EXPR, function(match, name) { - var val = REPLACEMENTS[name](); + let val = REPLACEMENTS[name](); if (!val && val !== 0) { val = ''; } return encodeURIComponent(val); }); - var image = new Image(); + const image = new Image(); image.src = src; image.width = 1; image.height = 1; 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 c35df92eddb4..e537f1481a2e 100644 --- a/extensions/amp-audio/0.1/test/test-amp-audio.js +++ b/extensions/amp-audio/0.1/test/test-amp-audio.js @@ -24,9 +24,9 @@ require('../amp-audio'); adopt(window); describe('amp-audio', () => { - var iframe; - var ampAudio; - var sandbox; + let iframe; + let ampAudio; + let sandbox; beforeEach(() => { sandbox = sinon.sandbox.create(); @@ -43,7 +43,7 @@ describe('amp-audio', () => { function getAmpAudio(attributes, opt_childNodesAttrs) { ampAudio = iframe.doc.createElement('amp-audio'); - for (var key in attributes) { + for (const key in attributes) { ampAudio.setAttribute(key, attributes[key]); } if (opt_childNodesAttrs) { @@ -66,7 +66,7 @@ describe('amp-audio', () => { } function attachAndRun(attributes, opt_childNodesAttrs) { - var ampAudio = getAmpAudio(attributes, opt_childNodesAttrs); + const ampAudio = getAmpAudio(attributes, opt_childNodesAttrs); naturalDimensions_['AMP-AUDIO'] = {width: 300, height: 30}; return iframe.addElement(ampAudio); } @@ -75,7 +75,7 @@ describe('amp-audio', () => { return attachAndRun({ src: 'https://origin.com/audio.mp3' }).then(a => { - var audio = a.querySelector('audio'); + const audio = a.querySelector('audio'); expect(audio).to.be.an.instanceof(Element); expect(audio.tagName).to.equal('AUDIO'); expect(audio.getAttribute('src')) @@ -99,7 +99,7 @@ describe('amp-audio', () => { {tag: 'source', src: 'https://origin.com/audio.ogg', type: 'audio/ogg'}, {tag: 'text', text: 'Unsupported.'}, ]).then(a => { - var audio = a.querySelector('audio'); + const audio = a.querySelector('audio'); expect(audio).to.be.an.instanceof(Element); expect(audio.tagName).to.equal('AUDIO'); expect(a.getAttribute('width')).to.be.equal('503'); @@ -124,7 +124,7 @@ describe('amp-audio', () => { it('should set its dimensions to the browser natural', () => { return attachAndRun({}).then(a => { - var audio = a.querySelector('audio'); + const audio = a.querySelector('audio'); expect(a.style.width).to.be.equal('300px'); expect(a.style.height).to.be.equal('30px'); if (/Safari|Firefox/.test(navigator.userAgent)) { @@ -141,7 +141,7 @@ describe('amp-audio', () => { return attachAndRun({ 'width': '500' }).then(a => { - var audio = a.querySelector('audio'); + const audio = a.querySelector('audio'); expect(a.style.width).to.be.equal('500px'); expect(a.style.height).to.be.equal('30px'); }); diff --git a/extensions/amp-carousel/0.1/carousel.js b/extensions/amp-carousel/0.1/carousel.js index ecc87ae7327d..18cb888f793b 100644 --- a/extensions/amp-carousel/0.1/carousel.js +++ b/extensions/amp-carousel/0.1/carousel.js @@ -78,9 +78,9 @@ export class AmpCarousel extends BaseCarousel { /** @override */ goCallback(dir, animate) { - var newPos = this.nextPos_(this.pos_, dir); + const newPos = this.nextPos_(this.pos_, dir); if (newPos != this.pos_) { - var oldPos = this.pos_; + const oldPos = this.pos_; this.pos_ = newPos; if (!animate) { @@ -160,7 +160,7 @@ export class AmpCarousel extends BaseCarousel { * @private */ preloadNext_(pos, dir) { - var nextPos = this.nextPos_(pos, dir); + const nextPos = this.nextPos_(pos, dir); if (nextPos != pos) { this.withinWindow_(nextPos, cell => { this.schedulePreload(cell); diff --git a/extensions/amp-carousel/0.1/slides.js b/extensions/amp-carousel/0.1/slides.js index 170c8e5bd133..997bcdfdc7cb 100644 --- a/extensions/amp-carousel/0.1/slides.js +++ b/extensions/amp-carousel/0.1/slides.js @@ -77,10 +77,10 @@ export class AmpSlides extends BaseCarousel { /** @override */ goCallback(dir, animate) { - var newIndex = this.nextIndex_(dir); + const newIndex = this.nextIndex_(dir); if (newIndex != this.currentIndex_) { - var newSlide = this.slides_[newIndex]; - var oldSlide = this.slides_[this.currentIndex_]; + const newSlide = this.slides_[newIndex]; + const oldSlide = this.slides_[this.currentIndex_]; this.currentIndex_ = newIndex; this.prepareSlide_(newSlide, dir); if (!animate) { @@ -158,7 +158,7 @@ export class AmpSlides extends BaseCarousel { * @param {number} dir */ prepareSlide_(slide, dir) { - var containerWidth = this.element./*OK*/offsetWidth; + const containerWidth = this.element./*OK*/offsetWidth; st.setStyles(slide, { transform: st.translateX(dir * containerWidth), zIndex: 1, @@ -175,7 +175,7 @@ export class AmpSlides extends BaseCarousel { * @return {!Transition} */ createTransition_(oldSlide, newSlide, dir) { - var containerWidth = this.element./*OK*/offsetWidth; + const containerWidth = this.element./*OK*/offsetWidth; return tr.all([ tr.setStyles(newSlide, { transform: tr.translateX(tr.numeric(dir * containerWidth, 0)), @@ -233,7 +233,7 @@ export class AmpSlides extends BaseCarousel { preloadNext_(dir) { // TODO(dvoytenko): can we actually preload it here? There's no // guarantee of it has display!=none. - var nextIndex = this.nextIndex_(dir); + const nextIndex = this.nextIndex_(dir); if (nextIndex != this.currentIndex_) { this.schedulePreload(this.slides_[nextIndex]); } 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 2828d5850272..eb2572534482 100644 --- a/extensions/amp-fit-text/0.1/amp-fit-text.js +++ b/extensions/amp-fit-text/0.1/amp-fit-text.js @@ -36,7 +36,7 @@ class AmpFitText extends AMP.BaseElement { /** @override */ buildCallback() { - var childNodes = this.getRealChildNodes(); + const childNodes = this.getRealChildNodes(); /** @private @const */ this.content_ = document.createElement('div'); 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 276d8a6be926..37f30dae0770 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 @@ -28,7 +28,7 @@ describe('amp-fit-text component', () => { function getFitText(text, opt_responsive) { return createIframePromise().then(iframe => { - var ft = iframe.doc.createElement('amp-fit-text'); + const ft = iframe.doc.createElement('amp-fit-text'); ft.setAttribute('width', '111'); ft.setAttribute('height', '222'); ft.style.fontFamily = 'Arial'; @@ -51,9 +51,9 @@ describe('amp-fit-text component', () => { } it('renders', () => { - var text = 'Lorem ipsum'; + const text = 'Lorem ipsum'; return getFitText(text).then(ft => { - var content = ft.querySelector('.-amp-fit-text-content'); + const content = ft.querySelector('.-amp-fit-text-content'); expect(content).to.not.equal(null); expect(content.textContent).to.equal(text); }); diff --git a/extensions/amp-iframe/0.1/amp-iframe.js b/extensions/amp-iframe/0.1/amp-iframe.js index 4e74506bec21..05230609123c 100644 --- a/extensions/amp-iframe/0.1/amp-iframe.js +++ b/extensions/amp-iframe/0.1/amp-iframe.js @@ -24,7 +24,7 @@ import {parseUrl} from '../../../src/url'; const TAG_ = 'AmpIframe'; /** @type {number} */ -var count = 0; +let count = 0; /** @const */ const assert = AMP.assert; @@ -36,14 +36,14 @@ class AmpIframe extends AMP.BaseElement { } assertSource(src, containerSrc, sandbox) { - var url = parseUrl(src); + const url = parseUrl(src); assert( url.protocol == 'https:' || url.protocol == 'data:' || url.origin.indexOf('http://iframe.localhost:') == 0, 'Invalid src. Must start with https://. Found %s', this.element); - var containerUrl = parseUrl(containerSrc); + const containerUrl = parseUrl(containerSrc); assert( !((' ' + sandbox + ' ').match(/\s+allow-same-origin\s+/)) || url.origin != containerUrl.origin, @@ -54,8 +54,8 @@ class AmpIframe extends AMP.BaseElement { } assertPosition() { - var pos = this.element.getLayoutBox(); - var minTop = Math.min(600, this.getViewport().getSize().height * .75); + const pos = this.element.getLayoutBox(); + const minTop = Math.min(600, this.getViewport().getSize().height * .75); assert(pos.top >= minTop, ' elements must be positioned outside the first 75% ' + 'of the viewport or 600px from the top (whichever is smaller): %s ' + @@ -77,11 +77,11 @@ class AmpIframe extends AMP.BaseElement { * @return {string} Data URI for the srcdoc */ transformSrcDoc() { - var srcdoc = this.element.getAttribute('srcdoc'); + const srcdoc = this.element.getAttribute('srcdoc'); if (!srcdoc) { return; } - var sandbox = this.element.getAttribute('sandbox'); + const sandbox = this.element.getAttribute('sandbox'); assert( !((' ' + sandbox + ' ').match(/\s+allow-same-origin\s+/)), 'allow-same-origin is not allowed with the srcdoc attribute %s.', @@ -91,7 +91,8 @@ class AmpIframe extends AMP.BaseElement { /** @override */ firstAttachedCallback() { - var iframeSrc = this.element.getAttribute('src') || this.transformSrcDoc(); + const iframeSrc = this.element.getAttribute('src') || + this.transformSrcDoc(); this.iframeSrc = this.assertSource(iframeSrc, window.location.href, this.element.getAttribute('sandbox')); this.preconnect.url(this.iframeSrc); @@ -115,9 +116,9 @@ class AmpIframe extends AMP.BaseElement { return Promise.resolve(); } - var width = this.element.getAttribute('width'); - var height = this.element.getAttribute('height'); - var iframe = document.createElement('iframe'); + const width = this.element.getAttribute('width'); + const height = this.element.getAttribute('height'); + const iframe = document.createElement('iframe'); /** @private @const {!HTMLIFrameElement} */ this.iframe_ = iframe; @@ -194,7 +195,7 @@ class AmpIframe extends AMP.BaseElement { * @param {!Element} iframe */ function setSandbox(element, iframe) { - var allows = element.getAttribute('sandbox') || ''; + const allows = element.getAttribute('sandbox') || ''; iframe.setAttribute('sandbox', allows); } @@ -208,7 +209,7 @@ function setSandbox(element, iframe) { */ function makeIOsScrollable(element, iframe) { if (element.getAttribute('scrolling') != 'no') { - var wrapper = document.createElement('i-amp-scroll-container'); + const wrapper = document.createElement('i-amp-scroll-container'); wrapper.appendChild(iframe); return wrapper; } 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 8b66b8714ecd..24dad5c6ce2f 100644 --- a/extensions/amp-iframe/0.1/test/test-amp-iframe.js +++ b/extensions/amp-iframe/0.1/test/test-amp-iframe.js @@ -25,11 +25,11 @@ adopt(window); describe('amp-iframe', () => { - var iframeSrc = 'http://iframe.localhost:' + location.port + + const iframeSrc = 'http://iframe.localhost:' + location.port + '/base/test/fixtures/served/iframe.html'; - var timer = new Timer(window); - var ranJs = 0; + const timer = new Timer(window); + let ranJs = 0; beforeEach(() => { ranJs = 0; }); @@ -42,14 +42,14 @@ describe('amp-iframe', () => { function getAmpIframe(attributes, opt_top, opt_height, opt_translateY) { return createIframePromise().then(function(iframe) { - var i = iframe.doc.createElement('amp-iframe'); - for (var key in attributes) { + const i = iframe.doc.createElement('amp-iframe'); + for (const key in attributes) { i.setAttribute(key, attributes[key]); } if (opt_height) { iframe.iframe.style.height = opt_height; } - var top = opt_top || '600px'; + const top = opt_top || '600px'; i.style.position = 'absolute'; i.style.top = top; if (opt_translateY) { @@ -63,7 +63,7 @@ describe('amp-iframe', () => { iframe.doc.body.appendChild(i); // Wait an event loop for the iframe to be created. return pollForLayout(iframe.win, 1).then(() => { - var created = i.querySelector('iframe'); + const created = i.querySelector('iframe'); if (created) { // Wait for the iframe to load return loadPromise(created).then(() => { @@ -176,7 +176,7 @@ describe('amp-iframe', () => { }); it('should allow data-uri', () => { - var dataUri = 'data:text/html;charset=utf-8;base64,' + + const dataUri = 'data:text/html;charset=utf-8;base64,' + 'PHNjcmlwdD5kb2N1bWVudC53cml0ZSgnUiAnICsgZG9jdW1lbnQucmVmZXJyZXIgK' + 'yAnLCAnICsgbG9jYXRpb24uaHJlZik8L3NjcmlwdD4='; return getAmpIframe({ 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 a848cb1ea33e..db9f47bb0d7d 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 @@ -30,7 +30,7 @@ describe('amp-image-lightbox component', () => { function getImageLightbox() { return createIframePromise().then(iframe => { - var el = iframe.doc.createElement('amp-image-lightbox'); + const el = iframe.doc.createElement('amp-image-lightbox'); el.setAttribute('layout', 'nodisplay'); iframe.doc.body.appendChild(el); return new Timer(window).promise(16).then(() => { diff --git a/extensions/amp-instagram/0.1/amp-instagram.js b/extensions/amp-instagram/0.1/amp-instagram.js index 6a95a182c162..65fee4bb4b4f 100644 --- a/extensions/amp-instagram/0.1/amp-instagram.js +++ b/extensions/amp-instagram/0.1/amp-instagram.js @@ -51,16 +51,16 @@ class AmpInstagram extends AMP.BaseElement { /** @override */ layoutCallback() { - var width = this.element.getAttribute('width'); - var height = this.element.getAttribute('height'); - var shortcode = AMP.assert( + const width = this.element.getAttribute('width'); + const height = this.element.getAttribute('height'); + const shortcode = AMP.assert( (this.element.getAttribute('data-shortcode') || this.element.getAttribute('shortcode')), 'The data-shortcode attribute is required for %s', this.element); // See // https://instagram.com/developer/embedding/?hl=en - var iframe = document.createElement('iframe'); + const iframe = document.createElement('iframe'); iframe.setAttribute('frameborder', '0'); iframe.setAttribute('allowtransparency', 'true'); iframe.src = 'https://instagram.com/p/' + diff --git a/extensions/amp-instagram/0.1/test/test-amp-instagram.js b/extensions/amp-instagram/0.1/test/test-amp-instagram.js index 96e49041ce97..f338b61ac4dd 100644 --- a/extensions/amp-instagram/0.1/test/test-amp-instagram.js +++ b/extensions/amp-instagram/0.1/test/test-amp-instagram.js @@ -24,7 +24,7 @@ describe('amp-instagram', () => { function getIns(shortcode, opt_responsive) { return createIframePromise().then(() => { - var ins = iframe.doc.createElement('amp-instagram'); + const ins = iframe.doc.createElement('amp-instagram'); ins.setAttribute('data-shortcode', shortcode); ins.setAttribute('width', '111'); ins.setAttribute('height', '222'); @@ -37,7 +37,7 @@ describe('amp-instagram', () => { it('renders', () => { getIns('fBwFP').then(ins => { - var iframe = ins.firstChild; + const iframe = ins.firstChild; expect(iframe).to.not.be.null; expect(iframe.tagName).to.equal('IFRAME'); expect(iframe.src).to.equal('https://instagram.com/p/fBwFP/embed/?v=4'); @@ -47,8 +47,8 @@ describe('amp-instagram', () => { }); it('renders responsively', () => { - var ins = getIns('fBwFP', true).then(ins => { - var iframe = ins.firstChild; + const ins = getIns('fBwFP', true).then(ins => { + const iframe = ins.firstChild; expect(iframe.className).to.match(/amp-responsive-item/); }); }); diff --git a/extensions/amp-pinterest/0.1/test/test-amp-pinterest.js b/extensions/amp-pinterest/0.1/test/test-amp-pinterest.js index 8b8149a4eace..0ce2fc880789 100644 --- a/extensions/amp-pinterest/0.1/test/test-amp-pinterest.js +++ b/extensions/amp-pinterest/0.1/test/test-amp-pinterest.js @@ -24,7 +24,7 @@ function createDivPromise() { return new Promise(function(resolve, reject) { - var div = document.createElement('div'); + const div = document.createElement('div'); resolve({ div: div, addElement: function(element) { @@ -41,7 +41,7 @@ function getPin(pinDo, pinUrl, pinMedia, pinDescription) { return createDivPromise().then(div => { - var pin = document.createElement('amp-pinterest'); + const pin = document.createElement('amp-pinterest'); pin.setAttribute('data-do', pinDo); pin.setAttribute('data-url', pinUrl); // force the guid to a known value so test will pass @@ -58,7 +58,7 @@ 'http://c2.staticflickr.com/8/7027/6851755809_df5b2051c9_b.jpg', 'Next stop: Pinterest' ).then(pin => { - var a = pin.querySelector('a'); + const a = pin.querySelector('a'); expect(a).to.not.be.null; expect(a.tagName).to.equal('A'); expect(a.href).to.equal('https://www.pinterest.com/pin/create/' + diff --git a/extensions/amp-slides/0.1/amp-slides.js b/extensions/amp-slides/0.1/amp-slides.js index a5260c516688..90976b746911 100644 --- a/extensions/amp-slides/0.1/amp-slides.js +++ b/extensions/amp-slides/0.1/amp-slides.js @@ -111,13 +111,13 @@ class AmpSlides extends AMP.BaseElement { * @param {boolean} animate */ go(dir, animate) { - var newIndex = this.nextIndex_(dir); + const newIndex = this.nextIndex_(dir); if (newIndex != this.currentIndex_) { - var newSlide = this.slides_[newIndex]; - var oldSlide = this.slides_[this.currentIndex_]; + const newSlide = this.slides_[newIndex]; + const oldSlide = this.slides_[this.currentIndex_]; this.currentIndex_ = newIndex; this.prepareSlide_(newSlide, dir); - var containerWidth = this.element./*OK*/offsetWidth; + const containerWidth = this.element./*OK*/offsetWidth; if (!animate) { this.commitSwitch_(oldSlide, newSlide); } else { @@ -136,7 +136,7 @@ class AmpSlides extends AMP.BaseElement { * @param {number} dir */ prepareSlide_(slide, dir) { - var containerWidth = this.element./*OK*/offsetWidth; + const containerWidth = this.element./*OK*/offsetWidth; st.setStyles(slide, { transform: st.translateX(dir * containerWidth), zIndex: 1, @@ -153,7 +153,7 @@ class AmpSlides extends AMP.BaseElement { * @return {!Transition} */ createTransition_(oldSlide, newSlide, dir) { - var containerWidth = this.element./*OK*/offsetWidth; + const containerWidth = this.element./*OK*/offsetWidth; return tr.all([ tr.setStyles(newSlide, { transform: tr.translateX(tr.numeric(dir * containerWidth, 0)), @@ -209,7 +209,7 @@ class AmpSlides extends AMP.BaseElement { preloadNext_(dir) { // TODO(dvoytenko): can we actually preload it here? There's no // guarantee of it has display!=none. - var nextIndex = this.nextIndex_(dir); + const nextIndex = this.nextIndex_(dir); if (nextIndex != this.currentIndex_) { this.schedulePreload(this.slides_[nextIndex]); } diff --git a/extensions/amp-twitter/0.1/amp-twitter.js b/extensions/amp-twitter/0.1/amp-twitter.js index a333a5cbc262..a2818d8d6236 100644 --- a/extensions/amp-twitter/0.1/amp-twitter.js +++ b/extensions/amp-twitter/0.1/amp-twitter.js @@ -38,7 +38,7 @@ class AmpTwitter extends AMP.BaseElement { /** @override */ layoutCallback() { // TODO(malteubl): Preconnect to twitter. - var iframe = getIframe(this.element.ownerDocument.defaultView, + const iframe = getIframe(this.element.ownerDocument.defaultView, this.element, 'twitter'); this.applyFillContent(iframe); this.element.appendChild(iframe); @@ -46,7 +46,7 @@ class AmpTwitter extends AMP.BaseElement { listen(iframe, 'embed-size', data => { iframe.height = data.height; iframe.width = data.width; - var amp = iframe.parentElement; + const amp = iframe.parentElement; amp.setAttribute('height', data.height); amp.setAttribute('width', data.width); this.changeHeight(data.height); diff --git a/extensions/amp-youtube/0.1/amp-youtube.js b/extensions/amp-youtube/0.1/amp-youtube.js index 9f4117b43db9..a45fe9030486 100644 --- a/extensions/amp-youtube/0.1/amp-youtube.js +++ b/extensions/amp-youtube/0.1/amp-youtube.js @@ -32,17 +32,17 @@ class AmpYoutube extends AMP.BaseElement { /** @override */ layoutCallback() { - var width = this.element.getAttribute('width'); - var height = this.element.getAttribute('height'); + const width = this.element.getAttribute('width'); + const height = this.element.getAttribute('height'); // The video-id is supported only for backward compatibility. - var videoid = AMP.assert( + const videoid = AMP.assert( (this.element.getAttribute('data-videoid') || this.element.getAttribute('video-id')), 'The data-videoid attribute is required for %s', this.element); // See // https://developers.google.com/youtube/iframe_api_reference - var iframe = document.createElement('iframe'); + const iframe = document.createElement('iframe'); iframe.setAttribute('frameborder', '0'); iframe.setAttribute('allowfullscreen', 'true'); iframe.src = 'https://www.youtube.com/embed/' + encodeURIComponent( diff --git a/extensions/amp-youtube/0.1/test/test-amp-youtube.js b/extensions/amp-youtube/0.1/test/test-amp-youtube.js index e5082d1bf1b9..7754daefc65c 100644 --- a/extensions/amp-youtube/0.1/test/test-amp-youtube.js +++ b/extensions/amp-youtube/0.1/test/test-amp-youtube.js @@ -24,7 +24,7 @@ describe('amp-youtube', () => { function getYt(videoId, opt_responsive) { return createIframePromise().then(iframe => { - var yt = iframe.doc.createElement('amp-youtube'); + const yt = iframe.doc.createElement('amp-youtube'); yt.setAttribute('data-videoid', videoId); yt.setAttribute('width', '111'); yt.setAttribute('height', '222'); @@ -39,7 +39,7 @@ describe('amp-youtube', () => { it('renders', () => { return getYt('mGENRKrdoGY').then(yt => { - var iframe = yt.querySelector('iframe'); + const iframe = yt.querySelector('iframe'); expect(iframe).to.not.be.null; expect(iframe.tagName).to.equal('IFRAME'); expect(iframe.src).to.equal( @@ -51,7 +51,7 @@ describe('amp-youtube', () => { it('renders responsively', () => { return getYt('mGENRKrdoGY', true).then(yt => { - var iframe = yt.querySelector('iframe'); + const iframe = yt.querySelector('iframe'); expect(iframe).to.not.be.null; expect(iframe.className).to.match(/-amp-fill-content/); }); diff --git a/src/3p-frame.js b/src/3p-frame.js index 0a0345ee4b46..d1ff681732df 100644 --- a/src/3p-frame.js +++ b/src/3p-frame.js @@ -41,16 +41,16 @@ const count = {}; * - A _context object for internal use. */ function getFrameAttributes(parentWindow, element, opt_type) { - var width = element.getAttribute('width'); - var height = element.getAttribute('height'); - var type = opt_type || element.getAttribute('type'); + const width = element.getAttribute('width'); + const height = element.getAttribute('height'); + const type = opt_type || element.getAttribute('type'); assert(type, 'Attribute type required for : %s', element); - var attributes = {}; + const attributes = {}; // Do these first, as the other attributes have precedence. addDataAndJsonAttributes_(element, attributes); attributes.width = getLengthNumeral(width); attributes.height = getLengthNumeral(height); - var box = element.getLayoutBox(); + const box = element.getLayoutBox(); attributes.initialWindowWidth = box.width; attributes.initialWindowHeight = box.height; attributes.type = type; @@ -62,7 +62,7 @@ function getFrameAttributes(parentWindow, element, opt_type) { }, mode: getMode() }; - var adSrc = element.getAttribute('src'); + const adSrc = element.getAttribute('src'); if (adSrc) { attributes.src = adSrc; } @@ -78,15 +78,15 @@ function getFrameAttributes(parentWindow, element, opt_type) { * @return {!Element} The iframe. */ export function getIframe(parentWindow, element, opt_type) { - var attributes = getFrameAttributes(parentWindow, element, opt_type); - var iframe = document.createElement('iframe'); + const attributes = getFrameAttributes(parentWindow, element, opt_type); + const iframe = document.createElement('iframe'); if (!count[attributes.type]) { count[attributes.type] = 0; } iframe.name = 'frame_' + attributes.type + '_' + count[attributes.type]++; // Pass ad attributes to iframe via the fragment. - var src = getBootstrapBaseUrl(parentWindow) + '#' + + const src = getBootstrapBaseUrl(parentWindow) + '#' + JSON.stringify(attributes); iframe.src = src; @@ -113,8 +113,8 @@ export function getIframe(parentWindow, element, opt_type) { * @return {!Unlisten} */ export function listen(iframe, typeOfMessage, callback) { - var win = iframe.ownerDocument.defaultView; - var origin = iframe.ampLocation.origin; + const win = iframe.ownerDocument.defaultView; + const origin = iframe.ampLocation.origin; const listener = function(event) { if (event.origin != origin) { return; @@ -177,23 +177,23 @@ export function postMessage(iframe, type, object) { * visibleForTesting */ export function addDataAndJsonAttributes_(element, attributes) { - for (var i = 0; i < element.attributes.length; i++) { - var attr = element.attributes[i]; + for (let i = 0; i < element.attributes.length; i++) { + const attr = element.attributes[i]; if (attr.name.indexOf('data-') != 0) { continue; } attributes[dashToCamelCase(attr.name.substr(5))] = attr.value; } - var json = element.getAttribute('json'); + const json = element.getAttribute('json'); if (json) { - var obj; + let obj; try { obj = JSON.parse(json); } catch (e) { assert(false, 'Error parsing JSON in json attribute in element %s', element); } - for (var key in obj) { + for (const key in obj) { attributes[key] = obj[key]; } } @@ -205,8 +205,8 @@ export function addDataAndJsonAttributes_(element, attributes) { * @return {string} */ export function prefetchBootstrap(window) { - var url = getBootstrapBaseUrl(window); - var preconnect = preconnectFor(window); + const url = getBootstrapBaseUrl(window); + const preconnect = preconnectFor(window); preconnect.prefetch(url); // While the URL may point to a custom domain, this URL will always be // fetched by it. @@ -233,7 +233,7 @@ export function getBootstrapBaseUrl(parentWindow) { * @return {string} */ function getDefaultBootstrapBaseUrl(parentWindow) { - var url = + let url = 'https://3p.ampproject.net/$internalRuntimeVersion$/frame.html'; if (getMode().localDev) { url = 'http://ads.localhost:' + parentWindow.location.port + @@ -251,12 +251,12 @@ function getDefaultBootstrapBaseUrl(parentWindow) { * @return {?string} */ function getCustomBootstrapBaseUrl(parentWindow) { - var meta = parentWindow.document + const meta = parentWindow.document .querySelector('meta[name="amp-3p-iframe-src"]'); if (!meta) { return null; } - var url = assertHttpsUrl(meta.getAttribute('content'), meta); + const url = assertHttpsUrl(meta.getAttribute('content'), meta); assert(url.indexOf('?') == -1, '3p iframe url must not include query string %s in element %s.', url, meta); diff --git a/src/3p.js b/src/3p.js index c42b42ce63cb..e662964677ad 100644 --- a/src/3p.js +++ b/src/3p.js @@ -54,7 +54,7 @@ export function register(id, draw) { * @param {!Object} data */ export function run(id, win, data) { - var fn = registrations[id]; + const fn = registrations[id]; assert(fn, 'Unknown 3p: ' + id); fn(win, data); } @@ -84,7 +84,7 @@ export function writeScript(win, url, opt_cb) { * @param {function()=} cb */ export function loadScript(win, url, cb) { - var s = win.document.createElement('script'); + const s = win.document.createElement('script'); s.src = url; s.onload = cb; win.document.body.appendChild(s); @@ -97,7 +97,7 @@ export function loadScript(win, url, cb) { * @param {function()} fn */ function executeAfterWriteScript(win, fn) { - var index = syncScriptLoads++; + const index = syncScriptLoads++; win['__runScript' + index] = fn; win.document.write('<' + 'script>__runScript' + index + '()<' + '/script>'); } diff --git a/src/asserts.js b/src/asserts.js index b1bd3b755589..271d99b52ed3 100644 --- a/src/asserts.js +++ b/src/asserts.js @@ -37,25 +37,25 @@ */ /*eslint "google-camelcase/google-camelcase": 0*/ export function assert(shouldBeTrueish, message, var_args) { - var firstElement; + let firstElement; if (!shouldBeTrueish) { message = message || 'Assertion failed'; - var splitMessage = message.split('%s'); - var first = splitMessage.shift(); - var formatted = first; - var messageArray = []; + const splitMessage = message.split('%s'); + const first = splitMessage.shift(); + let formatted = first; + const messageArray = []; pushIfNonEmpty(messageArray, first); - for (var i = 2; i < arguments.length; i++) { - var val = arguments[i]; + for (let i = 2; i < arguments.length; i++) { + const val = arguments[i]; if (val && val.tagName) { firstElement = val; } - var nextConstant = splitMessage.shift(); + const nextConstant = splitMessage.shift(); messageArray.push(val); pushIfNonEmpty(messageArray, nextConstant.trim()); formatted += toString(val) + nextConstant; } - var e = new Error(formatted); + const e = new Error(formatted); e.fromAssert = true; e.associatedElement = firstElement; e.messageArray = messageArray; diff --git a/src/curve.js b/src/curve.js index 50bdc08d9f99..41e76362cc23 100644 --- a/src/curve.js +++ b/src/curve.js @@ -122,10 +122,10 @@ class Bezier { */ solvePositionFromXValue(xVal) { // Desired precision on the computation. - var epsilon = 1e-6; + const epsilon = 1e-6; // Initial estimate of t using linear interpolation. - var t = (xVal - this.x0) / (this.x3 - this.x0); + let t = (xVal - this.x0) / (this.x3 - this.x0); if (t <= 0) { return 0; } else if (t >= 1) { @@ -133,11 +133,11 @@ class Bezier { } // Try gradient descent to solve for t. If it works, it is very fast. - var tMin = 0; - var tMax = 1; - for (var i = 0; i < 8; i++) { - var value = this.getPointX(t); - var derivative = (this.getPointX(t + epsilon) - value) / epsilon; + let tMin = 0; + let tMax = 1; + for (let i = 0; i < 8; i++) { + const value = this.getPointX(t); + const derivative = (this.getPointX(t + epsilon) - value) / epsilon; if (Math.abs(value - xVal) < epsilon) { return t; } else if (Math.abs(derivative) < epsilon) { @@ -182,9 +182,9 @@ class Bezier { } // Step one - from 4 points to 3 - var ix0 = this.lerp(this.x0, this.x1, t); - var ix1 = this.lerp(this.x1, this.x2, t); - var ix2 = this.lerp(this.x2, this.x3, t); + let ix0 = this.lerp(this.x0, this.x1, t); + let ix1 = this.lerp(this.x1, this.x2, t); + const ix2 = this.lerp(this.x2, this.x3, t); // Step two - from 3 points to 2 ix0 = this.lerp(ix0, ix1, t); @@ -208,9 +208,9 @@ class Bezier { } // Step one - from 4 points to 3 - var iy0 = this.lerp(this.y0, this.y1, t); - var iy1 = this.lerp(this.y1, this.y2, t); - var iy2 = this.lerp(this.y2, this.y3, t); + let iy0 = this.lerp(this.y0, this.y1, t); + let iy1 = this.lerp(this.y1, this.y2, t); + const iy2 = this.lerp(this.y2, this.y3, t); // Step two - from 3 points to 2 iy0 = this.lerp(iy0, iy1, t); @@ -273,7 +273,7 @@ export const Curves = { /** * @const {!Object} */ -var NAME_MAP = { +const NAME_MAP = { 'linear': Curves.LINEAR, 'ease': Curves.EASE, 'ease-in': Curves.EASE_IN, diff --git a/src/custom-element.js b/src/custom-element.js index 797b7adff705..ad22a39029b4 100644 --- a/src/custom-element.js +++ b/src/custom-element.js @@ -88,7 +88,7 @@ export function upgradeOrRegisterElement(win, name, toClass) { // implementation. // 3. A stub was attached. We upgrade which means we replay the // implementation. - var element = stub.element; + const element = stub.element; if (element.tagName.toLowerCase() == name) { try { element.upgrade(toClass); @@ -253,7 +253,7 @@ export function createAmpElementProto(win, name, implementationClass) { /** * @lends {AmpElement.prototype} */ - var ElementProto = win.Object.create(win.HTMLElement.prototype); + const ElementProto = win.Object.create(win.HTMLElement.prototype); /** * Called when elements is created. Sets instance vars since there is no @@ -594,10 +594,10 @@ export function createAmpElementProto(win, name, implementationClass) { * @final */ ElementProto.dispatchCustomEvent = function(name, opt_data) { - var data = opt_data || {}; + const data = opt_data || {}; // Constructors of events need to come from the correct window. Sigh. - var win = this.ownerDocument.defaultView; - var event = document.createEvent('Event'); + const win = this.ownerDocument.defaultView; + const event = document.createEvent('Event'); event.data = data; event.initEvent(name, true, true); this.dispatchEvent(event); @@ -658,7 +658,7 @@ export function createAmpElementProto(win, name, implementationClass) { assert(this.isUpgraded() && this.isBuilt(), 'Must be upgraded and built to receive viewport events'); this.dispatchCustomEvent('amp:load:start'); - var promise = this.implementation_.layoutCallback(); + const promise = this.implementation_.layoutCallback(); this.classList.add('-amp-layout'); assert(promise instanceof Promise, 'layoutCallback must return a promise'); diff --git a/src/document-state.js b/src/document-state.js index b94ce467d5e9..76efce5ebdd1 100644 --- a/src/document-state.js +++ b/src/document-state.js @@ -39,7 +39,7 @@ export function onDocumentReady(doc, callback) { if (ready) { callback(); } else { - var readyListener = () => { + const readyListener = () => { if (doc.readyState != 'loading') { if (!ready) { ready = true; diff --git a/src/error.js b/src/error.js index b91330694005..27f72d9184bd 100644 --- a/src/error.js +++ b/src/error.js @@ -19,7 +19,7 @@ import {getMode} from './mode'; import {exponentialBackoff} from './exponential-backoff.js'; import {makeBodyVisible} from './styles'; -var globalExponentialBackoff = exponentialBackoff(1.5); +const globalExponentialBackoff = exponentialBackoff(1.5); /** @@ -40,7 +40,7 @@ export function reportError(error, opt_associatedElement) { return; } error.reported = true; - var element = opt_associatedElement || error.associatedElement; + const element = opt_associatedElement || error.associatedElement; if (element) { element.classList.add('-amp-error'); if (getMode().development) { @@ -89,11 +89,11 @@ function reportErrorToServer(message, filename, line, col, error) { if (this && this.document) { makeBodyVisible(this.document); } - var mode = getMode(); + const mode = getMode(); if (mode.isLocalDev || mode.development || mode.test) { return; } - var url = getErrorReportUrl(message, filename, line, col, error); + const url = getErrorReportUrl(message, filename, line, col, error); globalExponentialBackoff(() => { new Image().src = url; }); @@ -114,12 +114,12 @@ export function getErrorReportUrl(message, filename, line, col, error) { return; } - var url = 'https://cdn.ampproject.org/error/report.gif' + + let url = 'https://cdn.ampproject.org/error/report.gif' + '?v=' + encodeURIComponent('$internalRuntimeVersion$') + '&m=' + encodeURIComponent(message); if (error) { - var tagName = error && error.associatedElement + const tagName = error && error.associatedElement ? error.associatedElement.tagName : 'u'; // Unknown // We may want to consider not reporting asserts but for now diff --git a/src/exponential-backoff.js b/src/exponential-backoff.js index a727e279c1ab..bfec16fbdf61 100644 --- a/src/exponential-backoff.js +++ b/src/exponential-backoff.js @@ -23,14 +23,14 @@ * later. */ export function exponentialBackoff(opt_base) { - var count = 0; + let count = 0; return work => { - var wait = Math.pow(opt_base || 2, count++); + let wait = Math.pow(opt_base || 2, count++); // Add jitter to avoid the thundering herd. This can e.g. happen when // we poll a backend and it fails for everyone at the same time. // We wait up to 30% longer or shorter than the time otherwise // given for this cycle. - var jitter = wait * .3 * Math.random(); + let jitter = wait * .3 * Math.random(); if (Math.random() > .5) { jitter *= -1; } diff --git a/src/gesture-recognizers.js b/src/gesture-recognizers.js index 49a425ea178f..c739fc909527 100644 --- a/src/gesture-recognizers.js +++ b/src/gesture-recognizers.js @@ -27,7 +27,7 @@ import {timer} from './timer'; * clientY: number * }} */ -var Tap; +let Tap; /** @@ -101,7 +101,7 @@ export class TapRecognizer extends GestureRecognizer { * clientY: number * }} */ -var Doubletap; +let Doubletap; /** @@ -199,7 +199,7 @@ export class DoubletapRecognizer extends GestureRecognizer { * velocityY: number * }} */ -var Swipe; +let Swipe; /** @@ -434,7 +434,7 @@ export class SwipeYRecognizer extends SwipeRecognizer { * velocityY: number * }} */ -var Tapzoom; +let Tapzoom; /** @@ -628,7 +628,7 @@ export class TapzoomRecognizer extends GestureRecognizer { * velocityY: number * }} */ -var Pinch; +let Pinch; /** diff --git a/src/history.js b/src/history.js index c3bbb54c0182..e9805a8c802a 100644 --- a/src/history.js +++ b/src/history.js @@ -42,7 +42,7 @@ function historyState_(stackIndex) { /** @typedef {number} */ -var HistoryId; +let HistoryId; export class History { @@ -146,7 +146,7 @@ export class History { enque_(callback) { let resolve; let reject; - var promise = new Promise((aResolve, aReject) => { + const promise = new Promise((aResolve, aReject) => { resolve = aResolve; reject = aReject; }); diff --git a/src/layout-rect.js b/src/layout-rect.js index 38334abe90cf..4bec09832b25 100644 --- a/src/layout-rect.js +++ b/src/layout-rect.js @@ -28,7 +28,7 @@ * height: number * }} */ -var LayoutRect; +let LayoutRect; /** diff --git a/src/log.js b/src/log.js index dfbc70c9673b..65023edd107c 100644 --- a/src/log.js +++ b/src/log.js @@ -17,7 +17,7 @@ import {getMode} from './mode'; /** @const Time when this JS loaded. */ -var start = new Date().getTime(); +const start = new Date().getTime(); /** @@ -49,8 +49,8 @@ export class Log { return false; } // Search for #log=0 or log=1 - var match = this.win.location.hash.match(/log=(\d)/); - var shouldLog = match && match[1]; + const match = this.win.location.hash.match(/log=(\d)/); + const shouldLog = match && match[1]; if (getMode().localDev && shouldLog != '0') { return true; } @@ -68,7 +68,7 @@ export class Log { */ msg_(tag, level, messages) { if (this.isEnabled_) { - var fn = this.win.console.log; + let fn = this.win.console.log; if (level == 'ERROR') { fn = this.win.console.error || fn; } else if (level == 'INFO') { diff --git a/src/mode.js b/src/mode.js index 2fd54491f47c..3d2009189277 100644 --- a/src/mode.js +++ b/src/mode.js @@ -22,10 +22,10 @@ import {parseQueryString} from './url'; * localDev: boolean * }} */ -var Mode; +let Mode; /** @typedef {?Mode} */ -var mode = null; +let mode = null; /** * Provides info about the current app. @@ -51,7 +51,7 @@ export function setModeForTesting(m) { * @return {!Mode} */ function getMode_() { - var isLocalDev = (location.hostname == 'localhost' || + const isLocalDev = (location.hostname == 'localhost' || (location.ancestorOrigins && location.ancestorOrigins[0] && location.ancestorOrigins[0].indexOf('http://localhost:') == 0)) && // Filter out localhost running against a prod script. @@ -59,8 +59,8 @@ function getMode_() { // occur during local dev. !!document.querySelector('script[src*="/dist/"],script[src*="/base/"]'); - var overrideDevelopment = parseQueryString(location.hash)['development']; - var development = overrideDevelopment != undefined + const overrideDevelopment = parseQueryString(location.hash)['development']; + const development = overrideDevelopment != undefined ? overrideDevelopment == '1' : !!document.querySelector('script[development]'); diff --git a/src/pass.js b/src/pass.js index f595e34ba39e..3e87cc7d794b 100644 --- a/src/pass.js +++ b/src/pass.js @@ -66,8 +66,8 @@ export class Pass { * @return {boolean} */ schedule(opt_delay) { - var delay = opt_delay || this.defaultDelay_; - var nextTime = timer.now() + delay; + const delay = opt_delay || this.defaultDelay_; + const nextTime = timer.now() + delay; // Schedule anew if nothing is scheduled currently of if the new time is // sooner then previously requested. if (this.scheduled_ == -1 || nextTime - this.nextTime_ < -10) { diff --git a/src/resources.js b/src/resources.js index 0faba9aff9bc..41311a2c47e7 100644 --- a/src/resources.js +++ b/src/resources.js @@ -687,7 +687,7 @@ export class Resources { } // Note that when the document is not visible, neither are any of its // elements to reduce CPU cycles. - var shouldBeInViewport = (this.visible_ && r.isDisplayed() && + const shouldBeInViewport = (this.visible_ && r.isDisplayed() && r.overlaps(visibleRect)); if (r.isInViewport() != shouldBeInViewport) { r.setInViewport(shouldBeInViewport); @@ -793,7 +793,7 @@ export class Resources { } // Idle pass. - var nextPassDelay = (now - this.exec_.getLastDequeueTime()) * 2; + let nextPassDelay = (now - this.exec_.getLastDequeueTime()) * 2; nextPassDelay = Math.max(Math.min(30000, nextPassDelay), 5000); return nextPassDelay; } @@ -1668,7 +1668,7 @@ export const ResourceState_ = { * }} * @private */ -var Task_; +let Task_; /** * @param {!Window} window diff --git a/src/runtime.js b/src/runtime.js index 5bcab3d1f104..b28e22c199ad 100644 --- a/src/runtime.js +++ b/src/runtime.js @@ -55,7 +55,7 @@ export function adopt(global) { * CSS file associated with the element. */ global.AMP.registerElement = function(name, implementationClass, opt_css) { - var register = function() { + const register = function() { registerExtendedElement(global, name, implementationClass); elementsForTesting.push({ name: name, diff --git a/src/service.js b/src/service.js index bc1634ca9877..eeb191497bbd 100644 --- a/src/service.js +++ b/src/service.js @@ -28,11 +28,11 @@ * @return {*} */ export function getService(win, id, factory) { - var services = win.services; + let services = win.services; if (!services) { services = win.services = {}; } - var s = services[id]; + const s = services[id]; if (!s) { return services[id] = factory(win); } diff --git a/src/size-list.js b/src/size-list.js index 825b69229c1f..4e5a0c8e6c14 100644 --- a/src/size-list.js +++ b/src/size-list.js @@ -25,7 +25,7 @@ import {assertLength} from './layout'; * size: (!Length) * }} */ -var SizeListOption; +let SizeListOption; /** diff --git a/src/srcset.js b/src/srcset.js index 0d88e2b78bd2..27533c0b0732 100644 --- a/src/srcset.js +++ b/src/srcset.js @@ -26,7 +26,7 @@ import {assert} from './asserts'; * dpr: (number|undefined) * }} */ -var SrcsetSource; +let SrcsetSource; /** diff --git a/src/styles.js b/src/styles.js index 3c7ce60e6e8b..3692977d4a1b 100644 --- a/src/styles.js +++ b/src/styles.js @@ -32,10 +32,10 @@ * after. */ export function installStyles(doc, cssText, cb, opt_isRuntimeCss) { - var length = doc.styleSheets.length; - var style = doc.createElement('style'); + const length = doc.styleSheets.length; + const style = doc.createElement('style'); style.textContent = cssText; - var afterElement = null; + let afterElement = null; // Make sure that we place style tags after the main runtime CSS. Otherwise // the order is random. if (opt_isRuntimeCss) { @@ -48,10 +48,10 @@ export function installStyles(doc, cssText, cb, opt_isRuntimeCss) { // pending style download, it will have to finish before the new // style is visible. // For this reason we poll until the style becomes available. - var done = () => { - var sheets = doc.styleSheets; - for (var i = 0; i < sheets.length; i++) { - var sheet = sheets[i]; + const done = () => { + const sheets = doc.styleSheets; + for (let i = 0; i < sheets.length; i++) { + const sheet = sheets[i]; if (sheet.ownerNode == style) { return true; } @@ -64,7 +64,7 @@ export function installStyles(doc, cssText, cb, opt_isRuntimeCss) { return; } // Poll until styles are available. - var interval = setInterval(() => { + const interval = setInterval(() => { if (done()) { clearInterval(interval); cb(); diff --git a/src/timer.js b/src/timer.js index 73be87b44ac9..c2ff7da56acc 100644 --- a/src/timer.js +++ b/src/timer.js @@ -57,7 +57,7 @@ export class Timer { if (!opt_delay) { // For a delay of zero, schedule a promise based micro task since // they are predictably fast. - var id = 'p' + this.taskCount_++; + const id = 'p' + this.taskCount_++; this.resolved_.then(() => { if (this.canceled_[id]) { delete this.canceled_[id]; @@ -91,7 +91,7 @@ export class Timer { * @template RESULT */ promise(opt_delay, opt_result) { - var timerKey = null; + let timerKey = null; return new Promise((resolve, reject) => { timerKey = this.delay(() => { timerKey = -1; @@ -120,8 +120,8 @@ export class Timer { * @template RESULT */ timeoutPromise(delay, opt_racePromise) { - var timerKey = null; - var delayPromise = new Promise((resolve, reject) => { + let timerKey = null; + const delayPromise = new Promise((resolve, reject) => { timerKey = this.delay(() => { timerKey = -1; reject('timeout'); diff --git a/src/url.js b/src/url.js index e85edce46650..7265a76fb83f 100644 --- a/src/url.js +++ b/src/url.js @@ -24,9 +24,9 @@ import {assert} from './asserts'; * @return {!Location} */ export function parseUrl(url) { - var a = document.createElement('a'); + const a = document.createElement('a'); a.href = url; - var info = { + const info = { href: a.href, protocol: a.protocol, host: a.host, @@ -52,7 +52,7 @@ export function parseUrl(url) { * @return {string} */ export function assertHttpsUrl(urlString, elementContext) { - var url = parseUrl(urlString); + const url = parseUrl(urlString); assert( url.protocol == 'https:' || /^(\/\/)/.test(urlString) || url.hostname == 'localhost' || @@ -74,7 +74,7 @@ export function assertHttpsUrl(urlString, elementContext) { * @return {!Object} */ export function parseQueryString(queryString) { - var params = Object.create(null); + const params = Object.create(null); if (!queryString) { return params; } diff --git a/src/uuid.js b/src/uuid.js index ccf1db80bbb5..41f5aa6f9d1b 100644 --- a/src/uuid.js +++ b/src/uuid.js @@ -23,9 +23,9 @@ import {timer} from './timer'; * @return {string} */ export function randomUUID() { - var d = timer.now(); + let d = timer.now(); return 'aaaaaaaa-aaaa-4aaa-baaa-aaaaaaaaaaaa'.replace(/[ab]/g, c => { - var r = (d + Math.random() * 16) % 16 | 0; + const r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c == 'a' ? r : (r & 0x3 | 0x8)).toString(16); }); diff --git a/src/validator-integration.js b/src/validator-integration.js index 8744f06af465..da7ad966e545 100644 --- a/src/validator-integration.js +++ b/src/validator-integration.js @@ -27,11 +27,11 @@ export function maybeValidate(win) { if (!getMode().development) { return; } - var filename = win.location.href; + const filename = win.location.href; if (filename.indexOf('about:') == 0) { // Should only happen in tests. return; } - var s = document.createElement('script'); + const s = document.createElement('script'); // TODO(@cramforce): Switch to locally build version when we integrated // the validator and switch to production URL. s.src = 'https://www.gstatic.com/amphtml/v0/validator.js'; diff --git a/src/viewer.js b/src/viewer.js index ee5fe490c6ef..e0f611c12fcb 100644 --- a/src/viewer.js +++ b/src/viewer.js @@ -200,7 +200,7 @@ export class Viewer { // Remove hash - no reason to keep it around, but only when embedded. if (this.isEmbedded_) { - var newUrl = removeFragment(this.win.location.href); + const newUrl = removeFragment(this.win.location.href); if (newUrl != this.win.location.href && this.win.history.replaceState) { this.win.history.replaceState({}, '', newUrl); log.fine(TAG_, 'replace url:' + this.win.location.href); @@ -543,7 +543,7 @@ export function parseParams_(str, allParams) { * newStackIndex: number * }} */ -var ViewerHistoryPoppedEvent; +let ViewerHistoryPoppedEvent; /** diff --git a/src/viewport.js b/src/viewport.js index bc2b24bd5336..50a8ca99d51d 100644 --- a/src/viewport.js +++ b/src/viewport.js @@ -38,7 +38,7 @@ const TAG_ = 'Viewport'; * velocity: number * }} */ -var ViewportChangedEvent; +let ViewportChangedEvent; /** @@ -377,7 +377,7 @@ export class Viewport { return; } - var newScrollTop = this.binding_.getScrollTop(); + const newScrollTop = this.binding_.getScrollTop(); if (newScrollTop < 0) { // iOS and some other browsers use negative values of scrollTop for // overscroll. Overscroll does not affect the viewport and thus should @@ -394,15 +394,15 @@ export class Viewport { /** @private */ scrollDeferred_() { this.scrollTracking_ = false; - var newScrollTop = this.binding_.getScrollTop(); + const newScrollTop = this.binding_.getScrollTop(); if (this.scrollTop_ === null) { // If the scrollTop was reset while waiting for the next scroll event // we have to assume that velocity is 0 - there's no other way we can // calculate it. this.scrollTop_ = newScrollTop; } - var now = timer.now(); - var velocity = 0; + const now = timer.now(); + let velocity = 0; if (now != this.scrollMeasureTime_) { velocity = (newScrollTop - this.scrollTop_) / (now - this.scrollMeasureTime_); @@ -570,13 +570,13 @@ export class ViewportBindingNatural_ { // and thus cannot be used. But when the values are undefined, fallback to // documentElement./*OK*/clientHeight. if (platform.isIos() && !platform.isChrome()) { - var winWidth = this.win./*OK*/innerWidth; - var winHeight = this.win./*OK*/innerHeight; + const winWidth = this.win./*OK*/innerWidth; + const winHeight = this.win./*OK*/innerHeight; if (winWidth && winHeight) { return {width: winWidth, height: winHeight}; } } - var el = this.win.document.documentElement; + const el = this.win.document.documentElement; return {width: el./*OK*/clientWidth, height: el./*OK*/clientHeight}; } @@ -599,9 +599,9 @@ export class ViewportBindingNatural_ { /** @override */ getLayoutRect(el) { - var scrollTop = this.getScrollTop(); - var scrollLeft = this.getScrollLeft(); - var b = el./*OK*/getBoundingClientRect(); + const scrollTop = this.getScrollTop(); + const scrollLeft = this.getScrollLeft(); + const b = el./*OK*/getBoundingClientRect(); return layoutRectLtwh(Math.round(b.left + scrollLeft), Math.round(b.top + scrollTop), Math.round(b.width), @@ -618,7 +618,7 @@ export class ViewportBindingNatural_ { * @private */ getScrollingElement_() { - var doc = this.win.document; + const doc = this.win.document; if (doc./*OK*/scrollingElement) { return doc./*OK*/scrollingElement; } @@ -798,7 +798,7 @@ export class ViewportBindingNaturalIosEmbed_ { /** @override */ getLayoutRect(el) { - var b = el./*OK*/getBoundingClientRect(); + const b = el./*OK*/getBoundingClientRect(); return layoutRectLtwh(Math.round(b.left + this.pos_.x), Math.round(b.top + this.pos_.y), Math.round(b.width), @@ -977,7 +977,7 @@ export class ViewportBindingVirtual_ { * @return {!LayoutRect} */ getLayoutRect(el) { - var b = el./*OK*/getBoundingClientRect(); + const b = el./*OK*/getBoundingClientRect(); return layoutRectLtwh(Math.round(b.left), Math.round(b.top), Math.round(b.width), diff --git a/test/_init_tests.js b/test/_init_tests.js index 49fd6e2e1721..cafd5010355c 100644 --- a/test/_init_tests.js +++ b/test/_init_tests.js @@ -51,8 +51,8 @@ it.skipOnFirefox = function(desc, fn) { // Global cleanup of tags added during tests. Cool to add more // to selector. afterEach(() => { - var cleanup = document.querySelectorAll('link,meta'); - for (var i = 0; i < cleanup.length; i++) { + const cleanup = document.querySelectorAll('link,meta'); + for (let i = 0; i < cleanup.length; i++) { try { cleanup[i].parentNode.removeChild(cleanup[i]); } catch (e) { @@ -63,8 +63,8 @@ afterEach(() => { }); chai.Assertion.addMethod('attribute', function(attr) { - var obj = this._obj; - var tagName = obj.tagName.toLowerCase(); + const obj = this._obj; + const tagName = obj.tagName.toLowerCase(); this.assert( obj.hasAttribute(attr), 'expected element \'' + tagName + '\' to have attribute #{exp}', @@ -75,8 +75,8 @@ chai.Assertion.addMethod('attribute', function(attr) { }); chai.Assertion.addMethod('class', function(className) { - var obj = this._obj; - var tagName = obj.tagName.toLowerCase(); + const obj = this._obj; + const tagName = obj.tagName.toLowerCase(); this.assert( obj.classList.contains(className), 'expected element \'' + tagName + '\' to have class #{exp}', @@ -87,10 +87,10 @@ chai.Assertion.addMethod('class', function(className) { }); chai.Assertion.addProperty('visible', function() { - var obj = this._obj; - var value = window.getComputedStyle(obj) + const obj = this._obj; + const value = window.getComputedStyle(obj) .getPropertyValue('visibility'); - var tagName = obj.tagName.toLowerCase(); + const tagName = obj.tagName.toLowerCase(); this.assert( value === 'visible', 'expected element \'' + @@ -103,9 +103,9 @@ chai.Assertion.addProperty('visible', function() { }); chai.Assertion.addProperty('hidden', function() { - var obj = this._obj; - var value = window.getComputedStyle(obj).getPropertyValue('visibility'); - var tagName = obj.tagName.toLowerCase(); + const obj = this._obj; + const value = window.getComputedStyle(obj).getPropertyValue('visibility'); + const tagName = obj.tagName.toLowerCase(); this.assert( value === 'hidden', 'expected element \'' + @@ -118,9 +118,9 @@ chai.Assertion.addProperty('hidden', function() { }); chai.Assertion.addMethod('display', function(display) { - var obj = this._obj; - var value = window.getComputedStyle(obj).getPropertyValue('display'); - var tagName = obj.tagName.toLowerCase(); + const obj = this._obj; + const value = window.getComputedStyle(obj).getPropertyValue('display'); + const tagName = obj.tagName.toLowerCase(); this.assert( value === display, 'expected element \'' + tagName + '\' to be #{exp}, got #{act}.', @@ -131,9 +131,9 @@ chai.Assertion.addMethod('display', function(display) { }); chai.Assertion.addMethod('jsonEqual', function(compare) { - var obj = this._obj; - var a = JSON.stringify(compare); - var b = JSON.stringify(obj); + const obj = this._obj; + const a = JSON.stringify(compare); + const b = JSON.stringify(obj); this.assert( a == b, 'expected JSON to be equal.\nExp: #{exp}\nAct: #{act}', diff --git a/test/functional/test-3p-frame.js b/test/functional/test-3p-frame.js index 6384f886c799..39cb2c15bd0b 100644 --- a/test/functional/test-3p-frame.js +++ b/test/functional/test-3p-frame.js @@ -40,11 +40,11 @@ describe('3p-frame', () => { } it('add attributes', () => { - var div = document.createElement('div'); + const div = document.createElement('div'); div.setAttribute('data-foo', 'foo'); div.setAttribute('data-bar', 'bar'); div.setAttribute('foo', 'nope'); - var obj = {}; + let obj = {}; addDataAndJsonAttributes_(div, obj); expect(obj).to.deep.equal({ 'foo': 'foo', @@ -64,12 +64,12 @@ describe('3p-frame', () => { it('should create an iframe', () => { - var link = document.createElement('link'); + const link = document.createElement('link'); link.setAttribute('rel', 'canonical'); link.setAttribute('href', 'https://foo.bar/baz'); document.head.appendChild(link); - var div = document.createElement('div'); + const div = document.createElement('div'); div.setAttribute('data-test-attr', 'value'); div.setAttribute('data-ping', 'pong'); div.setAttribute('width', '50'); @@ -82,13 +82,13 @@ describe('3p-frame', () => { }; }; - var iframe = getIframe(window, div, '_ping_'); - var src = iframe.src; - var referrer = document.referrer; + const iframe = getIframe(window, div, '_ping_'); + const src = iframe.src; + const referrer = document.referrer; expect(referrer).to.not.be.a.string; - var locationHref = location.href; + const locationHref = location.href; expect(locationHref).to.not.be.a.string; - var fragment = + const fragment = '#{"testAttr":"value","ping":"pong","width":50,"height":100,' + '"initialWindowWidth":100,"initialWindowHeight":200,"type":"_ping_"' + ',"_context":{"referrer":"' + referrer + '",' + @@ -104,7 +104,7 @@ describe('3p-frame', () => { document.body.appendChild(iframe); return loadPromise(iframe).then(() => { - var win = iframe.contentWindow; + const win = iframe.contentWindow; expect(win.context.canonicalUrl).to.equal('https://foo.bar/baz'); expect(win.context.location.href).to.equal(locationHref); expect(win.context.location.origin).to.equal('http://localhost:9876'); @@ -117,7 +117,7 @@ describe('3p-frame', () => { expect(win.context.data.testAttr).to.equal('value'); expect(win.context.noContentAvailable).to.be.function; expect(win.context.observeIntersection).to.be.function; - var c = win.document.getElementById('c'); + const c = win.document.getElementById('c'); expect(c).to.not.be.null; expect(c.textContent).to.contain('pong'); }); @@ -156,7 +156,7 @@ describe('3p-frame', () => { it('should prefetch bootstrap frame and JS', () => { prefetchBootstrap(window); - var fetches = document.querySelectorAll( + const fetches = document.querySelectorAll( 'link[rel=prefetch]'); expect(fetches).to.have.length(2); expect(fetches[0].href).to.equal( diff --git a/test/functional/test-action.js b/test/functional/test-action.js index 4526bd23aa05..0b668c5fe5c6 100644 --- a/test/functional/test-action.js +++ b/test/functional/test-action.js @@ -138,14 +138,14 @@ describe('Action findAction', () => { }); it('should create action map in getActionMap_', () => { - var element = document.createElement('div'); + const element = document.createElement('div'); element.setAttribute('on', 'event1:action1'); const m = action.getActionMap_(element); expect(m['event1'].target).to.equal('action1'); }); it('should cache action map', () => { - var element = document.createElement('div'); + const element = document.createElement('div'); element.setAttribute('on', 'event1:action1'); const m1 = action.getActionMap_(element); const m2 = action.getActionMap_(element); @@ -154,7 +154,7 @@ describe('Action findAction', () => { it('should find action on the same element', () => { - var element = document.createElement('div'); + const element = document.createElement('div'); element.setAttribute('on', 'event1:action1'); const a = action.findAction_(element, 'event1'); expect(a.node).to.equal(element); @@ -164,9 +164,9 @@ describe('Action findAction', () => { }); it('should find action in subtree', () => { - var parent = document.createElement('div'); + const parent = document.createElement('div'); parent.setAttribute('on', 'event1:action1'); - var element = document.createElement('div'); + const element = document.createElement('div'); element.setAttribute('on', 'event2:action2'); parent.appendChild(element); diff --git a/test/functional/test-amp-ad.js b/test/functional/test-amp-ad.js index ab45fe9412f6..591f719e8670 100644 --- a/test/functional/test-amp-ad.js +++ b/test/functional/test-amp-ad.js @@ -33,13 +33,13 @@ describe('amp-ad', () => { iframe.iframe.style.width = '400px'; installAd(iframe.win); if (canonical) { - var link = iframe.doc.createElement('link'); + const link = iframe.doc.createElement('link'); link.setAttribute('rel', 'canonical'); link.setAttribute('href', canonical); iframe.doc.head.appendChild(link); } - var a = iframe.doc.createElement('amp-ad'); - for (var key in attributes) { + let a = iframe.doc.createElement('amp-ad'); + for (const key in attributes) { a.setAttribute(key, attributes[key]); } // Make document long. @@ -63,15 +63,15 @@ describe('amp-ad', () => { // Test precedence 'data-width': '6666' }, 'https://schema.org').then(ad => { - var iframe = ad.firstChild; + const iframe = ad.firstChild; expect(iframe).to.not.be.null; expect(iframe.tagName).to.equal('IFRAME'); - var url = iframe.getAttribute('src'); + const url = iframe.getAttribute('src'); expect(url).to.match(/^http:\/\/ads.localhost:/); expect(url).to.match(/frame(.max)?.html#{/); - var fragment = url.substr(url.indexOf('#') + 1); - var data = JSON.parse(fragment); + const fragment = url.substr(url.indexOf('#') + 1); + const data = JSON.parse(fragment); expect(data.type).to.equal('a9'); expect(data.src).to.equal('https://testsrc'); @@ -80,8 +80,8 @@ describe('amp-ad', () => { expect(data._context.canonicalUrl).to.equal('https://schema.org/'); expect(data.aax_size).to.equal('300x250'); - var doc = iframe.ownerDocument; - var fetches = doc.querySelectorAll( + const doc = iframe.ownerDocument; + const fetches = doc.querySelectorAll( 'link[rel=prefetch]'); expect(fetches).to.have.length(3); expect(fetches[0].href).to.equal( @@ -90,7 +90,7 @@ describe('amp-ad', () => { 'https://3p.ampproject.net/$internalRuntimeVersion$/f.js'); expect(fetches[2].href).to.equal( 'https://c.amazon-adsystem.com/aax2/assoc.js'); - var preconnects = doc.querySelectorAll( + const preconnects = doc.querySelectorAll( 'link[rel=preconnect]'); expect(preconnects[preconnects.length - 1].href).to.equal( 'https://testsrc/'); @@ -131,10 +131,10 @@ describe('amp-ad', () => { type: 'a9', src: 'testsrc', }, 'https://schema.org', function(ad) { - var s = document.createElement('style'); + const s = document.createElement('style'); s.textContent = '.fixed {position:fixed;}'; ad.ownerDocument.body.appendChild(s); - var p = ad.ownerDocument.getElementById('parent'); + const p = ad.ownerDocument.getElementById('parent'); p.className = 'fixed'; return ad; })).to.be.rejectedWith(/fixed/); @@ -147,9 +147,9 @@ describe('amp-ad', () => { type: 'a9', src: 'testsrc', }, 'https://schema.org', function(ad) { - var lightbox = document.createElement('amp-lightbox'); + const lightbox = document.createElement('amp-lightbox'); lightbox.style.position = 'fixed'; - var p = ad.ownerDocument.getElementById('parent'); + const p = ad.ownerDocument.getElementById('parent'); p.parentElement.appendChild(lightbox); p.parentElement.removeChild(p); lightbox.appendChild(p); diff --git a/test/functional/test-amp-pixel.js b/test/functional/test-amp-pixel.js index e365f7670d33..c4d389cda9c4 100644 --- a/test/functional/test-amp-pixel.js +++ b/test/functional/test-amp-pixel.js @@ -24,10 +24,10 @@ describe('amp-pixel', () => { function getPixel(src) { return createIframePromise().then(iframe => { installPixel(iframe.win); - var p = iframe.doc.createElement('amp-pixel'); + const p = iframe.doc.createElement('amp-pixel'); p.setAttribute('src', src); iframe.doc.title = 'Pixel Test'; - var link = iframe.doc.createElement('link'); + const link = iframe.doc.createElement('link'); link.setAttribute('href', 'https://pinterest.com/pin1'); link.setAttribute('rel', 'canonical'); iframe.doc.head.appendChild(link); diff --git a/test/functional/test-amp-video.js b/test/functional/test-amp-video.js index 866c5399c5b3..8011ef838f76 100644 --- a/test/functional/test-amp-video.js +++ b/test/functional/test-amp-video.js @@ -26,7 +26,7 @@ describe('amp-video', () => { function getVideo(attributes, children) { return createIframePromise().then(iframe => { installVideo(iframe.win); - var v = iframe.doc.createElement('amp-video'); + const v = iframe.doc.createElement('amp-video'); for (const key in attributes) { v.setAttribute(key, attributes[key]); } @@ -45,7 +45,7 @@ describe('amp-video', () => { width: 160, height: 90 }).then(v => { - var video = v.querySelector('video'); + const video = v.querySelector('video'); expect(video).to.be.an.instanceof(Element); expect(video.tagName).to.equal('VIDEO'); expect(video.getAttribute('src')).to.equal('video.mp4'); @@ -63,7 +63,7 @@ describe('amp-video', () => { 'muted': '', 'loop': '' }).then(v => { - var video = v.querySelector('video'); + const video = v.querySelector('video'); expect(video).to.be.an.instanceof(Element); expect(video.tagName).to.equal('VIDEO'); expect(video.hasAttribute('controls')).to.be.true; @@ -74,11 +74,11 @@ describe('amp-video', () => { }); it('should load a video with source children', () => { - var sources = []; - var mediatypes = ['video/ogg', 'video/mp4', 'video/webm']; - for (var i = 0; i < mediatypes.length; i++) { - var mediatype = mediatypes[i]; - var source = document.createElement('source'); + const sources = []; + const mediatypes = ['video/ogg', 'video/mp4', 'video/webm']; + for (let i = 0; i < mediatypes.length; i++) { + const mediatype = mediatypes[i]; + const source = document.createElement('source'); source.setAttribute('src', getFooVideoSrc(mediatype)); source.setAttribute('type', mediatype); sources.push(source); @@ -92,11 +92,11 @@ describe('amp-video', () => { 'muted': '', 'loop': '' }, sources).then(v => { - var video = v.querySelector('video'); + const video = v.querySelector('video'); // check that the source tags were propogated expect(video.children.length).to.equal(mediatypes.length); - for (var i = 0; i < mediatypes.length; i++) { - var mediatype = mediatypes[i]; + for (let i = 0; i < mediatypes.length; i++) { + const mediatype = mediatypes[i]; expect(video.children.item(i).tagName).to.equal('SOURCE'); expect(video.children.item(i).hasAttribute('src')).to.be.true; expect(video.children.item(i).getAttribute('src')) @@ -107,11 +107,11 @@ describe('amp-video', () => { }); it('should not load a video with http source children', () => { - var sources = []; - var mediatypes = ['video/ogg', 'video/mp4', 'video/webm']; - for (var i = 0; i < mediatypes.length; i++) { - var mediatype = mediatypes[i]; - var source = document.createElement('source'); + const sources = []; + const mediatypes = ['video/ogg', 'video/mp4', 'video/webm']; + for (let i = 0; i < mediatypes.length; i++) { + const mediatype = mediatypes[i]; + const source = document.createElement('source'); source.setAttribute('src', 'http:' + getFooVideoSrc(mediatype)); source.setAttribute('type', mediatype); sources.push(source); diff --git a/test/functional/test-asserts.js b/test/functional/test-asserts.js index bd82c871ff70..94e73e4f2e26 100644 --- a/test/functional/test-asserts.js +++ b/test/functional/test-asserts.js @@ -37,14 +37,14 @@ describe('asserts', () => { expect(function() { assert(false, 'should fail %s %s', 'XYZ', 'YYY'); }).to.throw(/should fail XYZ YYY/); - var div = document.createElement('div'); + const div = document.createElement('div'); div.id = 'abc'; div.textContent = 'foo'; expect(function() { assert(false, 'should fail %s', div); }).to.throw(/should fail div#abc/); - var error; + let error; try { assert(false, '%s a %s b %s', 1, 2, 3); } catch (e) { @@ -56,8 +56,8 @@ describe('asserts', () => { }); it('should add element and assert info', () => { - var div = document.createElement('div'); - var error; + const div = document.createElement('div'); + let error; try { assert(false, '%s a %s b %s', div, 2, 3); } catch (e) { diff --git a/test/functional/test-document-info.js b/test/functional/test-document-info.js index ea28dc8fdcf7..623b27f95750 100644 --- a/test/functional/test-document-info.js +++ b/test/functional/test-document-info.js @@ -21,7 +21,7 @@ describe('document-info', () => { function getWin(canonical) { return createIframePromise().then(iframe => { if (canonical) { - var link = iframe.doc.createElement('link'); + const link = iframe.doc.createElement('link'); link.setAttribute('href', canonical); link.setAttribute('rel', 'canonical'); iframe.doc.head.appendChild(link); diff --git a/test/functional/test-error.js b/test/functional/test-error.js index 3a36d70e4bd4..95c1e0edad2f 100644 --- a/test/functional/test-error.js +++ b/test/functional/test-error.js @@ -42,10 +42,10 @@ describe('reportErrorToServer', () => { }); it('reportError with error object', () => { - var e = new Error('XYZ'); - var url = parseUrl( + const e = new Error('XYZ'); + const url = parseUrl( getErrorReportUrl(undefined, undefined, undefined, undefined, e)); - var query = parseQueryString(url.search); + const query = parseQueryString(url.search); expect(url.href.indexOf( 'https://cdn.ampproject.org/error/report.gif')).to.equal(0); @@ -57,12 +57,12 @@ describe('reportErrorToServer', () => { }); it('reportError with associatedElement', () => { - var e = new Error('XYZ'); - var el = document.createElement('foo-bar'); + const e = new Error('XYZ'); + const el = document.createElement('foo-bar'); e.associatedElement = el; - var url = parseUrl( + const url = parseUrl( getErrorReportUrl(undefined, undefined, undefined, undefined, e)); - var query = parseQueryString(url.search); + const query = parseQueryString(url.search); expect(query.m).to.equal('XYZ'); expect(query.el).to.equal('FOO-BAR'); @@ -71,11 +71,11 @@ describe('reportErrorToServer', () => { }); it('reportError mark asserts', () => { - var e = new Error('XYZ'); + const e = new Error('XYZ'); e.fromAssert = true; - var url = parseUrl( + const url = parseUrl( getErrorReportUrl(undefined, undefined, undefined, undefined, e)); - var query = parseQueryString(url.search); + const query = parseQueryString(url.search); expect(query.m).to.equal('XYZ'); expect(query.a).to.equal('1'); @@ -83,9 +83,9 @@ describe('reportErrorToServer', () => { }); it('reportError without error object', () => { - var url = parseUrl( + const url = parseUrl( getErrorReportUrl('foo bar', 'foo.js', '11', '22', undefined)); - var query = parseQueryString(url.search); + const query = parseQueryString(url.search); expect(url.href.indexOf( 'https://cdn.ampproject.org/error/report.gif')).to.equal(0); diff --git a/test/functional/test-event-helper.js b/test/functional/test-event-helper.js index dbabb3fd09d9..59ad70879673 100644 --- a/test/functional/test-event-helper.js +++ b/test/functional/test-event-helper.js @@ -22,7 +22,7 @@ import * as sinon from 'sinon'; describe('EventHelper', () => { function getEvent(name) { - var event = document.createEvent('Event'); + const event = document.createEvent('Event'); event.initEvent(name, true, true); return event; } diff --git a/test/functional/test-exponential-backoff.js b/test/functional/test-exponential-backoff.js index e3da5c6e963f..eff43d587399 100644 --- a/test/functional/test-exponential-backoff.js +++ b/test/functional/test-exponential-backoff.js @@ -34,10 +34,10 @@ describe('exponentialBackoff', () => { }); it('should backoff exponentially', () => { - var count = 0; - var backoff = exponentialBackoff(); - var backoff2 = exponentialBackoff(); - var increment = () => { + let count = 0; + const backoff = exponentialBackoff(); + const backoff2 = exponentialBackoff(); + const increment = () => { count++; }; diff --git a/test/functional/test-layout.js b/test/functional/test-layout.js index 5ffbf9523e15..05c5bb1a6eab 100644 --- a/test/functional/test-layout.js +++ b/test/functional/test-layout.js @@ -20,7 +20,7 @@ import {applyLayout_} from '../../src/custom-element'; describe('Layout', () => { - var div; + let div; beforeEach(() => { div = document.createElement('div'); diff --git a/test/functional/test-pass.js b/test/functional/test-pass.js index 7fff2ce68610..452231ed120f 100644 --- a/test/functional/test-pass.js +++ b/test/functional/test-pass.js @@ -44,7 +44,7 @@ describe('Pass', () => { }); it('handler called', () => { - var delayedFunc = null; + let delayedFunc = null; timerMock.expects('delay').withExactArgs(sinon.match(value => { delayedFunc = value; return true; diff --git a/test/functional/test-preconnect.js b/test/functional/test-preconnect.js index ef144d153e96..90f03e5ee14a 100644 --- a/test/functional/test-preconnect.js +++ b/test/functional/test-preconnect.js @@ -102,7 +102,7 @@ describe('preconnect', () => { expect(document.querySelector('link[rel=preconnect]').href) .to.equal('https://a.prefetch.com/'); // Actual prefetch - var fetches = document.querySelectorAll( + const fetches = document.querySelectorAll( 'link[rel=prefetch]'); expect(fetches).to.have.length(2); expect(fetches[0].href).to.equal('https://a.prefetch.com/foo/bar'); diff --git a/test/functional/test-service.js b/test/functional/test-service.js index 7f6f8798960d..3aa1c87a0533 100644 --- a/test/functional/test-service.js +++ b/test/functional/test-service.js @@ -18,18 +18,18 @@ import {getService} from '../../src/service'; describe('service`', () => { - var count = 1; + let count = 1; function inc() { return count++; } it('should make per window singletons', () => { - var a1 = getService(window, 'a', inc); - var a2 = getService(window, 'a', inc); + const a1 = getService(window, 'a', inc); + const a2 = getService(window, 'a', inc); expect(a1).to.equal(a2); expect(a1).to.equal(1); - var b1 = getService(window, 'b', inc); - var b2 = getService(window, 'b', inc); + const b1 = getService(window, 'b', inc); + const b2 = getService(window, 'b', inc); expect(b1).to.equal(b2); expect(b1).to.not.equal(a1); }); diff --git a/test/functional/test-size-list.js b/test/functional/test-size-list.js index 569b479ff19c..7555ab548c67 100644 --- a/test/functional/test-size-list.js +++ b/test/functional/test-size-list.js @@ -20,14 +20,14 @@ import {SizeList, parseSizeList} from '../../src/size-list'; describe('SizeList parseSizeList', () => { it('should accept single option', () => { - var res = parseSizeList(' \n 111px \n '); + const res = parseSizeList(' \n 111px \n '); expect(res.sizes_.length).to.equal(1); expect(res.sizes_[0].mediaQuery).to.equal(undefined); expect(res.sizes_[0].size).to.equal('111px'); }); it('should accept multiple options', () => { - var res = parseSizeList(' \n print 222px \n, 111px \n'); + const res = parseSizeList(' \n print 222px \n, 111px \n'); expect(res.sizes_.length).to.equal(2); expect(res.sizes_[0].mediaQuery).to.equal('print'); expect(res.sizes_[0].size).to.equal('222px'); @@ -36,7 +36,7 @@ describe('SizeList parseSizeList', () => { }); it('should accept even more multiple options', () => { - var res = parseSizeList(' \n screen 333px, print 222px \n, 111px \n'); + const res = parseSizeList(' \n screen 333px, print 222px \n, 111px \n'); expect(res.sizes_.length).to.equal(3); expect(res.sizes_[0].mediaQuery).to.equal('screen'); expect(res.sizes_[0].size).to.equal('333px'); @@ -47,7 +47,7 @@ describe('SizeList parseSizeList', () => { }); it('should accept complicated media conditions', () => { - var res = parseSizeList( + const res = parseSizeList( ' \n screen and (min-width: 1000px) \t ' + ' and (max-width: 2000px) 222px \n,' + ' 111px \n'); @@ -60,7 +60,7 @@ describe('SizeList parseSizeList', () => { }); it('should accept different length units', () => { - var res = parseSizeList(' \n 111vw \n '); + const res = parseSizeList(' \n 111vw \n '); expect(res.sizes_.length).to.equal(1); expect(res.sizes_[0].mediaQuery).to.equal(undefined); expect(res.sizes_[0].size).to.equal('111vw'); diff --git a/test/functional/test-srcset.js b/test/functional/test-srcset.js index 14e068b7f903..361c31b15c86 100644 --- a/test/functional/test-srcset.js +++ b/test/functional/test-srcset.js @@ -20,7 +20,7 @@ import {Srcset, parseSrcset} from '../../src/srcset'; describe('Srcset parseSrcset', () => { function test(s, expected) { - var res = parseSrcset(s); + const res = parseSrcset(s); expect(res.sources_.length).to.equal(expected.length); for (let i = 0; i < expected.length; i++) { const r = res.sources_[i]; diff --git a/test/functional/test-timer.js b/test/functional/test-timer.js index 525f12e68be8..ede86143d194 100644 --- a/test/functional/test-timer.js +++ b/test/functional/test-timer.js @@ -24,10 +24,10 @@ describe('Timer', () => { beforeEach(() => { sandbox = sinon.sandbox.create(); - var WindowApi = function() {}; + const WindowApi = function() {}; WindowApi.prototype.setTimeout = function(callback, delay) {}; WindowApi.prototype.clearTimeout = function(timerId) {}; - var windowApi = new WindowApi(); + const windowApi = new WindowApi(); windowMock = sandbox.mock(windowApi); timer = new Timer(windowApi); }); @@ -62,7 +62,7 @@ describe('Timer', () => { it('cancel default', done => { windowMock.expects('setTimeout').never(); windowMock.expects('clearTimeout').never(); - var id = timer.delay(() => { + const id = timer.delay(() => { throw new Error('should have been cancelled'); }); timer.cancel(id); diff --git a/test/functional/test-url.js b/test/functional/test-url.js index d9da54fed237..6170a90cc320 100644 --- a/test/functional/test-url.js +++ b/test/functional/test-url.js @@ -19,13 +19,13 @@ import {assertHttpsUrl, parseQueryString, parseUrl, removeFragment, getOrigin} describe('url', () => { - var currentPort = location.port; + const currentPort = location.port; function compareParse(url, result) { // Using JSON string comparison because Chai's deeply equal // errors are impossible to debug. - var parsed = JSON.stringify(parseUrl(url)); - var expected = JSON.stringify(result); + const parsed = JSON.stringify(parseUrl(url)); + const expected = JSON.stringify(result); expect(parsed).to.equal(expected); } @@ -164,7 +164,7 @@ describe('parseQueryString', () => { }); describe('assertHttpsUrl', () => { - var referenceElement = document.createElement('div'); + const referenceElement = document.createElement('div'); it('should allow https', () => { assertHttpsUrl('https://twitter.com', referenceElement); }); diff --git a/test/functional/test-viewer.js b/test/functional/test-viewer.js index 20e3a2acf800..0373968fb767 100644 --- a/test/functional/test-viewer.js +++ b/test/functional/test-viewer.js @@ -27,7 +27,7 @@ describe('Viewer', () => { beforeEach(() => { sandbox = sinon.sandbox.create(); - var WindowApi = function() {}; + const WindowApi = function() {}; WindowApi.prototype.setTimeout = function(callback, delay) {}; windowApi = new WindowApi(); windowApi.location = {hash: '', href: '/test/viewer'}; diff --git a/test/functional/test-viewport.js b/test/functional/test-viewport.js index 2fed7491f758..06348204eff3 100644 --- a/test/functional/test-viewport.js +++ b/test/functional/test-viewport.js @@ -454,7 +454,7 @@ describe('ViewportBindingNatural', () => { beforeEach(() => { sandbox = sinon.sandbox.create(); - var WindowApi = function() {}; + const WindowApi = function() {}; windowEventHandlers = {}; WindowApi.prototype.addEventListener = function(eventType, handler) { windowEventHandlers[eventType] = handler; @@ -568,7 +568,7 @@ describe('ViewportBindingNaturalIosEmbed', () => { beforeEach(() => { sandbox = sinon.sandbox.create(); clock = sandbox.useFakeTimers(); - var WindowApi = function() {}; + const WindowApi = function() {}; windowEventHandlers = {}; bodyEventListeners = {}; bodyChildren = []; diff --git a/test/functional/test-vsync.js b/test/functional/test-vsync.js index 63fdd30774aa..e3011c976560 100644 --- a/test/functional/test-vsync.js +++ b/test/functional/test-vsync.js @@ -27,7 +27,7 @@ describe('vsync', () => { }); it('should generate a frame and run callbacks', () => { - var result = ''; + let result = ''; return new Promise(resolve => { vsync.run({ measure: () => { @@ -69,7 +69,7 @@ describe('vsync', () => { }); it('should schedule nested vsyncs', () => { - var result = ''; + let result = ''; return new Promise(resolve => { vsync.run({ measure: () => { diff --git a/test/integration/test-amp-img.js b/test/integration/test-amp-img.js index 3657fb8a92fb..efdf7f8cde07 100644 --- a/test/integration/test-amp-img.js +++ b/test/integration/test-amp-img.js @@ -18,7 +18,7 @@ import {createFixtureIframe, expectBodyToBecomeVisible} from '../../testing/iframe.js'; describe('Rendering of amp-img', () => { - var fixture; + let fixture; beforeEach(() => { return createFixtureIframe('test/fixtures/images.html', 500).then(f => { fixture = f; @@ -39,7 +39,7 @@ describe('Rendering of amp-img', () => { }); it('should resize and load more elements', () => { - var p = fixture.awaitEvent('amp:load:start', 11).then(function() { + const p = fixture.awaitEvent('amp:load:start', 11).then(function() { expect(fixture.doc.querySelectorAll('amp-img img[src]')) .to.have.length(11); fixture.iframe.height = 2000; @@ -56,8 +56,8 @@ describe('Rendering of amp-img', () => { it('should respect media queries', () => { return fixture.awaitEvent('amp:load:start', 3).then(function() { - var smallScreen = fixture.doc.getElementById('img3'); - var largeScreen = fixture.doc.getElementById('img3_1'); + const smallScreen = fixture.doc.getElementById('img3'); + const largeScreen = fixture.doc.getElementById('img3_1'); expect(smallScreen.className).to.not.match(/-amp-hidden-by-media-query/); expect(largeScreen.className).to.match(/-amp-hidden-by-media-query/); expect(smallScreen.offsetHeight).to.not.equal(0); diff --git a/test/integration/test-errors.js b/test/integration/test-errors.js index 00d8cc0b6e18..7bf81a260620 100644 --- a/test/integration/test-errors.js +++ b/test/integration/test-errors.js @@ -20,7 +20,7 @@ import {createFixtureIframe, poll, expectBodyToBecomeVisible} from import {loadPromise} from '../../src/event-helper'; describe('error page', () => { - var fixture; + let fixture; beforeEach(() => { return createFixtureIframe('test/fixtures/errors.html', 500).then(f => { fixture = f; @@ -40,7 +40,7 @@ describe('error page', () => { function shouldFail(id) { // Skip for issue #110 it('should fail to load #' + id, () => { - var e = fixture.doc.getElementById(id); + const e = fixture.doc.getElementById(id); expect(fixture.errors.join('\n')).to.contain( e.getAttribute('data-expectederror')); expect(e.getAttribute('error-message')).to.contain( diff --git a/test/integration/test-example-validation.js b/test/integration/test-example-validation.js index 4624108e2506..81ecc3d922c1 100644 --- a/test/integration/test-example-validation.js +++ b/test/integration/test-example-validation.js @@ -23,7 +23,7 @@ import {loadPromise} from '../../src/event-helper'; // use it directly. if (!window.validatorLoad) { window.validatorLoad = (function() { - var s = document.createElement('script'); + const s = document.createElement('script'); s.src = 'https://www.gstatic.com/amphtml/v0/validator.js'; document.body.appendChild(s); return loadPromise(s); @@ -34,7 +34,7 @@ describe('example', function() { // TODO(@cramforce): Remove when test is hermetic. this.timeout(5000); - var examples = [ + const examples = [ 'ads.amp.html', 'metadata-examples/article-json-ld.amp.html', 'metadata-examples/article-microdata.amp.html', @@ -57,13 +57,13 @@ describe('example', function() { * * @constructor {!Array} */ - var errorWhitelist = [ + const errorWhitelist = [ // TODO(dvoytenko): Remove. Viewport values changed in #592. Waiting for // the validator to catch up. /INVALID_ATTR_VALUE.*vprt/ ]; - var usedWhitelist = []; + const usedWhitelist = []; beforeEach(() => { return window.validatorLoad; @@ -71,15 +71,15 @@ describe('example', function() { examples.forEach(filename => { it(filename + ' should validate', () => { - var url = '/base/examples/' + filename; + const url = '/base/examples/' + filename; return get(url).then(html => { - var validationResult = amp.validator.validateString(html); - var rendered = amp.validator.renderValidationResult(validationResult, + const validationResult = amp.validator.validateString(html); + const rendered = amp.validator.renderValidationResult(validationResult, url); - var errors = []; + const errors = []; LINES: for (let i = 0; i < rendered.length; i++) { - var line = rendered[i]; + const line = rendered[i]; if (line == 'PASS') { continue; } @@ -97,7 +97,7 @@ describe('example', function() { continue; } for (let n = 0; n < errorWhitelist.length; n++) { - var ok = errorWhitelist[n]; + const ok = errorWhitelist[n]; if (ok.test(rendered)) { usedWhitelist.push(ok); continue LINES; @@ -122,7 +122,7 @@ describe('example', function() { */ function get(filename) { return new Promise((resolve, reject) => { - var xhr = new XMLHttpRequest(); + const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { diff --git a/test/integration/test-released.js b/test/integration/test-released.js index 17d4a5df92be..ff0815d8d169 100644 --- a/test/integration/test-released.js +++ b/test/integration/test-released.js @@ -18,7 +18,7 @@ import {createFixtureIframe, pollForLayout, expectBodyToBecomeVisible} from '../../testing/iframe.js'; describe('Rendering of released components', () => { - var fixture; + let fixture; beforeEach(() => { return createFixtureIframe('test/fixtures/released.html', 3000) .then(f => { diff --git a/testing/iframe.js b/testing/iframe.js index 99195f18b0e4..5ff982c65fbe 100644 --- a/testing/iframe.js +++ b/testing/iframe.js @@ -19,7 +19,7 @@ require('../src/polyfills'); import {Timer} from '../src/timer'; import {registerForUnitTest} from '../src/runtime'; -var iframeCount = 0; +let iframeCount = 0; /** @@ -55,11 +55,11 @@ export function createFixtureIframe(fixture, initialIframeHeight, done) { 'amp:stubbed': 0, 'amp:load:start': 0 }; - var html = __html__[fixture]; + let html = __html__[fixture]; if (!html) { throw new Error('Cannot find fixture: ' + fixture); } - var firstLoad = true; + let firstLoad = true; // This global function will be called by the iframe immediately when it // starts loading. This appears to be the only way to get the correct // window object early enough to not miss any events that may get fired @@ -69,7 +69,7 @@ export function createFixtureIframe(fixture, initialIframeHeight, done) { win.AMP_TEST = true; // Function that returns a promise for when the given event fired at // least count times. - var awaitEvent = (eventName, count) => { + let awaitEvent = (eventName, count) => { if (!(eventName in events)) { throw new Error('Unknown custom event ' + eventName); } @@ -96,7 +96,7 @@ export function createFixtureIframe(fixture, initialIframeHeight, done) { file + ':' + line + '\n' + (error ? error.stack : 'no stack')); }; - var errors = []; + let errors = []; win.console.error = function() { errors.push('Error: ' + [].slice.call(arguments).join(' ')); }; @@ -105,7 +105,7 @@ export function createFixtureIframe(fixture, initialIframeHeight, done) { ms = ms || 0; setTimeout(fn, ms / 10); }; - var timeout = setTimeout(function() { + let timeout = setTimeout(function() { reject(new Error('Timeout waiting for elements to start loading.')); }, 1000); // Declare the test ready to run when the document was fully parsed. @@ -122,7 +122,7 @@ export function createFixtureIframe(fixture, initialIframeHeight, done) { // Add before and after load callbacks to the document. html = html.replace('>', '>'); html += ''; - var iframe = document.createElement('iframe'); + let iframe = document.createElement('iframe'); iframe.name = 'test_' + fixture + iframeCount++; iframe.onerror = function(event) { throw event.error; @@ -155,7 +155,7 @@ export function createFixtureIframe(fixture, initialIframeHeight, done) { */ export function createIframePromise(opt_runtimeOff, opt_beforeLayoutCallback) { return new Promise(function(resolve, reject) { - var iframe = document.createElement('iframe'); + let iframe = document.createElement('iframe'); iframe.name = 'test_' + iframeCount++; iframe.srcdoc = '' + '' + @@ -205,7 +205,7 @@ export function createIframePromise(opt_runtimeOff, opt_beforeLayoutCallback) { */ export function poll(description, condition, opt_onError, opt_timeout) { return new Promise((resolve, reject) => { - var start = new Date().getTime(); + let start = new Date().getTime(); function poll() { if (condition()) { clearInterval(interval); @@ -221,7 +221,7 @@ export function poll(description, condition, opt_onError, opt_timeout) { } } } - var interval = setInterval(poll, 50); + let interval = setInterval(poll, 50); poll(); }); } @@ -237,7 +237,7 @@ export function poll(description, condition, opt_onError, opt_timeout) { * @return {!Promise} */ export function pollForLayout(win, count, opt_timeout) { - var getCount = () => { + let getCount = () => { return win.document.querySelectorAll('.-amp-layout,.-amp-error').length; }; return poll('Waiting for elements to layout: ' + count, () => {