import { mkdir } from "node:fs/promises"; import { seedWorkspace } from "./seed.mjs"; /** * Shared plumbing for the demo capture scripts. Both the stills * (`capture.mjs`) and the clips (`clips.mjs`) boot the same seeded workspace * and control it through the dev-only `window.__typbase` handle. */ export const APP = process.env.DEMO_APP_URL ?? "http://127.0.0.1:3000"; export const IMAGES = new URL("../../docs/images/", import.meta.url).pathname; export const VIDEOS = new URL("../../docs/video/", import.meta.url).pathname; export const WORKSPACE_ID = "demo"; // Smaller viewport with the same 2x density: the chrome and text fill // more of the frame, which reads better when the images are scaled down. export const VIEWPORT = { width: 1280, height: 800 }; /** One theme per shot, covering the sizing and radius presets. */ export const SHOT_SETTINGS = { hero: { theme: "dark", themeName: "default", uiSize: "default", uiDensity: "default", uiRadius: "default", }, "notebook-hero": { theme: "light", themeName: "default", uiSize: "default", uiDensity: "default", uiRadius: "default", }, "query-split": { theme: "dark", themeName: "catppuccin", uiSize: "small", uiDensity: "compact", uiRadius: "square", }, wysiwyg: { theme: "light", themeName: "evergarden", uiSize: "large", uiDensity: "spacious", uiRadius: "round", }, }; /** * GIF settings shared by the clip and hero captures: 13 fps at 1200px with a * 160-color bayer-dithered palette. Long captures stay watchable without * ballooning. The full hero lands around 10 MB. */ export const GIF_FILTER = "fps=13,scale=1200:-2:flags=lanczos,split[s0][s1];[s0]palettegen=max_colors=160[p];[s1][p]paletteuse=dither=bayer:bayer_scale=3"; export async function ensureDirs() { await mkdir(IMAGES, { recursive: true }); await mkdir(VIDEOS, { recursive: true }); } /** Collapses the formatting strip so the stills are about the document. */ export async function installChromePreferences(context) { await context.addInitScript(() => localStorage.setItem("typbase:formatToolbar", "false")); } /** * A fake pointer for the clips: Playwright video does not render the real * cursor. The overlay follows `mousemove`, and `moveCursor` below dispatches * real moves over time, so the pointer glides instead of teleporting. The press * scale and ripple are CSS, triggered by real mousedown/mouseup events. */ export async function installCursor(context) { await context.addInitScript(() => { const attach = () => { if (document.getElementById("__demo-cursor")) return; const cursor = document.createElement("div"); cursor.id = "__demo-cursor"; cursor.innerHTML = ` `; const style = document.createElement("style"); style.textContent = ` #__demo-cursor { --cursor-tilt: 0deg; --cursor-speed: 0; --cursor-tip-x: 5.63px; --cursor-tip-y: 2.82px; position: fixed; left: 0; top: 0; width: 26px; height: 26px; z-index: 2147483647; pointer-events: none; opacity: 0; transition: opacity 0.18s ease; will-change: transform; } #__demo-cursor.is-visible { opacity: 1; } #__demo-cursor svg { position: relative; display: block; width: 100%; height: 100%; overflow: visible; filter: drop-shadow(0 1px 1.5px rgb(0 0 0 / 0.45)); transform: rotate(var(--cursor-tilt)) scale(calc(1 + var(--cursor-speed) * 0.04)); transform-origin: 5px 3px; transition: transform 80ms ease; } #__demo-cursor.is-pressed svg { transform: rotate(var(--cursor-tilt)) scale(0.82); } #__demo-cursor .__demo-cursor-ring { position: absolute; left: var(--cursor-tip-x); top: var(--cursor-tip-y); width: 24px; height: 24px; margin: -12px 0 0 -12px; border: 2px solid color-mix(in srgb, var(--color-accent, #6ea8fe) 68%, white); border-radius: 50%; opacity: 0; } #__demo-cursor.is-clicked .__demo-cursor-ring { animation: __demo-cursor-ripple var(--ripple-duration, 320ms) ease-out; } @keyframes __demo-cursor-ripple { from { opacity: 0.6; transform: scale(0.35); } to { opacity: 0; transform: scale(var(--ripple-scale, 1.5)); } } `; document.head.append(style); document.body.append(cursor); let lastMove = { x: 0, y: 0 }; let moveTimer; // A fixed seed keeps every capture reproducible. The values only vary the // ripple, never the pointer path, so clicks always land where they should. let entropy = 0x7a9e3b1f; const random = () => { entropy = (entropy * 1664525 + 1013904223) >>> 0; return entropy / 0x100000000; }; document.addEventListener( "mousemove", (event) => { // The overlay ignores events until `moveCursor` arms it. Chromium // reports a stray mousemove at (0,0) while the app boots, and // following it parked the pointer in the top-left corner before the // first glide started from the center. if (!window.__demoCursorArmed) return; const dx = event.clientX - lastMove.x; const speed = Math.min(1, Math.hypot(dx, event.clientY - lastMove.y) / 18); lastMove = { x: event.clientX, y: event.clientY }; cursor.classList.add("is-visible"); cursor.style.transform = `translate(${event.clientX}px, ${event.clientY}px)`; cursor.style.setProperty("--cursor-tilt", `${Math.max(-9, Math.min(9, dx * 1.6))}deg`); cursor.style.setProperty("--cursor-speed", speed.toFixed(2)); clearTimeout(moveTimer); moveTimer = setTimeout(() => { cursor.style.setProperty("--cursor-tilt", "0deg"); cursor.style.setProperty("--cursor-speed", "0"); }, 90); }, true, ); document.addEventListener( "mousedown", () => { if (window.__demoCursorArmed) cursor.classList.add("is-pressed"); }, true, ); document.addEventListener( "mouseup", () => { if (!window.__demoCursorArmed) return; cursor.classList.remove("is-pressed"); cursor.classList.remove("is-clicked"); cursor.style.setProperty("--ripple-scale", (1.35 + random() * 0.3).toFixed(2)); cursor.style.setProperty("--ripple-duration", `${280 + Math.round(random() * 80)}ms`); // Restart the ripple animation on every click. void cursor.offsetWidth; cursor.classList.add("is-clicked"); }, true, ); }; document.addEventListener("DOMContentLoaded", attach); if (document.body) attach(); }); } function easeInOutCubic(t) { return t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2; } /** Last animated pointer position, so moves start where the last one ended. */ let cursorPoint = { x: VIEWPORT.width / 2, y: VIEWPORT.height / 2 }; /** Lets the overlay track the pointer. See the guard in `installCursor`. */ async function armCursor(page) { await page.evaluate(() => { window.__demoCursorArmed = true; }); } /** * Moves the pointer to a point over `duration` ms along a slightly curved, * eased path, dispatching a real mousemove per frame. Playwright's built-in * `steps` all fire in one tick, which reads as a teleport on video. */ export async function moveCursor(page, x, y, { duration = 420 } = {}) { await armCursor(page); const from = cursorPoint; const dx = x - from.x; const dy = y - from.y; const distance = Math.hypot(dx, dy); if (distance < 2) { await page.mouse.move(x, y); return; } // A gentle arc, like a hand moving a mouse: control point perpendicular to // the straight line, scaled by the distance. const bow = Math.min(distance * 0.12, 46) * (dx >= 0 ? 1 : -1); const control = { x: (from.x + x) / 2 + (-dy / distance) * bow, y: (from.y + y) / 2 + (dx / distance) * bow, }; const started = Date.now(); for (;;) { const t = Math.min(1, (Date.now() - started) / duration); const e = easeInOutCubic(t); const point = { x: (1 - e) ** 2 * from.x + 2 * (1 - e) * e * control.x + e ** 2 * x, y: (1 - e) ** 2 * from.y + 2 * (1 - e) * e * control.y + e ** 2 * y, }; await page.mouse.move(point.x, point.y); cursorPoint = point; if (t >= 1) break; await page.waitForTimeout(12); } cursorPoint = { x, y }; } export async function boot(page) { await page.goto(APP, { waitUntil: "load", timeout: 180_000 }); await page.waitForSelector(".sidebar", { timeout: 180_000 }); await page.waitForSelector(".cm-editor", { timeout: 180_000 }); await page.waitForFunction(() => document.fonts.status === "loaded", null, { timeout: 60_000 }); } /** * Builds the demo workspace before the app ever loads. The seed runs on a * blank document on the app's origin, so OPFS is reachable and the app finds * `workspaces.json` on its first boot: no welcome workspace, no storage * chooser, no double seed. */ export async function seedBeforeBoot(context) { const page = await context.newPage(); await page.route(`${APP}/`, (route) => route.fulfill({ status: 200, contentType: "text/html", body: "seed", }), ); await page.goto(`${APP}/`, { waitUntil: "load", timeout: 60_000 }); const ids = await seedWorkspace(page, { workspaceId: WORKSPACE_ID }); await page.unroute(`${APP}/`); await page.close(); return ids; } export async function applySettings(page, patch) { await page.evaluate((settings) => window.__typbase.store.updateSettings(settings), patch); // The structure listener re-applies the chrome theme and recompiles Typst. await page.waitForTimeout(900); } /** In-app navigation: no reload, so settings just applied stay in memory. */ export async function show(page, pageId, mode, { editor = true } = {}) { await page.evaluate( ({ id, viewMode }) => { window.__typbase.openPage(id); window.__typbase.setMode(viewMode); }, { id: pageId, viewMode: mode }, ); // Read mode hides the editor, so it waits on the page shell instead. await page.waitForSelector(editor ? ".cm-editor" : ".page-view", { timeout: 120_000 }); await page.waitForFunction(() => document.fonts.status === "loaded", null, { timeout: 60_000 }); await page.waitForTimeout(900); if (!editor) return; // The linter runs after the editor compile. Wait for a clean gutter so no // red squiggles land in the shot. await page .waitForFunction( () => !document.querySelector(".cm-lintRange-error, .cm-lintRange-warning"), null, { timeout: 20_000 }, ) .catch(() => console.log("[warn] diagnostics still present")); } /** Glides the visible cursor to a locator and clicks it. */ export async function clickWithCursor(page, locator, options = {}) { const box = await locator.boundingBox(); if (!box) throw new Error("Locator has no box to click"); const x = box.x + box.width / 2; const y = box.y + box.height / 2; await moveCursor(page, x, y, { duration: options.duration ?? 420 }); await page.waitForTimeout(options.pause ?? 220); await page.mouse.click(x, y); } /** Center of the first text range containing `text` inside the editor. */ export async function tokenPoint(page, text) { return page.evaluate((needle) => { const root = document.querySelector(".cm-content"); if (!root) return null; const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); while (walker.nextNode()) { const node = walker.currentNode; const index = node.textContent.indexOf(needle); if (index === -1) continue; const range = document.createRange(); range.setStart(node, index); range.setEnd(node, index + needle.length); const rect = range.getBoundingClientRect(); if (rect.width === 0 && rect.height === 0) continue; return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }; } return null; }, text); } /** Moves the pointer over a token and keeps it there for a hover popup. */ export async function hoverToken(page, text, wait = 1200) { const point = await tokenPoint(page, text); if (!point) return false; await moveCursor(page, point.x, point.y, { duration: 380 }); await page.waitForTimeout(wait); return true; } /** Clicks a token, for placing the caret inside math. */ export async function clickToken(page, text, pause = 600) { const point = await tokenPoint(page, text); if (!point) return false; await moveCursor(page, point.x, point.y, { duration: 380 }); await page.waitForTimeout(200); await page.mouse.click(point.x, point.y); await page.waitForTimeout(pause); return true; } /** * Accepts a completion by label. Assumes the popup is already open from * typing. Retries with an explicit trigger if it is not. The engine ranks * completions by context, so the wanted item is not always the first. */ export async function acceptCompletion(page, labels) { const wanted = Array.isArray(labels) ? labels : [labels]; for (let attempt = 0; attempt < 3; attempt++) { if (attempt > 0) await page.keyboard.press("Control+Space"); await page .waitForFunction( () => document.querySelectorAll(".cm-tooltip-autocomplete li").length > 0, null, { timeout: 8000 }, ) .catch(() => {}); const items = await page.evaluate(() => [...document.querySelectorAll(".cm-tooltip-autocomplete li")].map( (item) => item.textContent?.trim() ?? "", ), ); if (items.length === 0) continue; for (let step = 0; step < items.length + 2; step++) { const selected = await page.evaluate( () => document .querySelector('.cm-tooltip-autocomplete li[aria-selected="true"]') ?.textContent?.trim() ?? null, ); if (selected !== null && wanted.includes(selected)) { await page.keyboard.press("Enter"); return true; } await page.keyboard.press("ArrowDown"); await page.waitForTimeout(120); } await page.keyboard.press("Escape"); } const seen = await page.evaluate(() => [...document.querySelectorAll(".cm-tooltip-autocomplete li")].map( (item) => item.textContent?.trim() ?? "", ), ); console.log(`[warn] completion ${wanted.join("/")} not found; saw: ${seen.join(", ")}`); return false; }