UNPKG

storycrawler

Version:

Utilities to build Storybook crawling tools with Puppeteer

73 lines (72 loc) 1.93 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MetricsWatcher = void 0; const async_utils_1 = require("../async-utils"); /** * * Helper to detect whether browser's rendering pipeline is stable * * @example * * ```ts * async function someTask() { * const watcher = new MetricsWatcher(previewBrowser.page); * await watcher.waitForStable(); * doSomething(previewBrowser.page); * } * ``` * **/ class MetricsWatcher { constructor(page, count = 1000) { this.page = page; this.count = count; this.length = 3; this.previous = []; } /** * * Waits until the page's rendering process is stable. * * @remarks * This method checks the following counts get steady: * * - The number of DOM nodes * - The number of calculation style * - The number of calculation layout * **/ async waitForStable() { for (let i = 0; i < this.count; ++i) { if (await this.check()) return i; await (0, async_utils_1.sleep)(16); } return this.count; } async check() { const current = await this.page.metrics(); if (this.previous.length < this.length) return this.next(current); if (this.diff('Nodes')) return this.next(current); if (this.diff('RecalcStyleCount')) return this.next(current); if (this.diff('LayoutCount')) return this.next(current); return true; } diff(k) { for (let i = 1; i < this.previous.length; ++i) { if (this.previous[i][k] !== this.previous[0][k]) return true; } return false; } next(m) { this.previous.push(m); this.previous = this.previous.slice(-this.length); return false; } } exports.MetricsWatcher = MetricsWatcher;