/* _chart_settle.js -- climatewatch.org /countries// pages only. * * WHY * The flagship "What are 's greenhouse gas emissions and emissions targets?" * chart is mounted only once /api/v1/emissions?gas=553&location=&source=274 lands in * the Redux store. The app dispatches that request LAST, behind ~20 other API JSONs, and * the benchmark's static file server (serving/site_server.py -> http.server.HTTPServer) * is single-threaded, so that burst is answered one response at a time. Measured on * /countries/BRA/: the burst is issued at t=2.23s and drains until t=4.9s; the emissions * request only goes out at t=4.89s and the chart mounts at t=5.6-9.6s, with ~3s of * run-to-run jitter. recharts then animates every series in from a zero-width * (animationBegin 500ms + animationDuration 1500ms), so for a further ~2.0s the chart * paints its axes, tick labels and target dots but NONE of its data series. * * Playwright's `networkidle` (0 connections for 500ms) is meanwhile governed by things * that have nothing to do with the chart -- third-party beacons when the cache is cold * (clarity c.gif redirect chain, engage.wri.org page-event, GA/GTM 404s), and NOTHING at * all when the cache is warm, because then the whole API waterfall is served from disk. * Measured: networkidle fires anywhere between 1.0s and 9.6s. Every capture recipe in this * repo is "networkidle + N ms", so the captured DOM lands, at random, in one of three * states: * 1. before the mount -> no .recharts-wrapper in the DOM at all * 2. inside the ~2.0s animation -> an empty axis grid with no data series * (this is the state the shipped countries_BRA desktop GT was frozen in) * 3. after the animation -> the correct chart * * WHAT THIS DOES * Nothing to the DOM, the styles or the app state. It only keeps one 1-byte request in * flight every 200ms -- below the 500ms networkidle threshold -- until the flagship chart * has both mounted and finished animating. That makes `networkidle` mean "the charts are * painted", which is what every capture recipe here already assumes it means, so captures * are always taken in state 3. * * The pinging is done from a Worker, not from this thread: parsing and booting the 10MB * app bundle blocks the main thread for ~3.5s, and a main-thread setInterval cannot fire * during that block -- which is exactly the window in which a warm-cache load goes quiet * and networkidle slips through. A Worker keeps pinging straight through it (verified). * * This file is loaded from WITHOUT defer so the Worker is started before the app * bundle begins executing. Readiness detection is read-only (Resource Timing + a DOM * query); nothing is monkey-patched. Every wait is hard-capped, so a page that never * mounts a chart still reaches networkidle well inside goto()'s 30s timeout. * * State 2 is ALSO fixed independently, and has to be: the full-page screenshot resizes the * layout viewport, the scrollbar disappears, every ResponsiveContainer gets ~15px wider and * recharts restarts the animation from zero AFTER networkidle, where no amount of waiting * can help. `repair.disable_chart_animations` therefore forces isAnimationActive false in * packs/main-*.js. This shim owns state 1 (capture before the mount); the ANIM_MS tail below * is now only margin. */ (function () { 'use strict'; // Only the country profiles carry the late-mounting flagship chart. if (!/^\/countries\/[A-Za-z]{3}\/?$/.test(location.pathname)) return; var POLL_MS = 100; // main-thread readiness poll var STABLE_MS = 400; // the mounted chart must hold this long before we start the anim wait var ANIM_MS = 2400; // recharts entry animation: 500ms begin + 1500ms duration + margin var DATA_CAP_MS = 12000; // stop waiting for the emissions payload to appear var HARD_CAP_MS = 17000; // absolute ceiling on this thread; the Worker has its own // This page requests far more than the 250-entry default, and we read Resource Timing // to know when the emissions payload landed. Raise the buffer before anything else loads. try { performance.setResourceTimingBufferSize(1000); } catch (e) { /* older engine */ } var worker = null; try { worker = new Worker('/_settle_worker.js'); } catch (e) { worker = null; } function stop() { if (!worker) return; // Ask it to stop; never terminate(). A hard terminate can strand an in-flight ping with no // finished/failed event, which leaves Playwright's networkidle counter above zero forever. try { worker.postMessage('stop'); } catch (e) { /* already gone */ } worker = null; } if (!worker) return; function emissionsSettled() { // Resource Timing lists cache hits too (transferSize 0), so this works warm or cold. var es; try { es = performance.getEntriesByType('resource'); } catch (e) { return false; } for (var i = 0; i < es.length; i++) { if (es[i].name.indexOf('/api/v1/emissions__') !== -1 && es[i].responseEnd > 0) return true; } return false; } function ghgMounted() { // recharts' ResponsiveContainer renders null until it has measured itself, so a // container with no .recharts-wrapper inside means "still mounting". var c = document.querySelector('[class*="country-ghg-emissions-styles__container"]'); if (!c) return false; var rc = c.querySelectorAll('.recharts-responsive-container'); if (!rc.length) return false; for (var i = 0; i < rc.length; i++) { if (!rc[i].querySelector('.recharts-wrapper')) return false; } return true; } var t0 = Date.now(), dataAt = 0, stableSince = 0, mountedAt = 0; var id = setInterval(function () { var now = Date.now(), age = now - t0; if (!dataAt && (emissionsSettled() || age >= DATA_CAP_MS)) dataAt = now; // Only trust the DOM once the payload has landed: before React's first render the DOM // still holds the frozen snapshot's own (already-rendered) chart markup. if (dataAt && !mountedAt) { if (ghgMounted()) { if (!stableSince) stableSince = now; if (now - stableSince >= STABLE_MS) mountedAt = now; } else { stableSince = 0; } } if ((mountedAt && now - mountedAt >= ANIM_MS) || age >= HARD_CAP_MS) { clearInterval(id); stop(); } }, POLL_MS); })();