diff --git a/README.md b/README.md index 8dbda83..0d6666a 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ To change settings later, call `Pace.configure({ ... })`; `Pace.start({ ... })` about requests and navigation (`restartOnNavigation`, `restartOnRequestAfter`, `trackXHR`, `trackFetch`, `trackWebSockets`, `requestMethods`, `ignoreRequests` and `maxWait`) apply from the next request or navigation; the others from the next time the bar starts, so a bar that is showing doesn't change halfway. `Pace.getOptions()` returns a -copy of the settings in use. +copy of the current settings (a bar that is showing keeps the other settings it started with). A wrong value or an unknown name is ignored, and the console shows a warning (once) that says what Pace expected. Pace never throws because of a wrong value. @@ -218,7 +218,7 @@ Configuration above. - `Pace.configure`: Change settings without starting the bar, see Configuration above. -- `Pace.getOptions`: A copy of the settings in use. +- `Pace.getOptions`: A copy of the current settings. - `Pace.restart`: Show the progress bar if it's hidden and start reporting the progress from scratch. Called automatically whenever `pushState` or `replaceState` is called by default. @@ -229,6 +229,17 @@ whenever `pushState` or `replaceState` is called by default. - `Pace.ignore`: Explicitly ignore one or more requests, see Tracking below +And these properties: + +- `Pace.running`: Whether a run is in progress, from `Pace.start()` until the bar is hidden or `Pace.stop()`. Read-only: +assigning to it does nothing, or throws a TypeError in strict-mode code such as modules. + +- `Pace.version`: The version of pace.js, such as `'2.0.0'`. + +If a page loads pace.js again after it's already there (a second script tag or bundle, or after Pace 1.x), the later +copy only logs a warning and the first one keeps running. Pace 1.x loaded after this version can't tell, so load only +one copy. + Events ------ @@ -236,8 +247,8 @@ Pace fires the following events: - `start`: When pace is initially started, or as a part of a restart - `stop`: When pace is manually stopped, or as a part of a restart -- `restart`: When pace is restarted (manually, or by a new AJAX request) -- `progress`: On every frame while the bar is running, with the current progress (0–100) +- `restart`: When pace is restarted (manually, by a new AJAX request, or on `pushState` or `replaceState`) +- `progress`: While the bar is running, with the current progress (0–100), up to about 30 times a second - `done`: When pace is finished - `hide`: When the pace is hidden (can be later than `done`, based on `hideDelay` and `minVisible`) @@ -368,7 +379,7 @@ If you run into a compatibility issue, please create an issue. Size ---- -pace.min.js is about 4 kB gzipped. The themes are between 0.2 and 3.2 kB gzipped. +pace.min.js is about 5.7 kB gzipped. The themes are between 0.3 and 3.2 kB gzipped. Issues ------ diff --git a/pace.js b/pace.js index 4a923e3..3d69fb5 100644 --- a/pace.js +++ b/pace.js @@ -4,7 +4,48 @@ * Licensed MIT © HubSpot, Inc. and Zachary Miller */ (function () { - // The longest delay a timer can wait: setTimeout treats more, and Infinity, as 0. + const VERSION = '1.3.1'; + + // Hands `value` to a module loader. False when pace was loaded by a " }); - const [search, running] = await page.evaluate(() => { - history.pushState({}, '', '?next'); - return [location.search, Pace.running]; + await open({ head: "" }); + // The working source after the two that throw still holds the bar. + await page.waitForTimeout(500); + await expect(page.locator('.pace')).toHaveClass('pace pace-active'); + await page.evaluate(() => { hold.progress = 100; }); + await idle(page); + await clearEvents(page); + await page.evaluate(() => { history.pushState({}, '', '?next'); hold.progress = 100; }); + await idle(page); + expect(await page.evaluate(() => [location.search, events, Pace.running])).toEqual(['?next', RESTARTED, false]); + // Each source, at load and on the navigation. + await expect.poll(() => errors.length).toBe(4); +}); + +test('Pace.start() while a run is finishing never throws or leaves Pace.running stuck', async ({ page, open }) => { + await open({ head: "" }); + await page.waitForFunction(() => events.includes('done')); + const [finishing, threw] = await page.evaluate(() => { + const finishing = Pace.running && !events.includes('hide'); + try { + Pace.start({ hideDelay: 0, extraSources: [function () { throw new Error('source'); }] }); + return [finishing, false]; + } catch { + return [finishing, true]; + } }); - expect([search, running]).toEqual(['?next', false]); - await expect.poll(() => errors.length).toBe(2); // at load, and on the navigation + expect([finishing, threw]).toEqual([true, false]); + await expect.poll(() => page.evaluate(() => [Pace.running, document.body.className]), { timeout: 5000 }).toEqual([false, 'pace-done']); +}); + +test('a target that exists before
gets the bar once exists', async ({ page, open }) => { + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + await open({ head: "" }); + await idle(page); + expect(await page.evaluate(() => [document.querySelector('.pace').parentElement.tagName, Pace.running])).toEqual(['HTML', false]); + expect(errors).toEqual([]); +}); + +test('an error listener that restarts pace while a source error is reported leaves one bar', async ({ page, open }) => { + await open({ + head: ``, + }); + await idle(page); + await clearEvents(page); + await page.evaluate(() => { window.restartOnError = true; Pace.restart(); }); + await idle(page); + await expect(page.locator('.pace')).toHaveCount(1); + expect(await page.evaluate(() => Pace.running)).toBe(false); +}); + +test('history.pushState before exists restarts the bar', async ({ page, paceFile }) => { + // A router that sets the URL from a script in , after pace. + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + const pace = fs.readFileSync(new URL(`../${paceFile}`, import.meta.url), 'utf8'); + await page.route('http://pace.test/**', (route) => (new URL(route.request().url()).pathname === '/pace.js' + ? route.fulfill({ contentType: 'text/javascript', body: pace }) + : route.fulfill({ + contentType: 'text/html', + body: ` + + + +page
`, + }))); + await page.goto('http://pace.test/'); + await idle(page); + expect(await page.evaluate(() => events)).toEqual(RESTARTED); + expect(errors).toEqual([]); }); diff --git a/tests/properties.spec.mjs b/tests/properties.spec.mjs new file mode 100644 index 0000000..935e82b --- /dev/null +++ b/tests/properties.spec.mjs @@ -0,0 +1,101 @@ +// Pace's small public properties, and what a second copy of pace on the page does. +import fs from 'node:fs'; +import { test, expect, idle, request, clearEvents, RESTARTED, NO_EVENT_LAG } from './fixtures.mjs'; + +const { version } = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')); + +// The console warnings the page logs, from now on. +const warnings = (page) => { + const messages = []; + page.on('console', (message) => { + if (message.type() === 'warning') messages.push(message.text()); + }); + return messages; +}; + +test('Pace.version is the package version', async ({ page, open }) => { + await open(); + expect(await page.evaluate(() => Pace.version)).toBe(version); +}); + +test('Pace.running is read-only', async ({ page, open }) => { + await open({ head: NO_EVENT_LAG }); + await idle(page); + expect(await page.evaluate(() => { + Pace.running = true; + return Pace.running; + })).toBe(false); +}); + +test('Pace has no internal properties', async ({ page, open }) => { + await open(); + expect(await page.evaluate(() => ['bar', 'sources', 'bindings', 'options'].filter((name) => name in Pace))).toEqual([]); +}); + +test('an element with id="Pace" is replaced, not used as pace', async ({ page, open }) => { + const logged = warnings(page); + await open({ head: '' + NO_EVENT_LAG }); + await idle(page); + expect(await page.evaluate(() => [window.Pace instanceof Element, typeof Pace.getOptions])).toEqual([false, 'function']); + expect(logged).toEqual([]); +}); + +test('a cross-origin frame named Pace is replaced, not used as pace', async ({ page, open }) => { + // Reading a property of a cross-origin frame throws. + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + await open({ head: '' + NO_EVENT_LAG }); + await idle(page); + expect(await page.evaluate(() => typeof Pace.getOptions)).toBe('function'); + expect(errors).toEqual([]); +}); + +test.describe('a second copy of pace on the page', () => { + test('only warns: the page keeps one bar, and the first copy tracks requests', async ({ page, open }) => { + const logged = warnings(page); + await open({ head: NO_EVENT_LAG + '' }); + await idle(page); + expect(logged).toEqual([`Pace: pace.js ${version} was loaded after another copy (${version}); only the first copy runs.`]); + await clearEvents(page); + await request(page, { ms: 900 }); + await idle(page); + expect(await page.evaluate(() => events)).toEqual(RESTARTED); + await expect(page.locator('.pace')).toHaveCount(1); + }); + + test('leaves the first copy and its hooks alone', async ({ page, open }) => { + await open({ + head: NO_EVENT_LAG + ` +`, + }); + expect(await page.evaluate(() => { + const hooks = [XMLHttpRequest.prototype.open, XMLHttpRequest.prototype.send, window.fetch, window.WebSocket, history.pushState, history.replaceState]; + return window.Pace === first.Pace && hooks.every((hook, i) => hook === first.hooks[i]); + })).toBe(true); + }); + + test('finds the first copy even when window.Pace no longer points to it', async ({ page, open }) => { + const logged = warnings(page); + await open({ head: NO_EVENT_LAG + '' }); + await page.waitForFunction(() => document.querySelector('.pace.pace-inactive')); + await expect(page.locator('.pace')).toHaveCount(1); + expect(logged).toEqual([`Pace: pace.js ${version} was loaded after another copy (${version}); only the first copy runs.`]); + }); + + test('an older pace already on the page counts as a first copy', async ({ page, open }) => { + // Pace 1.x puts an object with a start function on window.Pace. + const logged = warnings(page); + await open({ head: '' }); + await page.waitForTimeout(500); + await expect(page.locator('.pace')).toHaveCount(0); + expect(await page.evaluate(() => typeof Pace.getOptions)).toBe('undefined'); + expect(logged).toEqual([`Pace: pace.js ${version} was loaded after another copy; only the first copy runs.`]); + }); + + test('loaded with a bundler, exports the first copy', async ({ page, open }) => { + await open({ head: NO_EVENT_LAG + '' }); + expect(await page.evaluate(() => [module.exports === window.Pace, module.exports.version])).toEqual([true, version]); + }); +}); diff --git a/tests/settings.spec.mjs b/tests/settings.spec.mjs index 51986a1..29252a3 100644 --- a/tests/settings.spec.mjs +++ b/tests/settings.spec.mjs @@ -202,8 +202,8 @@ test.describe('wrong values and unknown names', () => { await open({ head: options("{ ajax: { trackMethods: ['POST'] }, eventLag: false, elements: { selectors: ['#x'] }, document: false, restartOnPushState: false, minTime: 0, ghostTime: 0 }") }); expect(logged).toEqual([ 'Pace: ignored the ajax option from window.paceOptions: use trackXHR, trackFetch, trackWebSockets, requestMethods, ignoreRequests and maxWait instead.', - 'Pace: ignored the eventLag option from window.paceOptions: use trackEventLag instead.', - 'Pace: ignored the elements option from window.paceOptions: use waitFor instead.', + 'Pace: ignored the eventLag option from window.paceOptions: use trackEventLag instead (its tuning settings were removed).', + 'Pace: ignored the elements option from window.paceOptions: use waitFor instead (checkInterval was removed).', 'Pace: ignored the document option from window.paceOptions: use trackDocument instead.', 'Pace: ignored the restartOnPushState option from window.paceOptions: use restartOnNavigation instead.', 'Pace: ignored the minTime option from window.paceOptions: use minVisible instead.',