38 lines
2.4 KiB
Python
38 lines
2.4 KiB
Python
|
|
#!/usr/bin/env python3
|
||
|
|
"""Regenerate the static crawler snapshot inside index.html's <div id="root"> from the live React render.
|
||
|
|
Run by build.sh after the .min.js bundles are built. Needs Python Playwright + its Chromium."""
|
||
|
|
import functools, glob, http.server, os, re, threading
|
||
|
|
from playwright.sync_api import sync_playwright
|
||
|
|
|
||
|
|
class Quiet(http.server.SimpleHTTPRequestHandler):
|
||
|
|
def log_message(self, *a): pass
|
||
|
|
|
||
|
|
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), functools.partial(Quiet, directory="."))
|
||
|
|
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||
|
|
|
||
|
|
with sync_playwright() as p:
|
||
|
|
# ponytail: reuse any cached Playwright chromium instead of pinning a version; CHROME_PATH overrides
|
||
|
|
exe = os.environ.get("CHROME_PATH") or (sorted(glob.glob(os.path.expanduser("~/.cache/ms-playwright/chromium-*/chrome-linux*/chrome"))) or [None])[-1]
|
||
|
|
b = p.chromium.launch(executable_path=exe, args=["--no-sandbox"])
|
||
|
|
pg = b.new_page(viewport={"width": 1280, "height": 900})
|
||
|
|
pg.goto(f"http://127.0.0.1:{srv.server_port}/", wait_until="networkidle")
|
||
|
|
# scroll through so IntersectionObserver-driven stats count up to their final values
|
||
|
|
pg.evaluate("async()=>{for(let y=0;y<document.body.scrollHeight;y+=600){scrollTo(0,y);await new Promise(r=>setTimeout(r,120))}scrollTo(0,0)}")
|
||
|
|
pg.wait_for_timeout(2600)
|
||
|
|
root = pg.inner_html("#root")
|
||
|
|
pg_role0 = pg.evaluate("HERO_ROLES[0]") if pg.evaluate("typeof HERO_ROLES") != "undefined" else None
|
||
|
|
b.close()
|
||
|
|
srv.shutdown()
|
||
|
|
|
||
|
|
assert "Years in Broadcast" in root and ">0<span" not in root, "stats did not finish counting"
|
||
|
|
# ponytail: reveal stays un-.visible so createRoot's fresh render fades in identically; nav reset to top state
|
||
|
|
# typing effect is mid-cycle at capture time; pin it to the first role (what createRoot starts with)
|
||
|
|
role0 = pg_role0 or re.search(r'HERO_ROLES\s*=\s*\[\s*"([^"]+)"', open("components.jsx").read())[1]
|
||
|
|
root = re.sub(r'(<span class="hero-tag-prefix">//</span> )[^<]*(<span class="caret">)', lambda m: m[1] + role0 + m[2], root, count=1)
|
||
|
|
root = root.replace("reveal visible", "reveal ").replace('class="nav scrolled"', 'class="nav "')
|
||
|
|
h = open("index.html").read()
|
||
|
|
i = h.index('<div id="root">') + len('<div id="root">')
|
||
|
|
j = h.rindex("</div>", i, h.index("<script", i)) # root's own closing tag, just before the scripts
|
||
|
|
open("index.html", "w").write(h[:i] + root + h[j:])
|
||
|
|
print(f"snapshot-home: {len(re.sub(r'<[^>]+>', ' ', root).split())} words")
|